1 //===- AssumptionCache.cpp - Cache finding @llvm.assume calls -------------===//
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 // This file contains a pass that keeps track of @llvm.assume intrinsics in
11 // the functions of a module.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Analysis/AssumptionCache.h"
16 #include "llvm/IR/CallSite.h"
17 #include "llvm/IR/Dominators.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/IR/PassManager.h"
22 #include "llvm/IR/PatternMatch.h"
23 #include "llvm/Support/Debug.h"
24 using namespace llvm;
25 using namespace llvm::PatternMatch;
26 
27 static cl::opt<bool>
28     VerifyAssumptionCache("verify-assumption-cache", cl::Hidden,
29                           cl::desc("Enable verification of assumption cache"),
30                           cl::init(false));
31 
32 SmallVector<WeakTrackingVH, 1> &
33 AssumptionCache::getOrInsertAffectedValues(Value *V) {
34   // Try using find_as first to avoid creating extra value handles just for the
35   // purpose of doing the lookup.
36   auto AVI = AffectedValues.find_as(V);
37   if (AVI != AffectedValues.end())
38     return AVI->second;
39 
40   auto AVIP = AffectedValues.insert(
41       {AffectedValueCallbackVH(V, this), SmallVector<WeakTrackingVH, 1>()});
42   return AVIP.first->second;
43 }
44 
45 void AssumptionCache::updateAffectedValues(CallInst *CI) {
46   // Note: This code must be kept in-sync with the code in
47   // computeKnownBitsFromAssume in ValueTracking.
48 
49   SmallVector<Value *, 16> Affected;
50   auto AddAffected = [&Affected](Value *V) {
51     if (isa<Argument>(V)) {
52       Affected.push_back(V);
53     } else if (auto *I = dyn_cast<Instruction>(V)) {
54       Affected.push_back(I);
55 
56       // Peek through unary operators to find the source of the condition.
57       Value *Op;
58       if (match(I, m_BitCast(m_Value(Op))) ||
59           match(I, m_PtrToInt(m_Value(Op))) ||
60           match(I, m_Not(m_Value(Op)))) {
61         if (isa<Instruction>(Op) || isa<Argument>(Op))
62           Affected.push_back(Op);
63       }
64     }
65   };
66 
67   Value *Cond = CI->getArgOperand(0), *A, *B;
68   AddAffected(Cond);
69 
70   CmpInst::Predicate Pred;
71   if (match(Cond, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
72     AddAffected(A);
73     AddAffected(B);
74 
75     if (Pred == ICmpInst::ICMP_EQ) {
76       // For equality comparisons, we handle the case of bit inversion.
77       auto AddAffectedFromEq = [&AddAffected](Value *V) {
78         Value *A;
79         if (match(V, m_Not(m_Value(A)))) {
80           AddAffected(A);
81           V = A;
82         }
83 
84         Value *B;
85         ConstantInt *C;
86         // (A & B) or (A | B) or (A ^ B).
87         if (match(V,
88                   m_CombineOr(m_And(m_Value(A), m_Value(B)),
89                     m_CombineOr(m_Or(m_Value(A), m_Value(B)),
90                                 m_Xor(m_Value(A), m_Value(B)))))) {
91           AddAffected(A);
92           AddAffected(B);
93         // (A << C) or (A >>_s C) or (A >>_u C) where C is some constant.
94         } else if (match(V,
95                          m_CombineOr(m_Shl(m_Value(A), m_ConstantInt(C)),
96                            m_CombineOr(m_LShr(m_Value(A), m_ConstantInt(C)),
97                                        m_AShr(m_Value(A),
98                                               m_ConstantInt(C)))))) {
99           AddAffected(A);
100         }
101       };
102 
103       AddAffectedFromEq(A);
104       AddAffectedFromEq(B);
105     }
106   }
107 
108   for (auto &AV : Affected) {
109     auto &AVV = getOrInsertAffectedValues(AV);
110     if (std::find(AVV.begin(), AVV.end(), CI) == AVV.end())
111       AVV.push_back(CI);
112   }
113 }
114 
115 void AssumptionCache::AffectedValueCallbackVH::deleted() {
116   auto AVI = AC->AffectedValues.find(getValPtr());
117   if (AVI != AC->AffectedValues.end())
118     AC->AffectedValues.erase(AVI);
119   // 'this' now dangles!
120 }
121 
122 void AssumptionCache::copyAffectedValuesInCache(Value *OV, Value *NV) {
123   auto &NAVV = getOrInsertAffectedValues(NV);
124   auto AVI = AffectedValues.find(OV);
125   if (AVI == AffectedValues.end())
126     return;
127 
128   for (auto &A : AVI->second)
129     if (std::find(NAVV.begin(), NAVV.end(), A) == NAVV.end())
130       NAVV.push_back(A);
131 }
132 
133 void AssumptionCache::AffectedValueCallbackVH::allUsesReplacedWith(Value *NV) {
134   if (!isa<Instruction>(NV) && !isa<Argument>(NV))
135     return;
136 
137   // Any assumptions that affected this value now affect the new value.
138 
139   AC->copyAffectedValuesInCache(getValPtr(), NV);
140   // 'this' now might dangle! If the AffectedValues map was resized to add an
141   // entry for NV then this object might have been destroyed in favor of some
142   // copy in the grown map.
143 }
144 
145 void AssumptionCache::scanFunction() {
146   assert(!Scanned && "Tried to scan the function twice!");
147   assert(AssumeHandles.empty() && "Already have assumes when scanning!");
148 
149   // Go through all instructions in all blocks, add all calls to @llvm.assume
150   // to this cache.
151   for (BasicBlock &B : F)
152     for (Instruction &II : B)
153       if (match(&II, m_Intrinsic<Intrinsic::assume>()))
154         AssumeHandles.push_back(&II);
155 
156   // Mark the scan as complete.
157   Scanned = true;
158 
159   // Update affected values.
160   for (auto &A : AssumeHandles)
161     updateAffectedValues(cast<CallInst>(A));
162 }
163 
164 void AssumptionCache::registerAssumption(CallInst *CI) {
165   assert(match(CI, m_Intrinsic<Intrinsic::assume>()) &&
166          "Registered call does not call @llvm.assume");
167 
168   // If we haven't scanned the function yet, just drop this assumption. It will
169   // be found when we scan later.
170   if (!Scanned)
171     return;
172 
173   AssumeHandles.push_back(CI);
174 
175 #ifndef NDEBUG
176   assert(CI->getParent() &&
177          "Cannot register @llvm.assume call not in a basic block");
178   assert(&F == CI->getParent()->getParent() &&
179          "Cannot register @llvm.assume call not in this function");
180 
181   // We expect the number of assumptions to be small, so in an asserts build
182   // check that we don't accumulate duplicates and that all assumptions point
183   // to the same function.
184   SmallPtrSet<Value *, 16> AssumptionSet;
185   for (auto &VH : AssumeHandles) {
186     if (!VH)
187       continue;
188 
189     assert(&F == cast<Instruction>(VH)->getParent()->getParent() &&
190            "Cached assumption not inside this function!");
191     assert(match(cast<CallInst>(VH), m_Intrinsic<Intrinsic::assume>()) &&
192            "Cached something other than a call to @llvm.assume!");
193     assert(AssumptionSet.insert(VH).second &&
194            "Cache contains multiple copies of a call!");
195   }
196 #endif
197 
198   updateAffectedValues(CI);
199 }
200 
201 AnalysisKey AssumptionAnalysis::Key;
202 
203 PreservedAnalyses AssumptionPrinterPass::run(Function &F,
204                                              FunctionAnalysisManager &AM) {
205   AssumptionCache &AC = AM.getResult<AssumptionAnalysis>(F);
206 
207   OS << "Cached assumptions for function: " << F.getName() << "\n";
208   for (auto &VH : AC.assumptions())
209     if (VH)
210       OS << "  " << *cast<CallInst>(VH)->getArgOperand(0) << "\n";
211 
212   return PreservedAnalyses::all();
213 }
214 
215 void AssumptionCacheTracker::FunctionCallbackVH::deleted() {
216   auto I = ACT->AssumptionCaches.find_as(cast<Function>(getValPtr()));
217   if (I != ACT->AssumptionCaches.end())
218     ACT->AssumptionCaches.erase(I);
219   // 'this' now dangles!
220 }
221 
222 AssumptionCache &AssumptionCacheTracker::getAssumptionCache(Function &F) {
223   // We probe the function map twice to try and avoid creating a value handle
224   // around the function in common cases. This makes insertion a bit slower,
225   // but if we have to insert we're going to scan the whole function so that
226   // shouldn't matter.
227   auto I = AssumptionCaches.find_as(&F);
228   if (I != AssumptionCaches.end())
229     return *I->second;
230 
231   // Ok, build a new cache by scanning the function, insert it and the value
232   // handle into our map, and return the newly populated cache.
233   auto IP = AssumptionCaches.insert(std::make_pair(
234       FunctionCallbackVH(&F, this), llvm::make_unique<AssumptionCache>(F)));
235   assert(IP.second && "Scanning function already in the map?");
236   return *IP.first->second;
237 }
238 
239 void AssumptionCacheTracker::verifyAnalysis() const {
240   // FIXME: In the long term the verifier should not be controllable with a
241   // flag. We should either fix all passes to correctly update the assumption
242   // cache and enable the verifier unconditionally or somehow arrange for the
243   // assumption list to be updated automatically by passes.
244   if (!VerifyAssumptionCache)
245     return;
246 
247   SmallPtrSet<const CallInst *, 4> AssumptionSet;
248   for (const auto &I : AssumptionCaches) {
249     for (auto &VH : I.second->assumptions())
250       if (VH)
251         AssumptionSet.insert(cast<CallInst>(VH));
252 
253     for (const BasicBlock &B : cast<Function>(*I.first))
254       for (const Instruction &II : B)
255         if (match(&II, m_Intrinsic<Intrinsic::assume>()) &&
256             !AssumptionSet.count(cast<CallInst>(&II)))
257           report_fatal_error("Assumption in scanned function not in cache");
258   }
259 }
260 
261 AssumptionCacheTracker::AssumptionCacheTracker() : ImmutablePass(ID) {
262   initializeAssumptionCacheTrackerPass(*PassRegistry::getPassRegistry());
263 }
264 
265 AssumptionCacheTracker::~AssumptionCacheTracker() {}
266 
267 INITIALIZE_PASS(AssumptionCacheTracker, "assumption-cache-tracker",
268                 "Assumption Cache Tracker", false, true)
269 char AssumptionCacheTracker::ID = 0;
270