1 //===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This builds an AST and converts it to LLVM Code.
12 //===----------------------------------------------------------------------===//
14 #include "clang/CodeGen/ModuleBuilder.h"
15 #include "CGDebugInfo.h"
16 #include "CodeGenModule.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Frontend/CodeGenOptions.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
28 using namespace clang;
31 class CodeGeneratorImpl : public CodeGenerator {
32 DiagnosticsEngine &Diags;
33 std::unique_ptr<const llvm::DataLayout> TD;
35 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
36 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
37 const CodeGenOptions CodeGenOpts; // Intentionally copied in.
39 unsigned HandlingTopLevelDecls;
40 struct HandlingTopLevelDeclRAII {
41 CodeGeneratorImpl &Self;
42 HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self) : Self(Self) {
43 ++Self.HandlingTopLevelDecls;
45 ~HandlingTopLevelDeclRAII() {
46 if (--Self.HandlingTopLevelDecls == 0)
47 Self.EmitDeferredDecls();
51 CoverageSourceInfo *CoverageInfo;
54 std::unique_ptr<llvm::Module> M;
55 std::unique_ptr<CodeGen::CodeGenModule> Builder;
58 SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
61 CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string &ModuleName,
62 const HeaderSearchOptions &HSO,
63 const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
65 CoverageSourceInfo *CoverageInfo = nullptr)
66 : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
67 PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
68 CoverageInfo(CoverageInfo),
69 M(new llvm::Module(ModuleName, C)) {}
71 ~CodeGeneratorImpl() override {
72 // There should normally not be any leftover inline method definitions.
73 assert(DeferredInlineMethodDefinitions.empty() ||
74 Diags.hasErrorOccurred());
77 llvm::Module* GetModule() override {
81 const Decl *GetDeclForMangledName(StringRef MangledName) override {
83 if (!Builder->lookupRepresentativeDecl(MangledName, Result))
85 const Decl *D = Result.getCanonicalDecl().getDecl();
86 if (auto FD = dyn_cast<FunctionDecl>(D)) {
89 } else if (auto TD = dyn_cast<TagDecl>(D)) {
90 if (auto Def = TD->getDefinition())
96 llvm::Module *ReleaseModule() override { return M.release(); }
98 void Initialize(ASTContext &Context) override {
101 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
102 M->setDataLayout(Ctx->getTargetInfo().getTargetDescription());
104 new llvm::DataLayout(Ctx->getTargetInfo().getTargetDescription()));
105 Builder.reset(new CodeGen::CodeGenModule(Context,
108 CodeGenOpts, *M, *TD,
109 Diags, CoverageInfo));
111 for (size_t i = 0, e = CodeGenOpts.DependentLibraries.size(); i < e; ++i)
112 HandleDependentLibrary(CodeGenOpts.DependentLibraries[i]);
115 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
116 if (Diags.hasErrorOccurred())
119 Builder->HandleCXXStaticMemberVarInstantiation(VD);
122 bool HandleTopLevelDecl(DeclGroupRef DG) override {
123 if (Diags.hasErrorOccurred())
126 HandlingTopLevelDeclRAII HandlingDecl(*this);
128 // Make sure to emit all elements of a Decl.
129 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
130 Builder->EmitTopLevelDecl(*I);
135 void EmitDeferredDecls() {
136 if (DeferredInlineMethodDefinitions.empty())
139 // Emit any deferred inline method definitions. Note that more deferred
140 // methods may be added during this loop, since ASTConsumer callbacks
141 // can be invoked if AST inspection results in declarations being added.
142 HandlingTopLevelDeclRAII HandlingDecl(*this);
143 for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
144 Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
145 DeferredInlineMethodDefinitions.clear();
148 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
149 if (Diags.hasErrorOccurred())
152 assert(D->doesThisDeclarationHaveABody());
154 // We may want to emit this definition. However, that decision might be
155 // based on computing the linkage, and we have to defer that in case we
156 // are inside of something that will change the method's final linkage,
160 // void foo() { bar(); }
162 DeferredInlineMethodDefinitions.push_back(D);
164 // Provide some coverage mapping even for methods that aren't emitted.
165 // Don't do this for templated classes though, as they may not be
167 if (!D->getParent()->getDescribedClassTemplate())
168 Builder->AddDeferredUnusedCoverageMapping(D);
171 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
172 /// to (e.g. struct, union, enum, class) is completed. This allows the
173 /// client hack on the type, which can occur at any point in the file
174 /// (because these can be defined in declspecs).
175 void HandleTagDeclDefinition(TagDecl *D) override {
176 if (Diags.hasErrorOccurred())
179 Builder->UpdateCompletedType(D);
181 // For MSVC compatibility, treat declarations of static data members with
182 // inline initializers as definitions.
183 if (Ctx->getLangOpts().MSVCCompat) {
184 for (Decl *Member : D->decls()) {
185 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
186 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
187 Ctx->DeclMustBeEmitted(VD)) {
188 Builder->EmitGlobal(VD);
195 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
196 if (Diags.hasErrorOccurred())
199 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
200 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
201 DI->completeRequiredType(RD);
204 void HandleTranslationUnit(ASTContext &Ctx) override {
205 if (Diags.hasErrorOccurred()) {
216 void CompleteTentativeDefinition(VarDecl *D) override {
217 if (Diags.hasErrorOccurred())
220 Builder->EmitTentativeDefinition(D);
223 void HandleVTable(CXXRecordDecl *RD) override {
224 if (Diags.hasErrorOccurred())
227 Builder->EmitVTable(RD);
230 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
231 Builder->AppendLinkerOptions(Opts);
234 void HandleDetectMismatch(llvm::StringRef Name,
235 llvm::StringRef Value) override {
236 Builder->AddDetectMismatch(Name, Value);
239 void HandleDependentLibrary(llvm::StringRef Lib) override {
240 Builder->AddDependentLib(Lib);
245 void CodeGenerator::anchor() { }
247 CodeGenerator *clang::CreateLLVMCodeGen(
248 DiagnosticsEngine &Diags, const std::string &ModuleName,
249 const HeaderSearchOptions &HeaderSearchOpts,
250 const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
251 llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
252 return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
253 PreprocessorOpts, CGO, C, CoverageInfo);