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