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