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       Ctx.setDiagnosticsHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
266       if (CodeGenOpts.DiagnosticsHotnessThreshold != 0)
267         Ctx.setDiagnosticsHotnessThreshold(
268             CodeGenOpts.DiagnosticsHotnessThreshold);
269 
270       std::unique_ptr<llvm::ToolOutputFile> OptRecordFile;
271       if (!CodeGenOpts.OptRecordFile.empty()) {
272         std::error_code EC;
273         OptRecordFile = llvm::make_unique<llvm::ToolOutputFile>(
274             CodeGenOpts.OptRecordFile, EC, sys::fs::F_None);
275         if (EC) {
276           Diags.Report(diag::err_cannot_open_file) <<
277             CodeGenOpts.OptRecordFile << EC.message();
278           return;
279         }
280 
281         Ctx.setRemarkStreamer(llvm::make_unique<RemarkStreamer>(
282             CodeGenOpts.OptRecordFile,
283             llvm::make_unique<remarks::YAMLSerializer>(OptRecordFile->os())));
284 
285         if (!CodeGenOpts.OptRecordPasses.empty())
286           if (Error E = Ctx.getRemarkStreamer()->setFilter(
287                   CodeGenOpts.OptRecordPasses))
288             Diags.Report(diag::err_drv_optimization_remark_pattern)
289                 << toString(std::move(E)) << CodeGenOpts.OptRecordPasses;
290 
291         if (CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
292           Ctx.setDiagnosticsHotnessRequested(true);
293       }
294 
295       // Link each LinkModule into our module.
296       if (LinkInModules())
297         return;
298 
299       EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
300 
301       EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
302                         LangOpts, C.getTargetInfo().getDataLayout(),
303                         getModule(), Action, std::move(AsmOutStream));
304 
305       Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
306 
307       Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
308 
309       if (OptRecordFile)
310         OptRecordFile->keep();
311     }
312 
313     void HandleTagDeclDefinition(TagDecl *D) override {
314       PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
315                                      Context->getSourceManager(),
316                                      "LLVM IR generation of declaration");
317       Gen->HandleTagDeclDefinition(D);
318     }
319 
320     void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
321       Gen->HandleTagDeclRequiredDefinition(D);
322     }
323 
324     void CompleteTentativeDefinition(VarDecl *D) override {
325       Gen->CompleteTentativeDefinition(D);
326     }
327 
328     void AssignInheritanceModel(CXXRecordDecl *RD) override {
329       Gen->AssignInheritanceModel(RD);
330     }
331 
332     void HandleVTable(CXXRecordDecl *RD) override {
333       Gen->HandleVTable(RD);
334     }
335 
336     static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
337                                      unsigned LocCookie) {
338       SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
339       ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
340     }
341 
342     /// Get the best possible source location to represent a diagnostic that
343     /// may have associated debug info.
344     const FullSourceLoc
345     getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
346                                 bool &BadDebugInfo, StringRef &Filename,
347                                 unsigned &Line, unsigned &Column) const;
348 
349     void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
350                                SourceLocation LocCookie);
351 
352     void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
353     /// Specialized handler for InlineAsm diagnostic.
354     /// \return True if the diagnostic has been successfully reported, false
355     /// otherwise.
356     bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
357     /// Specialized handler for StackSize diagnostic.
358     /// \return True if the diagnostic has been successfully reported, false
359     /// otherwise.
360     bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
361     /// Specialized handler for unsupported backend feature diagnostic.
362     void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
363     /// Specialized handlers for optimization remarks.
364     /// Note that these handlers only accept remarks and they always handle
365     /// them.
366     void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
367                                  unsigned DiagID);
368     void
369     OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
370     void OptimizationRemarkHandler(
371         const llvm::OptimizationRemarkAnalysisFPCommute &D);
372     void OptimizationRemarkHandler(
373         const llvm::OptimizationRemarkAnalysisAliasing &D);
374     void OptimizationFailureHandler(
375         const llvm::DiagnosticInfoOptimizationFailure &D);
376   };
377 
378   void BackendConsumer::anchor() {}
379 }
380 
381 bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
382   BackendCon->DiagnosticHandlerImpl(DI);
383   return true;
384 }
385 
386 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
387 /// buffer to be a valid FullSourceLoc.
388 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
389                                             SourceManager &CSM) {
390   // Get both the clang and llvm source managers.  The location is relative to
391   // a memory buffer that the LLVM Source Manager is handling, we need to add
392   // a copy to the Clang source manager.
393   const llvm::SourceMgr &LSM = *D.getSourceMgr();
394 
395   // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
396   // already owns its one and clang::SourceManager wants to own its one.
397   const MemoryBuffer *LBuf =
398   LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
399 
400   // Create the copy and transfer ownership to clang::SourceManager.
401   // TODO: Avoid copying files into memory.
402   std::unique_ptr<llvm::MemoryBuffer> CBuf =
403       llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
404                                            LBuf->getBufferIdentifier());
405   // FIXME: Keep a file ID map instead of creating new IDs for each location.
406   FileID FID = CSM.createFileID(std::move(CBuf));
407 
408   // Translate the offset into the file.
409   unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
410   SourceLocation NewLoc =
411   CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
412   return FullSourceLoc(NewLoc, CSM);
413 }
414 
415 
416 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
417 /// error parsing inline asm.  The SMDiagnostic indicates the error relative to
418 /// the temporary memory buffer that the inline asm parser has set up.
419 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
420                                             SourceLocation LocCookie) {
421   // There are a couple of different kinds of errors we could get here.  First,
422   // we re-format the SMDiagnostic in terms of a clang diagnostic.
423 
424   // Strip "error: " off the start of the message string.
425   StringRef Message = D.getMessage();
426   if (Message.startswith("error: "))
427     Message = Message.substr(7);
428 
429   // If the SMDiagnostic has an inline asm source location, translate it.
430   FullSourceLoc Loc;
431   if (D.getLoc() != SMLoc())
432     Loc = ConvertBackendLocation(D, Context->getSourceManager());
433 
434   unsigned DiagID;
435   switch (D.getKind()) {
436   case llvm::SourceMgr::DK_Error:
437     DiagID = diag::err_fe_inline_asm;
438     break;
439   case llvm::SourceMgr::DK_Warning:
440     DiagID = diag::warn_fe_inline_asm;
441     break;
442   case llvm::SourceMgr::DK_Note:
443     DiagID = diag::note_fe_inline_asm;
444     break;
445   case llvm::SourceMgr::DK_Remark:
446     llvm_unreachable("remarks unexpected");
447   }
448   // If this problem has clang-level source location information, report the
449   // issue in the source with a note showing the instantiated
450   // code.
451   if (LocCookie.isValid()) {
452     Diags.Report(LocCookie, DiagID).AddString(Message);
453 
454     if (D.getLoc().isValid()) {
455       DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
456       // Convert the SMDiagnostic ranges into SourceRange and attach them
457       // to the diagnostic.
458       for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
459         unsigned Column = D.getColumnNo();
460         B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
461                          Loc.getLocWithOffset(Range.second - Column));
462       }
463     }
464     return;
465   }
466 
467   // Otherwise, report the backend issue as occurring in the generated .s file.
468   // If Loc is invalid, we still need to report the issue, it just gets no
469   // location info.
470   Diags.Report(Loc, DiagID).AddString(Message);
471 }
472 
473 #define ComputeDiagID(Severity, GroupName, DiagID)                             \
474   do {                                                                         \
475     switch (Severity) {                                                        \
476     case llvm::DS_Error:                                                       \
477       DiagID = diag::err_fe_##GroupName;                                       \
478       break;                                                                   \
479     case llvm::DS_Warning:                                                     \
480       DiagID = diag::warn_fe_##GroupName;                                      \
481       break;                                                                   \
482     case llvm::DS_Remark:                                                      \
483       llvm_unreachable("'remark' severity not expected");                      \
484       break;                                                                   \
485     case llvm::DS_Note:                                                        \
486       DiagID = diag::note_fe_##GroupName;                                      \
487       break;                                                                   \
488     }                                                                          \
489   } while (false)
490 
491 #define ComputeDiagRemarkID(Severity, GroupName, DiagID)                       \
492   do {                                                                         \
493     switch (Severity) {                                                        \
494     case llvm::DS_Error:                                                       \
495       DiagID = diag::err_fe_##GroupName;                                       \
496       break;                                                                   \
497     case llvm::DS_Warning:                                                     \
498       DiagID = diag::warn_fe_##GroupName;                                      \
499       break;                                                                   \
500     case llvm::DS_Remark:                                                      \
501       DiagID = diag::remark_fe_##GroupName;                                    \
502       break;                                                                   \
503     case llvm::DS_Note:                                                        \
504       DiagID = diag::note_fe_##GroupName;                                      \
505       break;                                                                   \
506     }                                                                          \
507   } while (false)
508 
509 bool
510 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
511   unsigned DiagID;
512   ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
513   std::string Message = D.getMsgStr().str();
514 
515   // If this problem has clang-level source location information, report the
516   // issue as being a problem in the source with a note showing the instantiated
517   // code.
518   SourceLocation LocCookie =
519       SourceLocation::getFromRawEncoding(D.getLocCookie());
520   if (LocCookie.isValid())
521     Diags.Report(LocCookie, DiagID).AddString(Message);
522   else {
523     // Otherwise, report the backend diagnostic as occurring in the generated
524     // .s file.
525     // If Loc is invalid, we still need to report the diagnostic, it just gets
526     // no location info.
527     FullSourceLoc Loc;
528     Diags.Report(Loc, DiagID).AddString(Message);
529   }
530   // We handled all the possible severities.
531   return true;
532 }
533 
534 bool
535 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
536   if (D.getSeverity() != llvm::DS_Warning)
537     // For now, the only support we have for StackSize diagnostic is warning.
538     // We do not know how to format other severities.
539     return false;
540 
541   if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
542     // FIXME: Shouldn't need to truncate to uint32_t
543     Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
544                  diag::warn_fe_frame_larger_than)
545       << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
546     return true;
547   }
548 
549   return false;
550 }
551 
552 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
553     const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
554     StringRef &Filename, unsigned &Line, unsigned &Column) const {
555   SourceManager &SourceMgr = Context->getSourceManager();
556   FileManager &FileMgr = SourceMgr.getFileManager();
557   SourceLocation DILoc;
558 
559   if (D.isLocationAvailable()) {
560     D.getLocation(Filename, Line, Column);
561     if (Line > 0) {
562       const FileEntry *FE = FileMgr.getFile(Filename);
563       if (!FE)
564         FE = FileMgr.getFile(D.getAbsolutePath());
565       if (FE) {
566         // If -gcolumn-info was not used, Column will be 0. This upsets the
567         // source manager, so pass 1 if Column is not set.
568         DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
569       }
570     }
571     BadDebugInfo = DILoc.isInvalid();
572   }
573 
574   // If a location isn't available, try to approximate it using the associated
575   // function definition. We use the definition's right brace to differentiate
576   // from diagnostics that genuinely relate to the function itself.
577   FullSourceLoc Loc(DILoc, SourceMgr);
578   if (Loc.isInvalid())
579     if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
580       Loc = FD->getASTContext().getFullLoc(FD->getLocation());
581 
582   if (DILoc.isInvalid() && D.isLocationAvailable())
583     // If we were not able to translate the file:line:col information
584     // back to a SourceLocation, at least emit a note stating that
585     // we could not translate this location. This can happen in the
586     // case of #line directives.
587     Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
588         << Filename << Line << Column;
589 
590   return Loc;
591 }
592 
593 void BackendConsumer::UnsupportedDiagHandler(
594     const llvm::DiagnosticInfoUnsupported &D) {
595   // We only support errors.
596   assert(D.getSeverity() == llvm::DS_Error);
597 
598   StringRef Filename;
599   unsigned Line, Column;
600   bool BadDebugInfo = false;
601   FullSourceLoc Loc =
602       getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
603 
604   Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
605 
606   if (BadDebugInfo)
607     // If we were not able to translate the file:line:col information
608     // back to a SourceLocation, at least emit a note stating that
609     // we could not translate this location. This can happen in the
610     // case of #line directives.
611     Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
612         << Filename << Line << Column;
613 }
614 
615 void BackendConsumer::EmitOptimizationMessage(
616     const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
617   // We only support warnings and remarks.
618   assert(D.getSeverity() == llvm::DS_Remark ||
619          D.getSeverity() == llvm::DS_Warning);
620 
621   StringRef Filename;
622   unsigned Line, Column;
623   bool BadDebugInfo = false;
624   FullSourceLoc Loc =
625       getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
626 
627   std::string Msg;
628   raw_string_ostream MsgStream(Msg);
629   MsgStream << D.getMsg();
630 
631   if (D.getHotness())
632     MsgStream << " (hotness: " << *D.getHotness() << ")";
633 
634   Diags.Report(Loc, DiagID)
635       << AddFlagValue(D.getPassName())
636       << MsgStream.str();
637 
638   if (BadDebugInfo)
639     // If we were not able to translate the file:line:col information
640     // back to a SourceLocation, at least emit a note stating that
641     // we could not translate this location. This can happen in the
642     // case of #line directives.
643     Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
644         << Filename << Line << Column;
645 }
646 
647 void BackendConsumer::OptimizationRemarkHandler(
648     const llvm::DiagnosticInfoOptimizationBase &D) {
649   // Without hotness information, don't show noisy remarks.
650   if (D.isVerbose() && !D.getHotness())
651     return;
652 
653   if (D.isPassed()) {
654     // Optimization remarks are active only if the -Rpass flag has a regular
655     // expression that matches the name of the pass name in \p D.
656     if (CodeGenOpts.OptimizationRemarkPattern &&
657         CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
658       EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
659   } else if (D.isMissed()) {
660     // Missed optimization remarks are active only if the -Rpass-missed
661     // flag has a regular expression that matches the name of the pass
662     // name in \p D.
663     if (CodeGenOpts.OptimizationRemarkMissedPattern &&
664         CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
665       EmitOptimizationMessage(
666           D, diag::remark_fe_backend_optimization_remark_missed);
667   } else {
668     assert(D.isAnalysis() && "Unknown remark type");
669 
670     bool ShouldAlwaysPrint = false;
671     if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
672       ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
673 
674     if (ShouldAlwaysPrint ||
675         (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
676          CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
677       EmitOptimizationMessage(
678           D, diag::remark_fe_backend_optimization_remark_analysis);
679   }
680 }
681 
682 void BackendConsumer::OptimizationRemarkHandler(
683     const llvm::OptimizationRemarkAnalysisFPCommute &D) {
684   // Optimization analysis remarks are active if the pass name is set to
685   // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
686   // regular expression that matches the name of the pass name in \p D.
687 
688   if (D.shouldAlwaysPrint() ||
689       (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
690        CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
691     EmitOptimizationMessage(
692         D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
693 }
694 
695 void BackendConsumer::OptimizationRemarkHandler(
696     const llvm::OptimizationRemarkAnalysisAliasing &D) {
697   // Optimization analysis remarks are active if the pass name is set to
698   // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
699   // regular expression that matches the name of the pass name in \p D.
700 
701   if (D.shouldAlwaysPrint() ||
702       (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
703        CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
704     EmitOptimizationMessage(
705         D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
706 }
707 
708 void BackendConsumer::OptimizationFailureHandler(
709     const llvm::DiagnosticInfoOptimizationFailure &D) {
710   EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
711 }
712 
713 /// This function is invoked when the backend needs
714 /// to report something to the user.
715 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
716   unsigned DiagID = diag::err_fe_inline_asm;
717   llvm::DiagnosticSeverity Severity = DI.getSeverity();
718   // Get the diagnostic ID based.
719   switch (DI.getKind()) {
720   case llvm::DK_InlineAsm:
721     if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
722       return;
723     ComputeDiagID(Severity, inline_asm, DiagID);
724     break;
725   case llvm::DK_StackSize:
726     if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
727       return;
728     ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
729     break;
730   case DK_Linker:
731     assert(CurLinkModule);
732     // FIXME: stop eating the warnings and notes.
733     if (Severity != DS_Error)
734       return;
735     DiagID = diag::err_fe_cannot_link_module;
736     break;
737   case llvm::DK_OptimizationRemark:
738     // Optimization remarks are always handled completely by this
739     // handler. There is no generic way of emitting them.
740     OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
741     return;
742   case llvm::DK_OptimizationRemarkMissed:
743     // Optimization remarks are always handled completely by this
744     // handler. There is no generic way of emitting them.
745     OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
746     return;
747   case llvm::DK_OptimizationRemarkAnalysis:
748     // Optimization remarks are always handled completely by this
749     // handler. There is no generic way of emitting them.
750     OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
751     return;
752   case llvm::DK_OptimizationRemarkAnalysisFPCommute:
753     // Optimization remarks are always handled completely by this
754     // handler. There is no generic way of emitting them.
755     OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
756     return;
757   case llvm::DK_OptimizationRemarkAnalysisAliasing:
758     // Optimization remarks are always handled completely by this
759     // handler. There is no generic way of emitting them.
760     OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
761     return;
762   case llvm::DK_MachineOptimizationRemark:
763     // Optimization remarks are always handled completely by this
764     // handler. There is no generic way of emitting them.
765     OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
766     return;
767   case llvm::DK_MachineOptimizationRemarkMissed:
768     // Optimization remarks are always handled completely by this
769     // handler. There is no generic way of emitting them.
770     OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
771     return;
772   case llvm::DK_MachineOptimizationRemarkAnalysis:
773     // Optimization remarks are always handled completely by this
774     // handler. There is no generic way of emitting them.
775     OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
776     return;
777   case llvm::DK_OptimizationFailure:
778     // Optimization failures are always handled completely by this
779     // handler.
780     OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
781     return;
782   case llvm::DK_Unsupported:
783     UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
784     return;
785   default:
786     // Plugin IDs are not bound to any value as they are set dynamically.
787     ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
788     break;
789   }
790   std::string MsgStorage;
791   {
792     raw_string_ostream Stream(MsgStorage);
793     DiagnosticPrinterRawOStream DP(Stream);
794     DI.print(DP);
795   }
796 
797   if (DiagID == diag::err_fe_cannot_link_module) {
798     Diags.Report(diag::err_fe_cannot_link_module)
799         << CurLinkModule->getModuleIdentifier() << MsgStorage;
800     return;
801   }
802 
803   // Report the backend message using the usual diagnostic mechanism.
804   FullSourceLoc Loc;
805   Diags.Report(Loc, DiagID).AddString(MsgStorage);
806 }
807 #undef ComputeDiagID
808 
809 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
810     : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
811       OwnsVMContext(!_VMContext) {}
812 
813 CodeGenAction::~CodeGenAction() {
814   TheModule.reset();
815   if (OwnsVMContext)
816     delete VMContext;
817 }
818 
819 bool CodeGenAction::hasIRSupport() const { return true; }
820 
821 void CodeGenAction::EndSourceFileAction() {
822   // If the consumer creation failed, do nothing.
823   if (!getCompilerInstance().hasASTConsumer())
824     return;
825 
826   // Steal the module from the consumer.
827   TheModule = BEConsumer->takeModule();
828 }
829 
830 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
831   return std::move(TheModule);
832 }
833 
834 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
835   OwnsVMContext = false;
836   return VMContext;
837 }
838 
839 static std::unique_ptr<raw_pwrite_stream>
840 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
841   switch (Action) {
842   case Backend_EmitAssembly:
843     return CI.createDefaultOutputFile(false, InFile, "s");
844   case Backend_EmitLL:
845     return CI.createDefaultOutputFile(false, InFile, "ll");
846   case Backend_EmitBC:
847     return CI.createDefaultOutputFile(true, InFile, "bc");
848   case Backend_EmitNothing:
849     return nullptr;
850   case Backend_EmitMCNull:
851     return CI.createNullOutputFile();
852   case Backend_EmitObj:
853     return CI.createDefaultOutputFile(true, InFile, "o");
854   }
855 
856   llvm_unreachable("Invalid action!");
857 }
858 
859 std::unique_ptr<ASTConsumer>
860 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
861   BackendAction BA = static_cast<BackendAction>(Act);
862   std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
863   if (!OS)
864     OS = GetOutputStream(CI, InFile, BA);
865 
866   if (BA != Backend_EmitNothing && !OS)
867     return nullptr;
868 
869   // Load bitcode modules to link with, if we need to.
870   if (LinkModules.empty())
871     for (const CodeGenOptions::BitcodeFileToLink &F :
872          CI.getCodeGenOpts().LinkBitcodeFiles) {
873       auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
874       if (!BCBuf) {
875         CI.getDiagnostics().Report(diag::err_cannot_open_file)
876             << F.Filename << BCBuf.getError().message();
877         LinkModules.clear();
878         return nullptr;
879       }
880 
881       Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
882           getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
883       if (!ModuleOrErr) {
884         handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
885           CI.getDiagnostics().Report(diag::err_cannot_open_file)
886               << F.Filename << EIB.message();
887         });
888         LinkModules.clear();
889         return nullptr;
890       }
891       LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
892                              F.Internalize, F.LinkFlags});
893     }
894 
895   CoverageSourceInfo *CoverageInfo = nullptr;
896   // Add the preprocessor callback only when the coverage mapping is generated.
897   if (CI.getCodeGenOpts().CoverageMapping) {
898     CoverageInfo = new CoverageSourceInfo;
899     CI.getPreprocessor().addPPCallbacks(
900                                     std::unique_ptr<PPCallbacks>(CoverageInfo));
901   }
902 
903   std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
904       BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
905       CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
906       CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
907       std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
908   BEConsumer = Result.get();
909 
910   // Enable generating macro debug info only when debug info is not disabled and
911   // also macro debug info is enabled.
912   if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
913       CI.getCodeGenOpts().MacroDebugInfo) {
914     std::unique_ptr<PPCallbacks> Callbacks =
915         llvm::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
916                                             CI.getPreprocessor());
917     CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
918   }
919 
920   return std::move(Result);
921 }
922 
923 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
924                                          void *Context,
925                                          unsigned LocCookie) {
926   SM.print(nullptr, llvm::errs());
927 
928   auto Diags = static_cast<DiagnosticsEngine *>(Context);
929   unsigned DiagID;
930   switch (SM.getKind()) {
931   case llvm::SourceMgr::DK_Error:
932     DiagID = diag::err_fe_inline_asm;
933     break;
934   case llvm::SourceMgr::DK_Warning:
935     DiagID = diag::warn_fe_inline_asm;
936     break;
937   case llvm::SourceMgr::DK_Note:
938     DiagID = diag::note_fe_inline_asm;
939     break;
940   case llvm::SourceMgr::DK_Remark:
941     llvm_unreachable("remarks unexpected");
942   }
943 
944   Diags->Report(DiagID).AddString("cannot compile inline asm");
945 }
946 
947 std::unique_ptr<llvm::Module>
948 CodeGenAction::loadModule(MemoryBufferRef MBRef) {
949   CompilerInstance &CI = getCompilerInstance();
950   SourceManager &SM = CI.getSourceManager();
951 
952   // For ThinLTO backend invocations, ensure that the context
953   // merges types based on ODR identifiers. We also need to read
954   // the correct module out of a multi-module bitcode file.
955   if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
956     VMContext->enableDebugTypeODRUniquing();
957 
958     auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
959       unsigned DiagID =
960           CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
961       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
962         CI.getDiagnostics().Report(DiagID) << EIB.message();
963       });
964       return {};
965     };
966 
967     Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
968     if (!BMsOrErr)
969       return DiagErrors(BMsOrErr.takeError());
970     BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr);
971     // We have nothing to do if the file contains no ThinLTO module. This is
972     // possible if ThinLTO compilation was not able to split module. Content of
973     // the file was already processed by indexing and will be passed to the
974     // linker using merged object file.
975     if (!Bm) {
976       auto M = llvm::make_unique<llvm::Module>("empty", *VMContext);
977       M->setTargetTriple(CI.getTargetOpts().Triple);
978       return M;
979     }
980     Expected<std::unique_ptr<llvm::Module>> MOrErr =
981         Bm->parseModule(*VMContext);
982     if (!MOrErr)
983       return DiagErrors(MOrErr.takeError());
984     return std::move(*MOrErr);
985   }
986 
987   llvm::SMDiagnostic Err;
988   if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
989     return M;
990 
991   // Translate from the diagnostic info to the SourceManager location if
992   // available.
993   // TODO: Unify this with ConvertBackendLocation()
994   SourceLocation Loc;
995   if (Err.getLineNo() > 0) {
996     assert(Err.getColumnNo() >= 0);
997     Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
998                                   Err.getLineNo(), Err.getColumnNo() + 1);
999   }
1000 
1001   // Strip off a leading diagnostic code if there is one.
1002   StringRef Msg = Err.getMessage();
1003   if (Msg.startswith("error: "))
1004     Msg = Msg.substr(7);
1005 
1006   unsigned DiagID =
1007       CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1008 
1009   CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1010   return {};
1011 }
1012 
1013 void CodeGenAction::ExecuteAction() {
1014   // If this is an IR file, we have to treat it specially.
1015   if (getCurrentFileKind().getLanguage() == InputKind::LLVM_IR) {
1016     BackendAction BA = static_cast<BackendAction>(Act);
1017     CompilerInstance &CI = getCompilerInstance();
1018     std::unique_ptr<raw_pwrite_stream> OS =
1019         GetOutputStream(CI, getCurrentFile(), BA);
1020     if (BA != Backend_EmitNothing && !OS)
1021       return;
1022 
1023     bool Invalid;
1024     SourceManager &SM = CI.getSourceManager();
1025     FileID FID = SM.getMainFileID();
1026     const llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
1027     if (Invalid)
1028       return;
1029 
1030     TheModule = loadModule(*MainFile);
1031     if (!TheModule)
1032       return;
1033 
1034     const TargetOptions &TargetOpts = CI.getTargetOpts();
1035     if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1036       CI.getDiagnostics().Report(SourceLocation(),
1037                                  diag::warn_fe_override_module)
1038           << TargetOpts.Triple;
1039       TheModule->setTargetTriple(TargetOpts.Triple);
1040     }
1041 
1042     EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
1043                  MainFile->getMemBufferRef());
1044 
1045     LLVMContext &Ctx = TheModule->getContext();
1046     Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
1047                                       &CI.getDiagnostics());
1048 
1049     EmitBackendOutput(CI.getDiagnostics(), CI.getHeaderSearchOpts(),
1050                       CI.getCodeGenOpts(), TargetOpts, CI.getLangOpts(),
1051                       CI.getTarget().getDataLayout(), TheModule.get(), BA,
1052                       std::move(OS));
1053     return;
1054   }
1055 
1056   // Otherwise follow the normal AST path.
1057   this->ASTFrontendAction::ExecuteAction();
1058 }
1059 
1060 //
1061 
1062 void EmitAssemblyAction::anchor() { }
1063 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1064   : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1065 
1066 void EmitBCAction::anchor() { }
1067 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1068   : CodeGenAction(Backend_EmitBC, _VMContext) {}
1069 
1070 void EmitLLVMAction::anchor() { }
1071 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1072   : CodeGenAction(Backend_EmitLL, _VMContext) {}
1073 
1074 void EmitLLVMOnlyAction::anchor() { }
1075 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1076   : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1077 
1078 void EmitCodeGenOnlyAction::anchor() { }
1079 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1080   : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1081 
1082 void EmitObjAction::anchor() { }
1083 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1084   : CodeGenAction(Backend_EmitObj, _VMContext) {}
1085