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