CodeGenAction.cpp 41 KB

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