CodeGenAction.cpp 38 KB

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