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