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