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 Builder->EmitTopLevelDecl(D); 156 return; 157 } 158 159 // Otherwise, must be a method. 160 auto MD = cast<CXXMethodDecl>(D); 161 162 // We may want to emit this definition. However, that decision might be 163 // based on computing the linkage, and we have to defer that in case we 164 // are inside of something that will change the method's final linkage, 165 // e.g. 166 // typedef struct { 167 // void bar(); 168 // void foo() { bar(); } 169 // } A; 170 DeferredInlineMethodDefinitions.push_back(MD); 171 172 // Provide some coverage mapping even for methods that aren't emitted. 173 // Don't do this for templated classes though, as they may not be 174 // instantiable. 175 if (!MD->getParent()->getDescribedClassTemplate()) 176 Builder->AddDeferredUnusedCoverageMapping(MD); 177 } 178 179 /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl 180 /// to (e.g. struct, union, enum, class) is completed. This allows the 181 /// client hack on the type, which can occur at any point in the file 182 /// (because these can be defined in declspecs). 183 void HandleTagDeclDefinition(TagDecl *D) override { 184 if (Diags.hasErrorOccurred()) 185 return; 186 187 Builder->UpdateCompletedType(D); 188 189 // For MSVC compatibility, treat declarations of static data members with 190 // inline initializers as definitions. 191 if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) { 192 for (Decl *Member : D->decls()) { 193 if (VarDecl *VD = dyn_cast<VarDecl>(Member)) { 194 if (Ctx->isMSStaticDataMemberInlineDefinition(VD) && 195 Ctx->DeclMustBeEmitted(VD)) { 196 Builder->EmitGlobal(VD); 197 } 198 } 199 } 200 } 201 // For OpenMP emit declare reduction functions, if required. 202 if (Ctx->getLangOpts().OpenMP) { 203 for (Decl *Member : D->decls()) { 204 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) { 205 if (Ctx->DeclMustBeEmitted(DRD)) 206 Builder->EmitGlobal(DRD); 207 } 208 } 209 } 210 } 211 212 void HandleTagDeclRequiredDefinition(const TagDecl *D) override { 213 if (Diags.hasErrorOccurred()) 214 return; 215 216 if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo()) 217 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) 218 DI->completeRequiredType(RD); 219 } 220 221 void HandleTranslationUnit(ASTContext &Ctx) override { 222 // Release the Builder when there is no error. 223 if (!Diags.hasErrorOccurred() && Builder) 224 Builder->Release(); 225 226 // If there are errors before or when releasing the Builder, reset 227 // the module to stop here before invoking the backend. 228 if (Diags.hasErrorOccurred()) { 229 if (Builder) 230 Builder->clear(); 231 M.reset(); 232 return; 233 } 234 } 235 236 void AssignInheritanceModel(CXXRecordDecl *RD) override { 237 if (Diags.hasErrorOccurred()) 238 return; 239 240 Builder->RefreshTypeCacheForClass(RD); 241 } 242 243 void CompleteTentativeDefinition(VarDecl *D) override { 244 if (Diags.hasErrorOccurred()) 245 return; 246 247 Builder->EmitTentativeDefinition(D); 248 } 249 250 void HandleVTable(CXXRecordDecl *RD) override { 251 if (Diags.hasErrorOccurred()) 252 return; 253 254 Builder->EmitVTable(RD); 255 } 256 }; 257 } 258 259 void CodeGenerator::anchor() { } 260 261 CodeGenerator *clang::CreateLLVMCodeGen( 262 DiagnosticsEngine &Diags, const std::string &ModuleName, 263 const HeaderSearchOptions &HeaderSearchOpts, 264 const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, 265 llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) { 266 return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts, 267 PreprocessorOpts, CGO, C, CoverageInfo); 268 } 269