LLVM  5.0.0
DiagnosticInfo.cpp
Go to the documentation of this file.
1 //===- llvm/Support/DiagnosticInfo.cpp - Diagnostic Definitions -*- C++ -*-===//
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 // This file defines the different classes involved in low level diagnostics.
11 //
12 // Diagnostics reporting is still done as part of the LLVMContext.
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/IR/DiagnosticInfo.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Twine.h"
19 #include "llvm/IR/BasicBlock.h"
20 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/Instruction.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Metadata.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/Regex.h"
37 #include <atomic>
38 #include <cassert>
39 #include <memory>
40 #include <string>
41 
42 using namespace llvm;
43 
44 namespace {
45 
46 /// \brief Regular expression corresponding to the value given in one of the
47 /// -pass-remarks* command line flags. Passes whose name matches this regexp
48 /// will emit a diagnostic when calling the associated diagnostic function
49 /// (emitOptimizationRemark, emitOptimizationRemarkMissed or
50 /// emitOptimizationRemarkAnalysis).
51 struct PassRemarksOpt {
52  std::shared_ptr<Regex> Pattern;
53 
54  void operator=(const std::string &Val) {
55  // Create a regexp object to match pass names for emitOptimizationRemark.
56  if (!Val.empty()) {
57  Pattern = std::make_shared<Regex>(Val);
58  std::string RegexError;
59  if (!Pattern->isValid(RegexError))
60  report_fatal_error("Invalid regular expression '" + Val +
61  "' in -pass-remarks: " + RegexError,
62  false);
63  }
64  }
65 };
66 
67 } // end anonymous namespace
68 
69 static PassRemarksOpt PassRemarksOptLoc;
70 static PassRemarksOpt PassRemarksMissedOptLoc;
71 static PassRemarksOpt PassRemarksAnalysisOptLoc;
72 
73 // -pass-remarks
74 // Command line flag to enable emitOptimizationRemark()
76 PassRemarks("pass-remarks", cl::value_desc("pattern"),
77  cl::desc("Enable optimization remarks from passes whose name match "
78  "the given regular expression"),
81 
82 // -pass-remarks-missed
83 // Command line flag to enable emitOptimizationRemarkMissed()
85  "pass-remarks-missed", cl::value_desc("pattern"),
86  cl::desc("Enable missed optimization remarks from passes whose name match "
87  "the given regular expression"),
90 
91 // -pass-remarks-analysis
92 // Command line flag to enable emitOptimizationRemarkAnalysis()
95  "pass-remarks-analysis", cl::value_desc("pattern"),
96  cl::desc(
97  "Enable optimization analysis remarks from passes whose name match "
98  "the given regular expression"),
101 
103  static std::atomic<int> PluginKindID(DK_FirstPluginKind);
104  return ++PluginKindID;
105 }
106 
108 
110  const Twine &MsgStr,
111  DiagnosticSeverity Severity)
112  : DiagnosticInfo(DK_InlineAsm, Severity), MsgStr(MsgStr), Instr(&I) {
113  if (const MDNode *SrcLoc = I.getMetadata("srcloc")) {
114  if (SrcLoc->getNumOperands() != 0)
115  if (const auto *CI =
116  mdconst::dyn_extract<ConstantInt>(SrcLoc->getOperand(0)))
117  LocCookie = CI->getZExtValue();
118  }
119 }
120 
122  DP << getMsgStr();
123  if (getLocCookie())
124  DP << " at line " << getLocCookie();
125 }
126 
128  DP << getResourceName() << " limit";
129 
130  if (getResourceLimit() != 0)
131  DP << " of " << getResourceLimit();
132 
133  DP << " exceeded (" << getResourceSize() << ") in " << getFunction();
134 }
135 
137  DP << "ignoring debug info with an invalid version (" << getMetadataVersion()
138  << ") in " << getModule();
139 }
140 
142  DiagnosticPrinter &DP) const {
143  DP << "ignoring invalid debug info in " << getModule().getModuleIdentifier();
144 }
145 
147  if (!FileName.empty()) {
148  DP << getFileName();
149  if (LineNum > 0)
150  DP << ":" << getLineNum();
151  DP << ": ";
152  }
153  DP << getMsg();
154 }
155 
157  if (getFileName())
158  DP << getFileName() << ": ";
159  DP << getMsg();
160 }
161 
163  if (!DL)
164  return;
165  Filename = DL->getFilename();
166  Line = DL->getLine();
167  Column = DL->getColumn();
168 }
169 
171  if (!SP)
172  return;
173  Filename = SP->getFilename();
174  Line = SP->getScopeLine();
175  Column = 0;
176 }
177 
179  unsigned *Line,
180  unsigned *Column) const {
181  *Filename = Loc.getFilename();
182  *Line = Loc.getLine();
183  *Column = Loc.getColumn();
184 }
185 
187  StringRef Filename("<unknown>");
188  unsigned Line = 0;
189  unsigned Column = 0;
190  if (isLocationAvailable())
191  getLocation(&Filename, &Line, &Column);
192  return (Filename + ":" + Twine(Line) + ":" + Twine(Column)).str();
193 }
194 
196  : Key(Key) {
197  if (auto *F = dyn_cast<Function>(V)) {
198  if (DISubprogram *SP = F->getSubprogram())
199  Loc = SP;
200  }
201  else if (auto *I = dyn_cast<Instruction>(V))
202  Loc = I->getDebugLoc();
203 
204  // Only include names that correspond to user variables. FIXME: we should use
205  // debug info if available to get the name of the user variable.
206  if (isa<llvm::Argument>(V) || isa<GlobalValue>(V))
208  else if (isa<Constant>(V)) {
209  raw_string_ostream OS(Val);
210  V->printAsOperand(OS, /*PrintType=*/false);
211  } else if (auto *I = dyn_cast<Instruction>(V))
212  Val = I->getOpcodeName();
213 }
214 
216  : Key(Key) {
217  raw_string_ostream OS(Val);
218  OS << *T;
219 }
220 
222  : Key(Key), Val(itostr(N)) {}
223 
225  : Key(Key), Val(utostr(N)) {}
226 
228  DP << getLocationStr() << ": " << getMsg();
229  if (Hotness)
230  DP << " (hotness: " << *Hotness << ")";
231 }
232 
235  const DiagnosticLocation &Loc,
236  const Value *CodeRegion)
238  DK_OptimizationRemark, DS_Remark, PassName, RemarkName,
239  *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {}
240 
242  StringRef RemarkName,
243  const Instruction *Inst)
245  RemarkName, *Inst->getParent()->getParent(),
246  Inst->getDebugLoc(), Inst->getParent()) {}
247 
248 // Helper to allow for an assert before attempting to return an invalid
249 // reference.
250 static const BasicBlock &getFirstFunctionBlock(const Function *Func) {
251  assert(!Func->empty() && "Function does not have a body");
252  return Func->front();
253 }
254 
256  StringRef RemarkName,
257  const Function *Func)
259  RemarkName, *Func, Func->getSubprogram(),
260  &getFirstFunctionBlock(Func)) {}
261 
263  return PassRemarksOptLoc.Pattern &&
264  PassRemarksOptLoc.Pattern->match(PassName);
265 }
266 
268  const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc,
269  const Value *CodeRegion)
271  DK_OptimizationRemarkMissed, DS_Remark, PassName, RemarkName,
272  *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {}
273 
275  StringRef RemarkName,
276  const Instruction *Inst)
278  PassName, RemarkName,
279  *Inst->getParent()->getParent(),
280  Inst->getDebugLoc(), Inst->getParent()) {}
281 
283  return PassRemarksMissedOptLoc.Pattern &&
284  PassRemarksMissedOptLoc.Pattern->match(PassName);
285 }
286 
288  const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc,
289  const Value *CodeRegion)
291  DK_OptimizationRemarkAnalysis, DS_Remark, PassName, RemarkName,
292  *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {}
293 
295  StringRef RemarkName,
296  const Instruction *Inst)
298  PassName, RemarkName,
299  *Inst->getParent()->getParent(),
300  Inst->getDebugLoc(), Inst->getParent()) {}
301 
303  enum DiagnosticKind Kind, const char *PassName, StringRef RemarkName,
304  const DiagnosticLocation &Loc, const Value *CodeRegion)
305  : DiagnosticInfoIROptimization(Kind, DS_Remark, PassName, RemarkName,
306  *cast<BasicBlock>(CodeRegion)->getParent(),
307  Loc, CodeRegion) {}
308 
310  return PassRemarksAnalysisOptLoc.Pattern &&
311  PassRemarksAnalysisOptLoc.Pattern->match(PassName);
312 }
313 
315  DP << Diagnostic;
316 }
317 
318 void llvm::emitOptimizationRemark(LLVMContext &Ctx, const char *PassName,
319  const Function &Fn,
320  const DiagnosticLocation &Loc,
321  const Twine &Msg) {
322  Ctx.diagnose(OptimizationRemark(PassName, Fn, Loc, Msg));
323 }
324 
325 void llvm::emitOptimizationRemarkMissed(LLVMContext &Ctx, const char *PassName,
326  const Function &Fn,
327  const DiagnosticLocation &Loc,
328  const Twine &Msg) {
329  Ctx.diagnose(OptimizationRemarkMissed(PassName, Fn, Loc, Msg));
330 }
331 
333  const char *PassName,
334  const Function &Fn,
335  const DiagnosticLocation &Loc,
336  const Twine &Msg) {
337  Ctx.diagnose(OptimizationRemarkAnalysis(PassName, Fn, Loc, Msg));
338 }
339 
341  LLVMContext &Ctx, const char *PassName, const Function &Fn,
342  const DiagnosticLocation &Loc, const Twine &Msg) {
343  Ctx.diagnose(OptimizationRemarkAnalysisFPCommute(PassName, Fn, Loc, Msg));
344 }
345 
347  const char *PassName,
348  const Function &Fn,
349  const DiagnosticLocation &Loc,
350  const Twine &Msg) {
351  Ctx.diagnose(OptimizationRemarkAnalysisAliasing(PassName, Fn, Loc, Msg));
352 }
353 
355  const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc,
356  const Value *CodeRegion)
358  DK_OptimizationFailure, DS_Warning, PassName, RemarkName,
359  *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {}
360 
362  // Only print warnings.
363  return getSeverity() == DS_Warning;
364 }
365 
367  std::string Str;
368  raw_string_ostream OS(Str);
369 
370  OS << getLocationStr() << ": in function " << getFunction().getName() << ' '
371  << *getFunction().getFunctionType() << ": " << Msg << '\n';
372  OS.flush();
373  DP << Str;
374 }
375 
377  DP << "Instruction selection used fallback path for " << getFunction();
378 }
379 
382  Args.emplace_back(S);
383  return *this;
384 }
385 
388  Args.push_back(std::move(A));
389  return *this;
390 }
391 
394  IsVerbose = true;
395  return *this;
396 }
397 
400  FirstExtraArgIndex = Args.size();
401  return *this;
402 }
403 
405  std::string Str;
406  raw_string_ostream OS(Str);
408  make_range(Args.begin(), FirstExtraArgIndex == -1
409  ? Args.end()
410  : Args.begin() + FirstExtraArgIndex))
411  OS << Arg.Val;
412  return OS.str();
413 }
const char * PassName
Name of the pass that triggers this report.
DiagnosticKind
Defines the different supported kind of a diagnostic.
StringRef getFilename() const
Diagnostic information for missed-optimization remarks.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:103
bool isEnabled() const override
DiagnosticInfoInlineAsm(const Twine &MsgStr, DiagnosticSeverity Severity=DS_Error)
MsgStr is the message to be reported to the frontend.
OptimizationRemarkAnalysis(const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc, const Value *CodeRegion)
PassName is the name of the pass emitting this diagnostic.
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
DiagnosticInfoOptimizationBase & operator<<(StringRef S)
DataLayout DL
void print(DiagnosticPrinter &DP) const override
This file contains the declarations for metadata subclasses.
Used to set IsVerbose via the stream interface.
static cl::opt< PassRemarksOpt, true, cl::parser< std::string > > PassRemarks("pass-remarks", cl::value_desc("pattern"), cl::desc("Enable optimization remarks from passes whose name match ""the given regular expression"), cl::Hidden, cl::location(PassRemarksOptLoc), cl::ValueRequired, cl::ZeroOrMore)
static PassRemarksOpt PassRemarksAnalysisOptLoc
A debug info location.
Definition: DebugLoc.h:34
Metadata node.
Definition: Metadata.h:862
int FirstExtraArgIndex
If positive, the index of the first argument that only appear in the optimization records and not in ...
void emitOptimizationRemarkAnalysisFPCommute(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg)
Legacy interface to emit an optimization analysis remark related to messages about floating-point non...
When an instance of this is inserted into the stream, the arguments following will not appear in the ...
const Function & getFunction() const
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:218
bool isLocationAvailable() const
Return true if location information is available for this diagnostic.
const std::string getLocationStr() const
Return a string with the location information for this diagnostic in the format "file:line:col".
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
Diagnostic information for optimization analysis remarks.
StringRef getFilename() const
Interface for custom diagnostic printing.
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:208
static cl::opt< PassRemarksOpt, true, cl::parser< std::string > > PassRemarksAnalysis("pass-remarks-analysis", cl::value_desc("pattern"), cl::desc("Enable optimization analysis remarks from passes whose name match ""the given regular expression"), cl::Hidden, cl::location(PassRemarksAnalysisOptLoc), cl::ValueRequired, cl::ZeroOrMore)
Subprogram description.
#define F(x, y, z)
Definition: MD5.cpp:55
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:3538
#define T
void print(DiagnosticPrinter &DP) const override
static std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:160
DiagnosticSeverity getSeverity() const
StringRef RemarkName
Textual identifier for the remark (single-word, camel-case).
Diagnostic information for optimization analysis remarks related to pointer aliasing.
bool isEnabled() const override
std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type cast(const Y &Val)
Definition: Casting.h:240
const Function & getFunction() const
SmallVector< Argument, 4 > Args
Arguments collected via the streaming interface.
void emitOptimizationRemark(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg)
Legacy interface to emit an optimization-applied message.
void emitOptimizationRemarkAnalysisAliasing(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg)
Legacy interface to emit an optimization analysis remark related to messages about pointer aliasing...
This is the base abstract class for diagnostic reporting in the backend.
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
const Twine & getMsg() const
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:137
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define A
Definition: LargeTest.cpp:12
Diagnostic information for applied optimization remarks.
Common features for diagnostics dealing with optimization remarks that are used by IR passes...
const Twine & getMsg() const
const char * getFileName() const
static const BasicBlock & getFirstFunctionBlock(const Function *Func)
unsigned getColumn() const
Used in the streaming interface as the general argument type.
static std::string itostr(int64_t X)
Definition: StringExtras.h:175
OptimizationRemark(const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc, const Value *CodeRegion)
PassName is the name of the pass emitting this diagnostic.
void emitOptimizationRemarkMissed(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg)
Legacy interface to emit an optimization-missed message.
bool isEnabled() const override
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
Definition: raw_ostream.h:479
bool IsVerbose
The remark is expected to be noisy.
void print(DiagnosticPrinter &DP) const override
Print using the given DP a user-friendly message.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
DiagnosticLocation getLocation() const
unsigned getLocCookie() const
Diagnostic information for optimization analysis remarks related to floating-point non-commutativity...
OptimizationRemarkMissed(const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc, const Value *CodeRegion)
PassName is the name of the pass emitting this diagnostic.
Common features for diagnostics dealing with optimization remarks that are used by both IR and MIR pa...
Module.h This file contains the declarations for the Module class.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:190
const size_t N
static PassRemarksOpt PassRemarksOptLoc
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1', drop it.
Definition: GlobalValue.h:451
bool empty() const
Definition: Function.h:586
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
int getNextAvailablePluginDiagnosticKind()
Get the next available kind ID for a plugin diagnostic.
void print(DiagnosticPrinter &DP) const override
void print(DiagnosticPrinter &DP) const override
Print using the given DP a user-friendly message.
static PassRemarksOpt PassRemarksMissedOptLoc
const char * getResourceName() const
void print(DiagnosticPrinter &DP) const override
unsigned getLine() const
#define I(x, y, z)
Definition: MD5.cpp:58
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
void print(DiagnosticPrinter &DP) const override
static cl::opt< PassRemarksOpt, true, cl::parser< std::string > > PassRemarksMissed("pass-remarks-missed", cl::value_desc("pattern"), cl::desc("Enable missed optimization remarks from passes whose name match ""the given regular expression"), cl::Hidden, cl::location(PassRemarksMissedOptLoc), cl::ValueRequired, cl::ZeroOrMore)
const unsigned Kind
void emitOptimizationRemarkAnalysis(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg)
Legacy interface to emit an optimization analysis remark message.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
Definition: Function.h:587
const Twine & getMsgStr() const
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:463
LLVM Value Representation.
Definition: Value.h:73
const Function & getFunction() const
static DISubprogram * getSubprogram(bool IsDistinct, Ts &&...Args)
Definition: DIBuilder.cpp:678
Optional< uint64_t > Hotness
If profile information is available, this is the number of times the corresponding code was executed ...
static const Function * getParent(const Value *V)
void print(DiagnosticPrinter &DP) const override
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
void print(DiagnosticPrinter &DP) const override
void print(DiagnosticPrinter &DP) const override
Print using the given DP a user-friendly message.
LocationClass< Ty > location(Ty &L)
Definition: CommandLine.h:417
DiagnosticInfoOptimizationFailure(const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg)
Fn is the function where the diagnostic is being emitted.