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