1 //===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
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 // This builds an AST and converts it to LLVM Code.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
27 #include <memory>
28 using namespace clang;
29
30 namespace {
31 class CodeGeneratorImpl : public CodeGenerator {
32 DiagnosticsEngine &Diags;
33 std::unique_ptr<const llvm::DataLayout> TD;
34 ASTContext *Ctx;
35 const CodeGenOptions CodeGenOpts; // Intentionally copied in.
36
37 unsigned HandlingTopLevelDecls;
38 struct HandlingTopLevelDeclRAII {
39 CodeGeneratorImpl &Self;
HandlingTopLevelDeclRAII__anoncaca9f7e0111::CodeGeneratorImpl::HandlingTopLevelDeclRAII40 HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self) : Self(Self) {
41 ++Self.HandlingTopLevelDecls;
42 }
~HandlingTopLevelDeclRAII__anoncaca9f7e0111::CodeGeneratorImpl::HandlingTopLevelDeclRAII43 ~HandlingTopLevelDeclRAII() {
44 if (--Self.HandlingTopLevelDecls == 0)
45 Self.EmitDeferredDecls();
46 }
47 };
48
49 CoverageSourceInfo *CoverageInfo;
50
51 protected:
52 std::unique_ptr<llvm::Module> M;
53 std::unique_ptr<CodeGen::CodeGenModule> Builder;
54
55 private:
56 SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
57
58 public:
CodeGeneratorImpl(DiagnosticsEngine & diags,const std::string & ModuleName,const CodeGenOptions & CGO,llvm::LLVMContext & C,CoverageSourceInfo * CoverageInfo=nullptr)59 CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string& ModuleName,
60 const CodeGenOptions &CGO, llvm::LLVMContext& C,
61 CoverageSourceInfo *CoverageInfo = nullptr)
62 : Diags(diags), Ctx(nullptr), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
63 CoverageInfo(CoverageInfo),
64 M(new llvm::Module(ModuleName, C)) {}
65
~CodeGeneratorImpl()66 virtual ~CodeGeneratorImpl() {
67 // There should normally not be any leftover inline method definitions.
68 assert(DeferredInlineMethodDefinitions.empty() ||
69 Diags.hasErrorOccurred());
70 }
71
GetModule()72 llvm::Module* GetModule() override {
73 return M.get();
74 }
75
GetDeclForMangledName(StringRef MangledName)76 const Decl *GetDeclForMangledName(StringRef MangledName) override {
77 GlobalDecl Result;
78 if (!Builder->lookupRepresentativeDecl(MangledName, Result))
79 return nullptr;
80 const Decl *D = Result.getCanonicalDecl().getDecl();
81 if (auto FD = dyn_cast<FunctionDecl>(D)) {
82 if (FD->hasBody(FD))
83 return FD;
84 } else if (auto TD = dyn_cast<TagDecl>(D)) {
85 if (auto Def = TD->getDefinition())
86 return Def;
87 }
88 return D;
89 }
90
ReleaseModule()91 llvm::Module *ReleaseModule() override { return M.release(); }
92
Initialize(ASTContext & Context)93 void Initialize(ASTContext &Context) override {
94 Ctx = &Context;
95
96 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
97 M->setDataLayout(Ctx->getTargetInfo().getTargetDescription());
98 TD.reset(new llvm::DataLayout(Ctx->getTargetInfo().getTargetDescription()));
99 Builder.reset(new CodeGen::CodeGenModule(Context, CodeGenOpts, *M, *TD,
100 Diags, CoverageInfo));
101
102 for (size_t i = 0, e = CodeGenOpts.DependentLibraries.size(); i < e; ++i)
103 HandleDependentLibrary(CodeGenOpts.DependentLibraries[i]);
104 }
105
HandleCXXStaticMemberVarInstantiation(VarDecl * VD)106 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
107 if (Diags.hasErrorOccurred())
108 return;
109
110 Builder->HandleCXXStaticMemberVarInstantiation(VD);
111 }
112
HandleTopLevelDecl(DeclGroupRef DG)113 bool HandleTopLevelDecl(DeclGroupRef DG) override {
114 if (Diags.hasErrorOccurred())
115 return true;
116
117 HandlingTopLevelDeclRAII HandlingDecl(*this);
118
119 // Make sure to emit all elements of a Decl.
120 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
121 Builder->EmitTopLevelDecl(*I);
122
123 return true;
124 }
125
EmitDeferredDecls()126 void EmitDeferredDecls() {
127 if (DeferredInlineMethodDefinitions.empty())
128 return;
129
130 // Emit any deferred inline method definitions. Note that more deferred
131 // methods may be added during this loop, since ASTConsumer callbacks
132 // can be invoked if AST inspection results in declarations being added.
133 HandlingTopLevelDeclRAII HandlingDecl(*this);
134 for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
135 Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
136 DeferredInlineMethodDefinitions.clear();
137 }
138
HandleInlineMethodDefinition(CXXMethodDecl * D)139 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
140 if (Diags.hasErrorOccurred())
141 return;
142
143 assert(D->doesThisDeclarationHaveABody());
144
145 // We may want to emit this definition. However, that decision might be
146 // based on computing the linkage, and we have to defer that in case we
147 // are inside of something that will change the method's final linkage,
148 // e.g.
149 // typedef struct {
150 // void bar();
151 // void foo() { bar(); }
152 // } A;
153 DeferredInlineMethodDefinitions.push_back(D);
154
155 // Provide some coverage mapping even for methods that aren't emitted.
156 // Don't do this for templated classes though, as they may not be
157 // instantiable.
158 if (!D->getParent()->getDescribedClassTemplate())
159 Builder->AddDeferredUnusedCoverageMapping(D);
160 }
161
162 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
163 /// to (e.g. struct, union, enum, class) is completed. This allows the
164 /// client hack on the type, which can occur at any point in the file
165 /// (because these can be defined in declspecs).
HandleTagDeclDefinition(TagDecl * D)166 void HandleTagDeclDefinition(TagDecl *D) override {
167 if (Diags.hasErrorOccurred())
168 return;
169
170 Builder->UpdateCompletedType(D);
171
172 // For MSVC compatibility, treat declarations of static data members with
173 // inline initializers as definitions.
174 if (Ctx->getLangOpts().MSVCCompat) {
175 for (Decl *Member : D->decls()) {
176 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
177 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
178 Ctx->DeclMustBeEmitted(VD)) {
179 Builder->EmitGlobal(VD);
180 }
181 }
182 }
183 }
184 }
185
HandleTagDeclRequiredDefinition(const TagDecl * D)186 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
187 if (Diags.hasErrorOccurred())
188 return;
189
190 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
191 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
192 DI->completeRequiredType(RD);
193 }
194
HandleTranslationUnit(ASTContext & Ctx)195 void HandleTranslationUnit(ASTContext &Ctx) override {
196 if (Diags.hasErrorOccurred()) {
197 if (Builder)
198 Builder->clear();
199 M.reset();
200 return;
201 }
202
203 if (Builder)
204 Builder->Release();
205 }
206
CompleteTentativeDefinition(VarDecl * D)207 void CompleteTentativeDefinition(VarDecl *D) override {
208 if (Diags.hasErrorOccurred())
209 return;
210
211 Builder->EmitTentativeDefinition(D);
212 }
213
HandleVTable(CXXRecordDecl * RD,bool DefinitionRequired)214 void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
215 if (Diags.hasErrorOccurred())
216 return;
217
218 Builder->EmitVTable(RD, DefinitionRequired);
219 }
220
HandleLinkerOptionPragma(llvm::StringRef Opts)221 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
222 Builder->AppendLinkerOptions(Opts);
223 }
224
HandleDetectMismatch(llvm::StringRef Name,llvm::StringRef Value)225 void HandleDetectMismatch(llvm::StringRef Name,
226 llvm::StringRef Value) override {
227 Builder->AddDetectMismatch(Name, Value);
228 }
229
HandleDependentLibrary(llvm::StringRef Lib)230 void HandleDependentLibrary(llvm::StringRef Lib) override {
231 Builder->AddDependentLib(Lib);
232 }
233 };
234 }
235
anchor()236 void CodeGenerator::anchor() { }
237
CreateLLVMCodeGen(DiagnosticsEngine & Diags,const std::string & ModuleName,const CodeGenOptions & CGO,const TargetOptions &,llvm::LLVMContext & C,CoverageSourceInfo * CoverageInfo)238 CodeGenerator *clang::CreateLLVMCodeGen(DiagnosticsEngine &Diags,
239 const std::string& ModuleName,
240 const CodeGenOptions &CGO,
241 const TargetOptions &/*TO*/,
242 llvm::LLVMContext& C,
243 CoverageSourceInfo *CoverageInfo) {
244 return new CodeGeneratorImpl(Diags, ModuleName, CGO, C, CoverageInfo);
245 }
246