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