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