main.cpp 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. //===-- examples/clang-interpreter/main.cpp - Clang C Interpreter Example -===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "clang/CodeGen/CodeGenAction.h"
  10. #include "clang/Basic/DiagnosticOptions.h"
  11. #include "clang/Driver/Compilation.h"
  12. #include "clang/Driver/Driver.h"
  13. #include "clang/Driver/Tool.h"
  14. #include "clang/Frontend/CompilerInstance.h"
  15. #include "clang/Frontend/CompilerInvocation.h"
  16. #include "clang/Frontend/FrontendDiagnostic.h"
  17. #include "clang/Frontend/TextDiagnosticPrinter.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/ExecutionEngine/ExecutionEngine.h"
  20. #include "llvm/ExecutionEngine/JIT.h"
  21. #include "llvm/IR/Module.h"
  22. #include "llvm/Support/FileSystem.h"
  23. #include "llvm/Support/Host.h"
  24. #include "llvm/Support/ManagedStatic.h"
  25. #include "llvm/Support/Path.h"
  26. #include "llvm/Support/TargetSelect.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <memory>
  29. using namespace clang;
  30. using namespace clang::driver;
  31. // This function isn't referenced outside its translation unit, but it
  32. // can't use the "static" keyword because its address is used for
  33. // GetMainExecutable (since some platforms don't support taking the
  34. // address of main, and some platforms can't implement GetMainExecutable
  35. // without being given the address of a function in the main executable).
  36. std::string GetExecutablePath(const char *Argv0) {
  37. // This just needs to be some symbol in the binary; C++ doesn't
  38. // allow taking the address of ::main however.
  39. void *MainAddr = (void*) (intptr_t) GetExecutablePath;
  40. return llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
  41. }
  42. static int Execute(llvm::Module *Mod, char * const *envp) {
  43. llvm::InitializeNativeTarget();
  44. std::string Error;
  45. std::unique_ptr<llvm::ExecutionEngine> EE(
  46. llvm::ExecutionEngine::createJIT(Mod, &Error));
  47. if (!EE) {
  48. llvm::errs() << "unable to make execution engine: " << Error << "\n";
  49. return 255;
  50. }
  51. llvm::Function *EntryFn = Mod->getFunction("main");
  52. if (!EntryFn) {
  53. llvm::errs() << "'main' function not found in module.\n";
  54. return 255;
  55. }
  56. // FIXME: Support passing arguments.
  57. std::vector<std::string> Args;
  58. Args.push_back(Mod->getModuleIdentifier());
  59. return EE->runFunctionAsMain(EntryFn, Args, envp);
  60. }
  61. int main(int argc, const char **argv, char * const *envp) {
  62. void *MainAddr = (void*) (intptr_t) GetExecutablePath;
  63. std::string Path = GetExecutablePath(argv[0]);
  64. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  65. TextDiagnosticPrinter *DiagClient =
  66. new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
  67. IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  68. DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
  69. Driver TheDriver(Path, llvm::sys::getProcessTriple(), Diags);
  70. TheDriver.setTitle("clang interpreter");
  71. // FIXME: This is a hack to try to force the driver to do something we can
  72. // recognize. We need to extend the driver library to support this use model
  73. // (basically, exactly one input, and the operation mode is hard wired).
  74. SmallVector<const char *, 16> Args(argv, argv + argc);
  75. Args.push_back("-fsyntax-only");
  76. std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(Args));
  77. if (!C)
  78. return 0;
  79. // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.
  80. // We expect to get back exactly one command job, if we didn't something
  81. // failed. Extract that job from the compilation.
  82. const driver::JobList &Jobs = C->getJobs();
  83. if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) {
  84. SmallString<256> Msg;
  85. llvm::raw_svector_ostream OS(Msg);
  86. Jobs.Print(OS, "; ", true);
  87. Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
  88. return 1;
  89. }
  90. const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
  91. if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
  92. Diags.Report(diag::err_fe_expected_clang_command);
  93. return 1;
  94. }
  95. // Initialize a compiler invocation object from the clang (-cc1) arguments.
  96. const driver::ArgStringList &CCArgs = Cmd->getArguments();
  97. std::unique_ptr<CompilerInvocation> CI(new CompilerInvocation);
  98. CompilerInvocation::CreateFromArgs(*CI,
  99. const_cast<const char **>(CCArgs.data()),
  100. const_cast<const char **>(CCArgs.data()) +
  101. CCArgs.size(),
  102. Diags);
  103. // Show the invocation, with -v.
  104. if (CI->getHeaderSearchOpts().Verbose) {
  105. llvm::errs() << "clang invocation:\n";
  106. Jobs.Print(llvm::errs(), "\n", true);
  107. llvm::errs() << "\n";
  108. }
  109. // FIXME: This is copied from cc1_main.cpp; simplify and eliminate.
  110. // Create a compiler instance to handle the actual work.
  111. CompilerInstance Clang;
  112. Clang.setInvocation(CI.release());
  113. // Create the compilers actual diagnostics engine.
  114. Clang.createDiagnostics();
  115. if (!Clang.hasDiagnostics())
  116. return 1;
  117. // Infer the builtin include path if unspecified.
  118. if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
  119. Clang.getHeaderSearchOpts().ResourceDir.empty())
  120. Clang.getHeaderSearchOpts().ResourceDir =
  121. CompilerInvocation::GetResourcesPath(argv[0], MainAddr);
  122. // Create and execute the frontend to generate an LLVM bitcode module.
  123. std::unique_ptr<CodeGenAction> Act(new EmitLLVMOnlyAction());
  124. if (!Clang.ExecuteAction(*Act))
  125. return 1;
  126. int Res = 255;
  127. if (llvm::Module *Module = Act->takeModule())
  128. Res = Execute(Module, envp);
  129. // Shutdown.
  130. llvm::llvm_shutdown();
  131. return Res;
  132. }