LLVM 20.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"
13#include "llvm/ADT/StringRef.h"
16#include "llvm/IR/Constant.h"
17#include "llvm/IR/Constants.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/Metadata.h"
23#include "llvm/IR/Module.h"
25#include <memory>
26#include <random>
27
28using namespace llvm;
29
30#define DEBUG_TYPE "lower-allow-check"
31
32static cl::opt<int>
33 HotPercentileCutoff("lower-allow-check-percentile-cutoff-hot",
34 cl::desc("Hot percentile cuttoff."));
35
36static cl::opt<float>
37 RandomRate("lower-allow-check-random-rate",
38 cl::desc("Probability value in the range [0.0, 1.0] of "
39 "unconditional pseudo-random checks."));
40
41STATISTIC(NumChecksTotal, "Number of checks");
42STATISTIC(NumChecksRemoved, "Number of removed checks");
43
44struct RemarkInfo {
49 : Kind("Kind", II->getArgOperand(0)),
50 F("Function", II->getParent()->getParent()),
51 BB("Block", II->getParent()->getName()) {}
52};
53
55 bool Removed) {
56 if (Removed) {
57 ORE.emit([&]() {
59 return OptimizationRemark(DEBUG_TYPE, "Removed", II)
60 << "Removed check: Kind=" << Info.Kind << " F=" << Info.F
61 << " BB=" << Info.BB;
62 });
63 } else {
64 ORE.emit([&]() {
66 return OptimizationRemarkMissed(DEBUG_TYPE, "Allowed", II)
67 << "Allowed check: Kind=" << Info.Kind << " F=" << Info.F
68 << " BB=" << Info.BB;
69 });
70 }
71}
72
74 const ProfileSummaryInfo *PSI,
77 std::unique_ptr<RandomNumberGenerator> Rng;
78
79 auto GetRng = [&]() -> RandomNumberGenerator & {
80 if (!Rng)
81 Rng = F.getParent()->createRNG(F.getName());
82 return *Rng;
83 };
84
85 auto ShouldRemoveHot = [&](const BasicBlock &BB) {
86 return HotPercentileCutoff.getNumOccurrences() && PSI &&
88 HotPercentileCutoff, BFI.getBlockProfileCount(&BB).value_or(0));
89 };
90
91 auto ShouldRemoveRandom = [&]() {
92 return RandomRate.getNumOccurrences() &&
93 !std::bernoulli_distribution(RandomRate)(GetRng());
94 };
95
96 auto ShouldRemove = [&](const BasicBlock &BB) {
97 return ShouldRemoveRandom() || ShouldRemoveHot(BB);
98 };
99
100 for (BasicBlock &BB : F) {
101 for (Instruction &I : BB) {
102 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
103 if (!II)
104 continue;
105 auto ID = II->getIntrinsicID();
106 switch (ID) {
107 case Intrinsic::allow_ubsan_check:
108 case Intrinsic::allow_runtime_check: {
109 ++NumChecksTotal;
110
111 bool ToRemove = ShouldRemove(BB);
112 ReplaceWithValue.push_back({
113 II,
114 ToRemove,
115 });
116 if (ToRemove)
117 ++NumChecksRemoved;
118 emitRemark(II, ORE, ToRemove);
119 break;
120 }
121 default:
122 break;
123 }
124 }
125 }
126
127 for (auto [I, V] : ReplaceWithValue) {
128 I->replaceAllUsesWith(ConstantInt::getBool(I->getType(), !V));
129 I->eraseFromParent();
130 }
131
132 return !ReplaceWithValue.empty();
133}
134
137 if (F.isDeclaration())
138 return PreservedAnalyses::all();
139 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
140 ProfileSummaryInfo *PSI =
141 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
145
146 return removeUbsanTraps(F, BFI, PSI, ORE) ? PreservedAnalyses::none()
148}
149
151 return RandomRate.getNumOccurrences() ||
152 HotPercentileCutoff.getNumOccurrences();
153}
ReachingDefAnalysis InstSet & ToRemove
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...
static bool removeUbsanTraps(Function &F, const BlockFrequencyInfo &BFI, const ProfileSummaryInfo *PSI, OptimizationRemarkEmitter &ORE)
static cl::opt< int > HotPercentileCutoff("lower-allow-check-percentile-cutoff-hot", cl::desc("Hot percentile cuttoff."))
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 void emitRemark(IntrinsicInst *II, OptimizationRemarkEmitter &ORE, bool Removed)
#define DEBUG_TYPE
This file provides the interface for the pass responsible for removing expensive ubsan checks.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains the declarations for metadata subclasses.
Module.h This file contains the declarations for the Module class.
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:167
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
static ConstantInt * getBool(LLVMContext &Context, bool V)
Definition: Constants.cpp:864
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:48
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
The optimization diagnostic interface.
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.
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
Definition: PassManager.h:688
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:114
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
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.
bool empty() const
Definition: SmallVector.h:95
void push_back(const T &Elt)
Definition: SmallVector.h:427
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1210
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
RemarkInfo(IntrinsicInst *II)
Used in the streaming interface as the general argument type.