clang  15.0.0git
ModuleBuilder.cpp
Go to the documentation of this file.
1 //===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This builds an AST and converts it to LLVM Code.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "CGDebugInfo.h"
15 #include "CodeGenModule.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include <memory>
27 
28 using namespace clang;
29 using namespace CodeGen;
30 
31 namespace {
32  class CodeGeneratorImpl : public CodeGenerator {
33  DiagnosticsEngine &Diags;
34  ASTContext *Ctx;
35  const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
36  const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
37  const CodeGenOptions CodeGenOpts; // Intentionally copied in.
38 
39  unsigned HandlingTopLevelDecls;
40 
41  /// Use this when emitting decls to block re-entrant decl emission. It will
42  /// emit all deferred decls on scope exit. Set EmitDeferred to false if decl
43  /// emission must be deferred longer, like at the end of a tag definition.
44  struct HandlingTopLevelDeclRAII {
45  CodeGeneratorImpl &Self;
46  bool EmitDeferred;
47  HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
48  bool EmitDeferred = true)
49  : Self(Self), EmitDeferred(EmitDeferred) {
50  ++Self.HandlingTopLevelDecls;
51  }
52  ~HandlingTopLevelDeclRAII() {
53  unsigned Level = --Self.HandlingTopLevelDecls;
54  if (Level == 0 && EmitDeferred)
55  Self.EmitDeferredDecls();
56  }
57  };
58 
59  CoverageSourceInfo *CoverageInfo;
60 
61  protected:
62  std::unique_ptr<llvm::Module> M;
63  std::unique_ptr<CodeGen::CodeGenModule> Builder;
64 
65  private:
66  SmallVector<FunctionDecl *, 8> DeferredInlineMemberFuncDefs;
67 
68  static llvm::StringRef ExpandModuleName(llvm::StringRef ModuleName,
69  const CodeGenOptions &CGO) {
70  if (ModuleName == "-" && !CGO.MainFileName.empty())
71  return CGO.MainFileName;
72  return ModuleName;
73  }
74 
75  public:
76  CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
77  const HeaderSearchOptions &HSO,
78  const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
79  llvm::LLVMContext &C,
80  CoverageSourceInfo *CoverageInfo = nullptr)
81  : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
82  PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
83  CoverageInfo(CoverageInfo),
84  M(new llvm::Module(ExpandModuleName(ModuleName, CGO), C)) {
85  C.setDiscardValueNames(CGO.DiscardValueNames);
86  }
87 
88  ~CodeGeneratorImpl() override {
89  // There should normally not be any leftover inline method definitions.
90  assert(DeferredInlineMemberFuncDefs.empty() ||
91  Diags.hasErrorOccurred());
92  }
93 
94  CodeGenModule &CGM() {
95  return *Builder;
96  }
97 
98  llvm::Module *GetModule() {
99  return M.get();
100  }
101 
102  CGDebugInfo *getCGDebugInfo() {
103  return Builder->getModuleDebugInfo();
104  }
105 
106  llvm::Module *ReleaseModule() {
107  return M.release();
108  }
109 
110  const Decl *GetDeclForMangledName(StringRef MangledName) {
111  GlobalDecl Result;
112  if (!Builder->lookupRepresentativeDecl(MangledName, Result))
113  return nullptr;
114  const Decl *D = Result.getCanonicalDecl().getDecl();
115  if (auto FD = dyn_cast<FunctionDecl>(D)) {
116  if (FD->hasBody(FD))
117  return FD;
118  } else if (auto TD = dyn_cast<TagDecl>(D)) {
119  if (auto Def = TD->getDefinition())
120  return Def;
121  }
122  return D;
123  }
124 
125  llvm::StringRef GetMangledName(GlobalDecl GD) {
126  return Builder->getMangledName(GD);
127  }
128 
129  llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
130  return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
131  }
132 
133  llvm::Module *StartModule(llvm::StringRef ModuleName,
134  llvm::LLVMContext &C) {
135  assert(!M && "Replacing existing Module?");
136  M.reset(new llvm::Module(ExpandModuleName(ModuleName, CodeGenOpts), C));
137 
138  std::unique_ptr<CodeGenModule> OldBuilder = std::move(Builder);
139 
140  Initialize(*Ctx);
141 
142  if (OldBuilder)
143  OldBuilder->moveLazyEmissionStates(Builder.get());
144 
145  return M.get();
146  }
147 
148  void Initialize(ASTContext &Context) override {
149  Ctx = &Context;
150 
151  M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
152  M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
153  const auto &SDKVersion = Ctx->getTargetInfo().getSDKVersion();
154  if (!SDKVersion.empty())
155  M->setSDKVersion(SDKVersion);
156  if (const auto *TVT = Ctx->getTargetInfo().getDarwinTargetVariantTriple())
157  M->setDarwinTargetVariantTriple(TVT->getTriple());
158  if (auto TVSDKVersion =
160  M->setDarwinTargetVariantSDKVersion(*TVSDKVersion);
161  Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
162  PreprocessorOpts, CodeGenOpts,
163  *M, Diags, CoverageInfo));
164 
165  for (auto &&Lib : CodeGenOpts.DependentLibraries)
166  Builder->AddDependentLib(Lib);
167  for (auto &&Opt : CodeGenOpts.LinkerOptions)
168  Builder->AppendLinkerOptions(Opt);
169  }
170 
171  void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
172  if (Diags.hasErrorOccurred())
173  return;
174 
175  Builder->HandleCXXStaticMemberVarInstantiation(VD);
176  }
177 
178  bool HandleTopLevelDecl(DeclGroupRef DG) override {
179  if (Diags.hasErrorOccurred())
180  return true;
181 
182  HandlingTopLevelDeclRAII HandlingDecl(*this);
183 
184  // Make sure to emit all elements of a Decl.
185  for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
186  Builder->EmitTopLevelDecl(*I);
187 
188  return true;
189  }
190 
191  void EmitDeferredDecls() {
192  if (DeferredInlineMemberFuncDefs.empty())
193  return;
194 
195  // Emit any deferred inline method definitions. Note that more deferred
196  // methods may be added during this loop, since ASTConsumer callbacks
197  // can be invoked if AST inspection results in declarations being added.
198  HandlingTopLevelDeclRAII HandlingDecl(*this);
199  for (unsigned I = 0; I != DeferredInlineMemberFuncDefs.size(); ++I)
200  Builder->EmitTopLevelDecl(DeferredInlineMemberFuncDefs[I]);
201  DeferredInlineMemberFuncDefs.clear();
202  }
203 
204  void HandleInlineFunctionDefinition(FunctionDecl *D) override {
205  if (Diags.hasErrorOccurred())
206  return;
207 
208  assert(D->doesThisDeclarationHaveABody());
209 
210  // We may want to emit this definition. However, that decision might be
211  // based on computing the linkage, and we have to defer that in case we
212  // are inside of something that will change the method's final linkage,
213  // e.g.
214  // typedef struct {
215  // void bar();
216  // void foo() { bar(); }
217  // } A;
218  DeferredInlineMemberFuncDefs.push_back(D);
219 
220  // Provide some coverage mapping even for methods that aren't emitted.
221  // Don't do this for templated classes though, as they may not be
222  // instantiable.
224  Builder->AddDeferredUnusedCoverageMapping(D);
225  }
226 
227  /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
228  /// to (e.g. struct, union, enum, class) is completed. This allows the
229  /// client hack on the type, which can occur at any point in the file
230  /// (because these can be defined in declspecs).
231  void HandleTagDeclDefinition(TagDecl *D) override {
232  if (Diags.hasErrorOccurred())
233  return;
234 
235  // Don't allow re-entrant calls to CodeGen triggered by PCH
236  // deserialization to emit deferred decls.
237  HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
238 
239  Builder->UpdateCompletedType(D);
240 
241  // For MSVC compatibility, treat declarations of static data members with
242  // inline initializers as definitions.
243  if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
244  for (Decl *Member : D->decls()) {
245  if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
247  Ctx->DeclMustBeEmitted(VD)) {
248  Builder->EmitGlobal(VD);
249  }
250  }
251  }
252  }
253  // For OpenMP emit declare reduction functions, if required.
254  if (Ctx->getLangOpts().OpenMP) {
255  for (Decl *Member : D->decls()) {
256  if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
257  if (Ctx->DeclMustBeEmitted(DRD))
258  Builder->EmitGlobal(DRD);
259  } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Member)) {
260  if (Ctx->DeclMustBeEmitted(DMD))
261  Builder->EmitGlobal(DMD);
262  }
263  }
264  }
265  }
266 
267  void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
268  if (Diags.hasErrorOccurred())
269  return;
270 
271  // Don't allow re-entrant calls to CodeGen triggered by PCH
272  // deserialization to emit deferred decls.
273  HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
274 
275  if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
276  if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
277  DI->completeRequiredType(RD);
278  }
279 
280  void HandleTranslationUnit(ASTContext &Ctx) override {
281  // Release the Builder when there is no error.
282  if (!Diags.hasErrorOccurred() && Builder)
283  Builder->Release();
284 
285  // If there are errors before or when releasing the Builder, reset
286  // the module to stop here before invoking the backend.
287  if (Diags.hasErrorOccurred()) {
288  if (Builder)
289  Builder->clear();
290  M.reset();
291  return;
292  }
293  }
294 
295  void AssignInheritanceModel(CXXRecordDecl *RD) override {
296  if (Diags.hasErrorOccurred())
297  return;
298 
299  Builder->RefreshTypeCacheForClass(RD);
300  }
301 
302  void CompleteTentativeDefinition(VarDecl *D) override {
303  if (Diags.hasErrorOccurred())
304  return;
305 
306  Builder->EmitTentativeDefinition(D);
307  }
308 
309  void CompleteExternalDeclaration(VarDecl *D) override {
310  Builder->EmitExternalDeclaration(D);
311  }
312 
313  void HandleVTable(CXXRecordDecl *RD) override {
314  if (Diags.hasErrorOccurred())
315  return;
316 
317  Builder->EmitVTable(RD);
318  }
319  };
320 }
321 
322 void CodeGenerator::anchor() { }
323 
325  return static_cast<CodeGeneratorImpl*>(this)->CGM();
326 }
327 
328 llvm::Module *CodeGenerator::GetModule() {
329  return static_cast<CodeGeneratorImpl*>(this)->GetModule();
330 }
331 
333  return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
334 }
335 
337  return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
338 }
339 
341  return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
342 }
343 
345  return static_cast<CodeGeneratorImpl *>(this)->GetMangledName(GD);
346 }
347 
349  bool isForDefinition) {
350  return static_cast<CodeGeneratorImpl*>(this)
351  ->GetAddrOfGlobal(global, isForDefinition);
352 }
353 
354 llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
355  llvm::LLVMContext &C) {
356  return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
357 }
358 
360  DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
361  const HeaderSearchOptions &HeaderSearchOpts,
362  const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
363  llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
364  return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
365  PreprocessorOpts, CGO, C, CoverageInfo);
366 }
clang::TargetInfo::getDataLayoutString
const char * getDataLayoutString() const
Definition: TargetInfo.h:1179
clang::CodeGenerator::CGM
CodeGen::CodeGenModule & CGM()
Return an opaque reference to the CodeGenModule object, which can be used in various secondary APIs.
Definition: ModuleBuilder.cpp:324
clang::FunctionDecl::doesThisDeclarationHaveABody
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2179
clang::CodeGenerator
The primary public interface to the Clang code generator.
Definition: ModuleBuilder.h:43
llvm
YAML serialization mapping.
Definition: Dominators.h:30
clang::CodeGenerator::GetAddrOfGlobal
llvm::Constant * GetAddrOfGlobal(GlobalDecl decl, bool isForDefinition)
Return the LLVM address of the given global entity.
Definition: ModuleBuilder.cpp:348
clang::DeclContext::decls
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2137
clang::PreprocessorOptions
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Definition: PreprocessorOptions.h:65
clang::CodeGenerator::getCGDebugInfo
CodeGen::CGDebugInfo * getCGDebugInfo()
Return debug info code generator.
Definition: ModuleBuilder.cpp:336
clang::CodeGen::ForDefinition_t
ForDefinition_t
Definition: CodeGenModule.h:92
clang::CreateLLVMCodeGen
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.
Definition: ModuleBuilder.cpp:359
llvm::SmallVector
Definition: LLVM.h:38
clang::TargetCXXABI::isMicrosoft
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:138
TargetInfo.h
AttributeLangSupport::C
@ C
Definition: SemaDeclAttr.cpp:55
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
clang::TargetInfo::getCXXABI
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1245
clang::TargetInfo::getSDKVersion
const llvm::VersionTuple & getSDKVersion() const
Definition: TargetInfo.h:1619
ModuleBuilder.h
clang::DeclGroupRef::begin
iterator begin()
Definition: DeclGroup.h:99
clang::DeclGroupRef::end
iterator end()
Definition: DeclGroup.h:105
clang::CodeGenerator::GetDeclForMangledName
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...
Definition: ModuleBuilder.cpp:340
clang::CoverageSourceInfo
Stores additional source code information like skipped ranges which is required by the coverage mappi...
Definition: CoverageMappingGen.h:62
CGDebugInfo.h
DeclObjC.h
clang::GlobalDecl
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
clang::CodeGenerator::GetMangledName
llvm::StringRef GetMangledName(GlobalDecl GD)
Given a global declaration, return a mangled name for this declaration which has been added to this c...
Definition: ModuleBuilder.cpp:344
CodeGenOptions.h
clang::Decl::getLexicalDeclContext
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:852
clang::Module
Describes a module or submodule.
Definition: Module.h:96
clang::DiagnosticsEngine::hasErrorOccurred
bool hasErrorOccurred() const
Definition: Diagnostic.h:838
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:208
clang::CodeGenerator::StartModule
llvm::Module * StartModule(llvm::StringRef ModuleName, llvm::LLVMContext &C)
Create a new llvm::Module after calling HandleTranslationUnit.
Definition: ModuleBuilder.cpp:354
Diagnostic.h
clang::Decl::getCanonicalDecl
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:910
clang::CodeGen::CGDebugInfo
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:55
Expr.h
ASTContext.h
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:874
clang::TagDecl
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3355
CodeGenModule.h
clang::CodeGenOptions::DependentLibraries
std::vector< std::string > DependentLibraries
A list of dependent libraries.
Definition: CodeGenOptions.h:241
clang::CodeGenOptions
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
Definition: CodeGenOptions.h:49
clang::TargetInfo::getDarwinTargetVariantTriple
const llvm::Triple * getDarwinTargetVariantTriple() const
Returns the darwin target variant triple, the variant of the deployment target for which the code is ...
Definition: TargetInfo.h:1640
clang::TargetInfo::getTriple
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1172
clang::CXXRecordDecl
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
clang::CodeGenerator::GetModule
llvm::Module * GetModule()
Return the module that this code generator is building into.
Definition: ModuleBuilder.cpp:328
clang::CodeGen::CodeGenModule
This class organizes the cross-function state that is used while generating LLVM code.
Definition: CodeGenModule.h:275
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
clang::DeclGroupRef
Definition: DeclGroup.h:51
clang::TargetInfo::getDarwinTargetVariantSDKVersion
const Optional< VersionTuple > getDarwinTargetVariantSDKVersion() const
Returns the version of the darwin target variant SDK which was used during the compilation if one was...
Definition: TargetInfo.h:1647
clang::ASTContext::getTargetInfo
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:768
clang
Definition: CalledOnceCheck.h:17
clang::prec::Level
Level
Definition: OperatorPrecedence.h:26
clang::DeclContext::isDependentContext
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1152
clang::CodeGenerator::ReleaseModule
llvm::Module * ReleaseModule()
Release ownership of the module to the caller.
Definition: ModuleBuilder.cpp:332
clang::ASTContext::isMSStaticDataMemberInlineDefinition
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
Definition: ASTContext.cpp:7441
clang::CodeGenOptions::LinkerOptions
std::vector< std::string > LinkerOptions
A list of linker options to embed in the object file.
Definition: CodeGenOptions.h:244
clang::transformer::name
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
Definition: RangeSelector.cpp:200
clang::ASTContext::DeclMustBeEmitted
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
Definition: ASTContext.cpp:11486
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1872
clang::RecordDecl
Represents a struct/union/class.
Definition: Decl.h:3908
clang::ASTContext::getLangOpts
const LangOptions & getLangOpts() const
Definition: ASTContext.h:786
clang::CodeGenOptions::MainFileName
std::string MainFileName
The user provided name for the "main file", if non-empty.
Definition: CodeGenOptions.h:221
clang::HeaderSearchOptions
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
Definition: HeaderSearchOptions.h:68