1 //===- AssumptionCache.cpp - Cache finding @llvm.assume calls -------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains a pass that keeps track of @llvm.assume intrinsics in
10 // the functions of a module.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Analysis/AssumeBundleQueries.h"
15 #include "llvm/Analysis/AssumptionCache.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/IR/BasicBlock.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/InstrTypes.h"
22 #include "llvm/IR/Instruction.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/PassManager.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/InitializePasses.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
38 using namespace llvm::PatternMatch
;
41 VerifyAssumptionCache("verify-assumption-cache", cl::Hidden
,
42 cl::desc("Enable verification of assumption cache"),
45 SmallVector
<AssumptionCache::ResultElem
, 1> &
46 AssumptionCache::getOrInsertAffectedValues(Value
*V
) {
47 // Try using find_as first to avoid creating extra value handles just for the
48 // purpose of doing the lookup.
49 auto AVI
= AffectedValues
.find_as(V
);
50 if (AVI
!= AffectedValues
.end())
53 auto AVIP
= AffectedValues
.insert(
54 {AffectedValueCallbackVH(V
, this), SmallVector
<ResultElem
, 1>()});
55 return AVIP
.first
->second
;
59 findAffectedValues(CallBase
*CI
,
60 SmallVectorImpl
<AssumptionCache::ResultElem
> &Affected
) {
61 // Note: This code must be kept in-sync with the code in
62 // computeKnownBitsFromAssume in ValueTracking.
64 auto AddAffected
= [&Affected
](Value
*V
, unsigned Idx
=
65 AssumptionCache::ExprResultIdx
) {
66 if (isa
<Argument
>(V
)) {
67 Affected
.push_back({V
, Idx
});
68 } else if (auto *I
= dyn_cast
<Instruction
>(V
)) {
69 Affected
.push_back({I
, Idx
});
71 // Peek through unary operators to find the source of the condition.
73 if (match(I
, m_BitCast(m_Value(Op
))) ||
74 match(I
, m_PtrToInt(m_Value(Op
))) || match(I
, m_Not(m_Value(Op
)))) {
75 if (isa
<Instruction
>(Op
) || isa
<Argument
>(Op
))
76 Affected
.push_back({Op
, Idx
});
81 for (unsigned Idx
= 0; Idx
!= CI
->getNumOperandBundles(); Idx
++) {
82 if (CI
->getOperandBundleAt(Idx
).Inputs
.size() > ABA_WasOn
&&
83 CI
->getOperandBundleAt(Idx
).getTagName() != IgnoreBundleTag
)
84 AddAffected(CI
->getOperandBundleAt(Idx
).Inputs
[ABA_WasOn
], Idx
);
87 Value
*Cond
= CI
->getArgOperand(0), *A
, *B
;
90 CmpInst::Predicate Pred
;
91 if (match(Cond
, m_ICmp(Pred
, m_Value(A
), m_Value(B
)))) {
95 if (Pred
== ICmpInst::ICMP_EQ
) {
96 // For equality comparisons, we handle the case of bit inversion.
97 auto AddAffectedFromEq
= [&AddAffected
](Value
*V
) {
99 if (match(V
, m_Not(m_Value(A
)))) {
105 // (A & B) or (A | B) or (A ^ B).
106 if (match(V
, m_BitwiseLogic(m_Value(A
), m_Value(B
)))) {
109 // (A << C) or (A >>_s C) or (A >>_u C) where C is some constant.
110 } else if (match(V
, m_Shift(m_Value(A
), m_ConstantInt()))) {
115 AddAffectedFromEq(A
);
116 AddAffectedFromEq(B
);
120 // Handle (A + C1) u< C2, which is the canonical form of A > C3 && A < C4,
121 // and recognized by LVI at least.
122 if (Pred
== ICmpInst::ICMP_ULT
&&
123 match(A
, m_Add(m_Value(X
), m_ConstantInt())) &&
124 match(B
, m_ConstantInt()))
129 void AssumptionCache::updateAffectedValues(AssumeInst
*CI
) {
130 SmallVector
<AssumptionCache::ResultElem
, 16> Affected
;
131 findAffectedValues(CI
, Affected
);
133 for (auto &AV
: Affected
) {
134 auto &AVV
= getOrInsertAffectedValues(AV
.Assume
);
135 if (std::find_if(AVV
.begin(), AVV
.end(), [&](ResultElem
&Elem
) {
136 return Elem
.Assume
== CI
&& Elem
.Index
== AV
.Index
;
138 AVV
.push_back({CI
, AV
.Index
});
142 void AssumptionCache::unregisterAssumption(AssumeInst
*CI
) {
143 SmallVector
<AssumptionCache::ResultElem
, 16> Affected
;
144 findAffectedValues(CI
, Affected
);
146 for (auto &AV
: Affected
) {
147 auto AVI
= AffectedValues
.find_as(AV
.Assume
);
148 if (AVI
== AffectedValues
.end())
151 bool HasNonnull
= false;
152 for (ResultElem
&Elem
: AVI
->second
) {
153 if (Elem
.Assume
== CI
) {
155 Elem
.Assume
= nullptr;
157 HasNonnull
|= !!Elem
.Assume
;
158 if (HasNonnull
&& Found
)
161 assert(Found
&& "already unregistered or incorrect cache state");
163 AffectedValues
.erase(AVI
);
166 erase_value(AssumeHandles
, CI
);
169 void AssumptionCache::AffectedValueCallbackVH::deleted() {
170 AC
->AffectedValues
.erase(getValPtr());
171 // 'this' now dangles!
174 void AssumptionCache::transferAffectedValuesInCache(Value
*OV
, Value
*NV
) {
175 auto &NAVV
= getOrInsertAffectedValues(NV
);
176 auto AVI
= AffectedValues
.find(OV
);
177 if (AVI
== AffectedValues
.end())
180 for (auto &A
: AVI
->second
)
181 if (!llvm::is_contained(NAVV
, A
))
183 AffectedValues
.erase(OV
);
186 void AssumptionCache::AffectedValueCallbackVH::allUsesReplacedWith(Value
*NV
) {
187 if (!isa
<Instruction
>(NV
) && !isa
<Argument
>(NV
))
190 // Any assumptions that affected this value now affect the new value.
192 AC
->transferAffectedValuesInCache(getValPtr(), NV
);
193 // 'this' now might dangle! If the AffectedValues map was resized to add an
194 // entry for NV then this object might have been destroyed in favor of some
195 // copy in the grown map.
198 void AssumptionCache::scanFunction() {
199 assert(!Scanned
&& "Tried to scan the function twice!");
200 assert(AssumeHandles
.empty() && "Already have assumes when scanning!");
202 // Go through all instructions in all blocks, add all calls to @llvm.assume
204 for (BasicBlock
&B
: F
)
205 for (Instruction
&I
: B
)
206 if (isa
<AssumeInst
>(&I
))
207 AssumeHandles
.push_back({&I
, ExprResultIdx
});
209 // Mark the scan as complete.
212 // Update affected values.
213 for (auto &A
: AssumeHandles
)
214 updateAffectedValues(cast
<AssumeInst
>(A
));
217 void AssumptionCache::registerAssumption(AssumeInst
*CI
) {
218 // If we haven't scanned the function yet, just drop this assumption. It will
219 // be found when we scan later.
223 AssumeHandles
.push_back({CI
, ExprResultIdx
});
226 assert(CI
->getParent() &&
227 "Cannot register @llvm.assume call not in a basic block");
228 assert(&F
== CI
->getParent()->getParent() &&
229 "Cannot register @llvm.assume call not in this function");
231 // We expect the number of assumptions to be small, so in an asserts build
232 // check that we don't accumulate duplicates and that all assumptions point
233 // to the same function.
234 SmallPtrSet
<Value
*, 16> AssumptionSet
;
235 for (auto &VH
: AssumeHandles
) {
239 assert(&F
== cast
<Instruction
>(VH
)->getParent()->getParent() &&
240 "Cached assumption not inside this function!");
241 assert(match(cast
<CallInst
>(VH
), m_Intrinsic
<Intrinsic::assume
>()) &&
242 "Cached something other than a call to @llvm.assume!");
243 assert(AssumptionSet
.insert(VH
).second
&&
244 "Cache contains multiple copies of a call!");
248 updateAffectedValues(CI
);
251 AnalysisKey
AssumptionAnalysis::Key
;
253 PreservedAnalyses
AssumptionPrinterPass::run(Function
&F
,
254 FunctionAnalysisManager
&AM
) {
255 AssumptionCache
&AC
= AM
.getResult
<AssumptionAnalysis
>(F
);
257 OS
<< "Cached assumptions for function: " << F
.getName() << "\n";
258 for (auto &VH
: AC
.assumptions())
260 OS
<< " " << *cast
<CallInst
>(VH
)->getArgOperand(0) << "\n";
262 return PreservedAnalyses::all();
265 void AssumptionCacheTracker::FunctionCallbackVH::deleted() {
266 auto I
= ACT
->AssumptionCaches
.find_as(cast
<Function
>(getValPtr()));
267 if (I
!= ACT
->AssumptionCaches
.end())
268 ACT
->AssumptionCaches
.erase(I
);
269 // 'this' now dangles!
272 AssumptionCache
&AssumptionCacheTracker::getAssumptionCache(Function
&F
) {
273 // We probe the function map twice to try and avoid creating a value handle
274 // around the function in common cases. This makes insertion a bit slower,
275 // but if we have to insert we're going to scan the whole function so that
277 auto I
= AssumptionCaches
.find_as(&F
);
278 if (I
!= AssumptionCaches
.end())
281 // Ok, build a new cache by scanning the function, insert it and the value
282 // handle into our map, and return the newly populated cache.
283 auto IP
= AssumptionCaches
.insert(std::make_pair(
284 FunctionCallbackVH(&F
, this), std::make_unique
<AssumptionCache
>(F
)));
285 assert(IP
.second
&& "Scanning function already in the map?");
286 return *IP
.first
->second
;
289 AssumptionCache
*AssumptionCacheTracker::lookupAssumptionCache(Function
&F
) {
290 auto I
= AssumptionCaches
.find_as(&F
);
291 if (I
!= AssumptionCaches
.end())
292 return I
->second
.get();
296 void AssumptionCacheTracker::verifyAnalysis() const {
297 // FIXME: In the long term the verifier should not be controllable with a
298 // flag. We should either fix all passes to correctly update the assumption
299 // cache and enable the verifier unconditionally or somehow arrange for the
300 // assumption list to be updated automatically by passes.
301 if (!VerifyAssumptionCache
)
304 SmallPtrSet
<const CallInst
*, 4> AssumptionSet
;
305 for (const auto &I
: AssumptionCaches
) {
306 for (auto &VH
: I
.second
->assumptions())
308 AssumptionSet
.insert(cast
<CallInst
>(VH
));
310 for (const BasicBlock
&B
: cast
<Function
>(*I
.first
))
311 for (const Instruction
&II
: B
)
312 if (match(&II
, m_Intrinsic
<Intrinsic::assume
>()) &&
313 !AssumptionSet
.count(cast
<CallInst
>(&II
)))
314 report_fatal_error("Assumption in scanned function not in cache");
318 AssumptionCacheTracker::AssumptionCacheTracker() : ImmutablePass(ID
) {
319 initializeAssumptionCacheTrackerPass(*PassRegistry::getPassRegistry());
322 AssumptionCacheTracker::~AssumptionCacheTracker() = default;
324 char AssumptionCacheTracker::ID
= 0;
326 INITIALIZE_PASS(AssumptionCacheTracker
, "assumption-cache-tracker",
327 "Assumption Cache Tracker", false, true)