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().getTargetDescription(),
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 OptimizationFailureHandler(
260         const llvm::DiagnosticInfoOptimizationFailure &D);
261   };
262 
263   void BackendConsumer::anchor() {}
264 }
265 
266 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
267 /// buffer to be a valid FullSourceLoc.
268 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
269                                             SourceManager &CSM) {
270   // Get both the clang and llvm source managers.  The location is relative to
271   // a memory buffer that the LLVM Source Manager is handling, we need to add
272   // a copy to the Clang source manager.
273   const llvm::SourceMgr &LSM = *D.getSourceMgr();
274 
275   // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
276   // already owns its one and clang::SourceManager wants to own its one.
277   const MemoryBuffer *LBuf =
278   LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
279 
280   // Create the copy and transfer ownership to clang::SourceManager.
281   // TODO: Avoid copying files into memory.
282   std::unique_ptr<llvm::MemoryBuffer> CBuf =
283       llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
284                                            LBuf->getBufferIdentifier());
285   // FIXME: Keep a file ID map instead of creating new IDs for each location.
286   FileID FID = CSM.createFileID(std::move(CBuf));
287 
288   // Translate the offset into the file.
289   unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
290   SourceLocation NewLoc =
291   CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
292   return FullSourceLoc(NewLoc, CSM);
293 }
294 
295 
296 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
297 /// error parsing inline asm.  The SMDiagnostic indicates the error relative to
298 /// the temporary memory buffer that the inline asm parser has set up.
299 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
300                                             SourceLocation LocCookie) {
301   // There are a couple of different kinds of errors we could get here.  First,
302   // we re-format the SMDiagnostic in terms of a clang diagnostic.
303 
304   // Strip "error: " off the start of the message string.
305   StringRef Message = D.getMessage();
306   if (Message.startswith("error: "))
307     Message = Message.substr(7);
308 
309   // If the SMDiagnostic has an inline asm source location, translate it.
310   FullSourceLoc Loc;
311   if (D.getLoc() != SMLoc())
312     Loc = ConvertBackendLocation(D, Context->getSourceManager());
313 
314   unsigned DiagID;
315   switch (D.getKind()) {
316   case llvm::SourceMgr::DK_Error:
317     DiagID = diag::err_fe_inline_asm;
318     break;
319   case llvm::SourceMgr::DK_Warning:
320     DiagID = diag::warn_fe_inline_asm;
321     break;
322   case llvm::SourceMgr::DK_Note:
323     DiagID = diag::note_fe_inline_asm;
324     break;
325   }
326   // If this problem has clang-level source location information, report the
327   // issue in the source with a note showing the instantiated
328   // code.
329   if (LocCookie.isValid()) {
330     Diags.Report(LocCookie, DiagID).AddString(Message);
331 
332     if (D.getLoc().isValid()) {
333       DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
334       // Convert the SMDiagnostic ranges into SourceRange and attach them
335       // to the diagnostic.
336       for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
337         unsigned Column = D.getColumnNo();
338         B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
339                          Loc.getLocWithOffset(Range.second - Column));
340       }
341     }
342     return;
343   }
344 
345   // Otherwise, report the backend issue as occurring in the generated .s file.
346   // If Loc is invalid, we still need to report the issue, it just gets no
347   // location info.
348   Diags.Report(Loc, DiagID).AddString(Message);
349 }
350 
351 #define ComputeDiagID(Severity, GroupName, DiagID)                             \
352   do {                                                                         \
353     switch (Severity) {                                                        \
354     case llvm::DS_Error:                                                       \
355       DiagID = diag::err_fe_##GroupName;                                       \
356       break;                                                                   \
357     case llvm::DS_Warning:                                                     \
358       DiagID = diag::warn_fe_##GroupName;                                      \
359       break;                                                                   \
360     case llvm::DS_Remark:                                                      \
361       llvm_unreachable("'remark' severity not expected");                      \
362       break;                                                                   \
363     case llvm::DS_Note:                                                        \
364       DiagID = diag::note_fe_##GroupName;                                      \
365       break;                                                                   \
366     }                                                                          \
367   } while (false)
368 
369 #define ComputeDiagRemarkID(Severity, GroupName, DiagID)                       \
370   do {                                                                         \
371     switch (Severity) {                                                        \
372     case llvm::DS_Error:                                                       \
373       DiagID = diag::err_fe_##GroupName;                                       \
374       break;                                                                   \
375     case llvm::DS_Warning:                                                     \
376       DiagID = diag::warn_fe_##GroupName;                                      \
377       break;                                                                   \
378     case llvm::DS_Remark:                                                      \
379       DiagID = diag::remark_fe_##GroupName;                                    \
380       break;                                                                   \
381     case llvm::DS_Note:                                                        \
382       DiagID = diag::note_fe_##GroupName;                                      \
383       break;                                                                   \
384     }                                                                          \
385   } while (false)
386 
387 bool
388 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
389   unsigned DiagID;
390   ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
391   std::string Message = D.getMsgStr().str();
392 
393   // If this problem has clang-level source location information, report the
394   // issue as being a problem in the source with a note showing the instantiated
395   // code.
396   SourceLocation LocCookie =
397       SourceLocation::getFromRawEncoding(D.getLocCookie());
398   if (LocCookie.isValid())
399     Diags.Report(LocCookie, DiagID).AddString(Message);
400   else {
401     // Otherwise, report the backend diagnostic as occurring in the generated
402     // .s file.
403     // If Loc is invalid, we still need to report the diagnostic, it just gets
404     // no location info.
405     FullSourceLoc Loc;
406     Diags.Report(Loc, DiagID).AddString(Message);
407   }
408   // We handled all the possible severities.
409   return true;
410 }
411 
412 bool
413 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
414   if (D.getSeverity() != llvm::DS_Warning)
415     // For now, the only support we have for StackSize diagnostic is warning.
416     // We do not know how to format other severities.
417     return false;
418 
419   if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
420     Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
421                  diag::warn_fe_frame_larger_than)
422         << D.getStackSize() << Decl::castToDeclContext(ND);
423     return true;
424   }
425 
426   return false;
427 }
428 
429 void BackendConsumer::EmitOptimizationMessage(
430     const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
431   // We only support warnings and remarks.
432   assert(D.getSeverity() == llvm::DS_Remark ||
433          D.getSeverity() == llvm::DS_Warning);
434 
435   SourceManager &SourceMgr = Context->getSourceManager();
436   FileManager &FileMgr = SourceMgr.getFileManager();
437   StringRef Filename;
438   unsigned Line, Column;
439   SourceLocation DILoc;
440 
441   if (D.isLocationAvailable()) {
442     D.getLocation(&Filename, &Line, &Column);
443     const FileEntry *FE = FileMgr.getFile(Filename);
444     if (FE && Line > 0) {
445       // If -gcolumn-info was not used, Column will be 0. This upsets the
446       // source manager, so pass 1 if Column is not set.
447       DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
448     }
449   }
450 
451   // If a location isn't available, try to approximate it using the associated
452   // function definition. We use the definition's right brace to differentiate
453   // from diagnostics that genuinely relate to the function itself.
454   FullSourceLoc Loc(DILoc, SourceMgr);
455   if (Loc.isInvalid())
456     if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
457       Loc = FD->getASTContext().getFullLoc(FD->getBodyRBrace());
458 
459   Diags.Report(Loc, DiagID)
460       << AddFlagValue(D.getPassName() ? D.getPassName() : "")
461       << D.getMsg().str();
462 
463   if (DILoc.isInvalid() && D.isLocationAvailable())
464     // If we were not able to translate the file:line:col information
465     // back to a SourceLocation, at least emit a note stating that
466     // we could not translate this location. This can happen in the
467     // case of #line directives.
468     Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc)
469         << Filename << Line << Column;
470 }
471 
472 void BackendConsumer::OptimizationRemarkHandler(
473     const llvm::DiagnosticInfoOptimizationRemark &D) {
474   // Optimization remarks are active only if the -Rpass flag has a regular
475   // expression that matches the name of the pass name in \p D.
476   if (CodeGenOpts.OptimizationRemarkPattern &&
477       CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
478     EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
479 }
480 
481 void BackendConsumer::OptimizationRemarkHandler(
482     const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
483   // Missed optimization remarks are active only if the -Rpass-missed
484   // flag has a regular expression that matches the name of the pass
485   // name in \p D.
486   if (CodeGenOpts.OptimizationRemarkMissedPattern &&
487       CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
488     EmitOptimizationMessage(D,
489                             diag::remark_fe_backend_optimization_remark_missed);
490 }
491 
492 void BackendConsumer::OptimizationRemarkHandler(
493     const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
494   // Optimization analysis remarks are active only if the -Rpass-analysis
495   // flag has a regular expression that matches the name of the pass
496   // name in \p D.
497   if (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
498       CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))
499     EmitOptimizationMessage(
500         D, diag::remark_fe_backend_optimization_remark_analysis);
501 }
502 
503 void BackendConsumer::OptimizationFailureHandler(
504     const llvm::DiagnosticInfoOptimizationFailure &D) {
505   EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
506 }
507 
508 void BackendConsumer::linkerDiagnosticHandler(const DiagnosticInfo &DI) {
509   if (DI.getSeverity() != DS_Error)
510     return;
511 
512   std::string MsgStorage;
513   {
514     raw_string_ostream Stream(MsgStorage);
515     DiagnosticPrinterRawOStream DP(Stream);
516     DI.print(DP);
517   }
518 
519   Diags.Report(diag::err_fe_cannot_link_module)
520       << LinkModule->getModuleIdentifier() << MsgStorage;
521 }
522 
523 /// \brief This function is invoked when the backend needs
524 /// to report something to the user.
525 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
526   unsigned DiagID = diag::err_fe_inline_asm;
527   llvm::DiagnosticSeverity Severity = DI.getSeverity();
528   // Get the diagnostic ID based.
529   switch (DI.getKind()) {
530   case llvm::DK_InlineAsm:
531     if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
532       return;
533     ComputeDiagID(Severity, inline_asm, DiagID);
534     break;
535   case llvm::DK_StackSize:
536     if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
537       return;
538     ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
539     break;
540   case llvm::DK_OptimizationRemark:
541     // Optimization remarks are always handled completely by this
542     // handler. There is no generic way of emitting them.
543     OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
544     return;
545   case llvm::DK_OptimizationRemarkMissed:
546     // Optimization remarks are always handled completely by this
547     // handler. There is no generic way of emitting them.
548     OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
549     return;
550   case llvm::DK_OptimizationRemarkAnalysis:
551     // Optimization remarks are always handled completely by this
552     // handler. There is no generic way of emitting them.
553     OptimizationRemarkHandler(
554         cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
555     return;
556   case llvm::DK_OptimizationFailure:
557     // Optimization failures are always handled completely by this
558     // handler.
559     OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
560     return;
561   default:
562     // Plugin IDs are not bound to any value as they are set dynamically.
563     ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
564     break;
565   }
566   std::string MsgStorage;
567   {
568     raw_string_ostream Stream(MsgStorage);
569     DiagnosticPrinterRawOStream DP(Stream);
570     DI.print(DP);
571   }
572 
573   // Report the backend message using the usual diagnostic mechanism.
574   FullSourceLoc Loc;
575   Diags.Report(Loc, DiagID).AddString(MsgStorage);
576 }
577 #undef ComputeDiagID
578 
579 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
580   : Act(_Act), LinkModule(nullptr),
581     VMContext(_VMContext ? _VMContext : new LLVMContext),
582     OwnsVMContext(!_VMContext) {}
583 
584 CodeGenAction::~CodeGenAction() {
585   TheModule.reset();
586   if (OwnsVMContext)
587     delete VMContext;
588 }
589 
590 bool CodeGenAction::hasIRSupport() const { return true; }
591 
592 void CodeGenAction::EndSourceFileAction() {
593   // If the consumer creation failed, do nothing.
594   if (!getCompilerInstance().hasASTConsumer())
595     return;
596 
597   // If we were given a link module, release consumer's ownership of it.
598   if (LinkModule)
599     BEConsumer->takeLinkModule();
600 
601   // Steal the module from the consumer.
602   TheModule = BEConsumer->takeModule();
603 }
604 
605 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
606   return std::move(TheModule);
607 }
608 
609 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
610   OwnsVMContext = false;
611   return VMContext;
612 }
613 
614 static raw_pwrite_stream *
615 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
616   switch (Action) {
617   case Backend_EmitAssembly:
618     return CI.createDefaultOutputFile(false, InFile, "s");
619   case Backend_EmitLL:
620     return CI.createDefaultOutputFile(false, InFile, "ll");
621   case Backend_EmitBC:
622     return CI.createDefaultOutputFile(true, InFile, "bc");
623   case Backend_EmitNothing:
624     return nullptr;
625   case Backend_EmitMCNull:
626     return CI.createNullOutputFile();
627   case Backend_EmitObj:
628     return CI.createDefaultOutputFile(true, InFile, "o");
629   }
630 
631   llvm_unreachable("Invalid action!");
632 }
633 
634 std::unique_ptr<ASTConsumer>
635 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
636   BackendAction BA = static_cast<BackendAction>(Act);
637   raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
638   if (BA != Backend_EmitNothing && !OS)
639     return nullptr;
640 
641   llvm::Module *LinkModuleToUse = LinkModule;
642 
643   // If we were not given a link module, and the user requested that one be
644   // loaded from bitcode, do so now.
645   const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
646   if (!LinkModuleToUse && !LinkBCFile.empty()) {
647     auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
648     if (!BCBuf) {
649       CI.getDiagnostics().Report(diag::err_cannot_open_file)
650           << LinkBCFile << BCBuf.getError().message();
651       return nullptr;
652     }
653 
654     ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
655         getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
656     if (std::error_code EC = ModuleOrErr.getError()) {
657       CI.getDiagnostics().Report(diag::err_cannot_open_file)
658         << LinkBCFile << EC.message();
659       return nullptr;
660     }
661     LinkModuleToUse = ModuleOrErr.get().release();
662   }
663 
664   CoverageSourceInfo *CoverageInfo = nullptr;
665   // Add the preprocessor callback only when the coverage mapping is generated.
666   if (CI.getCodeGenOpts().CoverageMapping) {
667     CoverageInfo = new CoverageSourceInfo;
668     CI.getPreprocessor().addPPCallbacks(
669                                     std::unique_ptr<PPCallbacks>(CoverageInfo));
670   }
671   std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
672       BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
673       CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
674       CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
675       LinkModuleToUse, OS, *VMContext, CoverageInfo));
676   BEConsumer = Result.get();
677   return std::move(Result);
678 }
679 
680 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
681                                          void *Context,
682                                          unsigned LocCookie) {
683   SM.print(nullptr, llvm::errs());
684 }
685 
686 void CodeGenAction::ExecuteAction() {
687   // If this is an IR file, we have to treat it specially.
688   if (getCurrentFileKind() == IK_LLVM_IR) {
689     BackendAction BA = static_cast<BackendAction>(Act);
690     CompilerInstance &CI = getCompilerInstance();
691     raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
692     if (BA != Backend_EmitNothing && !OS)
693       return;
694 
695     bool Invalid;
696     SourceManager &SM = CI.getSourceManager();
697     FileID FID = SM.getMainFileID();
698     llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
699     if (Invalid)
700       return;
701 
702     llvm::SMDiagnostic Err;
703     TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
704     if (!TheModule) {
705       // Translate from the diagnostic info to the SourceManager location if
706       // available.
707       // TODO: Unify this with ConvertBackendLocation()
708       SourceLocation Loc;
709       if (Err.getLineNo() > 0) {
710         assert(Err.getColumnNo() >= 0);
711         Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
712                                       Err.getLineNo(), Err.getColumnNo() + 1);
713       }
714 
715       // Strip off a leading diagnostic code if there is one.
716       StringRef Msg = Err.getMessage();
717       if (Msg.startswith("error: "))
718         Msg = Msg.substr(7);
719 
720       unsigned DiagID =
721           CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
722 
723       CI.getDiagnostics().Report(Loc, DiagID) << Msg;
724       return;
725     }
726     const TargetOptions &TargetOpts = CI.getTargetOpts();
727     if (TheModule->getTargetTriple() != TargetOpts.Triple) {
728       CI.getDiagnostics().Report(SourceLocation(),
729                                  diag::warn_fe_override_module)
730           << TargetOpts.Triple;
731       TheModule->setTargetTriple(TargetOpts.Triple);
732     }
733 
734     LLVMContext &Ctx = TheModule->getContext();
735     Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler);
736     EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
737                       CI.getLangOpts(), CI.getTarget().getTargetDescription(),
738                       TheModule.get(), BA, OS);
739     return;
740   }
741 
742   // Otherwise follow the normal AST path.
743   this->ASTFrontendAction::ExecuteAction();
744 }
745 
746 //
747 
748 void EmitAssemblyAction::anchor() { }
749 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
750   : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
751 
752 void EmitBCAction::anchor() { }
753 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
754   : CodeGenAction(Backend_EmitBC, _VMContext) {}
755 
756 void EmitLLVMAction::anchor() { }
757 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
758   : CodeGenAction(Backend_EmitLL, _VMContext) {}
759 
760 void EmitLLVMOnlyAction::anchor() { }
761 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
762   : CodeGenAction(Backend_EmitNothing, _VMContext) {}
763 
764 void EmitCodeGenOnlyAction::anchor() { }
765 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
766   : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
767 
768 void EmitObjAction::anchor() { }
769 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
770   : CodeGenAction(Backend_EmitObj, _VMContext) {}
771