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