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