CodeGenAction.cpp 28 KB

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