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