blob: 84e4c7137eb2a0223648fd28f80753cb0a48fed7 [file] [log] [blame]
Daniel Dunbare2246282010-02-25 08:49:05 +00001//===-- 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
Daniel Dunbar9b414d32010-06-15 17:48:49 +000010#include "clang/CodeGen/CodeGenAction.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000011#include "clang/Driver/Compilation.h"
12#include "clang/Driver/Driver.h"
13#include "clang/Driver/Tool.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000014#include "clang/Frontend/CompilerInvocation.h"
15#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000016#include "clang/Frontend/FrontendDiagnostic.h"
17#include "clang/Frontend/TextDiagnosticPrinter.h"
Douglas Gregor35d516c2012-10-23 22:36:49 +000018#include "clang/Basic/DiagnosticOptions.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000019
Daniel Dunbare2246282010-02-25 08:49:05 +000020#include "llvm/Module.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000021#include "llvm/ADT/OwningPtr.h"
22#include "llvm/ADT/SmallString.h"
Eli Friedman17e27942011-10-06 22:24:13 +000023#include "llvm/ExecutionEngine/JIT.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000024#include "llvm/ExecutionEngine/ExecutionEngine.h"
25#include "llvm/Support/ManagedStatic.h"
26#include "llvm/Support/raw_ostream.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000027#include "llvm/Support/Host.h"
28#include "llvm/Support/Path.h"
Evan Chenga6b40452011-08-24 18:09:14 +000029#include "llvm/Support/TargetSelect.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000030using namespace clang;
31using namespace clang::driver;
32
Dan Gohmanea1924e2010-11-17 17:23:53 +000033// 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).
Benjamin Krameraeed3da2010-10-30 17:32:40 +000038llvm::sys::Path GetExecutablePath(const char *Argv0) {
Daniel Dunbare2246282010-02-25 08:49:05 +000039 // 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::Path::GetMainExecutable(Argv0, MainAddr);
43}
44
Dan Gohmanf1295622010-10-29 22:41:35 +000045static int Execute(llvm::Module *Mod, char * const *envp) {
Daniel Dunbare2246282010-02-25 08:49:05 +000046 llvm::InitializeNativeTarget();
47
48 std::string Error;
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +000049 OwningPtr<llvm::ExecutionEngine> EE(
Daniel Dunbare2246282010-02-25 08:49:05 +000050 llvm::ExecutionEngine::createJIT(Mod, &Error));
51 if (!EE) {
52 llvm::errs() << "unable to make execution engine: " << Error << "\n";
53 return 255;
54 }
55
56 llvm::Function *EntryFn = Mod->getFunction("main");
57 if (!EntryFn) {
58 llvm::errs() << "'main' function not found in module.\n";
59 return 255;
60 }
61
62 // FIXME: Support passing arguments.
63 std::vector<std::string> Args;
64 Args.push_back(Mod->getModuleIdentifier());
65
66 return EE->runFunctionAsMain(EntryFn, Args, envp);
67}
68
69int main(int argc, const char **argv, char * const *envp) {
70 void *MainAddr = (void*) (intptr_t) GetExecutablePath;
71 llvm::sys::Path Path = GetExecutablePath(argv[0]);
Douglas Gregor35d516c2012-10-23 22:36:49 +000072 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Benjamin Kramer06b901b2010-08-26 13:48:56 +000073 TextDiagnosticPrinter *DiagClient =
Douglas Gregor35d516c2012-10-23 22:36:49 +000074 new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
Daniel Dunbare2246282010-02-25 08:49:05 +000075
Dylan Noblesmithc93dc782012-02-20 14:00:23 +000076 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Douglas Gregor35d516c2012-10-23 22:36:49 +000077 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
Sebastian Pop5d8b9542011-11-01 21:33:06 +000078 Driver TheDriver(Path.str(), llvm::sys::getDefaultTargetTriple(),
Bob Wilson10a82cd2011-10-04 05:34:14 +000079 "a.out", /*IsProduction=*/false, Diags);
Daniel Dunbare2246282010-02-25 08:49:05 +000080 TheDriver.setTitle("clang interpreter");
81
82 // FIXME: This is a hack to try to force the driver to do something we can
83 // recognize. We need to extend the driver library to support this use model
84 // (basically, exactly one input, and the operation mode is hard wired).
85 llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
86 Args.push_back("-fsyntax-only");
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +000087 OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args));
Daniel Dunbare2246282010-02-25 08:49:05 +000088 if (!C)
89 return 0;
90
91 // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.
92
93 // We expect to get back exactly one command job, if we didn't something
94 // failed. Extract that job from the compilation.
95 const driver::JobList &Jobs = C->getJobs();
Manuel Klimekc8b3e632011-05-23 18:25:41 +000096 if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +000097 SmallString<256> Msg;
Daniel Dunbare2246282010-02-25 08:49:05 +000098 llvm::raw_svector_ostream OS(Msg);
99 C->PrintJob(OS, C->getJobs(), "; ", true);
100 Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
101 return 1;
102 }
103
104 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
105 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
106 Diags.Report(diag::err_fe_expected_clang_command);
107 return 1;
108 }
109
110 // Initialize a compiler invocation object from the clang (-cc1) arguments.
111 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +0000112 OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Benjamin Kramer9e8635a2010-04-20 11:50:39 +0000113 CompilerInvocation::CreateFromArgs(*CI,
114 const_cast<const char **>(CCArgs.data()),
115 const_cast<const char **>(CCArgs.data()) +
116 CCArgs.size(),
Benjamin Kramera4f0a802010-04-20 11:55:38 +0000117 Diags);
Daniel Dunbare2246282010-02-25 08:49:05 +0000118
119 // Show the invocation, with -v.
120 if (CI->getHeaderSearchOpts().Verbose) {
121 llvm::errs() << "clang invocation:\n";
122 C->PrintJob(llvm::errs(), C->getJobs(), "\n", true);
123 llvm::errs() << "\n";
124 }
125
126 // FIXME: This is copied from cc1_main.cpp; simplify and eliminate.
127
128 // Create a compiler instance to handle the actual work.
129 CompilerInstance Clang;
Daniel Dunbare2246282010-02-25 08:49:05 +0000130 Clang.setInvocation(CI.take());
131
132 // Create the compilers actual diagnostics engine.
Benjamin Kramera4f0a802010-04-20 11:55:38 +0000133 Clang.createDiagnostics(int(CCArgs.size()),const_cast<char**>(CCArgs.data()));
Daniel Dunbare2246282010-02-25 08:49:05 +0000134 if (!Clang.hasDiagnostics())
135 return 1;
136
137 // Infer the builtin include path if unspecified.
138 if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
139 Clang.getHeaderSearchOpts().ResourceDir.empty())
140 Clang.getHeaderSearchOpts().ResourceDir =
141 CompilerInvocation::GetResourcesPath(argv[0], MainAddr);
142
143 // Create and execute the frontend to generate an LLVM bitcode module.
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +0000144 OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction());
Daniel Dunbare2246282010-02-25 08:49:05 +0000145 if (!Clang.ExecuteAction(*Act))
146 return 1;
147
148 int Res = 255;
149 if (llvm::Module *Module = Act->takeModule())
150 Res = Execute(Module, envp);
151
152 // Shutdown.
153
154 llvm::llvm_shutdown();
155
156 return Res;
157}