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