CodeGenAction.cpp 28 KB

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