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