15#include "llvm/ADT/Hashing.h"
16#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
17#include "llvm/Demangle/Demangle.h"
18#include "llvm/IR/DiagnosticInfo.h"
19#include "llvm/IR/DiagnosticPrinter.h"
20#include "llvm/IR/Function.h"
21#include "llvm/IR/Module.h"
22#include "llvm/Support/raw_ostream.h"
29class BackendDiagnosticHandlerImpl final :
public DiagnosticHandler {
31 BackendDiagnosticHandlerImpl(
const clang::CodeGenOptions &CGOpts,
32 BackendDiagnosticConsumer *Consumer)
33 : CodeGenOpts(CGOpts), Consumer(Consumer) {}
35 bool handleDiagnostics(
const DiagnosticInfo &DI)
override {
36 Consumer->handleDiagnostics(DI);
40 bool isAnalysisRemarkEnabled(StringRef PassName)
const override {
41 return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
43 bool isMissedOptRemarkEnabled(StringRef PassName)
const override {
44 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
46 bool isPassedOptRemarkEnabled(StringRef PassName)
const override {
47 return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
50 bool isAnyRemarkEnabled()
const override {
51 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
52 CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||
53 CodeGenOpts.OptimizationRemark.hasValidPattern();
57 const clang::CodeGenOptions &CodeGenOpts;
58 BackendDiagnosticConsumer *Consumer;
63FullSourceLoc ConvertBackendLocation(
const llvm::SMDiagnostic &D,
68 const llvm::SourceMgr &LSM = *D.getSourceMgr();
72 const MemoryBuffer *LBuf =
73 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
77 std::unique_ptr<llvm::MemoryBuffer> CBuf =
78 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
79 LBuf->getBufferIdentifier());
84 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
92#define ComputeDiagID(Severity, GroupName, DiagID) \
95 case llvm::DS_Error: \
96 DiagID = diag::err_fe_##GroupName; \
98 case llvm::DS_Warning: \
99 DiagID = diag::warn_fe_##GroupName; \
101 case llvm::DS_Remark: \
102 llvm_unreachable("'remark' severity not expected"); \
104 case llvm::DS_Note: \
105 DiagID = diag::note_fe_##GroupName; \
110#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
112 switch (Severity) { \
113 case llvm::DS_Error: \
114 DiagID = diag::err_fe_##GroupName; \
116 case llvm::DS_Warning: \
117 DiagID = diag::warn_fe_##GroupName; \
119 case llvm::DS_Remark: \
120 DiagID = diag::remark_fe_##GroupName; \
122 case llvm::DS_Note: \
123 DiagID = diag::note_fe_##GroupName; \
128std::unique_ptr<llvm::DiagnosticHandler>
130 return std::make_unique<BackendDiagnosticHandlerImpl>(CodeGenOpts,
this);
137 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
140std::optional<FullSourceLoc>
143 for (
const auto &Pair : ManglingFullSourceLocs) {
144 if (Pair.first == Hash)
151BackendDiagnosticConsumer::getSourceFile(
const llvm::DIFile *
File,
153 auto It = DIFileSources.find(
File);
156 if (It != DIFileSources.end())
159 for (StringRef Name : Names)
160 if (
auto FE =
FileMgr.getOptionalFileRef(Name))
166 const llvm::DiagnosticInfoWithLocationBase &D,
bool &BadDebugInfo,
167 StringRef &Filename,
unsigned &
Line,
unsigned &
Column)
const {
171 if (D.isLocationAvailable()) {
174 auto FE = getSourceFile(D.getLocation().getFile(),
175 {Filename, D.getAbsolutePath()});
194 if (DILoc.
isInvalid() && D.isLocationAvailable())
199 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
205void BackendDiagnosticConsumer::SrcMgrDiagHandler(
206 const llvm::DiagnosticInfoSrcMgr &DI) {
207 const llvm::SMDiagnostic &D = DI.getSMDiag();
210 if (DI.isInlineAsmDiag())
218 D.print(
nullptr, llvm::errs());
227 StringRef Message = D.getMessage();
228 (void)Message.consume_front(
"error: ");
232 if (D.getLoc() != SMLoc())
233 Loc = ConvertBackendLocation(D, *SM);
238 if (DI.isInlineAsmDiag()) {
244 if (D.getLoc().isValid()) {
248 for (
const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
249 unsigned Column = D.getColumnNo();
261 Diags.Report(Loc, DiagID).AddString(Message);
264bool BackendDiagnosticConsumer::InlineAsmDiagHandler(
265 const llvm::DiagnosticInfoInlineAsm &D) {
268 std::string
Message = D.getMsgStr().str();
273 SourceLocation LocCookie =
276 Diags.Report(LocCookie, DiagID).AddString(Message);
283 Diags.Report(Loc, DiagID).AddString(Message);
289bool BackendDiagnosticConsumer::StackSizeDiagHandler(
290 const llvm::DiagnosticInfoStackSize &D) {
291 if (D.getSeverity() != llvm::DS_Warning)
300 Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
301 << D.getStackSize() << D.getStackLimit()
302 << llvm::demangle(D.getFunction().getName());
306bool BackendDiagnosticConsumer::ResourceLimitDiagHandler(
307 const llvm::DiagnosticInfoResourceLimit &D) {
311 unsigned DiagID = diag::err_fe_backend_resource_limit;
312 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
314 Diags.Report(*Loc, DiagID)
315 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
316 << llvm::demangle(D.getFunction().getName());
320void BackendDiagnosticConsumer::UnsupportedDiagHandler(
321 const llvm::DiagnosticInfoUnsupported &D) {
323 assert(D.getSeverity() == llvm::DS_Error ||
324 D.getSeverity() == llvm::DS_Warning);
328 bool BadDebugInfo =
false;
331 raw_string_ostream MsgStream(Msg);
337 MsgStream << D.getMessage();
339 DiagnosticPrinterRawOStream DP(MsgStream);
343 auto DiagType = D.getSeverity() == llvm::DS_Error
344 ? diag::err_fe_backend_unsupported
345 : diag::warn_fe_backend_unsupported;
346 Diags.Report(Loc, DiagType) << Msg;
353 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
357void BackendDiagnosticConsumer::UnsupportedTargetIntrinsicDiagHandler(
358 const llvm::DiagnosticInfoUnsupportedTargetIntrinsic &D) {
359 assert(D.getSeverity() == llvm::DS_Error &&
360 "unsupported target intrinsic diagnostic should be an error");
364 bool BadDebugInfo =
false;
367 raw_string_ostream MsgStream(Msg);
373 MsgStream << D.getMessage();
375 DiagnosticPrinterRawOStream DP(MsgStream);
379 Diags.Report(Loc, diag::err_fe_backend_unsupported) << Msg;
386 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
391void BackendDiagnosticConsumer::EmitOptimizationMessage(
392 const llvm::DiagnosticInfoOptimizationBase &D,
unsigned DiagID) {
394 assert(D.getSeverity() == llvm::DS_Remark ||
395 D.getSeverity() == llvm::DS_Warning);
399 bool BadDebugInfo =
false;
402 raw_string_ostream MsgStream(Msg);
408 MsgStream << D.getMsg();
410 DiagnosticPrinterRawOStream DP(MsgStream);
415 MsgStream <<
" (hotness: " << *D.getHotness() <<
")";
417 Diags.Report(Loc, DiagID) << AddFlagValue(D.getPassName()) << Msg;
424 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
428void BackendDiagnosticConsumer::OptimizationRemarkHandler(
429 const llvm::DiagnosticInfoOptimizationBase &D) {
431 if (D.isVerbose() && !D.getHotness())
437 if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
438 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
439 }
else if (D.isMissed()) {
443 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
444 EmitOptimizationMessage(
445 D, diag::remark_fe_backend_optimization_remark_missed);
447 assert(D.isAnalysis() &&
"Unknown remark type");
449 bool ShouldAlwaysPrint =
false;
450 if (
auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
451 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
453 if (ShouldAlwaysPrint ||
454 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
455 EmitOptimizationMessage(
456 D, diag::remark_fe_backend_optimization_remark_analysis);
460void BackendDiagnosticConsumer::OptimizationRemarkHandler(
461 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
466 if (D.shouldAlwaysPrint() ||
467 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
468 EmitOptimizationMessage(
469 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
472void BackendDiagnosticConsumer::OptimizationRemarkHandler(
473 const llvm::OptimizationRemarkAnalysisAliasing &D) {
478 if (D.shouldAlwaysPrint() ||
479 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
480 EmitOptimizationMessage(
481 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
484void BackendDiagnosticConsumer::OptimizationFailureHandler(
485 const llvm::DiagnosticInfoOptimizationFailure &D) {
486 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
489void BackendDiagnosticConsumer::DontCallDiagHandler(
490 const DiagnosticInfoDontCall &D) {
491 SourceLocation LocCookie =
499 Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
500 ? diag::err_fe_backend_error_attr
501 : diag::warn_fe_backend_warning_attr)
502 << llvm::demangle(D.getFunctionName()) << D.getNote();
504 if (!CodeGenOpts.ShowInliningChain)
507 auto EmitNote = [&](SourceLocation Loc, StringRef FuncName,
bool IsFirst) {
511 IsFirst ? diag::note_fe_backend_in : diag::note_fe_backend_inlined;
512 Diags.Report(Loc, DiagID) << llvm::demangle(FuncName.str());
516 if (!D.getDebugInlineChain().empty()) {
517 SourceManager &SrcMgr = *SM;
518 for (
const auto &[I, Info] : llvm::enumerate(D.getDebugInlineChain())) {
521 if (
auto FE = getSourceFile(Info.File, Info.Filename))
523 Info.Column ? Info.Column : 1);
524 EmitNote(Loc, Info.FuncName, I == 0);
530 auto InliningDecisions = D.getInliningDecisions();
531 if (InliningDecisions.empty())
534 for (
const auto &[I, Entry] : llvm::enumerate(InliningDecisions)) {
537 EmitNote(Loc, Entry.first, I == 0);
542 Diags.Report(LocCookie, diag::note_fe_backend_inlining_debug_info);
545void BackendDiagnosticConsumer::MisExpectDiagHandler(
546 const llvm::DiagnosticInfoMisExpect &D) {
549 bool BadDebugInfo =
false;
553 Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
560 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
565 unsigned DiagID = diag::err_fe_inline_asm;
566 llvm::DiagnosticSeverity Severity = DI.getSeverity();
568 switch (DI.getKind()) {
569 case llvm::DK_InlineAsm:
574 case llvm::DK_SrcMgr:
577 case llvm::DK_StackSize:
582 case llvm::DK_ResourceLimit:
590 case llvm::DK_OptimizationRemark:
595 case llvm::DK_OptimizationRemarkMissed:
600 case llvm::DK_OptimizationRemarkAnalysis:
605 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
610 case llvm::DK_OptimizationRemarkAnalysisAliasing:
615 case llvm::DK_MachineOptimizationRemark:
620 case llvm::DK_MachineOptimizationRemarkMissed:
625 case llvm::DK_MachineOptimizationRemarkAnalysis:
630 case llvm::DK_OptimizationFailure:
635 case llvm::DK_Unsupported:
638 case llvm::DK_UnsupportedTargetIntrinsic:
639 UnsupportedTargetIntrinsicDiagHandler(
642 case llvm::DK_DontCall:
645 case llvm::DK_MisExpect:
653 std::string MsgStorage;
655 raw_string_ostream Stream(MsgStorage);
656 DiagnosticPrinterRawOStream DP(Stream);
660 if (DI.getKind() == DK_Linker) {
661 assert(CurLinkModule &&
"CurLinkModule must be set for linker diagnostics");
662 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
668 Diags.Report(Loc, DiagID).AddString(MsgStorage);
672#undef ComputeDiagRemarkID
#define ComputeDiagID(Severity, GroupName, DiagID)
#define ComputeDiagRemarkID(Severity, GroupName, DiagID)
Defines the Diagnostic-related interfaces.
Defines the clang::FileManager interface and associated types.
Defines the SourceManager interface.
void addFunctionSourceLocation(StringRef MangledName, FullSourceLoc Loc)
Record the source location of the function with the given mangled name, used to approximate a locatio...
std::unique_ptr< llvm::DiagnosticHandler > createDiagnosticHandler()
Create an llvm::DiagnosticHandler that forwards diagnostics to this consumer.
std::optional< FullSourceLoc > getFunctionSourceLocation(const llvm::Function &F) const
void handleDiagnostics(const llvm::DiagnosticInfo &DI)
This is invoked when the backend needs to report something to the user.
const FullSourceLoc getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo, StringRef &Filename, unsigned &Line, unsigned &Column) const
Get the best possible source location to represent a diagnostic that may have associated debug info.
A little helper class used to produce diagnostics.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
A SourceLocation and its associated SourceManager.
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
FileID createFileID(FileEntryRef SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
FileManager & getFileManager() const
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
A trivial tuple used to represent a source range.
void AddString(StringRef V) const
Top level wrappers for InstallAPI frontend operations.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
U cast(CodeGen::Address addr)
Diagnostic wrappers for TextAPI types for error reporting.
hash_code hash_value(const clang::dependencies::ModuleID &ID)