clang  8.0.0svn
ModuleBuilder.cpp
Go to the documentation of this file.
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 
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"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/TargetInfo.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 
29 using namespace clang;
30 using namespace CodeGen;
31 
32 namespace {
33  class CodeGeneratorImpl : public CodeGenerator {
34  DiagnosticsEngine &Diags;
35  ASTContext *Ctx;
36  const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
37  const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
38  const CodeGenOptions CodeGenOpts; // Intentionally copied in.
39 
40  unsigned HandlingTopLevelDecls;
41 
42  /// Use this when emitting decls to block re-entrant decl emission. It will
43  /// emit all deferred decls on scope exit. Set EmitDeferred to false if decl
44  /// emission must be deferred longer, like at the end of a tag definition.
45  struct HandlingTopLevelDeclRAII {
46  CodeGeneratorImpl &Self;
47  bool EmitDeferred;
48  HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
49  bool EmitDeferred = true)
50  : Self(Self), EmitDeferred(EmitDeferred) {
51  ++Self.HandlingTopLevelDecls;
52  }
53  ~HandlingTopLevelDeclRAII() {
54  unsigned Level = --Self.HandlingTopLevelDecls;
55  if (Level == 0 && EmitDeferred)
56  Self.EmitDeferredDecls();
57  }
58  };
59 
60  CoverageSourceInfo *CoverageInfo;
61 
62  protected:
63  std::unique_ptr<llvm::Module> M;
64  std::unique_ptr<CodeGen::CodeGenModule> Builder;
65 
66  private:
67  SmallVector<FunctionDecl *, 8> DeferredInlineMemberFuncDefs;
68 
69  public:
70  CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
71  const HeaderSearchOptions &HSO,
72  const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
73  llvm::LLVMContext &C,
74  CoverageSourceInfo *CoverageInfo = nullptr)
75  : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
76  PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
77  CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) {
78  C.setDiscardValueNames(CGO.DiscardValueNames);
79  }
80 
81  ~CodeGeneratorImpl() override {
82  // There should normally not be any leftover inline method definitions.
83  assert(DeferredInlineMemberFuncDefs.empty() ||
84  Diags.hasErrorOccurred());
85  }
86 
87  CodeGenModule &CGM() {
88  return *Builder;
89  }
90 
91  llvm::Module *GetModule() {
92  return M.get();
93  }
94 
95  CGDebugInfo *getCGDebugInfo() {
96  return Builder->getModuleDebugInfo();
97  }
98 
99  llvm::Module *ReleaseModule() {
100  return M.release();
101  }
102 
103  const Decl *GetDeclForMangledName(StringRef MangledName) {
104  GlobalDecl Result;
105  if (!Builder->lookupRepresentativeDecl(MangledName, Result))
106  return nullptr;
107  const Decl *D = Result.getCanonicalDecl().getDecl();
108  if (auto FD = dyn_cast<FunctionDecl>(D)) {
109  if (FD->hasBody(FD))
110  return FD;
111  } else if (auto TD = dyn_cast<TagDecl>(D)) {
112  if (auto Def = TD->getDefinition())
113  return Def;
114  }
115  return D;
116  }
117 
118  llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
119  return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
120  }
121 
122  llvm::Module *StartModule(llvm::StringRef ModuleName,
123  llvm::LLVMContext &C) {
124  assert(!M && "Replacing existing Module?");
125  M.reset(new llvm::Module(ModuleName, C));
126  Initialize(*Ctx);
127  return M.get();
128  }
129 
130  void Initialize(ASTContext &Context) override {
131  Ctx = &Context;
132 
133  M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
134  M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
135  const auto &SDKVersion = Ctx->getTargetInfo().getSDKVersion();
136  if (!SDKVersion.empty())
137  M->setSDKVersion(SDKVersion);
138  Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
139  PreprocessorOpts, CodeGenOpts,
140  *M, Diags, CoverageInfo));
141 
142  for (auto &&Lib : CodeGenOpts.DependentLibraries)
143  Builder->AddDependentLib(Lib);
144  for (auto &&Opt : CodeGenOpts.LinkerOptions)
145  Builder->AppendLinkerOptions(Opt);
146  }
147 
148  void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
149  if (Diags.hasErrorOccurred())
150  return;
151 
152  Builder->HandleCXXStaticMemberVarInstantiation(VD);
153  }
154 
155  bool HandleTopLevelDecl(DeclGroupRef DG) override {
156  if (Diags.hasErrorOccurred())
157  return true;
158 
159  HandlingTopLevelDeclRAII HandlingDecl(*this);
160 
161  // Make sure to emit all elements of a Decl.
162  for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
163  Builder->EmitTopLevelDecl(*I);
164 
165  return true;
166  }
167 
168  void EmitDeferredDecls() {
169  if (DeferredInlineMemberFuncDefs.empty())
170  return;
171 
172  // Emit any deferred inline method definitions. Note that more deferred
173  // methods may be added during this loop, since ASTConsumer callbacks
174  // can be invoked if AST inspection results in declarations being added.
175  HandlingTopLevelDeclRAII HandlingDecl(*this);
176  for (unsigned I = 0; I != DeferredInlineMemberFuncDefs.size(); ++I)
177  Builder->EmitTopLevelDecl(DeferredInlineMemberFuncDefs[I]);
178  DeferredInlineMemberFuncDefs.clear();
179  }
180 
181  void HandleInlineFunctionDefinition(FunctionDecl *D) override {
182  if (Diags.hasErrorOccurred())
183  return;
184 
185  assert(D->doesThisDeclarationHaveABody());
186 
187  // We may want to emit this definition. However, that decision might be
188  // based on computing the linkage, and we have to defer that in case we
189  // are inside of something that will change the method's final linkage,
190  // e.g.
191  // typedef struct {
192  // void bar();
193  // void foo() { bar(); }
194  // } A;
195  DeferredInlineMemberFuncDefs.push_back(D);
196 
197  // Provide some coverage mapping even for methods that aren't emitted.
198  // Don't do this for templated classes though, as they may not be
199  // instantiable.
201  Builder->AddDeferredUnusedCoverageMapping(D);
202  }
203 
204  /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
205  /// to (e.g. struct, union, enum, class) is completed. This allows the
206  /// client hack on the type, which can occur at any point in the file
207  /// (because these can be defined in declspecs).
208  void HandleTagDeclDefinition(TagDecl *D) override {
209  if (Diags.hasErrorOccurred())
210  return;
211 
212  // Don't allow re-entrant calls to CodeGen triggered by PCH
213  // deserialization to emit deferred decls.
214  HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
215 
216  Builder->UpdateCompletedType(D);
217 
218  // For MSVC compatibility, treat declarations of static data members with
219  // inline initializers as definitions.
220  if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
221  for (Decl *Member : D->decls()) {
222  if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
224  Ctx->DeclMustBeEmitted(VD)) {
225  Builder->EmitGlobal(VD);
226  }
227  }
228  }
229  }
230  // For OpenMP emit declare reduction functions, if required.
231  if (Ctx->getLangOpts().OpenMP) {
232  for (Decl *Member : D->decls()) {
233  if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
234  if (Ctx->DeclMustBeEmitted(DRD))
235  Builder->EmitGlobal(DRD);
236  }
237  }
238  }
239  }
240 
241  void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
242  if (Diags.hasErrorOccurred())
243  return;
244 
245  // Don't allow re-entrant calls to CodeGen triggered by PCH
246  // deserialization to emit deferred decls.
247  HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
248 
249  if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
250  if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
251  DI->completeRequiredType(RD);
252  }
253 
254  void HandleTranslationUnit(ASTContext &Ctx) override {
255  // Release the Builder when there is no error.
256  if (!Diags.hasErrorOccurred() && Builder)
257  Builder->Release();
258 
259  // If there are errors before or when releasing the Builder, reset
260  // the module to stop here before invoking the backend.
261  if (Diags.hasErrorOccurred()) {
262  if (Builder)
263  Builder->clear();
264  M.reset();
265  return;
266  }
267  }
268 
269  void AssignInheritanceModel(CXXRecordDecl *RD) override {
270  if (Diags.hasErrorOccurred())
271  return;
272 
273  Builder->RefreshTypeCacheForClass(RD);
274  }
275 
276  void CompleteTentativeDefinition(VarDecl *D) override {
277  if (Diags.hasErrorOccurred())
278  return;
279 
280  Builder->EmitTentativeDefinition(D);
281  }
282 
283  void HandleVTable(CXXRecordDecl *RD) override {
284  if (Diags.hasErrorOccurred())
285  return;
286 
287  Builder->EmitVTable(RD);
288  }
289  };
290 }
291 
292 void CodeGenerator::anchor() { }
293 
295  return static_cast<CodeGeneratorImpl*>(this)->CGM();
296 }
297 
298 llvm::Module *CodeGenerator::GetModule() {
299  return static_cast<CodeGeneratorImpl*>(this)->GetModule();
300 }
301 
303  return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
304 }
305 
307  return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
308 }
309 
310 const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
311  return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
312 }
313 
315  bool isForDefinition) {
316  return static_cast<CodeGeneratorImpl*>(this)
317  ->GetAddrOfGlobal(global, isForDefinition);
318 }
319 
320 llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
321  llvm::LLVMContext &C) {
322  return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
323 }
324 
326  DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
327  const HeaderSearchOptions &HeaderSearchOpts,
328  const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
329  llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
330  return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
331  PreprocessorOpts, CGO, C, CoverageInfo);
332 }
Defines the clang::ASTContext interface.
llvm::Constant * GetAddrOfGlobal(GlobalDecl decl, bool isForDefinition)
Return the LLVM address of the given global entity.
Represents a function declaration or definition.
Definition: Decl.h:1739
bool hasErrorOccurred() const
Definition: Diagnostic.h:744
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:30
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:949
iterator end()
Definition: DeclGroup.h:106
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
GlobalDecl getCanonicalDecl() const
Definition: GlobalDecl.h:60
Stores additional source code information like skipped ranges which is required by the coverage mappi...
llvm::Module * StartModule(llvm::StringRef ModuleName, llvm::LLVMContext &C)
Create a new llvm::Module after calling HandleTranslationUnit.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:689
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
llvm::Module * ReleaseModule()
Release ownership of the module to the caller.
Represents a variable declaration or definition.
Definition: Decl.h:812
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:1997
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:54
Represents a struct/union/class.
Definition: Decl.h:3602
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1018
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
Describes a module or submodule.
Definition: Module.h:65
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
iterator begin()
Definition: DeclGroup.h:100
Defines the Diagnostic-related interfaces.
CodeGenerator * CreateLLVMCodeGen(DiagnosticsEngine &Diags, llvm::StringRef ModuleName, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:821
The primary public interface to the Clang code generator.
Definition: ModuleBuilder.h:44
std::vector< std::string > DependentLibraries
A list of dependent libraries.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1078
llvm::Module * GetModule()
Return the module that this code generator is building into.
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:35
CodeGen::CodeGenModule & CGM()
Return an opaque reference to the CodeGenModule object, which can be used in various secondary APIs...
const llvm::VersionTuple & getSDKVersion() const
Definition: TargetInfo.h:1326
const Decl * GetDeclForMangledName(llvm::StringRef MangledName)
Given a mangled name, return a declaration which mangles that way which has been added to this code g...
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3073
const Decl * getDecl() const
Definition: GlobalDecl.h:69
const llvm::DataLayout & getDataLayout() const
Definition: TargetInfo.h:953
This class organizes the cross-function state that is used while generating LLVM code.
Dataflow Directional Tag Classes.
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
std::vector< std::string > LinkerOptions
A list of linker options to embed in the object file.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
Defines the clang::TargetInfo interface.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:1990
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
CodeGen::CGDebugInfo * getCGDebugInfo()
Return debug info code generator.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen&#39;ed or deserialized from PCH lazily, only when used; this is onl...
const LangOptions & getLangOpts() const
Definition: ASTContext.h:706