main.cpp 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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/Driver/Compilation.h"
  11. #include "clang/Driver/Driver.h"
  12. #include "clang/Driver/Tool.h"
  13. #include "clang/Frontend/CompilerInvocation.h"
  14. #include "clang/Frontend/CompilerInstance.h"
  15. #include "clang/Frontend/DiagnosticOptions.h"
  16. #include "clang/Frontend/FrontendDiagnostic.h"
  17. #include "clang/Frontend/TextDiagnosticPrinter.h"
  18. #include "llvm/Module.h"
  19. #include "llvm/Config/config.h"
  20. #include "llvm/ADT/OwningPtr.h"
  21. #include "llvm/ADT/SmallString.h"
  22. #include "llvm/Config/config.h"
  23. #include "llvm/ExecutionEngine/ExecutionEngine.h"
  24. #include "llvm/Support/ManagedStatic.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include "llvm/Support/Host.h"
  27. #include "llvm/Support/Path.h"
  28. #include "llvm/Support/TargetSelect.h"
  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. llvm::sys::Path 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::Path::GetMainExecutable(Argv0, MainAddr);
  41. }
  42. static int Execute(llvm::Module *Mod, char * const *envp) {
  43. llvm::InitializeNativeTarget();
  44. std::string Error;
  45. llvm::OwningPtr<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. llvm::sys::Path Path = GetExecutablePath(argv[0]);
  64. TextDiagnosticPrinter *DiagClient =
  65. new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());
  66. llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  67. DiagnosticsEngine Diags(DiagID, DiagClient);
  68. Driver TheDriver(Path.str(), llvm::sys::getHostTriple(),
  69. "a.out", /*IsProduction=*/false, /*CXXIsProduction=*/false,
  70. Diags);
  71. TheDriver.setTitle("clang interpreter");
  72. // FIXME: This is a hack to try to force the driver to do something we can
  73. // recognize. We need to extend the driver library to support this use model
  74. // (basically, exactly one input, and the operation mode is hard wired).
  75. llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
  76. Args.push_back("-fsyntax-only");
  77. llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args));
  78. if (!C)
  79. return 0;
  80. // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.
  81. // We expect to get back exactly one command job, if we didn't something
  82. // failed. Extract that job from the compilation.
  83. const driver::JobList &Jobs = C->getJobs();
  84. if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) {
  85. llvm::SmallString<256> Msg;
  86. llvm::raw_svector_ostream OS(Msg);
  87. C->PrintJob(OS, C->getJobs(), "; ", true);
  88. Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
  89. return 1;
  90. }
  91. const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
  92. if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
  93. Diags.Report(diag::err_fe_expected_clang_command);
  94. return 1;
  95. }
  96. // Initialize a compiler invocation object from the clang (-cc1) arguments.
  97. const driver::ArgStringList &CCArgs = Cmd->getArguments();
  98. llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
  99. CompilerInvocation::CreateFromArgs(*CI,
  100. const_cast<const char **>(CCArgs.data()),
  101. const_cast<const char **>(CCArgs.data()) +
  102. CCArgs.size(),
  103. Diags);
  104. // Show the invocation, with -v.
  105. if (CI->getHeaderSearchOpts().Verbose) {
  106. llvm::errs() << "clang invocation:\n";
  107. C->PrintJob(llvm::errs(), C->getJobs(), "\n", true);
  108. llvm::errs() << "\n";
  109. }
  110. // FIXME: This is copied from cc1_main.cpp; simplify and eliminate.
  111. // Create a compiler instance to handle the actual work.
  112. CompilerInstance Clang;
  113. Clang.setInvocation(CI.take());
  114. // Create the compilers actual diagnostics engine.
  115. Clang.createDiagnostics(int(CCArgs.size()),const_cast<char**>(CCArgs.data()));
  116. if (!Clang.hasDiagnostics())
  117. return 1;
  118. // Infer the builtin include path if unspecified.
  119. if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
  120. Clang.getHeaderSearchOpts().ResourceDir.empty())
  121. Clang.getHeaderSearchOpts().ResourceDir =
  122. CompilerInvocation::GetResourcesPath(argv[0], MainAddr);
  123. // Create and execute the frontend to generate an LLVM bitcode module.
  124. llvm::OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction());
  125. if (!Clang.ExecuteAction(*Act))
  126. return 1;
  127. int Res = 255;
  128. if (llvm::Module *Module = Act->takeModule())
  129. Res = Execute(Module, envp);
  130. // Shutdown.
  131. llvm::llvm_shutdown();
  132. return Res;
  133. }