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 13 #include "clang/CodeGen/ModuleBuilder.h" 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" 19 #include "clang/Basic/CodeGenOptions.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 public: 69 CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName, 70 const HeaderSearchOptions &HSO, 71 const PreprocessorOptions &PPO, const CodeGenOptions &CGO, 72 llvm::LLVMContext &C, 73 CoverageSourceInfo *CoverageInfo = nullptr) 74 : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO), 75 PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0), 76 CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) { 77 C.setDiscardValueNames(CGO.DiscardValueNames); 78 } 79 80 ~CodeGeneratorImpl() override { 81 // There should normally not be any leftover inline method definitions. 82 assert(DeferredInlineMemberFuncDefs.empty() || 83 Diags.hasErrorOccurred()); 84 } 85 86 CodeGenModule &CGM() { 87 return *Builder; 88 } 89 90 llvm::Module *GetModule() { 91 return M.get(); 92 } 93 94 CGDebugInfo *getCGDebugInfo() { 95 return Builder->getModuleDebugInfo(); 96 } 97 98 llvm::Module *ReleaseModule() { 99 return M.release(); 100 } 101 102 const Decl *GetDeclForMangledName(StringRef MangledName) { 103 GlobalDecl Result; 104 if (!Builder->lookupRepresentativeDecl(MangledName, Result)) 105 return nullptr; 106 const Decl *D = Result.getCanonicalDecl().getDecl(); 107 if (auto FD = dyn_cast<FunctionDecl>(D)) { 108 if (FD->hasBody(FD)) 109 return FD; 110 } else if (auto TD = dyn_cast<TagDecl>(D)) { 111 if (auto Def = TD->getDefinition()) 112 return Def; 113 } 114 return D; 115 } 116 117 llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) { 118 return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition)); 119 } 120 121 llvm::Module *StartModule(llvm::StringRef ModuleName, 122 llvm::LLVMContext &C) { 123 assert(!M && "Replacing existing Module?"); 124 M.reset(new llvm::Module(ModuleName, C)); 125 Initialize(*Ctx); 126 return M.get(); 127 } 128 129 void Initialize(ASTContext &Context) override { 130 Ctx = &Context; 131 132 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple()); 133 M->setDataLayout(Ctx->getTargetInfo().getDataLayout()); 134 const auto &SDKVersion = Ctx->getTargetInfo().getSDKVersion(); 135 if (!SDKVersion.empty()) 136 M->setSDKVersion(SDKVersion); 137 Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts, 138 PreprocessorOpts, CodeGenOpts, 139 *M, Diags, CoverageInfo)); 140 141 for (auto &&Lib : CodeGenOpts.DependentLibraries) 142 Builder->AddDependentLib(Lib); 143 for (auto &&Opt : CodeGenOpts.LinkerOptions) 144 Builder->AppendLinkerOptions(Opt); 145 } 146 147 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override { 148 if (Diags.hasErrorOccurred()) 149 return; 150 151 Builder->HandleCXXStaticMemberVarInstantiation(VD); 152 } 153 154 bool HandleTopLevelDecl(DeclGroupRef DG) override { 155 if (Diags.hasErrorOccurred()) 156 return true; 157 158 HandlingTopLevelDeclRAII HandlingDecl(*this); 159 160 // Make sure to emit all elements of a Decl. 161 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 162 Builder->EmitTopLevelDecl(*I); 163 164 return true; 165 } 166 167 void EmitDeferredDecls() { 168 if (DeferredInlineMemberFuncDefs.empty()) 169 return; 170 171 // Emit any deferred inline method definitions. Note that more deferred 172 // methods may be added during this loop, since ASTConsumer callbacks 173 // can be invoked if AST inspection results in declarations being added. 174 HandlingTopLevelDeclRAII HandlingDecl(*this); 175 for (unsigned I = 0; I != DeferredInlineMemberFuncDefs.size(); ++I) 176 Builder->EmitTopLevelDecl(DeferredInlineMemberFuncDefs[I]); 177 DeferredInlineMemberFuncDefs.clear(); 178 } 179 180 void HandleInlineFunctionDefinition(FunctionDecl *D) override { 181 if (Diags.hasErrorOccurred()) 182 return; 183 184 assert(D->doesThisDeclarationHaveABody()); 185 186 // We may want to emit this definition. However, that decision might be 187 // based on computing the linkage, and we have to defer that in case we 188 // are inside of something that will change the method's final linkage, 189 // e.g. 190 // typedef struct { 191 // void bar(); 192 // void foo() { bar(); } 193 // } A; 194 DeferredInlineMemberFuncDefs.push_back(D); 195 196 // Provide some coverage mapping even for methods that aren't emitted. 197 // Don't do this for templated classes though, as they may not be 198 // instantiable. 199 if (!D->getLexicalDeclContext()->isDependentContext()) 200 Builder->AddDeferredUnusedCoverageMapping(D); 201 } 202 203 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl 204 /// to (e.g. struct, union, enum, class) is completed. This allows the 205 /// client hack on the type, which can occur at any point in the file 206 /// (because these can be defined in declspecs). 207 void HandleTagDeclDefinition(TagDecl *D) override { 208 if (Diags.hasErrorOccurred()) 209 return; 210 211 // Don't allow re-entrant calls to CodeGen triggered by PCH 212 // deserialization to emit deferred decls. 213 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false); 214 215 Builder->UpdateCompletedType(D); 216 217 // For MSVC compatibility, treat declarations of static data members with 218 // inline initializers as definitions. 219 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) { 220 for (Decl *Member : D->decls()) { 221 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) { 222 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) && 223 Ctx->DeclMustBeEmitted(VD)) { 224 Builder->EmitGlobal(VD); 225 } 226 } 227 } 228 } 229 // For OpenMP emit declare reduction functions, if required. 230 if (Ctx->getLangOpts().OpenMP) { 231 for (Decl *Member : D->decls()) { 232 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) { 233 if (Ctx->DeclMustBeEmitted(DRD)) 234 Builder->EmitGlobal(DRD); 235 } 236 } 237 } 238 } 239 240 void HandleTagDeclRequiredDefinition(const TagDecl *D) override { 241 if (Diags.hasErrorOccurred()) 242 return; 243 244 // Don't allow re-entrant calls to CodeGen triggered by PCH 245 // deserialization to emit deferred decls. 246 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false); 247 248 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo()) 249 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) 250 DI->completeRequiredType(RD); 251 } 252 253 void HandleTranslationUnit(ASTContext &Ctx) override { 254 // Release the Builder when there is no error. 255 if (!Diags.hasErrorOccurred() && Builder) 256 Builder->Release(); 257 258 // If there are errors before or when releasing the Builder, reset 259 // the module to stop here before invoking the backend. 260 if (Diags.hasErrorOccurred()) { 261 if (Builder) 262 Builder->clear(); 263 M.reset(); 264 return; 265 } 266 } 267 268 void AssignInheritanceModel(CXXRecordDecl *RD) override { 269 if (Diags.hasErrorOccurred()) 270 return; 271 272 Builder->RefreshTypeCacheForClass(RD); 273 } 274 275 void CompleteTentativeDefinition(VarDecl *D) override { 276 if (Diags.hasErrorOccurred()) 277 return; 278 279 Builder->EmitTentativeDefinition(D); 280 } 281 282 void HandleVTable(CXXRecordDecl *RD) override { 283 if (Diags.hasErrorOccurred()) 284 return; 285 286 Builder->EmitVTable(RD); 287 } 288 }; 289 } 290 291 void CodeGenerator::anchor() { } 292 293 CodeGenModule &CodeGenerator::CGM() { 294 return static_cast<CodeGeneratorImpl*>(this)->CGM(); 295 } 296 297 llvm::Module *CodeGenerator::GetModule() { 298 return static_cast<CodeGeneratorImpl*>(this)->GetModule(); 299 } 300 301 llvm::Module *CodeGenerator::ReleaseModule() { 302 return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule(); 303 } 304 305 CGDebugInfo *CodeGenerator::getCGDebugInfo() { 306 return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo(); 307 } 308 309 const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) { 310 return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name); 311 } 312 313 llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global, 314 bool isForDefinition) { 315 return static_cast<CodeGeneratorImpl*>(this) 316 ->GetAddrOfGlobal(global, isForDefinition); 317 } 318 319 llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName, 320 llvm::LLVMContext &C) { 321 return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C); 322 } 323 324 CodeGenerator *clang::CreateLLVMCodeGen( 325 DiagnosticsEngine &Diags, llvm::StringRef ModuleName, 326 const HeaderSearchOptions &HeaderSearchOpts, 327 const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, 328 llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) { 329 return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts, 330 PreprocessorOpts, CGO, C, CoverageInfo); 331 } 332