xref: /freebsd-src/contrib/llvm-project/clang/lib/CodeGen/CodeGenAction.cpp (revision fcaf7f8644a9988098ac6be2165bce3ea4786e91)
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       if (CodeGenOpts.MisExpect) {
344         Ctx.setMisExpectWarningRequested(true);
345       }
346 
347       if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
348         Ctx.setDiagnosticsMisExpectTolerance(
349             CodeGenOpts.DiagnosticsMisExpectTolerance);
350       }
351 
352       // Link each LinkModule into our module.
353       if (LinkInModules())
354         return;
355 
356       for (auto &F : getModule()->functions()) {
357         if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
358           auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
359           // TODO: use a fast content hash when available.
360           auto NameHash = llvm::hash_value(F.getName());
361           ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
362         }
363       }
364 
365       if (CodeGenOpts.ClearASTBeforeBackend) {
366         LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
367         // Access to the AST is no longer available after this.
368         // Other things that the ASTContext manages are still available, e.g.
369         // the SourceManager. It'd be nice if we could separate out all the
370         // things in ASTContext used after this point and null out the
371         // ASTContext, but too many various parts of the ASTContext are still
372         // used in various parts.
373         C.cleanup();
374         C.getAllocator().Reset();
375       }
376 
377       EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
378 
379       EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
380                         LangOpts, C.getTargetInfo().getDataLayoutString(),
381                         getModule(), Action, std::move(AsmOutStream));
382 
383       Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
384 
385       if (OptRecordFile)
386         OptRecordFile->keep();
387     }
388 
389     void HandleTagDeclDefinition(TagDecl *D) override {
390       PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
391                                      Context->getSourceManager(),
392                                      "LLVM IR generation of declaration");
393       Gen->HandleTagDeclDefinition(D);
394     }
395 
396     void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
397       Gen->HandleTagDeclRequiredDefinition(D);
398     }
399 
400     void CompleteTentativeDefinition(VarDecl *D) override {
401       Gen->CompleteTentativeDefinition(D);
402     }
403 
404     void CompleteExternalDeclaration(VarDecl *D) override {
405       Gen->CompleteExternalDeclaration(D);
406     }
407 
408     void AssignInheritanceModel(CXXRecordDecl *RD) override {
409       Gen->AssignInheritanceModel(RD);
410     }
411 
412     void HandleVTable(CXXRecordDecl *RD) override {
413       Gen->HandleVTable(RD);
414     }
415 
416     /// Get the best possible source location to represent a diagnostic that
417     /// may have associated debug info.
418     const FullSourceLoc
419     getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
420                                 bool &BadDebugInfo, StringRef &Filename,
421                                 unsigned &Line, unsigned &Column) const;
422 
423     Optional<FullSourceLoc> getFunctionSourceLocation(const Function &F) const;
424 
425     void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
426     /// Specialized handler for InlineAsm diagnostic.
427     /// \return True if the diagnostic has been successfully reported, false
428     /// otherwise.
429     bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
430     /// Specialized handler for diagnostics reported using SMDiagnostic.
431     void SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &D);
432     /// Specialized handler for StackSize diagnostic.
433     /// \return True if the diagnostic has been successfully reported, false
434     /// otherwise.
435     bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
436     /// Specialized handler for unsupported backend feature diagnostic.
437     void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
438     /// Specialized handlers for optimization remarks.
439     /// Note that these handlers only accept remarks and they always handle
440     /// them.
441     void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
442                                  unsigned DiagID);
443     void
444     OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
445     void OptimizationRemarkHandler(
446         const llvm::OptimizationRemarkAnalysisFPCommute &D);
447     void OptimizationRemarkHandler(
448         const llvm::OptimizationRemarkAnalysisAliasing &D);
449     void OptimizationFailureHandler(
450         const llvm::DiagnosticInfoOptimizationFailure &D);
451     void DontCallDiagHandler(const DiagnosticInfoDontCall &D);
452     /// Specialized handler for misexpect warnings.
453     /// Note that misexpect remarks are emitted through ORE
454     void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D);
455   };
456 
457   void BackendConsumer::anchor() {}
458 }
459 
460 bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
461   BackendCon->DiagnosticHandlerImpl(DI);
462   return true;
463 }
464 
465 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
466 /// buffer to be a valid FullSourceLoc.
467 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
468                                             SourceManager &CSM) {
469   // Get both the clang and llvm source managers.  The location is relative to
470   // a memory buffer that the LLVM Source Manager is handling, we need to add
471   // a copy to the Clang source manager.
472   const llvm::SourceMgr &LSM = *D.getSourceMgr();
473 
474   // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
475   // already owns its one and clang::SourceManager wants to own its one.
476   const MemoryBuffer *LBuf =
477   LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
478 
479   // Create the copy and transfer ownership to clang::SourceManager.
480   // TODO: Avoid copying files into memory.
481   std::unique_ptr<llvm::MemoryBuffer> CBuf =
482       llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
483                                            LBuf->getBufferIdentifier());
484   // FIXME: Keep a file ID map instead of creating new IDs for each location.
485   FileID FID = CSM.createFileID(std::move(CBuf));
486 
487   // Translate the offset into the file.
488   unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
489   SourceLocation NewLoc =
490   CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
491   return FullSourceLoc(NewLoc, CSM);
492 }
493 
494 #define ComputeDiagID(Severity, GroupName, DiagID)                             \
495   do {                                                                         \
496     switch (Severity) {                                                        \
497     case llvm::DS_Error:                                                       \
498       DiagID = diag::err_fe_##GroupName;                                       \
499       break;                                                                   \
500     case llvm::DS_Warning:                                                     \
501       DiagID = diag::warn_fe_##GroupName;                                      \
502       break;                                                                   \
503     case llvm::DS_Remark:                                                      \
504       llvm_unreachable("'remark' severity not expected");                      \
505       break;                                                                   \
506     case llvm::DS_Note:                                                        \
507       DiagID = diag::note_fe_##GroupName;                                      \
508       break;                                                                   \
509     }                                                                          \
510   } while (false)
511 
512 #define ComputeDiagRemarkID(Severity, GroupName, DiagID)                       \
513   do {                                                                         \
514     switch (Severity) {                                                        \
515     case llvm::DS_Error:                                                       \
516       DiagID = diag::err_fe_##GroupName;                                       \
517       break;                                                                   \
518     case llvm::DS_Warning:                                                     \
519       DiagID = diag::warn_fe_##GroupName;                                      \
520       break;                                                                   \
521     case llvm::DS_Remark:                                                      \
522       DiagID = diag::remark_fe_##GroupName;                                    \
523       break;                                                                   \
524     case llvm::DS_Note:                                                        \
525       DiagID = diag::note_fe_##GroupName;                                      \
526       break;                                                                   \
527     }                                                                          \
528   } while (false)
529 
530 void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) {
531   const llvm::SMDiagnostic &D = DI.getSMDiag();
532 
533   unsigned DiagID;
534   if (DI.isInlineAsmDiag())
535     ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);
536   else
537     ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);
538 
539   // This is for the empty BackendConsumer that uses the clang diagnostic
540   // handler for IR input files.
541   if (!Context) {
542     D.print(nullptr, llvm::errs());
543     Diags.Report(DiagID).AddString("cannot compile inline asm");
544     return;
545   }
546 
547   // There are a couple of different kinds of errors we could get here.
548   // First, we re-format the SMDiagnostic in terms of a clang diagnostic.
549 
550   // Strip "error: " off the start of the message string.
551   StringRef Message = D.getMessage();
552   (void)Message.consume_front("error: ");
553 
554   // If the SMDiagnostic has an inline asm source location, translate it.
555   FullSourceLoc Loc;
556   if (D.getLoc() != SMLoc())
557     Loc = ConvertBackendLocation(D, Context->getSourceManager());
558 
559   // If this problem has clang-level source location information, report the
560   // issue in the source with a note showing the instantiated
561   // code.
562   if (DI.isInlineAsmDiag()) {
563     SourceLocation LocCookie =
564         SourceLocation::getFromRawEncoding(DI.getLocCookie());
565     if (LocCookie.isValid()) {
566       Diags.Report(LocCookie, DiagID).AddString(Message);
567 
568       if (D.getLoc().isValid()) {
569         DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
570         // Convert the SMDiagnostic ranges into SourceRange and attach them
571         // to the diagnostic.
572         for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
573           unsigned Column = D.getColumnNo();
574           B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
575                            Loc.getLocWithOffset(Range.second - Column));
576         }
577       }
578       return;
579     }
580   }
581 
582   // Otherwise, report the backend issue as occurring in the generated .s file.
583   // If Loc is invalid, we still need to report the issue, it just gets no
584   // location info.
585   Diags.Report(Loc, DiagID).AddString(Message);
586 }
587 
588 bool
589 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
590   unsigned DiagID;
591   ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
592   std::string Message = D.getMsgStr().str();
593 
594   // If this problem has clang-level source location information, report the
595   // issue as being a problem in the source with a note showing the instantiated
596   // code.
597   SourceLocation LocCookie =
598       SourceLocation::getFromRawEncoding(D.getLocCookie());
599   if (LocCookie.isValid())
600     Diags.Report(LocCookie, DiagID).AddString(Message);
601   else {
602     // Otherwise, report the backend diagnostic as occurring in the generated
603     // .s file.
604     // If Loc is invalid, we still need to report the diagnostic, it just gets
605     // no location info.
606     FullSourceLoc Loc;
607     Diags.Report(Loc, DiagID).AddString(Message);
608   }
609   // We handled all the possible severities.
610   return true;
611 }
612 
613 bool
614 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
615   if (D.getSeverity() != llvm::DS_Warning)
616     // For now, the only support we have for StackSize diagnostic is warning.
617     // We do not know how to format other severities.
618     return false;
619 
620   auto Loc = getFunctionSourceLocation(D.getFunction());
621   if (!Loc)
622     return false;
623 
624   // FIXME: Shouldn't need to truncate to uint32_t
625   Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
626       << static_cast<uint32_t>(D.getStackSize())
627       << static_cast<uint32_t>(D.getStackLimit())
628       << llvm::demangle(D.getFunction().getName().str());
629   return true;
630 }
631 
632 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
633     const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
634     StringRef &Filename, unsigned &Line, unsigned &Column) const {
635   SourceManager &SourceMgr = Context->getSourceManager();
636   FileManager &FileMgr = SourceMgr.getFileManager();
637   SourceLocation DILoc;
638 
639   if (D.isLocationAvailable()) {
640     D.getLocation(Filename, Line, Column);
641     if (Line > 0) {
642       auto FE = FileMgr.getFile(Filename);
643       if (!FE)
644         FE = FileMgr.getFile(D.getAbsolutePath());
645       if (FE) {
646         // If -gcolumn-info was not used, Column will be 0. This upsets the
647         // source manager, so pass 1 if Column is not set.
648         DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);
649       }
650     }
651     BadDebugInfo = DILoc.isInvalid();
652   }
653 
654   // If a location isn't available, try to approximate it using the associated
655   // function definition. We use the definition's right brace to differentiate
656   // from diagnostics that genuinely relate to the function itself.
657   FullSourceLoc Loc(DILoc, SourceMgr);
658   if (Loc.isInvalid()) {
659     if (auto MaybeLoc = getFunctionSourceLocation(D.getFunction()))
660       Loc = *MaybeLoc;
661   }
662 
663   if (DILoc.isInvalid() && D.isLocationAvailable())
664     // If we were not able to translate the file:line:col information
665     // back to a SourceLocation, at least emit a note stating that
666     // we could not translate this location. This can happen in the
667     // case of #line directives.
668     Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
669         << Filename << Line << Column;
670 
671   return Loc;
672 }
673 
674 Optional<FullSourceLoc>
675 BackendConsumer::getFunctionSourceLocation(const Function &F) const {
676   auto Hash = llvm::hash_value(F.getName());
677   for (const auto &Pair : ManglingFullSourceLocs) {
678     if (Pair.first == Hash)
679       return Pair.second;
680   }
681   return Optional<FullSourceLoc>();
682 }
683 
684 void BackendConsumer::UnsupportedDiagHandler(
685     const llvm::DiagnosticInfoUnsupported &D) {
686   // We only support warnings or errors.
687   assert(D.getSeverity() == llvm::DS_Error ||
688          D.getSeverity() == llvm::DS_Warning);
689 
690   StringRef Filename;
691   unsigned Line, Column;
692   bool BadDebugInfo = false;
693   FullSourceLoc Loc;
694   std::string Msg;
695   raw_string_ostream MsgStream(Msg);
696 
697   // Context will be nullptr for IR input files, we will construct the diag
698   // message from llvm::DiagnosticInfoUnsupported.
699   if (Context != nullptr) {
700     Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
701     MsgStream << D.getMessage();
702   } else {
703     DiagnosticPrinterRawOStream DP(MsgStream);
704     D.print(DP);
705   }
706 
707   auto DiagType = D.getSeverity() == llvm::DS_Error
708                       ? diag::err_fe_backend_unsupported
709                       : diag::warn_fe_backend_unsupported;
710   Diags.Report(Loc, DiagType) << MsgStream.str();
711 
712   if (BadDebugInfo)
713     // If we were not able to translate the file:line:col information
714     // back to a SourceLocation, at least emit a note stating that
715     // we could not translate this location. This can happen in the
716     // case of #line directives.
717     Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
718         << Filename << Line << Column;
719 }
720 
721 void BackendConsumer::EmitOptimizationMessage(
722     const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
723   // We only support warnings and remarks.
724   assert(D.getSeverity() == llvm::DS_Remark ||
725          D.getSeverity() == llvm::DS_Warning);
726 
727   StringRef Filename;
728   unsigned Line, Column;
729   bool BadDebugInfo = false;
730   FullSourceLoc Loc;
731   std::string Msg;
732   raw_string_ostream MsgStream(Msg);
733 
734   // Context will be nullptr for IR input files, we will construct the remark
735   // message from llvm::DiagnosticInfoOptimizationBase.
736   if (Context != nullptr) {
737     Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
738     MsgStream << D.getMsg();
739   } else {
740     DiagnosticPrinterRawOStream DP(MsgStream);
741     D.print(DP);
742   }
743 
744   if (D.getHotness())
745     MsgStream << " (hotness: " << *D.getHotness() << ")";
746 
747   Diags.Report(Loc, DiagID)
748       << AddFlagValue(D.getPassName())
749       << MsgStream.str();
750 
751   if (BadDebugInfo)
752     // If we were not able to translate the file:line:col information
753     // back to a SourceLocation, at least emit a note stating that
754     // we could not translate this location. This can happen in the
755     // case of #line directives.
756     Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
757         << Filename << Line << Column;
758 }
759 
760 void BackendConsumer::OptimizationRemarkHandler(
761     const llvm::DiagnosticInfoOptimizationBase &D) {
762   // Without hotness information, don't show noisy remarks.
763   if (D.isVerbose() && !D.getHotness())
764     return;
765 
766   if (D.isPassed()) {
767     // Optimization remarks are active only if the -Rpass flag has a regular
768     // expression that matches the name of the pass name in \p D.
769     if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
770       EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
771   } else if (D.isMissed()) {
772     // Missed optimization remarks are active only if the -Rpass-missed
773     // flag has a regular expression that matches the name of the pass
774     // name in \p D.
775     if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
776       EmitOptimizationMessage(
777           D, diag::remark_fe_backend_optimization_remark_missed);
778   } else {
779     assert(D.isAnalysis() && "Unknown remark type");
780 
781     bool ShouldAlwaysPrint = false;
782     if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
783       ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
784 
785     if (ShouldAlwaysPrint ||
786         CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
787       EmitOptimizationMessage(
788           D, diag::remark_fe_backend_optimization_remark_analysis);
789   }
790 }
791 
792 void BackendConsumer::OptimizationRemarkHandler(
793     const llvm::OptimizationRemarkAnalysisFPCommute &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_fpcommute);
802 }
803 
804 void BackendConsumer::OptimizationRemarkHandler(
805     const llvm::OptimizationRemarkAnalysisAliasing &D) {
806   // Optimization analysis remarks are active if the pass name is set to
807   // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
808   // regular expression that matches the name of the pass name in \p D.
809 
810   if (D.shouldAlwaysPrint() ||
811       CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
812     EmitOptimizationMessage(
813         D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
814 }
815 
816 void BackendConsumer::OptimizationFailureHandler(
817     const llvm::DiagnosticInfoOptimizationFailure &D) {
818   EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
819 }
820 
821 void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) {
822   SourceLocation LocCookie =
823       SourceLocation::getFromRawEncoding(D.getLocCookie());
824 
825   // FIXME: we can't yet diagnose indirect calls. When/if we can, we
826   // should instead assert that LocCookie.isValid().
827   if (!LocCookie.isValid())
828     return;
829 
830   Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
831                               ? diag::err_fe_backend_error_attr
832                               : diag::warn_fe_backend_warning_attr)
833       << llvm::demangle(D.getFunctionName().str()) << D.getNote();
834 }
835 
836 void BackendConsumer::MisExpectDiagHandler(
837     const llvm::DiagnosticInfoMisExpect &D) {
838   StringRef Filename;
839   unsigned Line, Column;
840   bool BadDebugInfo = false;
841   FullSourceLoc Loc =
842       getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
843 
844   Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
845 
846   if (BadDebugInfo)
847     // If we were not able to translate the file:line:col information
848     // back to a SourceLocation, at least emit a note stating that
849     // we could not translate this location. This can happen in the
850     // case of #line directives.
851     Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
852         << Filename << Line << Column;
853 }
854 
855 /// This function is invoked when the backend needs
856 /// to report something to the user.
857 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
858   unsigned DiagID = diag::err_fe_inline_asm;
859   llvm::DiagnosticSeverity Severity = DI.getSeverity();
860   // Get the diagnostic ID based.
861   switch (DI.getKind()) {
862   case llvm::DK_InlineAsm:
863     if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
864       return;
865     ComputeDiagID(Severity, inline_asm, DiagID);
866     break;
867   case llvm::DK_SrcMgr:
868     SrcMgrDiagHandler(cast<DiagnosticInfoSrcMgr>(DI));
869     return;
870   case llvm::DK_StackSize:
871     if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
872       return;
873     ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
874     break;
875   case DK_Linker:
876     ComputeDiagID(Severity, linking_module, DiagID);
877     break;
878   case llvm::DK_OptimizationRemark:
879     // Optimization remarks are always handled completely by this
880     // handler. There is no generic way of emitting them.
881     OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
882     return;
883   case llvm::DK_OptimizationRemarkMissed:
884     // Optimization remarks are always handled completely by this
885     // handler. There is no generic way of emitting them.
886     OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
887     return;
888   case llvm::DK_OptimizationRemarkAnalysis:
889     // Optimization remarks are always handled completely by this
890     // handler. There is no generic way of emitting them.
891     OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
892     return;
893   case llvm::DK_OptimizationRemarkAnalysisFPCommute:
894     // Optimization remarks are always handled completely by this
895     // handler. There is no generic way of emitting them.
896     OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
897     return;
898   case llvm::DK_OptimizationRemarkAnalysisAliasing:
899     // Optimization remarks are always handled completely by this
900     // handler. There is no generic way of emitting them.
901     OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
902     return;
903   case llvm::DK_MachineOptimizationRemark:
904     // Optimization remarks are always handled completely by this
905     // handler. There is no generic way of emitting them.
906     OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
907     return;
908   case llvm::DK_MachineOptimizationRemarkMissed:
909     // Optimization remarks are always handled completely by this
910     // handler. There is no generic way of emitting them.
911     OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
912     return;
913   case llvm::DK_MachineOptimizationRemarkAnalysis:
914     // Optimization remarks are always handled completely by this
915     // handler. There is no generic way of emitting them.
916     OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
917     return;
918   case llvm::DK_OptimizationFailure:
919     // Optimization failures are always handled completely by this
920     // handler.
921     OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
922     return;
923   case llvm::DK_Unsupported:
924     UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
925     return;
926   case llvm::DK_DontCall:
927     DontCallDiagHandler(cast<DiagnosticInfoDontCall>(DI));
928     return;
929   case llvm::DK_MisExpect:
930     MisExpectDiagHandler(cast<DiagnosticInfoMisExpect>(DI));
931     return;
932   default:
933     // Plugin IDs are not bound to any value as they are set dynamically.
934     ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
935     break;
936   }
937   std::string MsgStorage;
938   {
939     raw_string_ostream Stream(MsgStorage);
940     DiagnosticPrinterRawOStream DP(Stream);
941     DI.print(DP);
942   }
943 
944   if (DI.getKind() == DK_Linker) {
945     assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");
946     Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
947     return;
948   }
949 
950   // Report the backend message using the usual diagnostic mechanism.
951   FullSourceLoc Loc;
952   Diags.Report(Loc, DiagID).AddString(MsgStorage);
953 }
954 #undef ComputeDiagID
955 
956 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
957     : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
958       OwnsVMContext(!_VMContext) {}
959 
960 CodeGenAction::~CodeGenAction() {
961   TheModule.reset();
962   if (OwnsVMContext)
963     delete VMContext;
964 }
965 
966 bool CodeGenAction::hasIRSupport() const { return true; }
967 
968 void CodeGenAction::EndSourceFileAction() {
969   // If the consumer creation failed, do nothing.
970   if (!getCompilerInstance().hasASTConsumer())
971     return;
972 
973   // Steal the module from the consumer.
974   TheModule = BEConsumer->takeModule();
975 }
976 
977 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
978   return std::move(TheModule);
979 }
980 
981 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
982   OwnsVMContext = false;
983   return VMContext;
984 }
985 
986 CodeGenerator *CodeGenAction::getCodeGenerator() const {
987   return BEConsumer->getCodeGenerator();
988 }
989 
990 static std::unique_ptr<raw_pwrite_stream>
991 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
992   switch (Action) {
993   case Backend_EmitAssembly:
994     return CI.createDefaultOutputFile(false, InFile, "s");
995   case Backend_EmitLL:
996     return CI.createDefaultOutputFile(false, InFile, "ll");
997   case Backend_EmitBC:
998     return CI.createDefaultOutputFile(true, InFile, "bc");
999   case Backend_EmitNothing:
1000     return nullptr;
1001   case Backend_EmitMCNull:
1002     return CI.createNullOutputFile();
1003   case Backend_EmitObj:
1004     return CI.createDefaultOutputFile(true, InFile, "o");
1005   }
1006 
1007   llvm_unreachable("Invalid action!");
1008 }
1009 
1010 std::unique_ptr<ASTConsumer>
1011 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
1012   BackendAction BA = static_cast<BackendAction>(Act);
1013   std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
1014   if (!OS)
1015     OS = GetOutputStream(CI, InFile, BA);
1016 
1017   if (BA != Backend_EmitNothing && !OS)
1018     return nullptr;
1019 
1020   VMContext->setOpaquePointers(CI.getCodeGenOpts().OpaquePointers);
1021 
1022   // Load bitcode modules to link with, if we need to.
1023   if (LinkModules.empty())
1024     for (const CodeGenOptions::BitcodeFileToLink &F :
1025          CI.getCodeGenOpts().LinkBitcodeFiles) {
1026       auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
1027       if (!BCBuf) {
1028         CI.getDiagnostics().Report(diag::err_cannot_open_file)
1029             << F.Filename << BCBuf.getError().message();
1030         LinkModules.clear();
1031         return nullptr;
1032       }
1033 
1034       Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
1035           getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
1036       if (!ModuleOrErr) {
1037         handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1038           CI.getDiagnostics().Report(diag::err_cannot_open_file)
1039               << F.Filename << EIB.message();
1040         });
1041         LinkModules.clear();
1042         return nullptr;
1043       }
1044       LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
1045                              F.Internalize, F.LinkFlags});
1046     }
1047 
1048   CoverageSourceInfo *CoverageInfo = nullptr;
1049   // Add the preprocessor callback only when the coverage mapping is generated.
1050   if (CI.getCodeGenOpts().CoverageMapping)
1051     CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks(
1052         CI.getPreprocessor());
1053 
1054   std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
1055       BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
1056       CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
1057       CI.getLangOpts(), std::string(InFile), std::move(LinkModules),
1058       std::move(OS), *VMContext, CoverageInfo));
1059   BEConsumer = Result.get();
1060 
1061   // Enable generating macro debug info only when debug info is not disabled and
1062   // also macro debug info is enabled.
1063   if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1064       CI.getCodeGenOpts().MacroDebugInfo) {
1065     std::unique_ptr<PPCallbacks> Callbacks =
1066         std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
1067                                             CI.getPreprocessor());
1068     CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
1069   }
1070 
1071   return std::move(Result);
1072 }
1073 
1074 std::unique_ptr<llvm::Module>
1075 CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1076   CompilerInstance &CI = getCompilerInstance();
1077   SourceManager &SM = CI.getSourceManager();
1078 
1079   // For ThinLTO backend invocations, ensure that the context
1080   // merges types based on ODR identifiers. We also need to read
1081   // the correct module out of a multi-module bitcode file.
1082   if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
1083     VMContext->enableDebugTypeODRUniquing();
1084 
1085     auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1086       unsigned DiagID =
1087           CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1088       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1089         CI.getDiagnostics().Report(DiagID) << EIB.message();
1090       });
1091       return {};
1092     };
1093 
1094     Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1095     if (!BMsOrErr)
1096       return DiagErrors(BMsOrErr.takeError());
1097     BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1098     // We have nothing to do if the file contains no ThinLTO module. This is
1099     // possible if ThinLTO compilation was not able to split module. Content of
1100     // the file was already processed by indexing and will be passed to the
1101     // linker using merged object file.
1102     if (!Bm) {
1103       auto M = std::make_unique<llvm::Module>("empty", *VMContext);
1104       M->setTargetTriple(CI.getTargetOpts().Triple);
1105       return M;
1106     }
1107     Expected<std::unique_ptr<llvm::Module>> MOrErr =
1108         Bm->parseModule(*VMContext);
1109     if (!MOrErr)
1110       return DiagErrors(MOrErr.takeError());
1111     return std::move(*MOrErr);
1112   }
1113 
1114   llvm::SMDiagnostic Err;
1115   if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1116     return M;
1117 
1118   // Translate from the diagnostic info to the SourceManager location if
1119   // available.
1120   // TODO: Unify this with ConvertBackendLocation()
1121   SourceLocation Loc;
1122   if (Err.getLineNo() > 0) {
1123     assert(Err.getColumnNo() >= 0);
1124     Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1125                                   Err.getLineNo(), Err.getColumnNo() + 1);
1126   }
1127 
1128   // Strip off a leading diagnostic code if there is one.
1129   StringRef Msg = Err.getMessage();
1130   if (Msg.startswith("error: "))
1131     Msg = Msg.substr(7);
1132 
1133   unsigned DiagID =
1134       CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1135 
1136   CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1137   return {};
1138 }
1139 
1140 void CodeGenAction::ExecuteAction() {
1141   if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
1142     this->ASTFrontendAction::ExecuteAction();
1143     return;
1144   }
1145 
1146   // If this is an IR file, we have to treat it specially.
1147   BackendAction BA = static_cast<BackendAction>(Act);
1148   CompilerInstance &CI = getCompilerInstance();
1149   auto &CodeGenOpts = CI.getCodeGenOpts();
1150   auto &Diagnostics = CI.getDiagnostics();
1151   std::unique_ptr<raw_pwrite_stream> OS =
1152       GetOutputStream(CI, getCurrentFileOrBufferName(), BA);
1153   if (BA != Backend_EmitNothing && !OS)
1154     return;
1155 
1156   SourceManager &SM = CI.getSourceManager();
1157   FileID FID = SM.getMainFileID();
1158   Optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
1159   if (!MainFile)
1160     return;
1161 
1162   TheModule = loadModule(*MainFile);
1163   if (!TheModule)
1164     return;
1165 
1166   const TargetOptions &TargetOpts = CI.getTargetOpts();
1167   if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1168     Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
1169         << TargetOpts.Triple;
1170     TheModule->setTargetTriple(TargetOpts.Triple);
1171   }
1172 
1173   EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
1174   EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
1175 
1176   LLVMContext &Ctx = TheModule->getContext();
1177 
1178   // Restore any diagnostic handler previously set before returning from this
1179   // function.
1180   struct RAII {
1181     LLVMContext &Ctx;
1182     std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1183     ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1184   } _{Ctx};
1185 
1186   // Set clang diagnostic handler. To do this we need to create a fake
1187   // BackendConsumer.
1188   BackendConsumer Result(BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
1189                          CI.getPreprocessorOpts(), CI.getCodeGenOpts(),
1190                          CI.getTargetOpts(), CI.getLangOpts(), TheModule.get(),
1191                          std::move(LinkModules), *VMContext, nullptr);
1192   // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1193   // true here because the valued names are needed for reading textual IR.
1194   Ctx.setDiscardValueNames(false);
1195   Ctx.setDiagnosticHandler(
1196       std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1197 
1198   Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr =
1199       setupLLVMOptimizationRemarks(
1200           Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1201           CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1202           CodeGenOpts.DiagnosticsHotnessThreshold);
1203 
1204   if (Error E = OptRecordFileOrErr.takeError()) {
1205     reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
1206     return;
1207   }
1208   std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1209       std::move(*OptRecordFileOrErr);
1210 
1211   EmitBackendOutput(Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts,
1212                     TargetOpts, CI.getLangOpts(),
1213                     CI.getTarget().getDataLayoutString(), TheModule.get(), BA,
1214                     std::move(OS));
1215   if (OptRecordFile)
1216     OptRecordFile->keep();
1217 }
1218 
1219 //
1220 
1221 void EmitAssemblyAction::anchor() { }
1222 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1223   : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1224 
1225 void EmitBCAction::anchor() { }
1226 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1227   : CodeGenAction(Backend_EmitBC, _VMContext) {}
1228 
1229 void EmitLLVMAction::anchor() { }
1230 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1231   : CodeGenAction(Backend_EmitLL, _VMContext) {}
1232 
1233 void EmitLLVMOnlyAction::anchor() { }
1234 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1235   : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1236 
1237 void EmitCodeGenOnlyAction::anchor() { }
1238 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1239   : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1240 
1241 void EmitObjAction::anchor() { }
1242 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1243   : CodeGenAction(Backend_EmitObj, _VMContext) {}
1244