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