ModuleBuilder.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. namespace {
  29. class CodeGeneratorImpl : public CodeGenerator {
  30. DiagnosticsEngine &Diags;
  31. std::unique_ptr<const llvm::DataLayout> TD;
  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. struct HandlingTopLevelDeclRAII {
  38. CodeGeneratorImpl &Self;
  39. HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self) : Self(Self) {
  40. ++Self.HandlingTopLevelDecls;
  41. }
  42. ~HandlingTopLevelDeclRAII() {
  43. if (--Self.HandlingTopLevelDecls == 0)
  44. Self.EmitDeferredDecls();
  45. }
  46. };
  47. CoverageSourceInfo *CoverageInfo;
  48. protected:
  49. std::unique_ptr<llvm::Module> M;
  50. std::unique_ptr<CodeGen::CodeGenModule> Builder;
  51. private:
  52. SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
  53. public:
  54. CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string &ModuleName,
  55. const HeaderSearchOptions &HSO,
  56. const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
  57. llvm::LLVMContext &C,
  58. CoverageSourceInfo *CoverageInfo = nullptr)
  59. : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
  60. PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
  61. CoverageInfo(CoverageInfo),
  62. M(new llvm::Module(ModuleName, C)) {}
  63. ~CodeGeneratorImpl() override {
  64. // There should normally not be any leftover inline method definitions.
  65. assert(DeferredInlineMethodDefinitions.empty() ||
  66. Diags.hasErrorOccurred());
  67. }
  68. llvm::Module* GetModule() override {
  69. return M.get();
  70. }
  71. const Decl *GetDeclForMangledName(StringRef MangledName) override {
  72. GlobalDecl Result;
  73. if (!Builder->lookupRepresentativeDecl(MangledName, Result))
  74. return nullptr;
  75. const Decl *D = Result.getCanonicalDecl().getDecl();
  76. if (auto FD = dyn_cast<FunctionDecl>(D)) {
  77. if (FD->hasBody(FD))
  78. return FD;
  79. } else if (auto TD = dyn_cast<TagDecl>(D)) {
  80. if (auto Def = TD->getDefinition())
  81. return Def;
  82. }
  83. return D;
  84. }
  85. llvm::Module *ReleaseModule() override { return M.release(); }
  86. void Initialize(ASTContext &Context) override {
  87. Ctx = &Context;
  88. M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
  89. M->setDataLayout(Ctx->getTargetInfo().getTargetDescription());
  90. TD.reset(
  91. new llvm::DataLayout(Ctx->getTargetInfo().getTargetDescription()));
  92. Builder.reset(new CodeGen::CodeGenModule(Context,
  93. HeaderSearchOpts,
  94. PreprocessorOpts,
  95. CodeGenOpts, *M, *TD,
  96. Diags, CoverageInfo));
  97. for (size_t i = 0, e = CodeGenOpts.DependentLibraries.size(); i < e; ++i)
  98. HandleDependentLibrary(CodeGenOpts.DependentLibraries[i]);
  99. }
  100. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
  101. if (Diags.hasErrorOccurred())
  102. return;
  103. Builder->HandleCXXStaticMemberVarInstantiation(VD);
  104. }
  105. bool HandleTopLevelDecl(DeclGroupRef DG) override {
  106. if (Diags.hasErrorOccurred())
  107. return true;
  108. HandlingTopLevelDeclRAII HandlingDecl(*this);
  109. // Make sure to emit all elements of a Decl.
  110. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
  111. Builder->EmitTopLevelDecl(*I);
  112. return true;
  113. }
  114. void EmitDeferredDecls() {
  115. if (DeferredInlineMethodDefinitions.empty())
  116. return;
  117. // Emit any deferred inline method definitions. Note that more deferred
  118. // methods may be added during this loop, since ASTConsumer callbacks
  119. // can be invoked if AST inspection results in declarations being added.
  120. HandlingTopLevelDeclRAII HandlingDecl(*this);
  121. for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
  122. Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
  123. DeferredInlineMethodDefinitions.clear();
  124. }
  125. void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
  126. if (Diags.hasErrorOccurred())
  127. return;
  128. assert(D->doesThisDeclarationHaveABody());
  129. // We may want to emit this definition. However, that decision might be
  130. // based on computing the linkage, and we have to defer that in case we
  131. // are inside of something that will change the method's final linkage,
  132. // e.g.
  133. // typedef struct {
  134. // void bar();
  135. // void foo() { bar(); }
  136. // } A;
  137. DeferredInlineMethodDefinitions.push_back(D);
  138. // Provide some coverage mapping even for methods that aren't emitted.
  139. // Don't do this for templated classes though, as they may not be
  140. // instantiable.
  141. if (!D->getParent()->getDescribedClassTemplate())
  142. Builder->AddDeferredUnusedCoverageMapping(D);
  143. }
  144. /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
  145. /// to (e.g. struct, union, enum, class) is completed. This allows the
  146. /// client hack on the type, which can occur at any point in the file
  147. /// (because these can be defined in declspecs).
  148. void HandleTagDeclDefinition(TagDecl *D) override {
  149. if (Diags.hasErrorOccurred())
  150. return;
  151. Builder->UpdateCompletedType(D);
  152. // For MSVC compatibility, treat declarations of static data members with
  153. // inline initializers as definitions.
  154. if (Ctx->getLangOpts().MSVCCompat) {
  155. for (Decl *Member : D->decls()) {
  156. if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
  157. if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
  158. Ctx->DeclMustBeEmitted(VD)) {
  159. Builder->EmitGlobal(VD);
  160. }
  161. }
  162. }
  163. }
  164. }
  165. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  166. if (Diags.hasErrorOccurred())
  167. return;
  168. if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
  169. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
  170. DI->completeRequiredType(RD);
  171. }
  172. void HandleTranslationUnit(ASTContext &Ctx) override {
  173. if (Diags.hasErrorOccurred()) {
  174. if (Builder)
  175. Builder->clear();
  176. M.reset();
  177. return;
  178. }
  179. if (Builder)
  180. Builder->Release();
  181. // HLSL Change Begins
  182. // Error may happen in Builder->Release for HLSL
  183. if (CodeGenOpts.getDebugInfo() == CodeGenOptions::DebugInfoKind::FullDebugInfo) {
  184. // Add all file contents in a list of filename/content pairs.
  185. llvm::NamedMDNode *pContents = nullptr;
  186. llvm::LLVMContext &LLVMCtx = M->getContext();
  187. for (SourceManager::fileinfo_iterator
  188. it = Ctx.getSourceManager().fileinfo_begin(),
  189. end = Ctx.getSourceManager().fileinfo_end();
  190. it != end; ++it) {
  191. if (it->first->isValid() && !it->second->IsSystemFile) {
  192. if (pContents == nullptr) {
  193. pContents = M->getOrInsertNamedMetadata("llvm.dbg.contents");
  194. }
  195. llvm::MDTuple *pFileInfo = llvm::MDNode::get(
  196. LLVMCtx,
  197. {llvm::MDString::get(LLVMCtx, it->first->getName()),
  198. llvm::MDString::get(LLVMCtx,
  199. it->second->getRawBuffer()->getBuffer())});
  200. pContents->addOperand(pFileInfo);
  201. }
  202. }
  203. // Add Defines to Debug Info
  204. llvm::NamedMDNode *pDefines = M->getOrInsertNamedMetadata("llvm.dbg.defines");
  205. std::vector<llvm::Metadata *> vecDefines;
  206. vecDefines.resize(CodeGenOpts.HLSLDefines.size());
  207. std::transform(CodeGenOpts.HLSLDefines.begin(), CodeGenOpts.HLSLDefines.end(),
  208. vecDefines.begin(), [&LLVMCtx](const std::string &str) { return llvm::MDString::get(LLVMCtx, str); });
  209. llvm::MDTuple *pDefinesInfo = llvm::MDNode::get(LLVMCtx, vecDefines);
  210. pDefines->addOperand(pDefinesInfo);
  211. // Add main file name to debug info
  212. llvm::NamedMDNode *pSourceFilename = M->getOrInsertNamedMetadata("llvm.dbg.mainFileName");
  213. llvm::MDTuple *pFileName = llvm::MDNode::get(
  214. LLVMCtx, llvm::MDString::get(LLVMCtx, CodeGenOpts.MainFileName));
  215. pSourceFilename->addOperand(pFileName);
  216. // Pass in any other arguments to debug info
  217. llvm::NamedMDNode *pArgs = M->getOrInsertNamedMetadata("llvm.dbg.args");
  218. std::vector<llvm::Metadata *> vecArguments;
  219. vecArguments.resize(CodeGenOpts.HLSLArguments.size());
  220. std::transform(CodeGenOpts.HLSLArguments.begin(), CodeGenOpts.HLSLArguments.end(),
  221. vecArguments.begin(), [&LLVMCtx](const std::string &str) { return llvm::MDString::get(LLVMCtx, str); });
  222. llvm::MDTuple *pArgumentsInfo = llvm::MDNode::get(LLVMCtx, vecArguments);
  223. pArgs->addOperand(pArgumentsInfo);
  224. }
  225. if (Diags.hasErrorOccurred())
  226. M.reset();
  227. // HLSL Change Ends
  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. void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
  240. Builder->AppendLinkerOptions(Opts);
  241. }
  242. void HandleDetectMismatch(llvm::StringRef Name,
  243. llvm::StringRef Value) override {
  244. Builder->AddDetectMismatch(Name, Value);
  245. }
  246. void HandleDependentLibrary(llvm::StringRef Lib) override {
  247. Builder->AddDependentLib(Lib);
  248. }
  249. };
  250. }
  251. void CodeGenerator::anchor() { }
  252. CodeGenerator *clang::CreateLLVMCodeGen(
  253. DiagnosticsEngine &Diags, const std::string &ModuleName,
  254. const HeaderSearchOptions &HeaderSearchOpts,
  255. const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
  256. llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
  257. return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
  258. PreprocessorOpts, CGO, C, CoverageInfo);
  259. }