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:
57     ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
58         : CodeGenOpts(CGOpts), BackendCon(BCon) {}
59 
60     bool handleDiagnostics(const DiagnosticInfo &DI) override;
61 
62     bool isAnalysisRemarkEnabled(StringRef PassName) const override {
63       return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
64     }
65     bool isMissedOptRemarkEnabled(StringRef PassName) const override {
66       return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
67     }
68     bool isPassedOptRemarkEnabled(StringRef PassName) const override {
69       return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
70     }
71 
72     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 
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:
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.
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     }
178     llvm::Module *getModule() const { return Gen->GetModule(); }
179     std::unique_ptr<llvm::Module> takeModule() {
180       return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
181     }
182 
183     CodeGenerator *getCodeGenerator() { return Gen.get(); }
184 
185     void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
186       Gen->HandleCXXStaticMemberVarInstantiation(VD);
187     }
188 
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 
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 
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 
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.
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 
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 
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 
351     void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
352       Gen->HandleTagDeclRequiredDefinition(D);
353     }
354 
355     void CompleteTentativeDefinition(VarDecl *D) override {
356       Gen->CompleteTentativeDefinition(D);
357     }
358 
359     void CompleteExternalDeclaration(VarDecl *D) override {
360       Gen->CompleteExternalDeclaration(D);
361     }
362 
363     void AssignInheritanceModel(CXXRecordDecl *RD) override {
364       Gen->AssignInheritanceModel(RD);
365     }
366 
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 
406   void BackendConsumer::anchor() {}
407 }
408 
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.
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 
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
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
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 
581 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 
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 
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 
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 
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 
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 
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.
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 
858 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
859     : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
860       OwnsVMContext(!_VMContext) {}
861 
862 CodeGenAction::~CodeGenAction() {
863   TheModule.reset();
864   if (OwnsVMContext)
865     delete VMContext;
866 }
867 
868 bool CodeGenAction::hasIRSupport() const { return true; }
869 
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 
879 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
880   return std::move(TheModule);
881 }
882 
883 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
884   OwnsVMContext = false;
885   return VMContext;
886 }
887 
888 static std::unique_ptr<raw_pwrite_stream>
889 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
890   switch (Action) {
891   case Backend_EmitAssembly:
892     return CI.createDefaultOutputFile(false, InFile, "s");
893   case Backend_EmitLL:
894     return CI.createDefaultOutputFile(false, InFile, "ll");
895   case Backend_EmitBC:
896     return CI.createDefaultOutputFile(true, InFile, "bc");
897   case Backend_EmitNothing:
898     return nullptr;
899   case Backend_EmitMCNull:
900     return CI.createNullOutputFile();
901   case Backend_EmitObj:
902     return CI.createDefaultOutputFile(true, InFile, "o");
903   }
904 
905   llvm_unreachable("Invalid action!");
906 }
907 
908 std::unique_ptr<ASTConsumer>
909 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
910   BackendAction BA = static_cast<BackendAction>(Act);
911   std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
912   if (!OS)
913     OS = GetOutputStream(CI, InFile, BA);
914 
915   if (BA != Backend_EmitNothing && !OS)
916     return nullptr;
917 
918   // Load bitcode modules to link with, if we need to.
919   if (LinkModules.empty())
920     for (const CodeGenOptions::BitcodeFileToLink &F :
921          CI.getCodeGenOpts().LinkBitcodeFiles) {
922       auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
923       if (!BCBuf) {
924         CI.getDiagnostics().Report(diag::err_cannot_open_file)
925             << F.Filename << BCBuf.getError().message();
926         LinkModules.clear();
927         return nullptr;
928       }
929 
930       Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
931           getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
932       if (!ModuleOrErr) {
933         handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
934           CI.getDiagnostics().Report(diag::err_cannot_open_file)
935               << F.Filename << EIB.message();
936         });
937         LinkModules.clear();
938         return nullptr;
939       }
940       LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
941                              F.Internalize, F.LinkFlags});
942     }
943 
944   CoverageSourceInfo *CoverageInfo = nullptr;
945   // Add the preprocessor callback only when the coverage mapping is generated.
946   if (CI.getCodeGenOpts().CoverageMapping)
947     CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks(
948         CI.getPreprocessor());
949 
950   std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
951       BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
952       CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
953       CI.getLangOpts(), std::string(InFile), std::move(LinkModules),
954       std::move(OS), *VMContext, CoverageInfo));
955   BEConsumer = Result.get();
956 
957   // Enable generating macro debug info only when debug info is not disabled and
958   // also macro debug info is enabled.
959   if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
960       CI.getCodeGenOpts().MacroDebugInfo) {
961     std::unique_ptr<PPCallbacks> Callbacks =
962         std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
963                                             CI.getPreprocessor());
964     CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
965   }
966 
967   return std::move(Result);
968 }
969 
970 std::unique_ptr<llvm::Module>
971 CodeGenAction::loadModule(MemoryBufferRef MBRef) {
972   CompilerInstance &CI = getCompilerInstance();
973   SourceManager &SM = CI.getSourceManager();
974 
975   // For ThinLTO backend invocations, ensure that the context
976   // merges types based on ODR identifiers. We also need to read
977   // the correct module out of a multi-module bitcode file.
978   if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
979     VMContext->enableDebugTypeODRUniquing();
980 
981     auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
982       unsigned DiagID =
983           CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
984       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
985         CI.getDiagnostics().Report(DiagID) << EIB.message();
986       });
987       return {};
988     };
989 
990     Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
991     if (!BMsOrErr)
992       return DiagErrors(BMsOrErr.takeError());
993     BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
994     // We have nothing to do if the file contains no ThinLTO module. This is
995     // possible if ThinLTO compilation was not able to split module. Content of
996     // the file was already processed by indexing and will be passed to the
997     // linker using merged object file.
998     if (!Bm) {
999       auto M = std::make_unique<llvm::Module>("empty", *VMContext);
1000       M->setTargetTriple(CI.getTargetOpts().Triple);
1001       return M;
1002     }
1003     Expected<std::unique_ptr<llvm::Module>> MOrErr =
1004         Bm->parseModule(*VMContext);
1005     if (!MOrErr)
1006       return DiagErrors(MOrErr.takeError());
1007     return std::move(*MOrErr);
1008   }
1009 
1010   llvm::SMDiagnostic Err;
1011   if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1012     return M;
1013 
1014   // Translate from the diagnostic info to the SourceManager location if
1015   // available.
1016   // TODO: Unify this with ConvertBackendLocation()
1017   SourceLocation Loc;
1018   if (Err.getLineNo() > 0) {
1019     assert(Err.getColumnNo() >= 0);
1020     Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1021                                   Err.getLineNo(), Err.getColumnNo() + 1);
1022   }
1023 
1024   // Strip off a leading diagnostic code if there is one.
1025   StringRef Msg = Err.getMessage();
1026   if (Msg.startswith("error: "))
1027     Msg = Msg.substr(7);
1028 
1029   unsigned DiagID =
1030       CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1031 
1032   CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1033   return {};
1034 }
1035 
1036 void CodeGenAction::ExecuteAction() {
1037   if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
1038     this->ASTFrontendAction::ExecuteAction();
1039     return;
1040   }
1041 
1042   // If this is an IR file, we have to treat it specially.
1043   BackendAction BA = static_cast<BackendAction>(Act);
1044   CompilerInstance &CI = getCompilerInstance();
1045   auto &CodeGenOpts = CI.getCodeGenOpts();
1046   auto &Diagnostics = CI.getDiagnostics();
1047   std::unique_ptr<raw_pwrite_stream> OS =
1048       GetOutputStream(CI, getCurrentFile(), BA);
1049   if (BA != Backend_EmitNothing && !OS)
1050     return;
1051 
1052   SourceManager &SM = CI.getSourceManager();
1053   FileID FID = SM.getMainFileID();
1054   Optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
1055   if (!MainFile)
1056     return;
1057 
1058   TheModule = loadModule(*MainFile);
1059   if (!TheModule)
1060     return;
1061 
1062   const TargetOptions &TargetOpts = CI.getTargetOpts();
1063   if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1064     Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
1065         << TargetOpts.Triple;
1066     TheModule->setTargetTriple(TargetOpts.Triple);
1067   }
1068 
1069   EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
1070 
1071   LLVMContext &Ctx = TheModule->getContext();
1072 
1073   // Restore any diagnostic handler previously set before returning from this
1074   // function.
1075   struct RAII {
1076     LLVMContext &Ctx;
1077     std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1078     ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1079   } _{Ctx};
1080 
1081   // Set clang diagnostic handler. To do this we need to create a fake
1082   // BackendConsumer.
1083   BackendConsumer Result(BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
1084                          CI.getPreprocessorOpts(), CI.getCodeGenOpts(),
1085                          CI.getTargetOpts(), CI.getLangOpts(),
1086                          std::move(LinkModules), *VMContext, nullptr);
1087   // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1088   // true here because the valued names are needed for reading textual IR.
1089   Ctx.setDiscardValueNames(false);
1090   Ctx.setDiagnosticHandler(
1091       std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1092 
1093   Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr =
1094       setupLLVMOptimizationRemarks(
1095           Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1096           CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1097           CodeGenOpts.DiagnosticsHotnessThreshold);
1098 
1099   if (Error E = OptRecordFileOrErr.takeError()) {
1100     reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
1101     return;
1102   }
1103   std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1104       std::move(*OptRecordFileOrErr);
1105 
1106   EmitBackendOutput(Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts,
1107                     TargetOpts, CI.getLangOpts(),
1108                     CI.getTarget().getDataLayoutString(), TheModule.get(), BA,
1109                     std::move(OS));
1110   if (OptRecordFile)
1111     OptRecordFile->keep();
1112 }
1113 
1114 //
1115 
1116 void EmitAssemblyAction::anchor() { }
1117 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1118   : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1119 
1120 void EmitBCAction::anchor() { }
1121 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1122   : CodeGenAction(Backend_EmitBC, _VMContext) {}
1123 
1124 void EmitLLVMAction::anchor() { }
1125 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1126   : CodeGenAction(Backend_EmitLL, _VMContext) {}
1127 
1128 void EmitLLVMOnlyAction::anchor() { }
1129 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1130   : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1131 
1132 void EmitCodeGenOnlyAction::anchor() { }
1133 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1134   : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1135 
1136 void EmitObjAction::anchor() { }
1137 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1138   : CodeGenAction(Backend_EmitObj, _VMContext) {}
1139