LLVM  5.0.0
OptimizationDiagnosticInfo.cpp
Go to the documentation of this file.
1 //===- OptimizationDiagnosticInfo.cpp - Optimization Diagnostic -*- 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 // Optimization diagnostic interfaces. It's packaged as an analysis pass so
11 // that by using this service passes become dependent on BFI as well. BFI is
12 // used to compute the "hotness" of the diagnostic message.
13 //===----------------------------------------------------------------------===//
14 
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DiagnosticInfo.h"
21 #include "llvm/IR/Dominators.h"
22 #include "llvm/IR/LLVMContext.h"
23 
24 using namespace llvm;
25 
27  : F(F), BFI(nullptr) {
29  return;
30 
31  // First create a dominator tree.
32  DominatorTree DT;
33  DT.recalculate(*const_cast<Function *>(F));
34 
35  // Generate LoopInfo from it.
36  LoopInfo LI;
37  LI.analyze(DT);
38 
39  // Then compute BranchProbabilityInfo.
41  BPI.calculate(*F, LI);
42 
43  // Finally compute BFI.
44  OwnedBFI = llvm::make_unique<BlockFrequencyInfo>(*F, BPI, LI);
45  BFI = OwnedBFI.get();
46 }
47 
49  Function &F, const PreservedAnalyses &PA,
51  // This analysis has no state and so can be trivially preserved but it needs
52  // a fresh view of BFI if it was constructed with one.
53  if (BFI && Inv.invalidate<BlockFrequencyAnalysis>(F, PA))
54  return true;
55 
56  // Otherwise this analysis result remains valid.
57  return false;
58 }
59 
60 Optional<uint64_t> OptimizationRemarkEmitter::computeHotness(const Value *V) {
61  if (!BFI)
62  return None;
63 
64  return BFI->getBlockProfileCount(cast<BasicBlock>(V));
65 }
66 
67 namespace llvm {
68 namespace yaml {
69 
71  IO &io, DiagnosticInfoOptimizationBase *&OptDiag) {
72  assert(io.outputting() && "input not yet implemented");
73 
74  if (io.mapTag("!Passed",
75  (OptDiag->getKind() == DK_OptimizationRemark ||
76  OptDiag->getKind() == DK_MachineOptimizationRemark)))
77  ;
78  else if (io.mapTag(
79  "!Missed",
80  (OptDiag->getKind() == DK_OptimizationRemarkMissed ||
82  ;
83  else if (io.mapTag(
84  "!Analysis",
85  (OptDiag->getKind() == DK_OptimizationRemarkAnalysis ||
87  ;
88  else if (io.mapTag("!AnalysisFPCommute",
89  OptDiag->getKind() ==
91  ;
92  else if (io.mapTag("!AnalysisAliasing",
93  OptDiag->getKind() ==
95  ;
96  else if (io.mapTag("!Failure", OptDiag->getKind() == DK_OptimizationFailure))
97  ;
98  else
99  llvm_unreachable("Unknown remark type");
100 
101  // These are read-only for now.
102  DiagnosticLocation DL = OptDiag->getLocation();
103  StringRef FN =
105 
106  StringRef PassName(OptDiag->PassName);
107  io.mapRequired("Pass", PassName);
108  io.mapRequired("Name", OptDiag->RemarkName);
109  if (!io.outputting() || DL.isValid())
110  io.mapOptional("DebugLoc", DL);
111  io.mapRequired("Function", FN);
112  io.mapOptional("Hotness", OptDiag->Hotness);
113  io.mapOptional("Args", OptDiag->Args);
114 }
115 
116 template <> struct MappingTraits<DiagnosticLocation> {
117  static void mapping(IO &io, DiagnosticLocation &DL) {
118  assert(io.outputting() && "input not yet implemented");
119 
120  StringRef File = DL.getFilename();
121  unsigned Line = DL.getLine();
122  unsigned Col = DL.getColumn();
123 
124  io.mapRequired("File", File);
125  io.mapRequired("Line", Line);
126  io.mapRequired("Column", Col);
127  }
128 
129  static const bool flow = true;
130 };
131 
132 // Implement this as a mapping for now to get proper quotation for the value.
135  assert(io.outputting() && "input not yet implemented");
136  io.mapRequired(A.Key.data(), A.Val);
137  if (A.Loc.isValid())
138  io.mapOptional("DebugLoc", A.Loc);
139  }
140 };
141 
142 } // end namespace yaml
143 } // end namespace llvm
144 
146 
147 void OptimizationRemarkEmitter::computeHotness(
148  DiagnosticInfoIROptimization &OptDiag) {
149  const Value *V = OptDiag.getCodeRegion();
150  if (V)
151  OptDiag.setHotness(computeHotness(V));
152 }
153 
154 void OptimizationRemarkEmitter::emit(
155  DiagnosticInfoOptimizationBase &OptDiagBase) {
156  auto &OptDiag = cast<DiagnosticInfoIROptimization>(OptDiagBase);
157  computeHotness(OptDiag);
158  // If a diagnostic has a hotness value, then only emit it if its hotness
159  // meets the threshold.
160  if (OptDiag.getHotness() &&
161  *OptDiag.getHotness() <
163  return;
164  }
165 
167  if (Out) {
168  auto *P = const_cast<DiagnosticInfoOptimizationBase *>(&OptDiagBase);
169  *Out << P;
170  }
171  // FIXME: now that IsVerbose is part of DI, filtering for this will be moved
172  // from here to clang.
173  if (!OptDiag.isVerbose() || shouldEmitVerbose())
174  F->getContext().diagnose(OptDiag);
175 }
176 
178  : FunctionPass(ID) {
181 }
182 
185 
187  BFI = &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
188  else
189  BFI = nullptr;
190 
191  ORE = llvm::make_unique<OptimizationRemarkEmitter>(&Fn, BFI);
192  return false;
193 }
194 
196  AnalysisUsage &AU) const {
198  AU.setPreservesAll();
199 }
200 
201 AnalysisKey OptimizationRemarkEmitterAnalysis::Key;
202 
207 
209  BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
210  else
211  BFI = nullptr;
212 
213  return OptimizationRemarkEmitter(&F, BFI);
214 }
215 
217 static const char ore_name[] = "Optimization Remark Emitter";
218 #define ORE_NAME "opt-remark-emitter"
219 
221  false, true)
222 INITIALIZE_PASS_DEPENDENCY(LazyBFIPass)
224  false, true)
const char * PassName
Name of the pass that triggers this report.
static void mapping(IO &io, DiagnosticInfoOptimizationBase::Argument &A)
StringRef getFilename() const
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void mapOptional(const char *Key, T &Val)
Definition: YAMLTraits.h:656
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:194
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
Result run(Function &F, FunctionAnalysisManager &AM)
Run the analysis pass over a function and produce BFI.
void calculate(const Function &F, const LoopInfo &LI, const TargetLibraryInfo *TLI=nullptr)
void initializeOptimizationRemarkEmitterWrapperPassPass(PassRegistry &)
DataLayout DL
bool getDiagnosticsHotnessRequested() const
Return if a code hotness metric should be included in optimization diagnostics.
#define LLVM_YAML_IS_SEQUENCE_VECTOR(type)
Utility for declaring that a std::vector of a particular type should be considered a YAML sequence...
Definition: YAMLTraits.h:1643
INITIALIZE_PASS_BEGIN(OptimizationRemarkEmitterWrapperPass, ORE_NAME, ore_name, false, true) INITIALIZE_PASS_END(OptimizationRemarkEmitterWrapperPass
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:218
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:687
void getLocation(StringRef *Filename, unsigned *Line, unsigned *Column) const
Return location information for this diagnostic in three parts: the source file name, line number and column.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
#define F(x, y, z)
Definition: MD5.cpp:55
This class should be specialized by any type that needs to be converted to/from a YAML mapping...
StringRef RemarkName
Textual identifier for the remark (single-word, camel-case).
virtual bool mapTag(StringRef Tag, bool Default=false)=0
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:134
yaml::Output * getDiagnosticsOutputFile()
Return the YAML file used by the backend to save optimization diagnostics.
const Function & getFunction() const
SmallVector< Argument, 4 > Args
Arguments collected via the streaming interface.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
#define P(N)
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
#define A
Definition: LargeTest.cpp:12
void analyze(const DominatorTreeBase< BlockT, false > &DomTree)
Create the loop forest using a stable algorithm.
Definition: LoopInfoImpl.h:466
Represent the analysis usage information of a pass.
Common features for diagnostics dealing with optimization remarks that are used by IR passes...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle invalidation events in the new pass manager.
unsigned getColumn() const
The Output class is used to generate a yaml document from in-memory structs and vectors.
Definition: YAMLTraits.h:1260
Used in the streaming interface as the general argument type.
uint64_t getDiagnosticsHotnessThreshold() const
Return the minimum hotness value a diagnostic would need in order to be included in optimization diag...
static void mapping(IO &io, DiagnosticLocation &DL)
Analysis pass which computes BlockFrequencyInfo.
Common features for diagnostics dealing with optimization remarks that are used by both IR and MIR pa...
OptimizationRemarkEmitter(const Function *F, BlockFrequencyInfo *BFI)
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1', drop it.
Definition: GlobalValue.h:451
void setPreservesAll()
Set by analyses that do not transform their input at all.
static void getLazyBFIAnalysisUsage(AnalysisUsage &AU)
Helper for client passes to set up the analysis usage on behalf of this pass.
llvm_unreachable("Unknown RegBank!")
Basic Alias true
Analysis providing branch probability information.
unsigned getLine() const
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
static const char ore_name[]
virtual bool outputting()=0
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:559
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
Optional< uint64_t > Hotness
If profile information is available, this is the number of times the corresponding code was executed ...
OptimizationRemarkEmitter legacy analysis pass.
void recalculate(FT &F)
recalculate - compute a dominator tree for the given function
#define ORE_NAME
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:128
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
A container for analyses that lazily runs them and caches their results.
void mapRequired(const char *Key, T &Val)
Definition: YAMLTraits.h:646
Optional< uint64_t > getBlockProfileCount(const BasicBlock *BB) const
Returns the estimated profile count of BB.
bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Trigger the invalidation of some other analysis pass if not already handled and return whether it was...
Definition: PassManager.h:577
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
The optimization diagnostic interface.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:70