LLVM 22.0.0git
LowerAllowCheckPass.cpp
Go to the documentation of this file.
1//===- LowerAllowCheckPass.cpp ----------------------------------*- 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
10
12#include "llvm/ADT/Statistic.h"
14#include "llvm/ADT/StringRef.h"
17#include "llvm/IR/Constants.h"
22#include "llvm/IR/Intrinsics.h"
23#include "llvm/IR/Metadata.h"
24#include "llvm/IR/Module.h"
25#include "llvm/Support/Debug.h"
27#include <memory>
28#include <optional>
29#include <random>
30
31using namespace llvm;
32
33#define DEBUG_TYPE "lower-allow-check"
34
35static cl::opt<int>
36 HotPercentileCutoff("lower-allow-check-percentile-cutoff-hot",
37 cl::desc("Hot percentile cutoff."));
38
39static cl::opt<float>
40 RandomRate("lower-allow-check-random-rate",
41 cl::desc("Probability value in the range [0.0, 1.0] of "
42 "unconditional pseudo-random checks."));
43
44STATISTIC(NumChecksTotal, "Number of checks");
45STATISTIC(NumChecksRemoved, "Number of removed checks");
46
47struct RemarkInfo {
52 : Kind("Kind", II->getArgOperand(0)),
53 F("Function", II->getParent()->getParent()),
54 BB("Block", II->getParent()->getName()) {}
55};
56
58 bool Removed) {
59 if (Removed) {
60 ORE.emit([&]() {
62 return OptimizationRemark(DEBUG_TYPE, "Removed", II)
63 << "Removed check: Kind=" << Info.Kind << " F=" << Info.F
64 << " BB=" << Info.BB;
65 });
66 } else {
67 ORE.emit([&]() {
69 return OptimizationRemarkMissed(DEBUG_TYPE, "Allowed", II)
70 << "Allowed check: Kind=" << Info.Kind << " F=" << Info.F
71 << " BB=" << Info.BB;
72 });
73 }
74}
75
77 const LowerAllowCheckPass::Options &Opts) {
78 // Lazy analysis getters.
79 auto GetBFI = [&AM, &F, BFI = (BlockFrequencyInfo *)nullptr]() mutable
80 -> const BlockFrequencyInfo & {
81 if (!BFI)
83 return *BFI;
84 };
85 auto GetPSI = [&AM, &F, PSI = std::optional<ProfileSummaryInfo *>()]() mutable
86 -> const ProfileSummaryInfo * {
87 if (!PSI.has_value()) {
89 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
90 }
91 return *PSI;
92 };
93 auto GetORE = [&AM, &F, ORE = (OptimizationRemarkEmitter *)nullptr]() mutable
95 if (!ORE)
97 return *ORE;
98 };
99
100 // List of intrinsics and the constant value they should be lowered to.
102 std::unique_ptr<RandomNumberGenerator> Rng;
103
104 auto GetRng = [&]() -> RandomNumberGenerator & {
105 if (!Rng)
106 Rng = F.getParent()->createRNG(F.getName());
107 return *Rng;
108 };
109
110 auto GetCutoff = [&](const IntrinsicInst *II) -> unsigned {
111 if (HotPercentileCutoff.getNumOccurrences())
112 return HotPercentileCutoff;
113 else if (II->getIntrinsicID() == Intrinsic::allow_ubsan_check) {
114 auto *Kind = cast<ConstantInt>(II->getArgOperand(0));
115 if (Kind->getZExtValue() < Opts.cutoffs.size())
116 return Opts.cutoffs[Kind->getZExtValue()];
117 } else if (II->getIntrinsicID() == Intrinsic::allow_runtime_check) {
118 return Opts.runtime_check;
119 }
120
121 return 0;
122 };
123
124 auto ShouldRemoveHot = [&](const BasicBlock &BB, unsigned int cutoff) {
125 if (cutoff == 1000000)
126 return true;
127 const ProfileSummaryInfo *PSI = GetPSI();
128 return PSI && PSI->isHotCountNthPercentile(
129 cutoff, GetBFI().getBlockProfileCount(&BB).value_or(0));
130 };
131
132 auto ShouldRemoveRandom = [&]() {
133 return RandomRate.getNumOccurrences() &&
134 !std::bernoulli_distribution(RandomRate)(GetRng());
135 };
136
137 auto ShouldRemove = [&](const IntrinsicInst *II) {
138 unsigned int cutoff = GetCutoff(II);
139 return ShouldRemoveRandom() || ShouldRemoveHot(*(II->getParent()), cutoff);
140 };
141
142 for (Instruction &I : instructions(F)) {
144 if (!II)
145 continue;
146 auto ID = II->getIntrinsicID();
147 switch (ID) {
148 case Intrinsic::allow_ubsan_check:
149 case Intrinsic::allow_runtime_check: {
150 bool ToRemove = ShouldRemove(II);
151
152 ReplaceWithValue.push_back({
153 II,
154 !ToRemove,
155 });
156 emitRemark(II, GetORE(), ToRemove);
157 break;
158 }
159 case Intrinsic::allow_sanitize_address:
160 ReplaceWithValue.push_back(
161 {II, F.hasFnAttribute(Attribute::SanitizeAddress)});
162 break;
163 case Intrinsic::allow_sanitize_thread:
164 ReplaceWithValue.push_back(
165 {II, F.hasFnAttribute(Attribute::SanitizeThread)});
166 break;
167 case Intrinsic::allow_sanitize_memory:
168 ReplaceWithValue.push_back(
169 {II, F.hasFnAttribute(Attribute::SanitizeMemory)});
170 break;
171 case Intrinsic::allow_sanitize_hwaddress:
172 ReplaceWithValue.push_back(
173 {II, F.hasFnAttribute(Attribute::SanitizeHWAddress)});
174 break;
175 default:
176 break;
177 }
178 }
179
180 for (auto [I, V] : ReplaceWithValue) {
181 ++NumChecksTotal;
182 if (!V) // If the final value is false, the check is considered removed.
183 ++NumChecksRemoved;
184 I->replaceAllUsesWith(ConstantInt::getBool(I->getType(), V));
185 I->eraseFromParent();
186 }
187
188 return !ReplaceWithValue.empty();
189}
190
193 if (F.isDeclaration())
194 return PreservedAnalyses::all();
195
196 return lowerAllowChecks(F, AM, Opts)
197 // We do not change the CFG, we only replace the intrinsics with
198 // true or false.
201}
202
204 return RandomRate.getNumOccurrences() ||
205 HotPercentileCutoff.getNumOccurrences();
206}
207
209 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
211 OS, MapClassName2PassName);
212 OS << "<";
213
214 // Format is <cutoffs[0,1,2]=70000;cutoffs[5,6,8]=90000>
215 // but it's equally valid to specify
216 // cutoffs[0]=70000;cutoffs[1]=70000;cutoffs[2]=70000;cutoffs[5]=90000;...
217 // and that's what we do here. It is verbose but valid and easy to verify
218 // correctness.
219 // TODO: print shorter output by combining adjacent runs, etc.
220 int i = 0;
221 ListSeparator LS(";");
222 for (unsigned int cutoff : Opts.cutoffs) {
223 if (cutoff > 0)
224 OS << LS << "cutoffs[" << i << "]=" << cutoff;
225 i++;
226 }
227 if (Opts.runtime_check)
228 OS << LS << "runtime_check=" << Opts.runtime_check;
229
230 OS << '>';
231}
ReachingDefInfo InstSet & ToRemove
Expand Atomic instructions
static const Function * getParent(const Value *V)
Analysis containing CSE Info
Definition CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
static cl::opt< float > RandomRate("lower-allow-check-random-rate", cl::desc("Probability value in the range [0.0, 1.0] of " "unconditional pseudo-random checks."))
static cl::opt< int > HotPercentileCutoff("lower-allow-check-percentile-cutoff-hot", cl::desc("Hot percentile cutoff."))
static void emitRemark(IntrinsicInst *II, OptimizationRemarkEmitter &ORE, bool Removed)
static bool lowerAllowChecks(Function &F, FunctionAnalysisManager &AM, const LowerAllowCheckPass::Options &Opts)
This file provides the interface for the pass responsible for removing expensive ubsan checks.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
static StringRef getName(Value *V)
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
A wrapper class for inspecting calls to intrinsic functions.
A helper class to return the specified delimiter string after the first invocation of operator String...
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
static LLVM_ABI bool IsRequested()
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
LLVM_ABI bool isHotCountNthPercentile(int PercentileCutoff, uint64_t C) const
Returns true if count C is considered hot with regard to a given hot percentile cutoff value.
A random number generator.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
RemarkInfo(IntrinsicInst *II)
std::vector< unsigned int > cutoffs
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition PassManager.h:70