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