CodeGenAction.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
  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. #include "CoverageMappingGen.h"
  10. #include "clang/AST/ASTConsumer.h"
  11. #include "clang/AST/ASTContext.h"
  12. #include "clang/AST/DeclCXX.h"
  13. #include "clang/AST/DeclGroup.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/SourceManager.h"
  16. #include "clang/Basic/TargetInfo.h"
  17. #include "clang/CodeGen/BackendUtil.h"
  18. #include "clang/CodeGen/CodeGenAction.h"
  19. #include "clang/CodeGen/ModuleBuilder.h"
  20. #include "clang/Frontend/CompilerInstance.h"
  21. #include "clang/Frontend/FrontendDiagnostic.h"
  22. #include "clang/Frontend/TextDiagnosticPrinter.h" // HLSL Change
  23. #include "clang/Lex/Preprocessor.h"
  24. #include "llvm/ADT/SmallString.h"
  25. #include "llvm/Bitcode/ReaderWriter.h"
  26. #include "llvm/IR/DebugInfo.h"
  27. #include "llvm/IR/DiagnosticInfo.h"
  28. #include "llvm/IR/DiagnosticPrinter.h"
  29. #include "llvm/IR/LLVMContext.h"
  30. #include "llvm/IR/Module.h"
  31. #include "llvm/IRReader/IRReader.h"
  32. #include "llvm/Linker/Linker.h"
  33. #include "llvm/Pass.h"
  34. #include "llvm/Support/MemoryBuffer.h"
  35. #include "llvm/Support/SourceMgr.h"
  36. #include "llvm/Support/Timer.h"
  37. #include <memory>
  38. using namespace clang;
  39. using namespace llvm;
  40. namespace clang {
  41. class BackendConsumer : public ASTConsumer {
  42. virtual void anchor();
  43. DiagnosticsEngine &Diags;
  44. BackendAction Action;
  45. const CodeGenOptions &CodeGenOpts;
  46. const TargetOptions &TargetOpts;
  47. const LangOptions &LangOpts;
  48. raw_pwrite_stream *AsmOutStream;
  49. ASTContext *Context;
  50. Timer LLVMIRGeneration;
  51. std::unique_ptr<CodeGenerator> Gen;
  52. std::unique_ptr<llvm::Module> TheModule, LinkModule;
  53. public:
  54. BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
  55. const HeaderSearchOptions &HeaderSearchOpts,
  56. const PreprocessorOptions &PPOpts,
  57. const CodeGenOptions &CodeGenOpts,
  58. const TargetOptions &TargetOpts,
  59. const LangOptions &LangOpts, bool TimePasses,
  60. const std::string &InFile, llvm::Module *LinkModule,
  61. raw_pwrite_stream *OS, LLVMContext &C,
  62. CoverageSourceInfo *CoverageInfo = nullptr)
  63. : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
  64. TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS),
  65. Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
  66. Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
  67. CodeGenOpts, C, CoverageInfo)),
  68. LinkModule(LinkModule) {
  69. llvm::TimePassesIsEnabled = TimePasses;
  70. }
  71. // HLSL Change Starts - avoid double free
  72. ~BackendConsumer() {
  73. if (TheModule.get() && Gen.get()) {
  74. Gen->ReleaseModule();
  75. }
  76. }
  77. // HLSL Change Ends - avoid double free
  78. std::unique_ptr<llvm::Module> takeModule() { return std::move(TheModule); }
  79. llvm::Module *takeLinkModule() { return LinkModule.release(); }
  80. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
  81. Gen->HandleCXXStaticMemberVarInstantiation(VD);
  82. }
  83. void Initialize(ASTContext &Ctx) override {
  84. if (Context) {
  85. assert(Context == &Ctx);
  86. return;
  87. }
  88. Context = &Ctx;
  89. if (llvm::TimePassesIsEnabled)
  90. LLVMIRGeneration.startTimer();
  91. Gen->Initialize(Ctx);
  92. TheModule.reset(Gen->GetModule());
  93. if (llvm::TimePassesIsEnabled)
  94. LLVMIRGeneration.stopTimer();
  95. }
  96. bool HandleTopLevelDecl(DeclGroupRef D) override {
  97. PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
  98. Context->getSourceManager(),
  99. "LLVM IR generation of declaration");
  100. if (llvm::TimePassesIsEnabled)
  101. LLVMIRGeneration.startTimer();
  102. Gen->HandleTopLevelDecl(D);
  103. if (llvm::TimePassesIsEnabled)
  104. LLVMIRGeneration.stopTimer();
  105. return true;
  106. }
  107. void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
  108. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  109. Context->getSourceManager(),
  110. "LLVM IR generation of inline method");
  111. if (llvm::TimePassesIsEnabled)
  112. LLVMIRGeneration.startTimer();
  113. Gen->HandleInlineMethodDefinition(D);
  114. if (llvm::TimePassesIsEnabled)
  115. LLVMIRGeneration.stopTimer();
  116. }
  117. void HandleTranslationUnit(ASTContext &C) override {
  118. {
  119. PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
  120. if (llvm::TimePassesIsEnabled)
  121. LLVMIRGeneration.startTimer();
  122. Gen->HandleTranslationUnit(C);
  123. if (llvm::TimePassesIsEnabled)
  124. LLVMIRGeneration.stopTimer();
  125. }
  126. // Silently ignore if we weren't initialized for some reason.
  127. if (!TheModule)
  128. return;
  129. // Make sure IR generation is happy with the module. This is released by
  130. // the module provider.
  131. llvm::Module *M = Gen->ReleaseModule();
  132. if (!M) {
  133. // The module has been released by IR gen on failures, do not double
  134. // free.
  135. TheModule.release();
  136. return;
  137. }
  138. assert(TheModule.get() == M &&
  139. "Unexpected module change during IR generation");
  140. // Link LinkModule into this module if present, preserving its validity.
  141. if (LinkModule) {
  142. if (Linker::LinkModules(
  143. M, LinkModule.get(),
  144. [=](const DiagnosticInfo &DI) { linkerDiagnosticHandler(DI); }))
  145. return;
  146. }
  147. // Install an inline asm handler so that diagnostics get printed through
  148. // our diagnostics hooks.
  149. LLVMContext &Ctx = TheModule->getContext();
  150. LLVMContext::InlineAsmDiagHandlerTy OldHandler =
  151. Ctx.getInlineAsmDiagnosticHandler();
  152. void *OldContext = Ctx.getInlineAsmDiagnosticContext();
  153. Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
  154. LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
  155. Ctx.getDiagnosticHandler();
  156. void *OldDiagnosticContext = Ctx.getDiagnosticContext();
  157. Ctx.setDiagnosticHandler(DiagnosticHandler, this);
  158. EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
  159. C.getTargetInfo().getTargetDescription(),
  160. TheModule.get(), Action, AsmOutStream);
  161. Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
  162. Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
  163. }
  164. void HandleTagDeclDefinition(TagDecl *D) override {
  165. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  166. Context->getSourceManager(),
  167. "LLVM IR generation of declaration");
  168. Gen->HandleTagDeclDefinition(D);
  169. }
  170. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  171. Gen->HandleTagDeclRequiredDefinition(D);
  172. }
  173. void CompleteTentativeDefinition(VarDecl *D) override {
  174. Gen->CompleteTentativeDefinition(D);
  175. }
  176. void HandleVTable(CXXRecordDecl *RD) override {
  177. Gen->HandleVTable(RD);
  178. }
  179. void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
  180. Gen->HandleLinkerOptionPragma(Opts);
  181. }
  182. void HandleDetectMismatch(llvm::StringRef Name,
  183. llvm::StringRef Value) override {
  184. Gen->HandleDetectMismatch(Name, Value);
  185. }
  186. void HandleDependentLibrary(llvm::StringRef Opts) override {
  187. Gen->HandleDependentLibrary(Opts);
  188. }
  189. static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
  190. unsigned LocCookie) {
  191. SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
  192. ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
  193. }
  194. void linkerDiagnosticHandler(const llvm::DiagnosticInfo &DI);
  195. static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
  196. void *Context) {
  197. ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
  198. }
  199. void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
  200. SourceLocation LocCookie);
  201. void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
  202. /// \brief Specialized handler for InlineAsm diagnostic.
  203. /// \return True if the diagnostic has been successfully reported, false
  204. /// otherwise.
  205. bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
  206. /// \brief Specialized handler for StackSize diagnostic.
  207. /// \return True if the diagnostic has been successfully reported, false
  208. /// otherwise.
  209. bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
  210. /// \brief Specialized handlers for optimization remarks.
  211. /// Note that these handlers only accept remarks and they always handle
  212. /// them.
  213. void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
  214. unsigned DiagID);
  215. void
  216. OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
  217. void OptimizationRemarkHandler(
  218. const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
  219. void OptimizationRemarkHandler(
  220. const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
  221. void OptimizationFailureHandler(
  222. const llvm::DiagnosticInfoOptimizationFailure &D);
  223. bool DxilDiagHandler(const llvm::DiagnosticInfoDxil &D);
  224. };
  225. void BackendConsumer::anchor() {}
  226. }
  227. /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
  228. /// buffer to be a valid FullSourceLoc.
  229. static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
  230. SourceManager &CSM) {
  231. // Get both the clang and llvm source managers. The location is relative to
  232. // a memory buffer that the LLVM Source Manager is handling, we need to add
  233. // a copy to the Clang source manager.
  234. const llvm::SourceMgr &LSM = *D.getSourceMgr();
  235. // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
  236. // already owns its one and clang::SourceManager wants to own its one.
  237. const MemoryBuffer *LBuf =
  238. LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
  239. // Create the copy and transfer ownership to clang::SourceManager.
  240. // TODO: Avoid copying files into memory.
  241. std::unique_ptr<llvm::MemoryBuffer> CBuf =
  242. llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
  243. LBuf->getBufferIdentifier());
  244. // FIXME: Keep a file ID map instead of creating new IDs for each location.
  245. FileID FID = CSM.createFileID(std::move(CBuf));
  246. // Translate the offset into the file.
  247. unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
  248. SourceLocation NewLoc =
  249. CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
  250. return FullSourceLoc(NewLoc, CSM);
  251. }
  252. /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
  253. /// error parsing inline asm. The SMDiagnostic indicates the error relative to
  254. /// the temporary memory buffer that the inline asm parser has set up.
  255. void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
  256. SourceLocation LocCookie) {
  257. // There are a couple of different kinds of errors we could get here. First,
  258. // we re-format the SMDiagnostic in terms of a clang diagnostic.
  259. // Strip "error: " off the start of the message string.
  260. StringRef Message = D.getMessage();
  261. if (Message.startswith("error: "))
  262. Message = Message.substr(7);
  263. // If the SMDiagnostic has an inline asm source location, translate it.
  264. FullSourceLoc Loc;
  265. if (D.getLoc() != SMLoc())
  266. Loc = ConvertBackendLocation(D, Context->getSourceManager());
  267. unsigned DiagID;
  268. switch (D.getKind()) {
  269. case llvm::SourceMgr::DK_Error:
  270. DiagID = diag::err_fe_inline_asm;
  271. break;
  272. case llvm::SourceMgr::DK_Warning:
  273. DiagID = diag::warn_fe_inline_asm;
  274. break;
  275. case llvm::SourceMgr::DK_Note:
  276. DiagID = diag::note_fe_inline_asm;
  277. break;
  278. }
  279. // If this problem has clang-level source location information, report the
  280. // issue in the source with a note showing the instantiated
  281. // code.
  282. if (LocCookie.isValid()) {
  283. Diags.Report(LocCookie, DiagID).AddString(Message);
  284. if (D.getLoc().isValid()) {
  285. DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
  286. // Convert the SMDiagnostic ranges into SourceRange and attach them
  287. // to the diagnostic.
  288. for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
  289. std::pair<unsigned, unsigned> Range = D.getRanges()[i];
  290. unsigned Column = D.getColumnNo();
  291. B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
  292. Loc.getLocWithOffset(Range.second - Column));
  293. }
  294. }
  295. return;
  296. }
  297. // Otherwise, report the backend issue as occurring in the generated .s file.
  298. // If Loc is invalid, we still need to report the issue, it just gets no
  299. // location info.
  300. Diags.Report(Loc, DiagID).AddString(Message);
  301. }
  302. #define ComputeDiagID(Severity, GroupName, DiagID) \
  303. do { \
  304. switch (Severity) { \
  305. case llvm::DS_Error: \
  306. DiagID = diag::err_fe_##GroupName; \
  307. break; \
  308. case llvm::DS_Warning: \
  309. DiagID = diag::warn_fe_##GroupName; \
  310. break; \
  311. case llvm::DS_Remark: \
  312. llvm_unreachable("'remark' severity not expected"); \
  313. break; \
  314. case llvm::DS_Note: \
  315. DiagID = diag::note_fe_##GroupName; \
  316. break; \
  317. } \
  318. } while (false)
  319. #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
  320. do { \
  321. switch (Severity) { \
  322. case llvm::DS_Error: \
  323. DiagID = diag::err_fe_##GroupName; \
  324. break; \
  325. case llvm::DS_Warning: \
  326. DiagID = diag::warn_fe_##GroupName; \
  327. break; \
  328. case llvm::DS_Remark: \
  329. DiagID = diag::remark_fe_##GroupName; \
  330. break; \
  331. case llvm::DS_Note: \
  332. DiagID = diag::note_fe_##GroupName; \
  333. break; \
  334. } \
  335. } while (false)
  336. bool
  337. BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
  338. unsigned DiagID;
  339. ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
  340. std::string Message = D.getMsgStr().str();
  341. // If this problem has clang-level source location information, report the
  342. // issue as being a problem in the source with a note showing the instantiated
  343. // code.
  344. SourceLocation LocCookie =
  345. SourceLocation::getFromRawEncoding(D.getLocCookie());
  346. if (LocCookie.isValid())
  347. Diags.Report(LocCookie, DiagID).AddString(Message);
  348. else {
  349. // Otherwise, report the backend diagnostic as occurring in the generated
  350. // .s file.
  351. // If Loc is invalid, we still need to report the diagnostic, it just gets
  352. // no location info.
  353. FullSourceLoc Loc;
  354. Diags.Report(Loc, DiagID).AddString(Message);
  355. }
  356. // We handled all the possible severities.
  357. return true;
  358. }
  359. bool
  360. BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
  361. if (D.getSeverity() != llvm::DS_Warning)
  362. // For now, the only support we have for StackSize diagnostic is warning.
  363. // We do not know how to format other severities.
  364. return false;
  365. if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
  366. Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
  367. diag::warn_fe_frame_larger_than)
  368. << D.getStackSize() << Decl::castToDeclContext(ND);
  369. return true;
  370. }
  371. return false;
  372. }
  373. void BackendConsumer::EmitOptimizationMessage(
  374. const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
  375. // We only support warnings and remarks.
  376. assert(D.getSeverity() == llvm::DS_Remark ||
  377. D.getSeverity() == llvm::DS_Warning);
  378. SourceManager &SourceMgr = Context->getSourceManager();
  379. FileManager &FileMgr = SourceMgr.getFileManager();
  380. StringRef Filename;
  381. unsigned Line, Column;
  382. SourceLocation DILoc;
  383. if (D.isLocationAvailable()) {
  384. D.getLocation(&Filename, &Line, &Column);
  385. const FileEntry *FE = FileMgr.getFile(Filename);
  386. if (FE && Line > 0) {
  387. // If -gcolumn-info was not used, Column will be 0. This upsets the
  388. // source manager, so pass 1 if Column is not set.
  389. DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
  390. }
  391. }
  392. // If a location isn't available, try to approximate it using the associated
  393. // function definition. We use the definition's right brace to differentiate
  394. // from diagnostics that genuinely relate to the function itself.
  395. FullSourceLoc Loc(DILoc, SourceMgr);
  396. if (Loc.isInvalid())
  397. if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
  398. Loc = FD->getASTContext().getFullLoc(FD->getBodyRBrace());
  399. Diags.Report(Loc, DiagID)
  400. << AddFlagValue(D.getPassName() ? D.getPassName() : "")
  401. << D.getMsg().str();
  402. if (DILoc.isInvalid() && D.isLocationAvailable())
  403. // If we were not able to translate the file:line:col information
  404. // back to a SourceLocation, at least emit a note stating that
  405. // we could not translate this location. This can happen in the
  406. // case of #line directives.
  407. Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc)
  408. << Filename << Line << Column;
  409. }
  410. void BackendConsumer::OptimizationRemarkHandler(
  411. const llvm::DiagnosticInfoOptimizationRemark &D) {
  412. // Optimization remarks are active only if the -Rpass flag has a regular
  413. // expression that matches the name of the pass name in \p D.
  414. if (CodeGenOpts.OptimizationRemarkPattern &&
  415. CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
  416. EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
  417. }
  418. void BackendConsumer::OptimizationRemarkHandler(
  419. const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
  420. // Missed optimization remarks are active only if the -Rpass-missed
  421. // flag has a regular expression that matches the name of the pass
  422. // name in \p D.
  423. if (CodeGenOpts.OptimizationRemarkMissedPattern &&
  424. CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
  425. EmitOptimizationMessage(D,
  426. diag::remark_fe_backend_optimization_remark_missed);
  427. }
  428. void BackendConsumer::OptimizationRemarkHandler(
  429. const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
  430. // Optimization analysis remarks are active only if the -Rpass-analysis
  431. // flag has a regular expression that matches the name of the pass
  432. // name in \p D.
  433. if (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
  434. CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))
  435. EmitOptimizationMessage(
  436. D, diag::remark_fe_backend_optimization_remark_analysis);
  437. }
  438. void BackendConsumer::OptimizationFailureHandler(
  439. const llvm::DiagnosticInfoOptimizationFailure &D) {
  440. EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
  441. }
  442. void BackendConsumer::linkerDiagnosticHandler(const DiagnosticInfo &DI) {
  443. if (DI.getSeverity() != DS_Error)
  444. return;
  445. std::string MsgStorage;
  446. {
  447. raw_string_ostream Stream(MsgStorage);
  448. DiagnosticPrinterRawOStream DP(Stream);
  449. DI.print(DP);
  450. }
  451. Diags.Report(diag::err_fe_cannot_link_module)
  452. << LinkModule->getModuleIdentifier() << MsgStorage;
  453. }
  454. // HLSL Change start - Dxil Diagnostic Info reporter
  455. bool
  456. BackendConsumer::DxilDiagHandler(const llvm::DiagnosticInfoDxil &D) {
  457. unsigned DiagID;
  458. ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
  459. SourceManager &SourceMgr = Context->getSourceManager();
  460. SourceLocation DILoc;
  461. std::string Message = D.getMsgStr().str();
  462. const DILocation *DLoc = D.getLocation();
  463. // Convert Filename/Line/Column triplet into SourceLocation
  464. if (DLoc) {
  465. FileManager &FileMgr = SourceMgr.getFileManager();
  466. StringRef Filename = DLoc->getFilename();
  467. unsigned Line = DLoc->getLine();
  468. unsigned Column = DLoc->getColumn();
  469. const FileEntry *FE = FileMgr.getFile(Filename);
  470. if (FE && Line > 0) {
  471. DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
  472. }
  473. }
  474. FullSourceLoc Loc(DILoc, SourceMgr);
  475. // If no location information is available, add function name
  476. if (Loc.isInvalid()) {
  477. auto *DiagClient = dynamic_cast<TextDiagnosticPrinter*>(Diags.getClient());
  478. auto *func = D.getFunction();
  479. if (DiagClient && func)
  480. DiagClient->setPrefix("Function: " + func->getName().str());
  481. }
  482. Diags.Report(Loc, DiagID).AddString(Message);
  483. return true;
  484. }
  485. // HLSL Change end - Dxil Diagnostic Info reporter
  486. /// \brief This function is invoked when the backend needs
  487. /// to report something to the user.
  488. void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
  489. unsigned DiagID = diag::err_fe_inline_asm;
  490. llvm::DiagnosticSeverity Severity = DI.getSeverity();
  491. // Get the diagnostic ID based.
  492. switch (DI.getKind()) {
  493. case llvm::DK_InlineAsm:
  494. if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
  495. return;
  496. ComputeDiagID(Severity, inline_asm, DiagID);
  497. break;
  498. case llvm::DK_StackSize:
  499. if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
  500. return;
  501. ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
  502. break;
  503. case llvm::DK_OptimizationRemark:
  504. // Optimization remarks are always handled completely by this
  505. // handler. There is no generic way of emitting them.
  506. OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
  507. return;
  508. case llvm::DK_OptimizationRemarkMissed:
  509. // Optimization remarks are always handled completely by this
  510. // handler. There is no generic way of emitting them.
  511. OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
  512. return;
  513. case llvm::DK_OptimizationRemarkAnalysis:
  514. // Optimization remarks are always handled completely by this
  515. // handler. There is no generic way of emitting them.
  516. OptimizationRemarkHandler(
  517. cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
  518. return;
  519. case llvm::DK_OptimizationFailure:
  520. // Optimization failures are always handled completely by this
  521. // handler.
  522. OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
  523. return;
  524. // HLSL Change start - Dxil Diagnostic Info reporter
  525. case llvm::DK_DXIL:
  526. if (DxilDiagHandler(cast<DiagnosticInfoDxil>(DI)))
  527. return;
  528. ComputeDiagID(Severity, inline_asm, DiagID);
  529. break;
  530. // HLSL Change end - Dxil Diagnostic Info reporter
  531. default:
  532. // Plugin IDs are not bound to any value as they are set dynamically.
  533. ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
  534. break;
  535. }
  536. std::string MsgStorage;
  537. {
  538. raw_string_ostream Stream(MsgStorage);
  539. DiagnosticPrinterRawOStream DP(Stream);
  540. DI.print(DP);
  541. }
  542. // Report the backend message using the usual diagnostic mechanism.
  543. FullSourceLoc Loc;
  544. Diags.Report(Loc, DiagID).AddString(MsgStorage);
  545. }
  546. #undef ComputeDiagID
  547. CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
  548. : Act(_Act), LinkModule(nullptr),
  549. VMContext(_VMContext ? _VMContext : new LLVMContext),
  550. OwnsVMContext(!_VMContext) {}
  551. CodeGenAction::~CodeGenAction() {
  552. TheModule.reset();
  553. if (OwnsVMContext)
  554. delete VMContext;
  555. }
  556. bool CodeGenAction::hasIRSupport() const { return true; }
  557. void CodeGenAction::EndSourceFileAction() {
  558. // If the consumer creation failed, do nothing.
  559. if (!getCompilerInstance().hasASTConsumer())
  560. return;
  561. // If we were given a link module, release consumer's ownership of it.
  562. if (LinkModule)
  563. BEConsumer->takeLinkModule();
  564. // Steal the module from the consumer.
  565. TheModule = BEConsumer->takeModule();
  566. }
  567. std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
  568. return std::move(TheModule);
  569. }
  570. llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
  571. OwnsVMContext = false;
  572. return VMContext;
  573. }
  574. static raw_pwrite_stream *
  575. GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
  576. switch (Action) {
  577. case Backend_EmitAssembly:
  578. return CI.createDefaultOutputFile(false, InFile, "s");
  579. case Backend_EmitLL:
  580. return CI.createDefaultOutputFile(false, InFile, "ll");
  581. case Backend_EmitBC:
  582. return CI.createDefaultOutputFile(true, InFile, "bc");
  583. case Backend_EmitPasses:
  584. return CI.createDefaultOutputFile(true, InFile, "passes.txt");
  585. case Backend_EmitNothing:
  586. return nullptr;
  587. case Backend_EmitMCNull:
  588. return CI.createNullOutputFile();
  589. case Backend_EmitObj:
  590. return CI.createDefaultOutputFile(true, InFile, "o");
  591. }
  592. llvm_unreachable("Invalid action!");
  593. }
  594. std::unique_ptr<ASTConsumer>
  595. CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  596. BackendAction BA = static_cast<BackendAction>(Act);
  597. raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
  598. if (BA != Backend_EmitNothing && !OS)
  599. return nullptr;
  600. llvm::Module *LinkModuleToUse = LinkModule;
  601. // If we were not given a link module, and the user requested that one be
  602. // loaded from bitcode, do so now.
  603. const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
  604. if (!LinkModuleToUse && !LinkBCFile.empty()) {
  605. auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
  606. if (!BCBuf) {
  607. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  608. << LinkBCFile << BCBuf.getError().message();
  609. return nullptr;
  610. }
  611. ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
  612. getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
  613. if (std::error_code EC = ModuleOrErr.getError()) {
  614. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  615. << LinkBCFile << EC.message();
  616. return nullptr;
  617. }
  618. LinkModuleToUse = ModuleOrErr.get().release();
  619. }
  620. CoverageSourceInfo *CoverageInfo = nullptr;
  621. // Add the preprocessor callback only when the coverage mapping is generated.
  622. if (CI.getCodeGenOpts().CoverageMapping) {
  623. CoverageInfo = new CoverageSourceInfo;
  624. CI.getPreprocessor().addPPCallbacks(
  625. std::unique_ptr<PPCallbacks>(CoverageInfo));
  626. }
  627. std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
  628. BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
  629. CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
  630. CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
  631. LinkModuleToUse, OS, *VMContext, CoverageInfo));
  632. BEConsumer = Result.get();
  633. return std::move(Result);
  634. }
  635. static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
  636. void *Context,
  637. unsigned LocCookie) {
  638. SM.print(nullptr, llvm::errs());
  639. }
  640. void CodeGenAction::ExecuteAction() {
  641. // If this is an IR file, we have to treat it specially.
  642. if (getCurrentFileKind() == IK_LLVM_IR) {
  643. BackendAction BA = static_cast<BackendAction>(Act);
  644. CompilerInstance &CI = getCompilerInstance();
  645. raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
  646. if (BA != Backend_EmitNothing && !OS)
  647. return;
  648. bool Invalid;
  649. SourceManager &SM = CI.getSourceManager();
  650. FileID FID = SM.getMainFileID();
  651. llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
  652. if (Invalid)
  653. return;
  654. llvm::SMDiagnostic Err;
  655. TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
  656. if (!TheModule) {
  657. // Translate from the diagnostic info to the SourceManager location if
  658. // available.
  659. // TODO: Unify this with ConvertBackendLocation()
  660. SourceLocation Loc;
  661. if (Err.getLineNo() > 0) {
  662. assert(Err.getColumnNo() >= 0);
  663. Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
  664. Err.getLineNo(), Err.getColumnNo() + 1);
  665. }
  666. // Strip off a leading diagnostic code if there is one.
  667. StringRef Msg = Err.getMessage();
  668. if (Msg.startswith("error: "))
  669. Msg = Msg.substr(7);
  670. unsigned DiagID =
  671. CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  672. CI.getDiagnostics().Report(Loc, DiagID) << Msg;
  673. return;
  674. }
  675. const TargetOptions &TargetOpts = CI.getTargetOpts();
  676. if (TheModule->getTargetTriple() != TargetOpts.Triple) {
  677. CI.getDiagnostics().Report(SourceLocation(),
  678. diag::warn_fe_override_module)
  679. << TargetOpts.Triple;
  680. TheModule->setTargetTriple(TargetOpts.Triple);
  681. }
  682. LLVMContext &Ctx = TheModule->getContext();
  683. Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler);
  684. EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
  685. CI.getLangOpts(), CI.getTarget().getTargetDescription(),
  686. TheModule.get(), BA, OS);
  687. return;
  688. }
  689. // Otherwise follow the normal AST path.
  690. this->ASTFrontendAction::ExecuteAction();
  691. }
  692. //
  693. void EmitAssemblyAction::anchor() { }
  694. EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
  695. : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
  696. void EmitBCAction::anchor() { }
  697. EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
  698. : CodeGenAction(Backend_EmitBC, _VMContext) {}
  699. void EmitLLVMAction::anchor() { }
  700. EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
  701. : CodeGenAction(Backend_EmitLL, _VMContext) {}
  702. void EmitLLVMOnlyAction::anchor() { }
  703. EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
  704. : CodeGenAction(Backend_EmitNothing, _VMContext) {}
  705. void EmitCodeGenOnlyAction::anchor() { }
  706. EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
  707. : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
  708. void EmitObjAction::anchor() { }
  709. EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
  710. : CodeGenAction(Backend_EmitObj, _VMContext) {}
  711. // HLSL Change Starts
  712. void EmitOptDumpAction::anchor() { }
  713. EmitOptDumpAction::EmitOptDumpAction(llvm::LLVMContext *_VMContext)
  714. : CodeGenAction(Backend_EmitPasses, _VMContext) {}
  715. // HLSL Change Ends