CodeGenAction.cpp 42 KB

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