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