]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - examples/clang-interpreter/main.cpp
Update clang to 97654.
[FreeBSD/FreeBSD.git] / examples / clang-interpreter / main.cpp
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/Driver/Compilation.h"
11 #include "clang/Driver/Driver.h"
12 #include "clang/Driver/Tool.h"
13 #include "clang/Frontend/CodeGenAction.h"
14 #include "clang/Frontend/CompilerInvocation.h"
15 #include "clang/Frontend/CompilerInstance.h"
16 #include "clang/Frontend/DiagnosticOptions.h"
17 #include "clang/Frontend/FrontendDiagnostic.h"
18 #include "clang/Frontend/TextDiagnosticPrinter.h"
19
20 #include "llvm/LLVMContext.h"
21 #include "llvm/Module.h"
22 #include "llvm/Config/config.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/ExecutionEngine/ExecutionEngine.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/System/Host.h"
30 #include "llvm/System/Path.h"
31 #include "llvm/Target/TargetSelect.h"
32 using namespace clang;
33 using namespace clang::driver;
34
35 llvm::sys::Path GetExecutablePath(const char *Argv0) {
36   // This just needs to be some symbol in the binary; C++ doesn't
37   // allow taking the address of ::main however.
38   void *MainAddr = (void*) (intptr_t) GetExecutablePath;
39   return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);
40 }
41
42 int Execute(llvm::Module *Mod, char * const *envp) {
43   llvm::InitializeNativeTarget();
44
45   std::string Error;
46   llvm::OwningPtr<llvm::ExecutionEngine> EE(
47     llvm::ExecutionEngine::createJIT(Mod, &Error));
48   if (!EE) {
49     llvm::errs() << "unable to make execution engine: " << Error << "\n";
50     return 255;
51   }
52
53   llvm::Function *EntryFn = Mod->getFunction("main");
54   if (!EntryFn) {
55     llvm::errs() << "'main' function not found in module.\n";
56     return 255;
57   }
58
59   // FIXME: Support passing arguments.
60   std::vector<std::string> Args;
61   Args.push_back(Mod->getModuleIdentifier());
62
63   return EE->runFunctionAsMain(EntryFn, Args, envp);
64 }
65
66 int main(int argc, const char **argv, char * const *envp) {
67   void *MainAddr = (void*) (intptr_t) GetExecutablePath;
68   llvm::sys::Path Path = GetExecutablePath(argv[0]);
69   TextDiagnosticPrinter DiagClient(llvm::errs(), DiagnosticOptions());
70
71   Diagnostic Diags(&DiagClient);
72   Driver TheDriver(Path.getBasename(), Path.getDirname(),
73                    llvm::sys::getHostTriple(),
74                    "a.out", /*IsProduction=*/false, Diags);
75   TheDriver.setTitle("clang interpreter");
76
77   // FIXME: This is a hack to try to force the driver to do something we can
78   // recognize. We need to extend the driver library to support this use model
79   // (basically, exactly one input, and the operation mode is hard wired).
80   llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
81   Args.push_back("-fsyntax-only");
82   llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(),
83                                                             Args.data()));
84   if (!C)
85     return 0;
86
87   // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.
88
89   // We expect to get back exactly one command job, if we didn't something
90   // failed. Extract that job from the compilation.
91   const driver::JobList &Jobs = C->getJobs();
92   if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
93     llvm::SmallString<256> Msg;
94     llvm::raw_svector_ostream OS(Msg);
95     C->PrintJob(OS, C->getJobs(), "; ", true);
96     Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
97     return 1;
98   }
99
100   const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
101   if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
102     Diags.Report(diag::err_fe_expected_clang_command);
103     return 1;
104   }
105
106   // Initialize a compiler invocation object from the clang (-cc1) arguments.
107   const driver::ArgStringList &CCArgs = Cmd->getArguments();
108   llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
109   CompilerInvocation::CreateFromArgs(*CI, (const char**) CCArgs.data(),
110                                      (const char**) CCArgs.data()+CCArgs.size(),
111                                      Diags);
112
113   // Show the invocation, with -v.
114   if (CI->getHeaderSearchOpts().Verbose) {
115     llvm::errs() << "clang invocation:\n";
116     C->PrintJob(llvm::errs(), C->getJobs(), "\n", true);
117     llvm::errs() << "\n";
118   }
119
120   // FIXME: This is copied from cc1_main.cpp; simplify and eliminate.
121
122   // Create a compiler instance to handle the actual work.
123   CompilerInstance Clang;
124   Clang.setLLVMContext(new llvm::LLVMContext);
125   Clang.setInvocation(CI.take());
126
127   // Create the compilers actual diagnostics engine.
128   Clang.createDiagnostics(int(CCArgs.size()), (char**) CCArgs.data());
129   if (!Clang.hasDiagnostics())
130     return 1;
131
132   // Infer the builtin include path if unspecified.
133   if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
134       Clang.getHeaderSearchOpts().ResourceDir.empty())
135     Clang.getHeaderSearchOpts().ResourceDir =
136       CompilerInvocation::GetResourcesPath(argv[0], MainAddr);
137
138   // Create and execute the frontend to generate an LLVM bitcode module.
139   llvm::OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction());
140   if (!Clang.ExecuteAction(*Act))
141     return 1;
142
143   int Res = 255;
144   if (llvm::Module *Module = Act->takeModule())
145     Res = Execute(Module, envp);
146
147   // Shutdown.
148
149   llvm::llvm_shutdown();
150
151   return Res;
152 }