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