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