2 * llvm C frontend for perf. Support dynamically compile C file
4 * Inspired by clang example code:
5 * http://llvm.org/svn/llvm-project/cfe/trunk/examples/clang-interpreter/main.cpp
7 * Copyright (C) 2016 Wang Nan <wangnan0@huawei.com>
8 * Copyright (C) 2016 Huawei Inc.
11 #include "clang/CodeGen/CodeGenAction.h"
12 #include "clang/Frontend/CompilerInvocation.h"
13 #include "clang/Frontend/CompilerInstance.h"
14 #include "clang/Frontend/TextDiagnosticPrinter.h"
15 #include "clang/Tooling/Tooling.h"
16 #include "llvm/IR/Module.h"
17 #include "llvm/Option/Option.h"
18 #include "llvm/Support/ManagedStatic.h"
26 static std::unique_ptr<llvm::LLVMContext> LLVMCtx;
28 using namespace clang;
30 static vfs::InMemoryFileSystem *
31 buildVFS(StringRef& Name, StringRef& Content)
33 vfs::InMemoryFileSystem *VFS = new vfs::InMemoryFileSystem(true);
34 VFS->addFile(Twine(Name), 0, llvm::MemoryBuffer::getMemBuffer(Content));
38 static CompilerInvocation *
39 createCompilerInvocation(StringRef& Path, DiagnosticsEngine& Diags)
41 llvm::opt::ArgStringList CCArgs {
43 "-triple", "bpf-pc-linux",
45 "-ferror-limit", "19",
46 "-fmessage-length", "127",
55 CompilerInvocation *CI = tooling::newInvocation(&Diags, CCArgs);
57 FrontendOptions& Opts = CI->getFrontendOpts();
59 Opts.Inputs.emplace_back(Path, IK_C);
63 std::unique_ptr<llvm::Module>
64 getModuleFromSource(StringRef Name, StringRef Content)
66 CompilerInstance Clang;
67 Clang.createDiagnostics();
69 IntrusiveRefCntPtr<vfs::FileSystem> VFS = buildVFS(Name, Content);
70 Clang.setVirtualFileSystem(&*VFS);
72 IntrusiveRefCntPtr<CompilerInvocation> CI =
73 createCompilerInvocation(Name, Clang.getDiagnostics());
74 Clang.setInvocation(&*CI);
76 std::unique_ptr<CodeGenAction> Act(new EmitLLVMOnlyAction(&*LLVMCtx));
77 if (!Clang.ExecuteAction(*Act))
78 return std::unique_ptr<llvm::Module>(nullptr);
80 return Act->takeModule();
86 void perf_clang__init(void)
88 perf::LLVMCtx.reset(new llvm::LLVMContext());
91 void perf_clang__cleanup(void)
93 perf::LLVMCtx.reset(nullptr);
94 llvm::llvm_shutdown();