1 //===- OptimizationRemarkEmitter.h - Optimization Diagnostic ----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Optimization diagnostic interfaces.  It's packaged as an analysis pass so
10 // that by using this service passes become dependent on BFI as well.  BFI is
11 // used to compute the "hotness" of the diagnostic message.
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_IR_OPTIMIZATIONDIAGNOSTICINFO_H
15 #define LLVM_IR_OPTIMIZATIONDIAGNOSTICINFO_H
16 
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/Analysis/BlockFrequencyInfo.h"
19 #include "llvm/IR/DiagnosticInfo.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/PassManager.h"
22 #include "llvm/Pass.h"
23 
24 namespace llvm {
25 class DebugLoc;
26 class Loop;
27 class Pass;
28 class Twine;
29 class Value;
30 
31 /// The optimization diagnostic interface.
32 ///
33 /// It allows reporting when optimizations are performed and when they are not
34 /// along with the reasons for it.  Hotness information of the corresponding
35 /// code region can be included in the remark if DiagnosticsHotnessRequested is
36 /// enabled in the LLVM context.
37 class OptimizationRemarkEmitter {
38 public:
39   OptimizationRemarkEmitter(const Function *F, BlockFrequencyInfo *BFI)
40       : F(F), BFI(BFI) {}
41 
42   /// This variant can be used to generate ORE on demand (without the
43   /// analysis pass).
44   ///
45   /// Note that this ctor has a very different cost depending on whether
46   /// F->getContext().getDiagnosticsHotnessRequested() is on or not.  If it's off
47   /// the operation is free.
48   ///
49   /// Whereas if DiagnosticsHotnessRequested is on, it is fairly expensive
50   /// operation since BFI and all its required analyses are computed.  This is
51   /// for example useful for CGSCC passes that can't use function analyses
52   /// passes in the old PM.
53   OptimizationRemarkEmitter(const Function *F);
54 
55   OptimizationRemarkEmitter(OptimizationRemarkEmitter &&Arg)
56       : F(Arg.F), BFI(Arg.BFI) {}
57 
58   OptimizationRemarkEmitter &operator=(OptimizationRemarkEmitter &&RHS) {
59     F = RHS.F;
60     BFI = RHS.BFI;
61     return *this;
62   }
63 
64   /// Handle invalidation events in the new pass manager.
65   bool invalidate(Function &F, const PreservedAnalyses &PA,
66                   FunctionAnalysisManager::Invalidator &Inv);
67 
68   /// Output the remark via the diagnostic handler and to the
69   /// optimization record file.
70   void emit(DiagnosticInfoOptimizationBase &OptDiag);
71 
72   /// Take a lambda that returns a remark which will be emitted.  Second
73   /// argument is only used to restrict this to functions.
74   template <typename T>
75   void emit(T RemarkBuilder, decltype(RemarkBuilder()) * = nullptr) {
76     // Avoid building the remark unless we know there are at least *some*
77     // remarks enabled. We can't currently check whether remarks are requested
78     // for the calling pass since that requires actually building the remark.
79 
80     if (F->getContext().getRemarkStreamer() ||
81         F->getContext().getDiagHandlerPtr()->isAnyRemarkEnabled()) {
82       auto R = RemarkBuilder();
83       emit((DiagnosticInfoOptimizationBase &)R);
84     }
85   }
86 
87   /// Whether we allow for extra compile-time budget to perform more
88   /// analysis to produce fewer false positives.
89   ///
90   /// This is useful when reporting missed optimizations.  In this case we can
91   /// use the extra analysis (1) to filter trivial false positives or (2) to
92   /// provide more context so that non-trivial false positives can be quickly
93   /// detected by the user.
94   bool allowExtraAnalysis(StringRef PassName) const {
95     return (F->getContext().getRemarkStreamer() ||
96             F->getContext().getDiagHandlerPtr()->isAnyRemarkEnabled(PassName));
97   }
98 
99 private:
100   const Function *F;
101 
102   BlockFrequencyInfo *BFI;
103 
104   /// If we generate BFI on demand, we need to free it when ORE is freed.
105   std::unique_ptr<BlockFrequencyInfo> OwnedBFI;
106 
107   /// Compute hotness from IR value (currently assumed to be a block) if PGO is
108   /// available.
109   Optional<uint64_t> computeHotness(const Value *V);
110 
111   /// Similar but use value from \p OptDiag and update hotness there.
112   void computeHotness(DiagnosticInfoIROptimization &OptDiag);
113 
114   /// Only allow verbose messages if we know we're filtering by hotness
115   /// (BFI is only set in this case).
116   bool shouldEmitVerbose() { return BFI != nullptr; }
117 
118   OptimizationRemarkEmitter(const OptimizationRemarkEmitter &) = delete;
119   void operator=(const OptimizationRemarkEmitter &) = delete;
120 };
121 
122 /// Add a small namespace to avoid name clashes with the classes used in
123 /// the streaming interface.  We want these to be short for better
124 /// write/readability.
125 namespace ore {
126 using NV = DiagnosticInfoOptimizationBase::Argument;
127 using setIsVerbose = DiagnosticInfoOptimizationBase::setIsVerbose;
128 using setExtraArgs = DiagnosticInfoOptimizationBase::setExtraArgs;
129 }
130 
131 /// OptimizationRemarkEmitter legacy analysis pass
132 ///
133 /// Note that this pass shouldn't generally be marked as preserved by other
134 /// passes.  It's holding onto BFI, so if the pass does not preserve BFI, BFI
135 /// could be freed.
136 class OptimizationRemarkEmitterWrapperPass : public FunctionPass {
137   std::unique_ptr<OptimizationRemarkEmitter> ORE;
138 
139 public:
140   OptimizationRemarkEmitterWrapperPass();
141 
142   bool runOnFunction(Function &F) override;
143 
144   void getAnalysisUsage(AnalysisUsage &AU) const override;
145 
146   OptimizationRemarkEmitter &getORE() {
147     assert(ORE && "pass not run yet");
148     return *ORE;
149   }
150 
151   static char ID;
152 };
153 
154 class OptimizationRemarkEmitterAnalysis
155     : public AnalysisInfoMixin<OptimizationRemarkEmitterAnalysis> {
156   friend AnalysisInfoMixin<OptimizationRemarkEmitterAnalysis>;
157   static AnalysisKey Key;
158 
159 public:
160   /// Provide the result typedef for this analysis pass.
161   typedef OptimizationRemarkEmitter Result;
162 
163   /// Run the analysis pass over a function and produce BFI.
164   Result run(Function &F, FunctionAnalysisManager &AM);
165 };
166 }
167 #endif // LLVM_IR_OPTIMIZATIONDIAGNOSTICINFO_H
168