CodeGenAction.cpp 34 KB

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