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