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