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 ASTContext *Ctx; 34 const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info. 35 const PreprocessorOptions &PreprocessorOpts; // Only used for debug info. 36 const CodeGenOptions CodeGenOpts; // Intentionally copied in. 37 38 unsigned HandlingTopLevelDecls; 39 struct HandlingTopLevelDeclRAII { 40 CodeGeneratorImpl &Self; 41 HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self) : Self(Self) { 42 ++Self.HandlingTopLevelDecls; 43 } 44 ~HandlingTopLevelDeclRAII() { 45 if (--Self.HandlingTopLevelDecls == 0) 46 Self.EmitDeferredDecls(); 47 } 48 }; 49 50 CoverageSourceInfo *CoverageInfo; 51 52 protected: 53 std::unique_ptr<llvm::Module> M; 54 std::unique_ptr<CodeGen::CodeGenModule> Builder; 55 56 private: 57 SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions; 58 59 public: 60 CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string &ModuleName, 61 const HeaderSearchOptions &HSO, 62 const PreprocessorOptions &PPO, const CodeGenOptions &CGO, 63 llvm::LLVMContext &C, 64 CoverageSourceInfo *CoverageInfo = nullptr) 65 : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO), 66 PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0), 67 CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) { 68 C.setDiscardValueNames(CGO.DiscardValueNames); 69 } 70 71 ~CodeGeneratorImpl() override { 72 // There should normally not be any leftover inline method definitions. 73 assert(DeferredInlineMethodDefinitions.empty() || 74 Diags.hasErrorOccurred()); 75 } 76 77 llvm::Module* GetModule() override { 78 return M.get(); 79 } 80 81 const Decl *GetDeclForMangledName(StringRef MangledName) override { 82 GlobalDecl Result; 83 if (!Builder->lookupRepresentativeDecl(MangledName, Result)) 84 return nullptr; 85 const Decl *D = Result.getCanonicalDecl().getDecl(); 86 if (auto FD = dyn_cast<FunctionDecl>(D)) { 87 if (FD->hasBody(FD)) 88 return FD; 89 } else if (auto TD = dyn_cast<TagDecl>(D)) { 90 if (auto Def = TD->getDefinition()) 91 return Def; 92 } 93 return D; 94 } 95 96 llvm::Module *ReleaseModule() override { return M.release(); } 97 98 void Initialize(ASTContext &Context) override { 99 Ctx = &Context; 100 101 M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple()); 102 M->setDataLayout(Ctx->getTargetInfo().getDataLayout()); 103 Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts, 104 PreprocessorOpts, CodeGenOpts, 105 *M, Diags, CoverageInfo)); 106 107 for (auto &&Lib : CodeGenOpts.DependentLibraries) 108 Builder->AddDependentLib(Lib); 109 for (auto &&Opt : CodeGenOpts.LinkerOptions) 110 Builder->AppendLinkerOptions(Opt); 111 } 112 113 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override { 114 if (Diags.hasErrorOccurred()) 115 return; 116 117 Builder->HandleCXXStaticMemberVarInstantiation(VD); 118 } 119 120 bool HandleTopLevelDecl(DeclGroupRef DG) override { 121 if (Diags.hasErrorOccurred()) 122 return true; 123 124 HandlingTopLevelDeclRAII HandlingDecl(*this); 125 126 // Make sure to emit all elements of a Decl. 127 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 128 Builder->EmitTopLevelDecl(*I); 129 130 return true; 131 } 132 133 void EmitDeferredDecls() { 134 if (DeferredInlineMethodDefinitions.empty()) 135 return; 136 137 // Emit any deferred inline method definitions. Note that more deferred 138 // methods may be added during this loop, since ASTConsumer callbacks 139 // can be invoked if AST inspection results in declarations being added. 140 HandlingTopLevelDeclRAII HandlingDecl(*this); 141 for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I) 142 Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]); 143 DeferredInlineMethodDefinitions.clear(); 144 } 145 146 void HandleInlineFunctionDefinition(FunctionDecl *D) override { 147 if (Diags.hasErrorOccurred()) 148 return; 149 150 assert(D->doesThisDeclarationHaveABody()); 151 152 // Handle friend functions. 153 if (D->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)) { 154 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft() 155 && !D->getLexicalDeclContext()->isDependentContext()) 156 Builder->EmitTopLevelDecl(D); 157 return; 158 } 159 160 // Otherwise, must be a method. 161 auto MD = cast<CXXMethodDecl>(D); 162 163 // We may want to emit this definition. However, that decision might be 164 // based on computing the linkage, and we have to defer that in case we 165 // are inside of something that will change the method's final linkage, 166 // e.g. 167 // typedef struct { 168 // void bar(); 169 // void foo() { bar(); } 170 // } A; 171 DeferredInlineMethodDefinitions.push_back(MD); 172 173 // Provide some coverage mapping even for methods that aren't emitted. 174 // Don't do this for templated classes though, as they may not be 175 // instantiable. 176 if (!MD->getParent()->getDescribedClassTemplate()) 177 Builder->AddDeferredUnusedCoverageMapping(MD); 178 } 179 180 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl 181 /// to (e.g. struct, union, enum, class) is completed. This allows the 182 /// client hack on the type, which can occur at any point in the file 183 /// (because these can be defined in declspecs). 184 void HandleTagDeclDefinition(TagDecl *D) override { 185 if (Diags.hasErrorOccurred()) 186 return; 187 188 Builder->UpdateCompletedType(D); 189 190 // For MSVC compatibility, treat declarations of static data members with 191 // inline initializers as definitions. 192 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) { 193 for (Decl *Member : D->decls()) { 194 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) { 195 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) && 196 Ctx->DeclMustBeEmitted(VD)) { 197 Builder->EmitGlobal(VD); 198 } 199 } 200 } 201 } 202 // For OpenMP emit declare reduction functions, if required. 203 if (Ctx->getLangOpts().OpenMP) { 204 for (Decl *Member : D->decls()) { 205 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) { 206 if (Ctx->DeclMustBeEmitted(DRD)) 207 Builder->EmitGlobal(DRD); 208 } 209 } 210 } 211 } 212 213 void HandleTagDeclRequiredDefinition(const TagDecl *D) override { 214 if (Diags.hasErrorOccurred()) 215 return; 216 217 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo()) 218 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) 219 DI->completeRequiredType(RD); 220 } 221 222 void HandleTranslationUnit(ASTContext &Ctx) override { 223 // Release the Builder when there is no error. 224 if (!Diags.hasErrorOccurred() && Builder) 225 Builder->Release(); 226 227 // If there are errors before or when releasing the Builder, reset 228 // the module to stop here before invoking the backend. 229 if (Diags.hasErrorOccurred()) { 230 if (Builder) 231 Builder->clear(); 232 M.reset(); 233 return; 234 } 235 } 236 237 void AssignInheritanceModel(CXXRecordDecl *RD) override { 238 if (Diags.hasErrorOccurred()) 239 return; 240 241 Builder->RefreshTypeCacheForClass(RD); 242 } 243 244 void CompleteTentativeDefinition(VarDecl *D) override { 245 if (Diags.hasErrorOccurred()) 246 return; 247 248 Builder->EmitTentativeDefinition(D); 249 } 250 251 void HandleVTable(CXXRecordDecl *RD) override { 252 if (Diags.hasErrorOccurred()) 253 return; 254 255 Builder->EmitVTable(RD); 256 } 257 }; 258 } 259 260 void CodeGenerator::anchor() { } 261 262 CodeGenerator *clang::CreateLLVMCodeGen( 263 DiagnosticsEngine &Diags, const std::string &ModuleName, 264 const HeaderSearchOptions &HeaderSearchOpts, 265 const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, 266 llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) { 267 return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts, 268 PreprocessorOpts, CGO, C, CoverageInfo); 269 } 270