]> granicus.if.org Git - clang/blob - lib/CodeGen/CodeGenAction.cpp
Update for LLVM api change.
[clang] / lib / CodeGen / CodeGenAction.cpp
1 //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "CoverageMappingGen.h"
11 #include "clang/CodeGen/CodeGenAction.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclGroup.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/CodeGen/BackendUtil.h"
21 #include "clang/CodeGen/ModuleBuilder.h"
22 #include "clang/Frontend/CompilerInstance.h"
23 #include "clang/Frontend/FrontendDiagnostic.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_ostream *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 CodeGenOptions &compopts,
61                     const TargetOptions &targetopts,
62                     const LangOptions &langopts, bool TimePasses,
63                     const std::string &infile, llvm::Module *LinkModule,
64                     raw_ostream *OS, LLVMContext &C,
65                     CoverageSourceInfo *CoverageInfo = nullptr)
66         : Diags(_Diags), Action(action), CodeGenOpts(compopts),
67           TargetOpts(targetopts), LangOpts(langopts), AsmOutStream(OS),
68           Context(), LLVMIRGeneration("LLVM IR Generation Time"),
69           Gen(CreateLLVMCodeGen(Diags, infile, compopts,
70                                 targetopts, C, CoverageInfo)),
71           LinkModule(LinkModule) {
72       llvm::TimePassesIsEnabled = TimePasses;
73     }
74
75     std::unique_ptr<llvm::Module> takeModule() { return std::move(TheModule); }
76     llvm::Module *takeLinkModule() { return LinkModule.release(); }
77
78     void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
79       Gen->HandleCXXStaticMemberVarInstantiation(VD);
80     }
81
82     void Initialize(ASTContext &Ctx) override {
83       Context = &Ctx;
84
85       if (llvm::TimePassesIsEnabled)
86         LLVMIRGeneration.startTimer();
87
88       Gen->Initialize(Ctx);
89
90       TheModule.reset(Gen->GetModule());
91
92       if (llvm::TimePassesIsEnabled)
93         LLVMIRGeneration.stopTimer();
94     }
95
96     bool HandleTopLevelDecl(DeclGroupRef D) override {
97       PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
98                                      Context->getSourceManager(),
99                                      "LLVM IR generation of declaration");
100
101       if (llvm::TimePassesIsEnabled)
102         LLVMIRGeneration.startTimer();
103
104       Gen->HandleTopLevelDecl(D);
105
106       if (llvm::TimePassesIsEnabled)
107         LLVMIRGeneration.stopTimer();
108
109       return true;
110     }
111
112     void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
113       PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
114                                      Context->getSourceManager(),
115                                      "LLVM IR generation of inline method");
116       if (llvm::TimePassesIsEnabled)
117         LLVMIRGeneration.startTimer();
118
119       Gen->HandleInlineMethodDefinition(D);
120
121       if (llvm::TimePassesIsEnabled)
122         LLVMIRGeneration.stopTimer();
123     }
124
125     void HandleTranslationUnit(ASTContext &C) override {
126       {
127         PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
128         if (llvm::TimePassesIsEnabled)
129           LLVMIRGeneration.startTimer();
130
131         Gen->HandleTranslationUnit(C);
132
133         if (llvm::TimePassesIsEnabled)
134           LLVMIRGeneration.stopTimer();
135       }
136
137       // Silently ignore if we weren't initialized for some reason.
138       if (!TheModule)
139         return;
140
141       // Make sure IR generation is happy with the module. This is released by
142       // the module provider.
143       llvm::Module *M = Gen->ReleaseModule();
144       if (!M) {
145         // The module has been released by IR gen on failures, do not double
146         // free.
147         TheModule.release();
148         return;
149       }
150
151       assert(TheModule.get() == M &&
152              "Unexpected module change during IR generation");
153
154       // Link LinkModule into this module if present, preserving its validity.
155       if (LinkModule) {
156         LLVMContext &Ctx = LinkModule->getContext();
157         LLVMContext::DiagnosticHandlerTy OldHandler =
158             Ctx.getDiagnosticHandler();
159         void *OldDiagnosticContext = Ctx.getDiagnosticContext();
160         Ctx.setDiagnosticHandler(linkerDiagnosticHandler, this);
161         bool Failed =
162             Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource);
163         Ctx.setDiagnosticHandler(OldHandler, OldDiagnosticContext);
164         if (Failed)
165           return;
166       }
167
168       // Install an inline asm handler so that diagnostics get printed through
169       // our diagnostics hooks.
170       LLVMContext &Ctx = TheModule->getContext();
171       LLVMContext::InlineAsmDiagHandlerTy OldHandler =
172         Ctx.getInlineAsmDiagnosticHandler();
173       void *OldContext = Ctx.getInlineAsmDiagnosticContext();
174       Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
175
176       LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
177           Ctx.getDiagnosticHandler();
178       void *OldDiagnosticContext = Ctx.getDiagnosticContext();
179       Ctx.setDiagnosticHandler(DiagnosticHandler, this);
180
181       EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
182                         C.getTargetInfo().getTargetDescription(),
183                         TheModule.get(), Action, AsmOutStream);
184
185       Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
186
187       Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
188     }
189
190     void HandleTagDeclDefinition(TagDecl *D) override {
191       PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
192                                      Context->getSourceManager(),
193                                      "LLVM IR generation of declaration");
194       Gen->HandleTagDeclDefinition(D);
195     }
196
197     void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
198       Gen->HandleTagDeclRequiredDefinition(D);
199     }
200
201     void CompleteTentativeDefinition(VarDecl *D) override {
202       Gen->CompleteTentativeDefinition(D);
203     }
204
205     void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
206       Gen->HandleVTable(RD, DefinitionRequired);
207     }
208
209     void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
210       Gen->HandleLinkerOptionPragma(Opts);
211     }
212
213     void HandleDetectMismatch(llvm::StringRef Name,
214                                       llvm::StringRef Value) override {
215       Gen->HandleDetectMismatch(Name, Value);
216     }
217
218     void HandleDependentLibrary(llvm::StringRef Opts) override {
219       Gen->HandleDependentLibrary(Opts);
220     }
221
222     static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
223                                      unsigned LocCookie) {
224       SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
225       ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
226     }
227
228     static void linkerDiagnosticHandler(const llvm::DiagnosticInfo &DI,
229                                         void *Context) {
230       ((BackendConsumer *)Context)->linkerDiagnosticHandlerImpl(DI);
231     }
232
233     void linkerDiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
234
235     static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
236                                   void *Context) {
237       ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
238     }
239
240     void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
241                                SourceLocation LocCookie);
242
243     void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
244     /// \brief Specialized handler for InlineAsm diagnostic.
245     /// \return True if the diagnostic has been successfully reported, false
246     /// otherwise.
247     bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
248     /// \brief Specialized handler for StackSize diagnostic.
249     /// \return True if the diagnostic has been successfully reported, false
250     /// otherwise.
251     bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
252     /// \brief Specialized handlers for optimization remarks.
253     /// Note that these handlers only accept remarks and they always handle
254     /// them.
255     void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
256                                  unsigned DiagID);
257     void
258     OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
259     void OptimizationRemarkHandler(
260         const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
261     void OptimizationRemarkHandler(
262         const llvm::DiagnosticInfoOptimizationRemarkAnalysis &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 (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
341         std::pair<unsigned, unsigned> Range = D.getRanges()[i];
342         unsigned Column = D.getColumnNo();
343         B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
344                          Loc.getLocWithOffset(Range.second - Column));
345       }
346     }
347     return;
348   }
349   
350   // Otherwise, report the backend issue as occurring in the generated .s file.
351   // If Loc is invalid, we still need to report the issue, it just gets no
352   // location info.
353   Diags.Report(Loc, DiagID).AddString(Message);
354 }
355
356 #define ComputeDiagID(Severity, GroupName, DiagID)                             \
357   do {                                                                         \
358     switch (Severity) {                                                        \
359     case llvm::DS_Error:                                                       \
360       DiagID = diag::err_fe_##GroupName;                                       \
361       break;                                                                   \
362     case llvm::DS_Warning:                                                     \
363       DiagID = diag::warn_fe_##GroupName;                                      \
364       break;                                                                   \
365     case llvm::DS_Remark:                                                      \
366       llvm_unreachable("'remark' severity not expected");                      \
367       break;                                                                   \
368     case llvm::DS_Note:                                                        \
369       DiagID = diag::note_fe_##GroupName;                                      \
370       break;                                                                   \
371     }                                                                          \
372   } while (false)
373
374 #define ComputeDiagRemarkID(Severity, GroupName, DiagID)                       \
375   do {                                                                         \
376     switch (Severity) {                                                        \
377     case llvm::DS_Error:                                                       \
378       DiagID = diag::err_fe_##GroupName;                                       \
379       break;                                                                   \
380     case llvm::DS_Warning:                                                     \
381       DiagID = diag::warn_fe_##GroupName;                                      \
382       break;                                                                   \
383     case llvm::DS_Remark:                                                      \
384       DiagID = diag::remark_fe_##GroupName;                                    \
385       break;                                                                   \
386     case llvm::DS_Note:                                                        \
387       DiagID = diag::note_fe_##GroupName;                                      \
388       break;                                                                   \
389     }                                                                          \
390   } while (false)
391
392 bool
393 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
394   unsigned DiagID;
395   ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
396   std::string Message = D.getMsgStr().str();
397
398   // If this problem has clang-level source location information, report the
399   // issue as being a problem in the source with a note showing the instantiated
400   // code.
401   SourceLocation LocCookie =
402       SourceLocation::getFromRawEncoding(D.getLocCookie());
403   if (LocCookie.isValid())
404     Diags.Report(LocCookie, DiagID).AddString(Message);
405   else {
406     // Otherwise, report the backend diagnostic as occurring in the generated
407     // .s file.
408     // If Loc is invalid, we still need to report the diagnostic, it just gets
409     // no location info.
410     FullSourceLoc Loc;
411     Diags.Report(Loc, DiagID).AddString(Message);
412   }
413   // We handled all the possible severities.
414   return true;
415 }
416
417 bool
418 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
419   if (D.getSeverity() != llvm::DS_Warning)
420     // For now, the only support we have for StackSize diagnostic is warning.
421     // We do not know how to format other severities.
422     return false;
423
424   if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
425     Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
426                  diag::warn_fe_frame_larger_than)
427         << D.getStackSize() << Decl::castToDeclContext(ND);
428     return true;
429   }
430
431   return false;
432 }
433
434 void BackendConsumer::EmitOptimizationMessage(
435     const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
436   // We only support warnings and remarks.
437   assert(D.getSeverity() == llvm::DS_Remark ||
438          D.getSeverity() == llvm::DS_Warning);
439
440   SourceManager &SourceMgr = Context->getSourceManager();
441   FileManager &FileMgr = SourceMgr.getFileManager();
442   StringRef Filename;
443   unsigned Line, Column;
444   D.getLocation(&Filename, &Line, &Column);
445   SourceLocation DILoc;
446   const FileEntry *FE = FileMgr.getFile(Filename);
447   if (FE && Line > 0) {
448     // If -gcolumn-info was not used, Column will be 0. This upsets the
449     // source manager, so pass 1 if Column is not set.
450     DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
451   }
452
453   // If a location isn't available, try to approximate it using the associated
454   // function definition. We use the definition's right brace to differentiate
455   // from diagnostics that genuinely relate to the function itself.
456   FullSourceLoc Loc(DILoc, SourceMgr);
457   if (Loc.isInvalid())
458     if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
459       Loc = FD->getASTContext().getFullLoc(FD->getBodyRBrace());
460
461   Diags.Report(Loc, DiagID)
462       << AddFlagValue(D.getPassName() ? D.getPassName() : "")
463       << D.getMsg().str();
464
465   if (DILoc.isInvalid())
466     // If we were not able to translate the file:line:col information
467     // back to a SourceLocation, at least emit a note stating that
468     // we could not translate this location. This can happen in the
469     // case of #line directives.
470     Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc)
471         << Filename << Line << Column;
472 }
473
474 void BackendConsumer::OptimizationRemarkHandler(
475     const llvm::DiagnosticInfoOptimizationRemark &D) {
476   // Optimization remarks are active only if the -Rpass flag has a regular
477   // expression that matches the name of the pass name in \p D.
478   if (CodeGenOpts.OptimizationRemarkPattern &&
479       CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
480     EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
481 }
482
483 void BackendConsumer::OptimizationRemarkHandler(
484     const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
485   // Missed optimization remarks are active only if the -Rpass-missed
486   // flag has a regular expression that matches the name of the pass
487   // name in \p D.
488   if (CodeGenOpts.OptimizationRemarkMissedPattern &&
489       CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
490     EmitOptimizationMessage(D,
491                             diag::remark_fe_backend_optimization_remark_missed);
492 }
493
494 void BackendConsumer::OptimizationRemarkHandler(
495     const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
496   // Optimization analysis remarks are active only if the -Rpass-analysis
497   // flag has a regular expression that matches the name of the pass
498   // name in \p D.
499   if (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
500       CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))
501     EmitOptimizationMessage(
502         D, diag::remark_fe_backend_optimization_remark_analysis);
503 }
504
505 void BackendConsumer::OptimizationFailureHandler(
506     const llvm::DiagnosticInfoOptimizationFailure &D) {
507   EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
508 }
509
510 void BackendConsumer::linkerDiagnosticHandlerImpl(const DiagnosticInfo &DI) {
511   if (DI.getSeverity() != DS_Error)
512     return;
513
514   std::string MsgStorage;
515   {
516     raw_string_ostream Stream(MsgStorage);
517     DiagnosticPrinterRawOStream DP(Stream);
518     DI.print(DP);
519   }
520
521   Diags.Report(diag::err_fe_cannot_link_module)
522       << LinkModule->getModuleIdentifier() << MsgStorage;
523 }
524
525 /// \brief This function is invoked when the backend needs
526 /// to report something to the user.
527 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
528   unsigned DiagID = diag::err_fe_inline_asm;
529   llvm::DiagnosticSeverity Severity = DI.getSeverity();
530   // Get the diagnostic ID based.
531   switch (DI.getKind()) {
532   case llvm::DK_InlineAsm:
533     if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
534       return;
535     ComputeDiagID(Severity, inline_asm, DiagID);
536     break;
537   case llvm::DK_StackSize:
538     if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
539       return;
540     ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
541     break;
542   case llvm::DK_OptimizationRemark:
543     // Optimization remarks are always handled completely by this
544     // handler. There is no generic way of emitting them.
545     OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
546     return;
547   case llvm::DK_OptimizationRemarkMissed:
548     // Optimization remarks are always handled completely by this
549     // handler. There is no generic way of emitting them.
550     OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
551     return;
552   case llvm::DK_OptimizationRemarkAnalysis:
553     // Optimization remarks are always handled completely by this
554     // handler. There is no generic way of emitting them.
555     OptimizationRemarkHandler(
556         cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
557     return;
558   case llvm::DK_OptimizationFailure:
559     // Optimization failures are always handled completely by this
560     // handler.
561     OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
562     return;
563   default:
564     // Plugin IDs are not bound to any value as they are set dynamically.
565     ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
566     break;
567   }
568   std::string MsgStorage;
569   {
570     raw_string_ostream Stream(MsgStorage);
571     DiagnosticPrinterRawOStream DP(Stream);
572     DI.print(DP);
573   }
574
575   // Report the backend message using the usual diagnostic mechanism.
576   FullSourceLoc Loc;
577   Diags.Report(Loc, DiagID).AddString(MsgStorage);
578 }
579 #undef ComputeDiagID
580
581 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
582   : Act(_Act), LinkModule(nullptr),
583     VMContext(_VMContext ? _VMContext : new LLVMContext),
584     OwnsVMContext(!_VMContext) {}
585
586 CodeGenAction::~CodeGenAction() {
587   TheModule.reset();
588   if (OwnsVMContext)
589     delete VMContext;
590 }
591
592 bool CodeGenAction::hasIRSupport() const { return true; }
593
594 void CodeGenAction::EndSourceFileAction() {
595   // If the consumer creation failed, do nothing.
596   if (!getCompilerInstance().hasASTConsumer())
597     return;
598
599   // If we were given a link module, release consumer's ownership of it.
600   if (LinkModule)
601     BEConsumer->takeLinkModule();
602
603   // Steal the module from the consumer.
604   TheModule = BEConsumer->takeModule();
605 }
606
607 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
608   return std::move(TheModule);
609 }
610
611 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
612   OwnsVMContext = false;
613   return VMContext;
614 }
615
616 static raw_ostream *GetOutputStream(CompilerInstance &CI,
617                                     StringRef InFile,
618                                     BackendAction Action) {
619   switch (Action) {
620   case Backend_EmitAssembly:
621     return CI.createDefaultOutputFile(false, InFile, "s");
622   case Backend_EmitLL:
623     return CI.createDefaultOutputFile(false, InFile, "ll");
624   case Backend_EmitBC:
625     return CI.createDefaultOutputFile(true, InFile, "bc");
626   case Backend_EmitNothing:
627     return nullptr;
628   case Backend_EmitMCNull:
629     return CI.createNullOutputFile();
630   case Backend_EmitObj:
631     return CI.createDefaultOutputFile(true, InFile, "o");
632   }
633
634   llvm_unreachable("Invalid action!");
635 }
636
637 std::unique_ptr<ASTConsumer>
638 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
639   BackendAction BA = static_cast<BackendAction>(Act);
640   std::unique_ptr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
641   if (BA != Backend_EmitNothing && !OS)
642     return nullptr;
643
644   llvm::Module *LinkModuleToUse = LinkModule;
645
646   // If we were not given a link module, and the user requested that one be
647   // loaded from bitcode, do so now.
648   const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
649   if (!LinkModuleToUse && !LinkBCFile.empty()) {
650     std::string ErrorStr;
651
652     std::unique_ptr<llvm::MemoryBuffer> BCBuf =
653       CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
654     if (!BCBuf) {
655       CI.getDiagnostics().Report(diag::err_cannot_open_file)
656         << LinkBCFile << ErrorStr;
657       return nullptr;
658     }
659
660     ErrorOr<llvm::Module *> ModuleOrErr =
661         getLazyBitcodeModule(std::move(BCBuf), *VMContext);
662     if (std::error_code EC = ModuleOrErr.getError()) {
663       CI.getDiagnostics().Report(diag::err_cannot_open_file)
664         << LinkBCFile << EC.message();
665       return nullptr;
666     }
667     LinkModuleToUse = ModuleOrErr.get();
668   }
669
670   CoverageSourceInfo *CoverageInfo = nullptr;
671   // Add the preprocessor callback only when the coverage mapping is generated.
672   if (CI.getCodeGenOpts().CoverageMapping) {
673     CoverageInfo = new CoverageSourceInfo;
674     CI.getPreprocessor().addPPCallbacks(
675                                     std::unique_ptr<PPCallbacks>(CoverageInfo));
676   }
677   std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
678       BA, CI.getDiagnostics(), CI.getCodeGenOpts(), CI.getTargetOpts(),
679       CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
680       LinkModuleToUse, OS.release(), *VMContext, CoverageInfo));
681   BEConsumer = Result.get();
682   return std::move(Result);
683 }
684
685 void CodeGenAction::ExecuteAction() {
686   // If this is an IR file, we have to treat it specially.
687   if (getCurrentFileKind() == IK_LLVM_IR) {
688     BackendAction BA = static_cast<BackendAction>(Act);
689     CompilerInstance &CI = getCompilerInstance();
690     raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
691     if (BA != Backend_EmitNothing && !OS)
692       return;
693
694     bool Invalid;
695     SourceManager &SM = CI.getSourceManager();
696     FileID FID = SM.getMainFileID();
697     llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
698     if (Invalid)
699       return;
700
701     llvm::SMDiagnostic Err;
702     TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
703     if (!TheModule) {
704       // Translate from the diagnostic info to the SourceManager location if
705       // available.
706       // TODO: Unify this with ConvertBackendLocation()
707       SourceLocation Loc;
708       if (Err.getLineNo() > 0) {
709         assert(Err.getColumnNo() >= 0);
710         Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
711                                       Err.getLineNo(), Err.getColumnNo() + 1);
712       }
713
714       // Strip off a leading diagnostic code if there is one.
715       StringRef Msg = Err.getMessage();
716       if (Msg.startswith("error: "))
717         Msg = Msg.substr(7);
718
719       unsigned DiagID =
720           CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
721
722       CI.getDiagnostics().Report(Loc, DiagID) << Msg;
723       return;
724     }
725     const TargetOptions &TargetOpts = CI.getTargetOpts();
726     if (TheModule->getTargetTriple() != TargetOpts.Triple) {
727       unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
728           DiagnosticsEngine::Warning,
729           "overriding the module target triple with %0");
730
731       CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple;
732       TheModule->setTargetTriple(TargetOpts.Triple);
733     }
734
735     EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
736                       CI.getLangOpts(), CI.getTarget().getTargetDescription(),
737                       TheModule.get(), BA, OS);
738     return;
739   }
740
741   // Otherwise follow the normal AST path.
742   this->ASTFrontendAction::ExecuteAction();
743 }
744
745 //
746
747 void EmitAssemblyAction::anchor() { }
748 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
749   : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
750
751 void EmitBCAction::anchor() { }
752 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
753   : CodeGenAction(Backend_EmitBC, _VMContext) {}
754
755 void EmitLLVMAction::anchor() { }
756 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
757   : CodeGenAction(Backend_EmitLL, _VMContext) {}
758
759 void EmitLLVMOnlyAction::anchor() { }
760 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
761   : CodeGenAction(Backend_EmitNothing, _VMContext) {}
762
763 void EmitCodeGenOnlyAction::anchor() { }
764 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
765   : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
766
767 void EmitObjAction::anchor() { }
768 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
769   : CodeGenAction(Backend_EmitObj, _VMContext) {}