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