CodeGenAction.cpp 36 KB

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