CodeGenAction.cpp 46 KB

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