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