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