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