CodeGenAction.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  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, prompt for debug flag
  476. // and add function name to give some information
  477. if (Loc.isInvalid()) {
  478. Message += " Use /Zi for source location.";
  479. auto *DiagClient = dynamic_cast<TextDiagnosticPrinter*>(Diags.getClient());
  480. auto *func = D.getFunction();
  481. if (DiagClient && func)
  482. DiagClient->setPrefix("Function: " + func->getName().str());
  483. }
  484. Diags.Report(Loc, DiagID).AddString(Message);
  485. return true;
  486. }
  487. // HLSL Change end - Dxil Diagnostic Info reporter
  488. /// \brief This function is invoked when the backend needs
  489. /// to report something to the user.
  490. void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
  491. unsigned DiagID = diag::err_fe_inline_asm;
  492. llvm::DiagnosticSeverity Severity = DI.getSeverity();
  493. // Get the diagnostic ID based.
  494. switch (DI.getKind()) {
  495. case llvm::DK_InlineAsm:
  496. if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
  497. return;
  498. ComputeDiagID(Severity, inline_asm, DiagID);
  499. break;
  500. case llvm::DK_StackSize:
  501. if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
  502. return;
  503. ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
  504. break;
  505. case llvm::DK_OptimizationRemark:
  506. // Optimization remarks are always handled completely by this
  507. // handler. There is no generic way of emitting them.
  508. OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
  509. return;
  510. case llvm::DK_OptimizationRemarkMissed:
  511. // Optimization remarks are always handled completely by this
  512. // handler. There is no generic way of emitting them.
  513. OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
  514. return;
  515. case llvm::DK_OptimizationRemarkAnalysis:
  516. // Optimization remarks are always handled completely by this
  517. // handler. There is no generic way of emitting them.
  518. OptimizationRemarkHandler(
  519. cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
  520. return;
  521. case llvm::DK_OptimizationFailure:
  522. // Optimization failures are always handled completely by this
  523. // handler.
  524. OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
  525. return;
  526. // HLSL Change start - Dxil Diagnostic Info reporter
  527. case llvm::DK_DXIL:
  528. if (DxilDiagHandler(cast<DiagnosticInfoDxil>(DI)))
  529. return;
  530. ComputeDiagID(Severity, inline_asm, DiagID);
  531. break;
  532. // HLSL Change end - Dxil Diagnostic Info reporter
  533. default:
  534. // Plugin IDs are not bound to any value as they are set dynamically.
  535. ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
  536. break;
  537. }
  538. std::string MsgStorage;
  539. {
  540. raw_string_ostream Stream(MsgStorage);
  541. DiagnosticPrinterRawOStream DP(Stream);
  542. DI.print(DP);
  543. }
  544. // Report the backend message using the usual diagnostic mechanism.
  545. FullSourceLoc Loc;
  546. Diags.Report(Loc, DiagID).AddString(MsgStorage);
  547. }
  548. #undef ComputeDiagID
  549. CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
  550. : Act(_Act), LinkModule(nullptr),
  551. VMContext(_VMContext ? _VMContext : new LLVMContext),
  552. OwnsVMContext(!_VMContext) {}
  553. CodeGenAction::~CodeGenAction() {
  554. TheModule.reset();
  555. if (OwnsVMContext)
  556. delete VMContext;
  557. }
  558. bool CodeGenAction::hasIRSupport() const { return true; }
  559. void CodeGenAction::EndSourceFileAction() {
  560. // If the consumer creation failed, do nothing.
  561. if (!getCompilerInstance().hasASTConsumer())
  562. return;
  563. // If we were given a link module, release consumer's ownership of it.
  564. if (LinkModule)
  565. BEConsumer->takeLinkModule();
  566. // Steal the module from the consumer.
  567. TheModule = BEConsumer->takeModule();
  568. }
  569. std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
  570. return std::move(TheModule);
  571. }
  572. llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
  573. OwnsVMContext = false;
  574. return VMContext;
  575. }
  576. static raw_pwrite_stream *
  577. GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
  578. switch (Action) {
  579. case Backend_EmitAssembly:
  580. return CI.createDefaultOutputFile(false, InFile, "s");
  581. case Backend_EmitLL:
  582. return CI.createDefaultOutputFile(false, InFile, "ll");
  583. case Backend_EmitBC:
  584. return CI.createDefaultOutputFile(true, InFile, "bc");
  585. case Backend_EmitPasses:
  586. return CI.createDefaultOutputFile(true, InFile, "passes.txt");
  587. case Backend_EmitNothing:
  588. return nullptr;
  589. case Backend_EmitMCNull:
  590. return CI.createNullOutputFile();
  591. case Backend_EmitObj:
  592. return CI.createDefaultOutputFile(true, InFile, "o");
  593. }
  594. llvm_unreachable("Invalid action!");
  595. }
  596. std::unique_ptr<ASTConsumer>
  597. CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  598. BackendAction BA = static_cast<BackendAction>(Act);
  599. raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
  600. if (BA != Backend_EmitNothing && !OS)
  601. return nullptr;
  602. llvm::Module *LinkModuleToUse = LinkModule;
  603. // If we were not given a link module, and the user requested that one be
  604. // loaded from bitcode, do so now.
  605. const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
  606. if (!LinkModuleToUse && !LinkBCFile.empty()) {
  607. auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
  608. if (!BCBuf) {
  609. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  610. << LinkBCFile << BCBuf.getError().message();
  611. return nullptr;
  612. }
  613. ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
  614. getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
  615. if (std::error_code EC = ModuleOrErr.getError()) {
  616. CI.getDiagnostics().Report(diag::err_cannot_open_file)
  617. << LinkBCFile << EC.message();
  618. return nullptr;
  619. }
  620. LinkModuleToUse = ModuleOrErr.get().release();
  621. }
  622. CoverageSourceInfo *CoverageInfo = nullptr;
  623. // Add the preprocessor callback only when the coverage mapping is generated.
  624. if (CI.getCodeGenOpts().CoverageMapping) {
  625. CoverageInfo = new CoverageSourceInfo;
  626. CI.getPreprocessor().addPPCallbacks(
  627. std::unique_ptr<PPCallbacks>(CoverageInfo));
  628. }
  629. std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
  630. BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
  631. CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
  632. CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
  633. LinkModuleToUse, OS, *VMContext, CoverageInfo));
  634. BEConsumer = Result.get();
  635. return std::move(Result);
  636. }
  637. static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
  638. void *Context,
  639. unsigned LocCookie) {
  640. SM.print(nullptr, llvm::errs());
  641. }
  642. void CodeGenAction::ExecuteAction() {
  643. // If this is an IR file, we have to treat it specially.
  644. if (getCurrentFileKind() == IK_LLVM_IR) {
  645. BackendAction BA = static_cast<BackendAction>(Act);
  646. CompilerInstance &CI = getCompilerInstance();
  647. raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
  648. if (BA != Backend_EmitNothing && !OS)
  649. return;
  650. bool Invalid;
  651. SourceManager &SM = CI.getSourceManager();
  652. FileID FID = SM.getMainFileID();
  653. llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
  654. if (Invalid)
  655. return;
  656. llvm::SMDiagnostic Err;
  657. TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
  658. if (!TheModule) {
  659. // Translate from the diagnostic info to the SourceManager location if
  660. // available.
  661. // TODO: Unify this with ConvertBackendLocation()
  662. SourceLocation Loc;
  663. if (Err.getLineNo() > 0) {
  664. assert(Err.getColumnNo() >= 0);
  665. Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
  666. Err.getLineNo(), Err.getColumnNo() + 1);
  667. }
  668. // Strip off a leading diagnostic code if there is one.
  669. StringRef Msg = Err.getMessage();
  670. if (Msg.startswith("error: "))
  671. Msg = Msg.substr(7);
  672. unsigned DiagID =
  673. CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  674. CI.getDiagnostics().Report(Loc, DiagID) << Msg;
  675. return;
  676. }
  677. const TargetOptions &TargetOpts = CI.getTargetOpts();
  678. if (TheModule->getTargetTriple() != TargetOpts.Triple) {
  679. CI.getDiagnostics().Report(SourceLocation(),
  680. diag::warn_fe_override_module)
  681. << TargetOpts.Triple;
  682. TheModule->setTargetTriple(TargetOpts.Triple);
  683. }
  684. LLVMContext &Ctx = TheModule->getContext();
  685. Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler);
  686. EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
  687. CI.getLangOpts(), CI.getTarget().getTargetDescription(),
  688. TheModule.get(), BA, OS);
  689. return;
  690. }
  691. // Otherwise follow the normal AST path.
  692. this->ASTFrontendAction::ExecuteAction();
  693. }
  694. //
  695. void EmitAssemblyAction::anchor() { }
  696. EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
  697. : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
  698. void EmitBCAction::anchor() { }
  699. EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
  700. : CodeGenAction(Backend_EmitBC, _VMContext) {}
  701. void EmitLLVMAction::anchor() { }
  702. EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
  703. : CodeGenAction(Backend_EmitLL, _VMContext) {}
  704. void EmitLLVMOnlyAction::anchor() { }
  705. EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
  706. : CodeGenAction(Backend_EmitNothing, _VMContext) {}
  707. void EmitCodeGenOnlyAction::anchor() { }
  708. EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
  709. : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
  710. void EmitObjAction::anchor() { }
  711. EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
  712. : CodeGenAction(Backend_EmitObj, _VMContext) {}
  713. // HLSL Change Starts
  714. void EmitOptDumpAction::anchor() { }
  715. EmitOptDumpAction::EmitOptDumpAction(llvm::LLVMContext *_VMContext)
  716. : CodeGenAction(Backend_EmitPasses, _VMContext) {}
  717. // HLSL Change Ends