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 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 Initialize(*Ctx); 138 return M.get(); 139 } 140 141 void Initialize(ASTContext &Context) override { 142 Ctx = &Context; 143 144 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple()); 145 M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString()); 146 const auto &SDKVersion = Ctx->getTargetInfo().getSDKVersion(); 147 if (!SDKVersion.empty()) 148 M->setSDKVersion(SDKVersion); 149 Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts, 150 PreprocessorOpts, CodeGenOpts, 151 *M, Diags, CoverageInfo)); 152 153 for (auto &&Lib : CodeGenOpts.DependentLibraries) 154 Builder->AddDependentLib(Lib); 155 for (auto &&Opt : CodeGenOpts.LinkerOptions) 156 Builder->AppendLinkerOptions(Opt); 157 } 158 159 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override { 160 if (Diags.hasErrorOccurred()) 161 return; 162 163 Builder->HandleCXXStaticMemberVarInstantiation(VD); 164 } 165 166 bool HandleTopLevelDecl(DeclGroupRef DG) override { 167 if (Diags.hasErrorOccurred()) 168 return true; 169 170 HandlingTopLevelDeclRAII HandlingDecl(*this); 171 172 // Make sure to emit all elements of a Decl. 173 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 174 Builder->EmitTopLevelDecl(*I); 175 176 return true; 177 } 178 179 void EmitDeferredDecls() { 180 if (DeferredInlineMemberFuncDefs.empty()) 181 return; 182 183 // Emit any deferred inline method definitions. Note that more deferred 184 // methods may be added during this loop, since ASTConsumer callbacks 185 // can be invoked if AST inspection results in declarations being added. 186 HandlingTopLevelDeclRAII HandlingDecl(*this); 187 for (unsigned I = 0; I != DeferredInlineMemberFuncDefs.size(); ++I) 188 Builder->EmitTopLevelDecl(DeferredInlineMemberFuncDefs[I]); 189 DeferredInlineMemberFuncDefs.clear(); 190 } 191 192 void HandleInlineFunctionDefinition(FunctionDecl *D) override { 193 if (Diags.hasErrorOccurred()) 194 return; 195 196 assert(D->doesThisDeclarationHaveABody()); 197 198 // We may want to emit this definition. However, that decision might be 199 // based on computing the linkage, and we have to defer that in case we 200 // are inside of something that will change the method's final linkage, 201 // e.g. 202 // typedef struct { 203 // void bar(); 204 // void foo() { bar(); } 205 // } A; 206 DeferredInlineMemberFuncDefs.push_back(D); 207 208 // Provide some coverage mapping even for methods that aren't emitted. 209 // Don't do this for templated classes though, as they may not be 210 // instantiable. 211 if (!D->getLexicalDeclContext()->isDependentContext()) 212 Builder->AddDeferredUnusedCoverageMapping(D); 213 } 214 215 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl 216 /// to (e.g. struct, union, enum, class) is completed. This allows the 217 /// client hack on the type, which can occur at any point in the file 218 /// (because these can be defined in declspecs). 219 void HandleTagDeclDefinition(TagDecl *D) override { 220 if (Diags.hasErrorOccurred()) 221 return; 222 223 // Don't allow re-entrant calls to CodeGen triggered by PCH 224 // deserialization to emit deferred decls. 225 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false); 226 227 Builder->UpdateCompletedType(D); 228 229 // For MSVC compatibility, treat declarations of static data members with 230 // inline initializers as definitions. 231 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) { 232 for (Decl *Member : D->decls()) { 233 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) { 234 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) && 235 Ctx->DeclMustBeEmitted(VD)) { 236 Builder->EmitGlobal(VD); 237 } 238 } 239 } 240 } 241 // For OpenMP emit declare reduction functions, if required. 242 if (Ctx->getLangOpts().OpenMP) { 243 for (Decl *Member : D->decls()) { 244 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) { 245 if (Ctx->DeclMustBeEmitted(DRD)) 246 Builder->EmitGlobal(DRD); 247 } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Member)) { 248 if (Ctx->DeclMustBeEmitted(DMD)) 249 Builder->EmitGlobal(DMD); 250 } 251 } 252 } 253 } 254 255 void HandleTagDeclRequiredDefinition(const TagDecl *D) override { 256 if (Diags.hasErrorOccurred()) 257 return; 258 259 // Don't allow re-entrant calls to CodeGen triggered by PCH 260 // deserialization to emit deferred decls. 261 HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false); 262 263 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo()) 264 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) 265 DI->completeRequiredType(RD); 266 } 267 268 void HandleTranslationUnit(ASTContext &Ctx) override { 269 // Release the Builder when there is no error. 270 if (!Diags.hasErrorOccurred() && Builder) 271 Builder->Release(); 272 273 // If there are errors before or when releasing the Builder, reset 274 // the module to stop here before invoking the backend. 275 if (Diags.hasErrorOccurred()) { 276 if (Builder) 277 Builder->clear(); 278 M.reset(); 279 return; 280 } 281 } 282 283 void AssignInheritanceModel(CXXRecordDecl *RD) override { 284 if (Diags.hasErrorOccurred()) 285 return; 286 287 Builder->RefreshTypeCacheForClass(RD); 288 } 289 290 void CompleteTentativeDefinition(VarDecl *D) override { 291 if (Diags.hasErrorOccurred()) 292 return; 293 294 Builder->EmitTentativeDefinition(D); 295 } 296 297 void CompleteExternalDeclaration(VarDecl *D) override { 298 Builder->EmitExternalDeclaration(D); 299 } 300 301 void HandleVTable(CXXRecordDecl *RD) override { 302 if (Diags.hasErrorOccurred()) 303 return; 304 305 Builder->EmitVTable(RD); 306 } 307 }; 308 } 309 310 void CodeGenerator::anchor() { } 311 312 CodeGenModule &CodeGenerator::CGM() { 313 return static_cast<CodeGeneratorImpl*>(this)->CGM(); 314 } 315 316 llvm::Module *CodeGenerator::GetModule() { 317 return static_cast<CodeGeneratorImpl*>(this)->GetModule(); 318 } 319 320 llvm::Module *CodeGenerator::ReleaseModule() { 321 return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule(); 322 } 323 324 CGDebugInfo *CodeGenerator::getCGDebugInfo() { 325 return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo(); 326 } 327 328 const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) { 329 return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name); 330 } 331 332 llvm::StringRef CodeGenerator::GetMangledName(GlobalDecl GD) { 333 return static_cast<CodeGeneratorImpl *>(this)->GetMangledName(GD); 334 } 335 336 llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global, 337 bool isForDefinition) { 338 return static_cast<CodeGeneratorImpl*>(this) 339 ->GetAddrOfGlobal(global, isForDefinition); 340 } 341 342 llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName, 343 llvm::LLVMContext &C) { 344 return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C); 345 } 346 347 CodeGenerator *clang::CreateLLVMCodeGen( 348 DiagnosticsEngine &Diags, llvm::StringRef ModuleName, 349 const HeaderSearchOptions &HeaderSearchOpts, 350 const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, 351 llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) { 352 return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts, 353 PreprocessorOpts, CGO, C, CoverageInfo); 354 } 355