ModuleBuilder.cpp 11 KB

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