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 "clang/CodeGen/CodeGenAction.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/DeclGroup.h"
14 #include "clang/Basic/FileManager.h"
15 #include "clang/Basic/SourceManager.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/CodeGen/BackendUtil.h"
18 #include "clang/CodeGen/ModuleBuilder.h"
19 #include "clang/Frontend/CompilerInstance.h"
20 #include "clang/Frontend/FrontendDiagnostic.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Bitcode/ReaderWriter.h"
23 #include "llvm/IR/DebugInfo.h"
24 #include "llvm/IR/DiagnosticInfo.h"
25 #include "llvm/IR/DiagnosticPrinter.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IRReader/IRReader.h"
29 #include "llvm/Linker/Linker.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/Timer.h"
34 #include <memory>
35 using namespace clang;
36 using namespace llvm;
37 
38 namespace clang {
39   class BackendConsumer : public ASTConsumer {
40     virtual void anchor();
41     DiagnosticsEngine &Diags;
42     BackendAction Action;
43     const CodeGenOptions &CodeGenOpts;
44     const TargetOptions &TargetOpts;
45     const LangOptions &LangOpts;
46     raw_ostream *AsmOutStream;
47     ASTContext *Context;
48 
49     Timer LLVMIRGeneration;
50 
51     std::unique_ptr<CodeGenerator> Gen;
52 
53     std::unique_ptr<llvm::Module> TheModule, LinkModule;
54 
55   public:
56     BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
57                     const CodeGenOptions &compopts,
58                     const TargetOptions &targetopts,
59                     const LangOptions &langopts, bool TimePasses,
60                     const std::string &infile, llvm::Module *LinkModule,
61                     raw_ostream *OS, LLVMContext &C)
62         : Diags(_Diags), Action(action), CodeGenOpts(compopts),
63           TargetOpts(targetopts), LangOpts(langopts), AsmOutStream(OS),
64           Context(), LLVMIRGeneration("LLVM IR Generation Time"),
65           Gen(CreateLLVMCodeGen(Diags, infile, compopts, targetopts, C)),
66           LinkModule(LinkModule) {
67       llvm::TimePassesIsEnabled = TimePasses;
68     }
69 
70     llvm::Module *takeModule() { return TheModule.release(); }
71     llvm::Module *takeLinkModule() { return LinkModule.release(); }
72 
73     void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
74       Gen->HandleCXXStaticMemberVarInstantiation(VD);
75     }
76 
77     void Initialize(ASTContext &Ctx) override {
78       Context = &Ctx;
79 
80       if (llvm::TimePassesIsEnabled)
81         LLVMIRGeneration.startTimer();
82 
83       Gen->Initialize(Ctx);
84 
85       TheModule.reset(Gen->GetModule());
86 
87       if (llvm::TimePassesIsEnabled)
88         LLVMIRGeneration.stopTimer();
89     }
90 
91     bool HandleTopLevelDecl(DeclGroupRef D) override {
92       PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
93                                      Context->getSourceManager(),
94                                      "LLVM IR generation of declaration");
95 
96       if (llvm::TimePassesIsEnabled)
97         LLVMIRGeneration.startTimer();
98 
99       Gen->HandleTopLevelDecl(D);
100 
101       if (llvm::TimePassesIsEnabled)
102         LLVMIRGeneration.stopTimer();
103 
104       return true;
105     }
106 
107     void HandleTranslationUnit(ASTContext &C) override {
108       {
109         PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
110         if (llvm::TimePassesIsEnabled)
111           LLVMIRGeneration.startTimer();
112 
113         Gen->HandleTranslationUnit(C);
114 
115         if (llvm::TimePassesIsEnabled)
116           LLVMIRGeneration.stopTimer();
117       }
118 
119       // Silently ignore if we weren't initialized for some reason.
120       if (!TheModule)
121         return;
122 
123       // Make sure IR generation is happy with the module. This is released by
124       // the module provider.
125       llvm::Module *M = Gen->ReleaseModule();
126       if (!M) {
127         // The module has been released by IR gen on failures, do not double
128         // free.
129         TheModule.release();
130         return;
131       }
132 
133       assert(TheModule.get() == M &&
134              "Unexpected module change during IR generation");
135 
136       // Link LinkModule into this module if present, preserving its validity.
137       if (LinkModule) {
138         std::string ErrorMsg;
139         if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource,
140                                 &ErrorMsg)) {
141           Diags.Report(diag::err_fe_cannot_link_module)
142             << LinkModule->getModuleIdentifier() << ErrorMsg;
143           return;
144         }
145       }
146 
147       // Install an inline asm handler so that diagnostics get printed through
148       // our diagnostics hooks.
149       LLVMContext &Ctx = TheModule->getContext();
150       LLVMContext::InlineAsmDiagHandlerTy OldHandler =
151         Ctx.getInlineAsmDiagnosticHandler();
152       void *OldContext = Ctx.getInlineAsmDiagnosticContext();
153       Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
154 
155       LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
156           Ctx.getDiagnosticHandler();
157       void *OldDiagnosticContext = Ctx.getDiagnosticContext();
158       Ctx.setDiagnosticHandler(DiagnosticHandler, this);
159 
160       EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
161                         C.getTargetInfo().getTargetDescription(),
162                         TheModule.get(), Action, AsmOutStream);
163 
164       Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
165 
166       Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
167     }
168 
169     void HandleTagDeclDefinition(TagDecl *D) override {
170       PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
171                                      Context->getSourceManager(),
172                                      "LLVM IR generation of declaration");
173       Gen->HandleTagDeclDefinition(D);
174     }
175 
176     void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
177       Gen->HandleTagDeclRequiredDefinition(D);
178     }
179 
180     void CompleteTentativeDefinition(VarDecl *D) override {
181       Gen->CompleteTentativeDefinition(D);
182     }
183 
184     void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
185       Gen->HandleVTable(RD, DefinitionRequired);
186     }
187 
188     void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
189       Gen->HandleLinkerOptionPragma(Opts);
190     }
191 
192     void HandleDetectMismatch(llvm::StringRef Name,
193                                       llvm::StringRef Value) override {
194       Gen->HandleDetectMismatch(Name, Value);
195     }
196 
197     void HandleDependentLibrary(llvm::StringRef Opts) override {
198       Gen->HandleDependentLibrary(Opts);
199     }
200 
201     static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
202                                      unsigned LocCookie) {
203       SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
204       ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
205     }
206 
207     static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
208                                   void *Context) {
209       ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
210     }
211 
212     void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
213                                SourceLocation LocCookie);
214 
215     void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
216     /// \brief Specialized handler for InlineAsm diagnostic.
217     /// \return True if the diagnostic has been successfully reported, false
218     /// otherwise.
219     bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
220     /// \brief Specialized handler for StackSize diagnostic.
221     /// \return True if the diagnostic has been successfully reported, false
222     /// otherwise.
223     bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
224     /// \brief Specialized handler for the optimization diagnostic.
225     /// Note that this handler only accepts remarks and it always handles
226     /// them.
227     void
228     OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
229   };
230 
231   void BackendConsumer::anchor() {}
232 }
233 
234 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
235 /// buffer to be a valid FullSourceLoc.
236 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
237                                             SourceManager &CSM) {
238   // Get both the clang and llvm source managers.  The location is relative to
239   // a memory buffer that the LLVM Source Manager is handling, we need to add
240   // a copy to the Clang source manager.
241   const llvm::SourceMgr &LSM = *D.getSourceMgr();
242 
243   // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
244   // already owns its one and clang::SourceManager wants to own its one.
245   const MemoryBuffer *LBuf =
246   LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
247 
248   // Create the copy and transfer ownership to clang::SourceManager.
249   llvm::MemoryBuffer *CBuf =
250   llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
251                                        LBuf->getBufferIdentifier());
252   FileID FID = CSM.createFileIDForMemBuffer(CBuf);
253 
254   // Translate the offset into the file.
255   unsigned Offset = D.getLoc().getPointer()  - LBuf->getBufferStart();
256   SourceLocation NewLoc =
257   CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
258   return FullSourceLoc(NewLoc, CSM);
259 }
260 
261 
262 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
263 /// error parsing inline asm.  The SMDiagnostic indicates the error relative to
264 /// the temporary memory buffer that the inline asm parser has set up.
265 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
266                                             SourceLocation LocCookie) {
267   // There are a couple of different kinds of errors we could get here.  First,
268   // we re-format the SMDiagnostic in terms of a clang diagnostic.
269 
270   // Strip "error: " off the start of the message string.
271   StringRef Message = D.getMessage();
272   if (Message.startswith("error: "))
273     Message = Message.substr(7);
274 
275   // If the SMDiagnostic has an inline asm source location, translate it.
276   FullSourceLoc Loc;
277   if (D.getLoc() != SMLoc())
278     Loc = ConvertBackendLocation(D, Context->getSourceManager());
279 
280 
281   // If this problem has clang-level source location information, report the
282   // issue as being an error in the source with a note showing the instantiated
283   // code.
284   if (LocCookie.isValid()) {
285     Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
286 
287     if (D.getLoc().isValid()) {
288       DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
289       // Convert the SMDiagnostic ranges into SourceRange and attach them
290       // to the diagnostic.
291       for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
292         std::pair<unsigned, unsigned> Range = D.getRanges()[i];
293         unsigned Column = D.getColumnNo();
294         B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
295                          Loc.getLocWithOffset(Range.second - Column));
296       }
297     }
298     return;
299   }
300 
301   // Otherwise, report the backend error as occurring in the generated .s file.
302   // If Loc is invalid, we still need to report the error, it just gets no
303   // location info.
304   Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
305 }
306 
307 #define ComputeDiagID(Severity, GroupName, DiagID)                             \
308   do {                                                                         \
309     switch (Severity) {                                                        \
310     case llvm::DS_Error:                                                       \
311       DiagID = diag::err_fe_##GroupName;                                       \
312       break;                                                                   \
313     case llvm::DS_Warning:                                                     \
314       DiagID = diag::warn_fe_##GroupName;                                      \
315       break;                                                                   \
316     case llvm::DS_Remark:                                                      \
317       llvm_unreachable("'remark' severity not expected");                      \
318       break;                                                                   \
319     case llvm::DS_Note:                                                        \
320       DiagID = diag::note_fe_##GroupName;                                      \
321       break;                                                                   \
322     }                                                                          \
323   } while (false)
324 
325 #define ComputeDiagRemarkID(Severity, GroupName, DiagID)                       \
326   do {                                                                         \
327     switch (Severity) {                                                        \
328     case llvm::DS_Error:                                                       \
329       DiagID = diag::err_fe_##GroupName;                                       \
330       break;                                                                   \
331     case llvm::DS_Warning:                                                     \
332       DiagID = diag::warn_fe_##GroupName;                                      \
333       break;                                                                   \
334     case llvm::DS_Remark:                                                      \
335       DiagID = diag::remark_fe_##GroupName;                                    \
336       break;                                                                   \
337     case llvm::DS_Note:                                                        \
338       DiagID = diag::note_fe_##GroupName;                                      \
339       break;                                                                   \
340     }                                                                          \
341   } while (false)
342 
343 bool
344 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
345   unsigned DiagID;
346   ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
347   std::string Message = D.getMsgStr().str();
348 
349   // If this problem has clang-level source location information, report the
350   // issue as being a problem in the source with a note showing the instantiated
351   // code.
352   SourceLocation LocCookie =
353       SourceLocation::getFromRawEncoding(D.getLocCookie());
354   if (LocCookie.isValid())
355     Diags.Report(LocCookie, DiagID).AddString(Message);
356   else {
357     // Otherwise, report the backend diagnostic as occurring in the generated
358     // .s file.
359     // If Loc is invalid, we still need to report the diagnostic, it just gets
360     // no location info.
361     FullSourceLoc Loc;
362     Diags.Report(Loc, DiagID).AddString(Message);
363   }
364   // We handled all the possible severities.
365   return true;
366 }
367 
368 bool
369 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
370   if (D.getSeverity() != llvm::DS_Warning)
371     // For now, the only support we have for StackSize diagnostic is warning.
372     // We do not know how to format other severities.
373     return false;
374 
375   // FIXME: We should demangle the function name.
376   // FIXME: Is there a way to get a location for that function?
377   FullSourceLoc Loc;
378   Diags.Report(Loc, diag::warn_fe_backend_frame_larger_than)
379       << D.getStackSize() << D.getFunction().getName();
380   return true;
381 }
382 
383 void BackendConsumer::OptimizationRemarkHandler(
384     const llvm::DiagnosticInfoOptimizationRemark &D) {
385   // We only support remarks.
386   assert(D.getSeverity() == llvm::DS_Remark);
387 
388   // Optimization remarks are active only if -Rpass=regexp is given and the
389   // regular expression pattern in 'regexp' matches the name of the pass
390   // name in \p D.
391   if (CodeGenOpts.OptimizationRemarkPattern &&
392       CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName())) {
393     SourceManager &SourceMgr = Context->getSourceManager();
394     FileManager &FileMgr = SourceMgr.getFileManager();
395     StringRef Filename;
396     unsigned Line, Column;
397     D.getLocation(&Filename, &Line, &Column);
398     SourceLocation Loc;
399     if (Line > 0) {
400       // If -gcolumn-info was not used, Column will be 0. This upsets the
401       // source manager, so if Column is not set, set it to 1.
402       if (Column == 0)
403         Column = 1;
404       Loc = SourceMgr.translateFileLineCol(FileMgr.getFile(Filename), Line,
405                                            Column);
406     }
407     Diags.Report(Loc, diag::remark_fe_backend_optimization_remark)
408         << AddFlagValue(D.getPassName()) << D.getMsg().str();
409 
410     if (Line == 0)
411       // If we could not extract a source location for the diagnostic,
412       // inform the user how they can get source locations back.
413       //
414       // FIXME: We should really be generating !srcloc annotations when
415       // -Rpass is used. !srcloc annotations need to be emitted in
416       // approximately the same spots as !dbg nodes.
417       Diags.Report(diag::note_fe_backend_optimization_remark_missing_loc);
418   }
419 }
420 
421 /// \brief This function is invoked when the backend needs
422 /// to report something to the user.
423 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
424   unsigned DiagID = diag::err_fe_inline_asm;
425   llvm::DiagnosticSeverity Severity = DI.getSeverity();
426   // Get the diagnostic ID based.
427   switch (DI.getKind()) {
428   case llvm::DK_InlineAsm:
429     if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
430       return;
431     ComputeDiagID(Severity, inline_asm, DiagID);
432     break;
433   case llvm::DK_StackSize:
434     if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
435       return;
436     ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
437     break;
438   case llvm::DK_OptimizationRemark:
439     // Optimization remarks are always handled completely by this
440     // handler. There is no generic way of emitting them.
441     OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
442     return;
443   default:
444     // Plugin IDs are not bound to any value as they are set dynamically.
445     ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
446     break;
447   }
448   std::string MsgStorage;
449   {
450     raw_string_ostream Stream(MsgStorage);
451     DiagnosticPrinterRawOStream DP(Stream);
452     DI.print(DP);
453   }
454 
455   // Report the backend message using the usual diagnostic mechanism.
456   FullSourceLoc Loc;
457   Diags.Report(Loc, DiagID).AddString(MsgStorage);
458 }
459 #undef ComputeDiagID
460 
461 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
462   : Act(_Act), LinkModule(0),
463     VMContext(_VMContext ? _VMContext : new LLVMContext),
464     OwnsVMContext(!_VMContext) {}
465 
466 CodeGenAction::~CodeGenAction() {
467   TheModule.reset();
468   if (OwnsVMContext)
469     delete VMContext;
470 }
471 
472 bool CodeGenAction::hasIRSupport() const { return true; }
473 
474 void CodeGenAction::EndSourceFileAction() {
475   // If the consumer creation failed, do nothing.
476   if (!getCompilerInstance().hasASTConsumer())
477     return;
478 
479   // If we were given a link module, release consumer's ownership of it.
480   if (LinkModule)
481     BEConsumer->takeLinkModule();
482 
483   // Steal the module from the consumer.
484   TheModule.reset(BEConsumer->takeModule());
485 }
486 
487 llvm::Module *CodeGenAction::takeModule() { return TheModule.release(); }
488 
489 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
490   OwnsVMContext = false;
491   return VMContext;
492 }
493 
494 static raw_ostream *GetOutputStream(CompilerInstance &CI,
495                                     StringRef InFile,
496                                     BackendAction Action) {
497   switch (Action) {
498   case Backend_EmitAssembly:
499     return CI.createDefaultOutputFile(false, InFile, "s");
500   case Backend_EmitLL:
501     return CI.createDefaultOutputFile(false, InFile, "ll");
502   case Backend_EmitBC:
503     return CI.createDefaultOutputFile(true, InFile, "bc");
504   case Backend_EmitNothing:
505     return 0;
506   case Backend_EmitMCNull:
507   case Backend_EmitObj:
508     return CI.createDefaultOutputFile(true, InFile, "o");
509   }
510 
511   llvm_unreachable("Invalid action!");
512 }
513 
514 ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
515                                               StringRef InFile) {
516   BackendAction BA = static_cast<BackendAction>(Act);
517   std::unique_ptr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
518   if (BA != Backend_EmitNothing && !OS)
519     return 0;
520 
521   llvm::Module *LinkModuleToUse = LinkModule;
522 
523   // If we were not given a link module, and the user requested that one be
524   // loaded from bitcode, do so now.
525   const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
526   if (!LinkModuleToUse && !LinkBCFile.empty()) {
527     std::string ErrorStr;
528 
529     llvm::MemoryBuffer *BCBuf =
530       CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
531     if (!BCBuf) {
532       CI.getDiagnostics().Report(diag::err_cannot_open_file)
533         << LinkBCFile << ErrorStr;
534       return 0;
535     }
536 
537     ErrorOr<llvm::Module *> ModuleOrErr =
538         getLazyBitcodeModule(BCBuf, *VMContext);
539     if (error_code EC = ModuleOrErr.getError()) {
540       CI.getDiagnostics().Report(diag::err_cannot_open_file)
541         << LinkBCFile << EC.message();
542       return 0;
543     }
544     LinkModuleToUse = ModuleOrErr.get();
545   }
546 
547   BEConsumer = new BackendConsumer(BA, CI.getDiagnostics(), CI.getCodeGenOpts(),
548                                    CI.getTargetOpts(), CI.getLangOpts(),
549                                    CI.getFrontendOpts().ShowTimers, InFile,
550                                    LinkModuleToUse, OS.release(), *VMContext);
551   return BEConsumer;
552 }
553 
554 void CodeGenAction::ExecuteAction() {
555   // If this is an IR file, we have to treat it specially.
556   if (getCurrentFileKind() == IK_LLVM_IR) {
557     BackendAction BA = static_cast<BackendAction>(Act);
558     CompilerInstance &CI = getCompilerInstance();
559     raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
560     if (BA != Backend_EmitNothing && !OS)
561       return;
562 
563     bool Invalid;
564     SourceManager &SM = CI.getSourceManager();
565     const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
566                                                       &Invalid);
567     if (Invalid)
568       return;
569 
570     // FIXME: This is stupid, IRReader shouldn't take ownership.
571     llvm::MemoryBuffer *MainFileCopy =
572       llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
573                                            getCurrentFile());
574 
575     llvm::SMDiagnostic Err;
576     TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
577     if (!TheModule) {
578       // Translate from the diagnostic info to the SourceManager location.
579       SourceLocation Loc = SM.translateFileLineCol(
580         SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
581         Err.getColumnNo() + 1);
582 
583       // Strip off a leading diagnostic code if there is one.
584       StringRef Msg = Err.getMessage();
585       if (Msg.startswith("error: "))
586         Msg = Msg.substr(7);
587 
588       unsigned DiagID =
589           CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
590 
591       CI.getDiagnostics().Report(Loc, DiagID) << Msg;
592       return;
593     }
594     const TargetOptions &TargetOpts = CI.getTargetOpts();
595     if (TheModule->getTargetTriple() != TargetOpts.Triple) {
596       unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
597           DiagnosticsEngine::Warning,
598           "overriding the module target triple with %0");
599 
600       CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple;
601       TheModule->setTargetTriple(TargetOpts.Triple);
602     }
603 
604     EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
605                       CI.getLangOpts(), CI.getTarget().getTargetDescription(),
606                       TheModule.get(), BA, OS);
607     return;
608   }
609 
610   // Otherwise follow the normal AST path.
611   this->ASTFrontendAction::ExecuteAction();
612 }
613 
614 //
615 
616 void EmitAssemblyAction::anchor() { }
617 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
618   : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
619 
620 void EmitBCAction::anchor() { }
621 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
622   : CodeGenAction(Backend_EmitBC, _VMContext) {}
623 
624 void EmitLLVMAction::anchor() { }
625 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
626   : CodeGenAction(Backend_EmitLL, _VMContext) {}
627 
628 void EmitLLVMOnlyAction::anchor() { }
629 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
630   : CodeGenAction(Backend_EmitNothing, _VMContext) {}
631 
632 void EmitCodeGenOnlyAction::anchor() { }
633 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
634   : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
635 
636 void EmitObjAction::anchor() { }
637 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
638   : CodeGenAction(Backend_EmitObj, _VMContext) {}
639