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