LLVM API Documentation
00001 //===- LazyValueInfo.cpp - Value constraint analysis ----------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines the interface for lazy computation of value constraint 00011 // information. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #include "llvm/Analysis/LazyValueInfo.h" 00016 #include "llvm/ADT/DenseSet.h" 00017 #include "llvm/ADT/STLExtras.h" 00018 #include "llvm/Analysis/AssumptionTracker.h" 00019 #include "llvm/Analysis/ConstantFolding.h" 00020 #include "llvm/Analysis/ValueTracking.h" 00021 #include "llvm/IR/CFG.h" 00022 #include "llvm/IR/ConstantRange.h" 00023 #include "llvm/IR/Constants.h" 00024 #include "llvm/IR/DataLayout.h" 00025 #include "llvm/IR/Dominators.h" 00026 #include "llvm/IR/Instructions.h" 00027 #include "llvm/IR/IntrinsicInst.h" 00028 #include "llvm/IR/PatternMatch.h" 00029 #include "llvm/IR/ValueHandle.h" 00030 #include "llvm/Support/Debug.h" 00031 #include "llvm/Support/raw_ostream.h" 00032 #include "llvm/Target/TargetLibraryInfo.h" 00033 #include <map> 00034 #include <stack> 00035 using namespace llvm; 00036 using namespace PatternMatch; 00037 00038 #define DEBUG_TYPE "lazy-value-info" 00039 00040 char LazyValueInfo::ID = 0; 00041 INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info", 00042 "Lazy Value Information Analysis", false, true) 00043 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker) 00044 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo) 00045 INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info", 00046 "Lazy Value Information Analysis", false, true) 00047 00048 namespace llvm { 00049 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); } 00050 } 00051 00052 00053 //===----------------------------------------------------------------------===// 00054 // LVILatticeVal 00055 //===----------------------------------------------------------------------===// 00056 00057 /// LVILatticeVal - This is the information tracked by LazyValueInfo for each 00058 /// value. 00059 /// 00060 /// FIXME: This is basically just for bringup, this can be made a lot more rich 00061 /// in the future. 00062 /// 00063 namespace { 00064 class LVILatticeVal { 00065 enum LatticeValueTy { 00066 /// undefined - This Value has no known value yet. 00067 undefined, 00068 00069 /// constant - This Value has a specific constant value. 00070 constant, 00071 /// notconstant - This Value is known to not have the specified value. 00072 notconstant, 00073 00074 /// constantrange - The Value falls within this range. 00075 constantrange, 00076 00077 /// overdefined - This value is not known to be constant, and we know that 00078 /// it has a value. 00079 overdefined 00080 }; 00081 00082 /// Val: This stores the current lattice value along with the Constant* for 00083 /// the constant if this is a 'constant' or 'notconstant' value. 00084 LatticeValueTy Tag; 00085 Constant *Val; 00086 ConstantRange Range; 00087 00088 public: 00089 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {} 00090 00091 static LVILatticeVal get(Constant *C) { 00092 LVILatticeVal Res; 00093 if (!isa<UndefValue>(C)) 00094 Res.markConstant(C); 00095 return Res; 00096 } 00097 static LVILatticeVal getNot(Constant *C) { 00098 LVILatticeVal Res; 00099 if (!isa<UndefValue>(C)) 00100 Res.markNotConstant(C); 00101 return Res; 00102 } 00103 static LVILatticeVal getRange(ConstantRange CR) { 00104 LVILatticeVal Res; 00105 Res.markConstantRange(CR); 00106 return Res; 00107 } 00108 00109 bool isUndefined() const { return Tag == undefined; } 00110 bool isConstant() const { return Tag == constant; } 00111 bool isNotConstant() const { return Tag == notconstant; } 00112 bool isConstantRange() const { return Tag == constantrange; } 00113 bool isOverdefined() const { return Tag == overdefined; } 00114 00115 Constant *getConstant() const { 00116 assert(isConstant() && "Cannot get the constant of a non-constant!"); 00117 return Val; 00118 } 00119 00120 Constant *getNotConstant() const { 00121 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!"); 00122 return Val; 00123 } 00124 00125 ConstantRange getConstantRange() const { 00126 assert(isConstantRange() && 00127 "Cannot get the constant-range of a non-constant-range!"); 00128 return Range; 00129 } 00130 00131 /// markOverdefined - Return true if this is a change in status. 00132 bool markOverdefined() { 00133 if (isOverdefined()) 00134 return false; 00135 Tag = overdefined; 00136 return true; 00137 } 00138 00139 /// markConstant - Return true if this is a change in status. 00140 bool markConstant(Constant *V) { 00141 assert(V && "Marking constant with NULL"); 00142 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 00143 return markConstantRange(ConstantRange(CI->getValue())); 00144 if (isa<UndefValue>(V)) 00145 return false; 00146 00147 assert((!isConstant() || getConstant() == V) && 00148 "Marking constant with different value"); 00149 assert(isUndefined()); 00150 Tag = constant; 00151 Val = V; 00152 return true; 00153 } 00154 00155 /// markNotConstant - Return true if this is a change in status. 00156 bool markNotConstant(Constant *V) { 00157 assert(V && "Marking constant with NULL"); 00158 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 00159 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue())); 00160 if (isa<UndefValue>(V)) 00161 return false; 00162 00163 assert((!isConstant() || getConstant() != V) && 00164 "Marking constant !constant with same value"); 00165 assert((!isNotConstant() || getNotConstant() == V) && 00166 "Marking !constant with different value"); 00167 assert(isUndefined() || isConstant()); 00168 Tag = notconstant; 00169 Val = V; 00170 return true; 00171 } 00172 00173 /// markConstantRange - Return true if this is a change in status. 00174 bool markConstantRange(const ConstantRange NewR) { 00175 if (isConstantRange()) { 00176 if (NewR.isEmptySet()) 00177 return markOverdefined(); 00178 00179 bool changed = Range != NewR; 00180 Range = NewR; 00181 return changed; 00182 } 00183 00184 assert(isUndefined()); 00185 if (NewR.isEmptySet()) 00186 return markOverdefined(); 00187 00188 Tag = constantrange; 00189 Range = NewR; 00190 return true; 00191 } 00192 00193 /// mergeIn - Merge the specified lattice value into this one, updating this 00194 /// one and returning true if anything changed. 00195 bool mergeIn(const LVILatticeVal &RHS) { 00196 if (RHS.isUndefined() || isOverdefined()) return false; 00197 if (RHS.isOverdefined()) return markOverdefined(); 00198 00199 if (isUndefined()) { 00200 Tag = RHS.Tag; 00201 Val = RHS.Val; 00202 Range = RHS.Range; 00203 return true; 00204 } 00205 00206 if (isConstant()) { 00207 if (RHS.isConstant()) { 00208 if (Val == RHS.Val) 00209 return false; 00210 return markOverdefined(); 00211 } 00212 00213 if (RHS.isNotConstant()) { 00214 if (Val == RHS.Val) 00215 return markOverdefined(); 00216 00217 // Unless we can prove that the two Constants are different, we must 00218 // move to overdefined. 00219 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding. 00220 if (ConstantInt *Res = dyn_cast<ConstantInt>( 00221 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE, 00222 getConstant(), 00223 RHS.getNotConstant()))) 00224 if (Res->isOne()) 00225 return markNotConstant(RHS.getNotConstant()); 00226 00227 return markOverdefined(); 00228 } 00229 00230 // RHS is a ConstantRange, LHS is a non-integer Constant. 00231 00232 // FIXME: consider the case where RHS is a range [1, 0) and LHS is 00233 // a function. The correct result is to pick up RHS. 00234 00235 return markOverdefined(); 00236 } 00237 00238 if (isNotConstant()) { 00239 if (RHS.isConstant()) { 00240 if (Val == RHS.Val) 00241 return markOverdefined(); 00242 00243 // Unless we can prove that the two Constants are different, we must 00244 // move to overdefined. 00245 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding. 00246 if (ConstantInt *Res = dyn_cast<ConstantInt>( 00247 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE, 00248 getNotConstant(), 00249 RHS.getConstant()))) 00250 if (Res->isOne()) 00251 return false; 00252 00253 return markOverdefined(); 00254 } 00255 00256 if (RHS.isNotConstant()) { 00257 if (Val == RHS.Val) 00258 return false; 00259 return markOverdefined(); 00260 } 00261 00262 return markOverdefined(); 00263 } 00264 00265 assert(isConstantRange() && "New LVILattice type?"); 00266 if (!RHS.isConstantRange()) 00267 return markOverdefined(); 00268 00269 ConstantRange NewR = Range.unionWith(RHS.getConstantRange()); 00270 if (NewR.isFullSet()) 00271 return markOverdefined(); 00272 return markConstantRange(NewR); 00273 } 00274 }; 00275 00276 } // end anonymous namespace. 00277 00278 namespace llvm { 00279 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) 00280 LLVM_ATTRIBUTE_USED; 00281 raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) { 00282 if (Val.isUndefined()) 00283 return OS << "undefined"; 00284 if (Val.isOverdefined()) 00285 return OS << "overdefined"; 00286 00287 if (Val.isNotConstant()) 00288 return OS << "notconstant<" << *Val.getNotConstant() << '>'; 00289 else if (Val.isConstantRange()) 00290 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", " 00291 << Val.getConstantRange().getUpper() << '>'; 00292 return OS << "constant<" << *Val.getConstant() << '>'; 00293 } 00294 } 00295 00296 //===----------------------------------------------------------------------===// 00297 // LazyValueInfoCache Decl 00298 //===----------------------------------------------------------------------===// 00299 00300 namespace { 00301 /// LVIValueHandle - A callback value handle updates the cache when 00302 /// values are erased. 00303 class LazyValueInfoCache; 00304 struct LVIValueHandle : public CallbackVH { 00305 LazyValueInfoCache *Parent; 00306 00307 LVIValueHandle(Value *V, LazyValueInfoCache *P) 00308 : CallbackVH(V), Parent(P) { } 00309 00310 void deleted() override; 00311 void allUsesReplacedWith(Value *V) override { 00312 deleted(); 00313 } 00314 }; 00315 } 00316 00317 namespace { 00318 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which 00319 /// maintains information about queries across the clients' queries. 00320 class LazyValueInfoCache { 00321 /// ValueCacheEntryTy - This is all of the cached block information for 00322 /// exactly one Value*. The entries are sorted by the BasicBlock* of the 00323 /// entries, allowing us to do a lookup with a binary search. 00324 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy; 00325 00326 /// ValueCache - This is all of the cached information for all values, 00327 /// mapped from Value* to key information. 00328 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache; 00329 00330 /// OverDefinedCache - This tracks, on a per-block basis, the set of 00331 /// values that are over-defined at the end of that block. This is required 00332 /// for cache updating. 00333 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy; 00334 DenseSet<OverDefinedPairTy> OverDefinedCache; 00335 00336 /// SeenBlocks - Keep track of all blocks that we have ever seen, so we 00337 /// don't spend time removing unused blocks from our caches. 00338 DenseSet<AssertingVH<BasicBlock> > SeenBlocks; 00339 00340 /// BlockValueStack - This stack holds the state of the value solver 00341 /// during a query. It basically emulates the callstack of the naive 00342 /// recursive value lookup process. 00343 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack; 00344 00345 /// A pointer to the cache of @llvm.assume calls. 00346 AssumptionTracker *AT; 00347 /// An optional DL pointer. 00348 const DataLayout *DL; 00349 /// An optional DT pointer. 00350 DominatorTree *DT; 00351 00352 friend struct LVIValueHandle; 00353 00354 /// OverDefinedCacheUpdater - A helper object that ensures that the 00355 /// OverDefinedCache is updated whenever solveBlockValue returns. 00356 struct OverDefinedCacheUpdater { 00357 LazyValueInfoCache *Parent; 00358 Value *Val; 00359 BasicBlock *BB; 00360 LVILatticeVal &BBLV; 00361 00362 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV, 00363 LazyValueInfoCache *P) 00364 : Parent(P), Val(V), BB(B), BBLV(LV) { } 00365 00366 bool markResult(bool changed) { 00367 if (changed && BBLV.isOverdefined()) 00368 Parent->OverDefinedCache.insert(std::make_pair(BB, Val)); 00369 return changed; 00370 } 00371 }; 00372 00373 00374 00375 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB); 00376 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T, 00377 LVILatticeVal &Result, 00378 Instruction *CxtI = nullptr); 00379 bool hasBlockValue(Value *Val, BasicBlock *BB); 00380 00381 // These methods process one work item and may add more. A false value 00382 // returned means that the work item was not completely processed and must 00383 // be revisited after going through the new items. 00384 bool solveBlockValue(Value *Val, BasicBlock *BB); 00385 bool solveBlockValueNonLocal(LVILatticeVal &BBLV, 00386 Value *Val, BasicBlock *BB); 00387 bool solveBlockValuePHINode(LVILatticeVal &BBLV, 00388 PHINode *PN, BasicBlock *BB); 00389 bool solveBlockValueConstantRange(LVILatticeVal &BBLV, 00390 Instruction *BBI, BasicBlock *BB); 00391 void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV, 00392 Instruction *BBI); 00393 00394 void solve(); 00395 00396 ValueCacheEntryTy &lookup(Value *V) { 00397 return ValueCache[LVIValueHandle(V, this)]; 00398 } 00399 00400 public: 00401 /// getValueInBlock - This is the query interface to determine the lattice 00402 /// value for the specified Value* at the end of the specified block. 00403 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB, 00404 Instruction *CxtI = nullptr); 00405 00406 /// getValueAt - This is the query interface to determine the lattice 00407 /// value for the specified Value* at the specified instruction (generally 00408 /// from an assume intrinsic). 00409 LVILatticeVal getValueAt(Value *V, Instruction *CxtI); 00410 00411 /// getValueOnEdge - This is the query interface to determine the lattice 00412 /// value for the specified Value* that is true on the specified edge. 00413 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB, 00414 Instruction *CxtI = nullptr); 00415 00416 /// threadEdge - This is the update interface to inform the cache that an 00417 /// edge from PredBB to OldSucc has been threaded to be from PredBB to 00418 /// NewSucc. 00419 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc); 00420 00421 /// eraseBlock - This is part of the update interface to inform the cache 00422 /// that a block has been deleted. 00423 void eraseBlock(BasicBlock *BB); 00424 00425 /// clear - Empty the cache. 00426 void clear() { 00427 SeenBlocks.clear(); 00428 ValueCache.clear(); 00429 OverDefinedCache.clear(); 00430 } 00431 00432 LazyValueInfoCache(AssumptionTracker *AT, 00433 const DataLayout *DL = nullptr, 00434 DominatorTree *DT = nullptr) : AT(AT), DL(DL), DT(DT) {} 00435 }; 00436 } // end anonymous namespace 00437 00438 void LVIValueHandle::deleted() { 00439 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy; 00440 00441 SmallVector<OverDefinedPairTy, 4> ToErase; 00442 for (DenseSet<OverDefinedPairTy>::iterator 00443 I = Parent->OverDefinedCache.begin(), 00444 E = Parent->OverDefinedCache.end(); 00445 I != E; ++I) { 00446 if (I->second == getValPtr()) 00447 ToErase.push_back(*I); 00448 } 00449 00450 for (SmallVectorImpl<OverDefinedPairTy>::iterator I = ToErase.begin(), 00451 E = ToErase.end(); I != E; ++I) 00452 Parent->OverDefinedCache.erase(*I); 00453 00454 // This erasure deallocates *this, so it MUST happen after we're done 00455 // using any and all members of *this. 00456 Parent->ValueCache.erase(*this); 00457 } 00458 00459 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) { 00460 // Shortcut if we have never seen this block. 00461 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB); 00462 if (I == SeenBlocks.end()) 00463 return; 00464 SeenBlocks.erase(I); 00465 00466 SmallVector<OverDefinedPairTy, 4> ToErase; 00467 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(), 00468 E = OverDefinedCache.end(); I != E; ++I) { 00469 if (I->first == BB) 00470 ToErase.push_back(*I); 00471 } 00472 00473 for (SmallVectorImpl<OverDefinedPairTy>::iterator I = ToErase.begin(), 00474 E = ToErase.end(); I != E; ++I) 00475 OverDefinedCache.erase(*I); 00476 00477 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator 00478 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I) 00479 I->second.erase(BB); 00480 } 00481 00482 void LazyValueInfoCache::solve() { 00483 while (!BlockValueStack.empty()) { 00484 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top(); 00485 if (solveBlockValue(e.second, e.first)) { 00486 assert(BlockValueStack.top() == e); 00487 BlockValueStack.pop(); 00488 } 00489 } 00490 } 00491 00492 bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) { 00493 // If already a constant, there is nothing to compute. 00494 if (isa<Constant>(Val)) 00495 return true; 00496 00497 LVIValueHandle ValHandle(Val, this); 00498 std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I = 00499 ValueCache.find(ValHandle); 00500 if (I == ValueCache.end()) return false; 00501 return I->second.count(BB); 00502 } 00503 00504 LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) { 00505 // If already a constant, there is nothing to compute. 00506 if (Constant *VC = dyn_cast<Constant>(Val)) 00507 return LVILatticeVal::get(VC); 00508 00509 SeenBlocks.insert(BB); 00510 return lookup(Val)[BB]; 00511 } 00512 00513 bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) { 00514 if (isa<Constant>(Val)) 00515 return true; 00516 00517 ValueCacheEntryTy &Cache = lookup(Val); 00518 SeenBlocks.insert(BB); 00519 LVILatticeVal &BBLV = Cache[BB]; 00520 00521 // OverDefinedCacheUpdater is a helper object that will update 00522 // the OverDefinedCache for us when this method exits. Make sure to 00523 // call markResult on it as we exist, passing a bool to indicate if the 00524 // cache needs updating, i.e. if we have solve a new value or not. 00525 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this); 00526 00527 // Once this BB is encountered, Val's value for this BB will not be Undefined 00528 // any longer. When we encounter this BB again, if Val's value is Overdefined, 00529 // we need to compute its value again. 00530 // 00531 // For example, considering this control flow, 00532 // BB1->BB2, BB1->BB3, BB2->BB3, BB2->BB4 00533 // 00534 // Suppose we have "icmp slt %v, 0" in BB1, and "icmp sgt %v, 0" in BB3. At 00535 // the very beginning, when analyzing edge BB2->BB3, we don't know %v's value 00536 // in BB2, and the data flow algorithm tries to compute BB2's predecessors, so 00537 // then we know %v has negative value on edge BB1->BB2. And then we return to 00538 // check BB2 again, and at this moment BB2 has Overdefined value for %v in 00539 // BB2. So we should have to follow data flow propagation algorithm to get the 00540 // value on edge BB1->BB2 propagated to BB2, and finally %v on BB2 has a 00541 // constant range describing a negative value. 00542 00543 if (!BBLV.isUndefined() && !BBLV.isOverdefined()) { 00544 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n'); 00545 00546 // Since we're reusing a cached value here, we don't need to update the 00547 // OverDefinedCahce. The cache will have been properly updated 00548 // whenever the cached value was inserted. 00549 ODCacheUpdater.markResult(false); 00550 return true; 00551 } 00552 00553 // Otherwise, this is the first time we're seeing this block. Reset the 00554 // lattice value to overdefined, so that cycles will terminate and be 00555 // conservatively correct. 00556 BBLV.markOverdefined(); 00557 00558 Instruction *BBI = dyn_cast<Instruction>(Val); 00559 if (!BBI || BBI->getParent() != BB) { 00560 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB)); 00561 } 00562 00563 if (PHINode *PN = dyn_cast<PHINode>(BBI)) { 00564 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB)); 00565 } 00566 00567 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) { 00568 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType())); 00569 return ODCacheUpdater.markResult(true); 00570 } 00571 00572 // We can only analyze the definitions of certain classes of instructions 00573 // (integral binops and casts at the moment), so bail if this isn't one. 00574 LVILatticeVal Result; 00575 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) || 00576 !BBI->getType()->isIntegerTy()) { 00577 DEBUG(dbgs() << " compute BB '" << BB->getName() 00578 << "' - overdefined because inst def found.\n"); 00579 BBLV.markOverdefined(); 00580 return ODCacheUpdater.markResult(true); 00581 } 00582 00583 // FIXME: We're currently limited to binops with a constant RHS. This should 00584 // be improved. 00585 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI); 00586 if (BO && !isa<ConstantInt>(BO->getOperand(1))) { 00587 DEBUG(dbgs() << " compute BB '" << BB->getName() 00588 << "' - overdefined because inst def found.\n"); 00589 00590 BBLV.markOverdefined(); 00591 return ODCacheUpdater.markResult(true); 00592 } 00593 00594 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB)); 00595 } 00596 00597 static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) { 00598 if (LoadInst *L = dyn_cast<LoadInst>(I)) { 00599 return L->getPointerAddressSpace() == 0 && 00600 GetUnderlyingObject(L->getPointerOperand()) == Ptr; 00601 } 00602 if (StoreInst *S = dyn_cast<StoreInst>(I)) { 00603 return S->getPointerAddressSpace() == 0 && 00604 GetUnderlyingObject(S->getPointerOperand()) == Ptr; 00605 } 00606 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) { 00607 if (MI->isVolatile()) return false; 00608 00609 // FIXME: check whether it has a valuerange that excludes zero? 00610 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength()); 00611 if (!Len || Len->isZero()) return false; 00612 00613 if (MI->getDestAddressSpace() == 0) 00614 if (GetUnderlyingObject(MI->getRawDest()) == Ptr) 00615 return true; 00616 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) 00617 if (MTI->getSourceAddressSpace() == 0) 00618 if (GetUnderlyingObject(MTI->getRawSource()) == Ptr) 00619 return true; 00620 } 00621 return false; 00622 } 00623 00624 bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV, 00625 Value *Val, BasicBlock *BB) { 00626 LVILatticeVal Result; // Start Undefined. 00627 00628 // If this is a pointer, and there's a load from that pointer in this BB, 00629 // then we know that the pointer can't be NULL. 00630 bool NotNull = false; 00631 if (Val->getType()->isPointerTy()) { 00632 if (isKnownNonNull(Val)) { 00633 NotNull = true; 00634 } else { 00635 Value *UnderlyingVal = GetUnderlyingObject(Val); 00636 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge 00637 // inside InstructionDereferencesPointer either. 00638 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, nullptr, 1)) { 00639 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); 00640 BI != BE; ++BI) { 00641 if (InstructionDereferencesPointer(BI, UnderlyingVal)) { 00642 NotNull = true; 00643 break; 00644 } 00645 } 00646 } 00647 } 00648 } 00649 00650 // If this is the entry block, we must be asking about an argument. The 00651 // value is overdefined. 00652 if (BB == &BB->getParent()->getEntryBlock()) { 00653 assert(isa<Argument>(Val) && "Unknown live-in to the entry block"); 00654 if (NotNull) { 00655 PointerType *PTy = cast<PointerType>(Val->getType()); 00656 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy)); 00657 } else { 00658 Result.markOverdefined(); 00659 } 00660 BBLV = Result; 00661 return true; 00662 } 00663 00664 // Loop over all of our predecessors, merging what we know from them into 00665 // result. 00666 bool EdgesMissing = false; 00667 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) { 00668 LVILatticeVal EdgeResult; 00669 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult); 00670 if (EdgesMissing) 00671 continue; 00672 00673 Result.mergeIn(EdgeResult); 00674 00675 // If we hit overdefined, exit early. The BlockVals entry is already set 00676 // to overdefined. 00677 if (Result.isOverdefined()) { 00678 DEBUG(dbgs() << " compute BB '" << BB->getName() 00679 << "' - overdefined because of pred.\n"); 00680 // If we previously determined that this is a pointer that can't be null 00681 // then return that rather than giving up entirely. 00682 if (NotNull) { 00683 PointerType *PTy = cast<PointerType>(Val->getType()); 00684 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy)); 00685 } 00686 00687 BBLV = Result; 00688 return true; 00689 } 00690 } 00691 if (EdgesMissing) 00692 return false; 00693 00694 // Return the merged value, which is more precise than 'overdefined'. 00695 assert(!Result.isOverdefined()); 00696 BBLV = Result; 00697 return true; 00698 } 00699 00700 bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV, 00701 PHINode *PN, BasicBlock *BB) { 00702 LVILatticeVal Result; // Start Undefined. 00703 00704 // Loop over all of our predecessors, merging what we know from them into 00705 // result. 00706 bool EdgesMissing = false; 00707 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 00708 BasicBlock *PhiBB = PN->getIncomingBlock(i); 00709 Value *PhiVal = PN->getIncomingValue(i); 00710 LVILatticeVal EdgeResult; 00711 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN); 00712 if (EdgesMissing) 00713 continue; 00714 00715 Result.mergeIn(EdgeResult); 00716 00717 // If we hit overdefined, exit early. The BlockVals entry is already set 00718 // to overdefined. 00719 if (Result.isOverdefined()) { 00720 DEBUG(dbgs() << " compute BB '" << BB->getName() 00721 << "' - overdefined because of pred.\n"); 00722 00723 BBLV = Result; 00724 return true; 00725 } 00726 } 00727 if (EdgesMissing) 00728 return false; 00729 00730 // Return the merged value, which is more precise than 'overdefined'. 00731 assert(!Result.isOverdefined() && "Possible PHI in entry block?"); 00732 BBLV = Result; 00733 return true; 00734 } 00735 00736 static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI, 00737 LVILatticeVal &Result, 00738 bool isTrueDest = true); 00739 00740 // If we can determine a constant range for the value Val at the context 00741 // provided by the instruction BBI, then merge it into BBLV. If we did find a 00742 // constant range, return true. 00743 void LazyValueInfoCache::mergeAssumeBlockValueConstantRange( 00744 Value *Val, LVILatticeVal &BBLV, Instruction *BBI) { 00745 BBI = BBI ? BBI : dyn_cast<Instruction>(Val); 00746 if (!BBI) 00747 return; 00748 00749 for (auto &I : AT->assumptions(BBI->getParent()->getParent())) { 00750 if (!isValidAssumeForContext(I, BBI, DL, DT)) 00751 continue; 00752 00753 Value *C = I->getArgOperand(0); 00754 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) { 00755 LVILatticeVal Result; 00756 if (getValueFromFromCondition(Val, ICI, Result)) { 00757 if (BBLV.isOverdefined()) 00758 BBLV = Result; 00759 else 00760 BBLV.mergeIn(Result); 00761 } 00762 } 00763 } 00764 } 00765 00766 bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV, 00767 Instruction *BBI, 00768 BasicBlock *BB) { 00769 // Figure out the range of the LHS. If that fails, bail. 00770 if (!hasBlockValue(BBI->getOperand(0), BB)) { 00771 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0))); 00772 return false; 00773 } 00774 00775 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB); 00776 mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI); 00777 if (!LHSVal.isConstantRange()) { 00778 BBLV.markOverdefined(); 00779 return true; 00780 } 00781 00782 ConstantRange LHSRange = LHSVal.getConstantRange(); 00783 ConstantRange RHSRange(1); 00784 IntegerType *ResultTy = cast<IntegerType>(BBI->getType()); 00785 if (isa<BinaryOperator>(BBI)) { 00786 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) { 00787 RHSRange = ConstantRange(RHS->getValue()); 00788 } else { 00789 BBLV.markOverdefined(); 00790 return true; 00791 } 00792 } 00793 00794 // NOTE: We're currently limited by the set of operations that ConstantRange 00795 // can evaluate symbolically. Enhancing that set will allows us to analyze 00796 // more definitions. 00797 LVILatticeVal Result; 00798 switch (BBI->getOpcode()) { 00799 case Instruction::Add: 00800 Result.markConstantRange(LHSRange.add(RHSRange)); 00801 break; 00802 case Instruction::Sub: 00803 Result.markConstantRange(LHSRange.sub(RHSRange)); 00804 break; 00805 case Instruction::Mul: 00806 Result.markConstantRange(LHSRange.multiply(RHSRange)); 00807 break; 00808 case Instruction::UDiv: 00809 Result.markConstantRange(LHSRange.udiv(RHSRange)); 00810 break; 00811 case Instruction::Shl: 00812 Result.markConstantRange(LHSRange.shl(RHSRange)); 00813 break; 00814 case Instruction::LShr: 00815 Result.markConstantRange(LHSRange.lshr(RHSRange)); 00816 break; 00817 case Instruction::Trunc: 00818 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth())); 00819 break; 00820 case Instruction::SExt: 00821 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth())); 00822 break; 00823 case Instruction::ZExt: 00824 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth())); 00825 break; 00826 case Instruction::BitCast: 00827 Result.markConstantRange(LHSRange); 00828 break; 00829 case Instruction::And: 00830 Result.markConstantRange(LHSRange.binaryAnd(RHSRange)); 00831 break; 00832 case Instruction::Or: 00833 Result.markConstantRange(LHSRange.binaryOr(RHSRange)); 00834 break; 00835 00836 // Unhandled instructions are overdefined. 00837 default: 00838 DEBUG(dbgs() << " compute BB '" << BB->getName() 00839 << "' - overdefined because inst def found.\n"); 00840 Result.markOverdefined(); 00841 break; 00842 } 00843 00844 BBLV = Result; 00845 return true; 00846 } 00847 00848 bool getValueFromFromCondition(Value *Val, ICmpInst *ICI, 00849 LVILatticeVal &Result, bool isTrueDest) { 00850 if (ICI && isa<Constant>(ICI->getOperand(1))) { 00851 if (ICI->isEquality() && ICI->getOperand(0) == Val) { 00852 // We know that V has the RHS constant if this is a true SETEQ or 00853 // false SETNE. 00854 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ)) 00855 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1))); 00856 else 00857 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1))); 00858 return true; 00859 } 00860 00861 // Recognize the range checking idiom that InstCombine produces. 00862 // (X-C1) u< C2 --> [C1, C1+C2) 00863 ConstantInt *NegOffset = nullptr; 00864 if (ICI->getPredicate() == ICmpInst::ICMP_ULT) 00865 match(ICI->getOperand(0), m_Add(m_Specific(Val), 00866 m_ConstantInt(NegOffset))); 00867 00868 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1)); 00869 if (CI && (ICI->getOperand(0) == Val || NegOffset)) { 00870 // Calculate the range of values that would satisfy the comparison. 00871 ConstantRange CmpRange(CI->getValue()); 00872 ConstantRange TrueValues = 00873 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange); 00874 00875 if (NegOffset) // Apply the offset from above. 00876 TrueValues = TrueValues.subtract(NegOffset->getValue()); 00877 00878 // If we're interested in the false dest, invert the condition. 00879 if (!isTrueDest) TrueValues = TrueValues.inverse(); 00880 00881 Result = LVILatticeVal::getRange(TrueValues); 00882 return true; 00883 } 00884 } 00885 00886 return false; 00887 } 00888 00889 /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if 00890 /// Val is not constrained on the edge. 00891 static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom, 00892 BasicBlock *BBTo, LVILatticeVal &Result) { 00893 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we 00894 // know that v != 0. 00895 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) { 00896 // If this is a conditional branch and only one successor goes to BBTo, then 00897 // we maybe able to infer something from the condition. 00898 if (BI->isConditional() && 00899 BI->getSuccessor(0) != BI->getSuccessor(1)) { 00900 bool isTrueDest = BI->getSuccessor(0) == BBTo; 00901 assert(BI->getSuccessor(!isTrueDest) == BBTo && 00902 "BBTo isn't a successor of BBFrom"); 00903 00904 // If V is the condition of the branch itself, then we know exactly what 00905 // it is. 00906 if (BI->getCondition() == Val) { 00907 Result = LVILatticeVal::get(ConstantInt::get( 00908 Type::getInt1Ty(Val->getContext()), isTrueDest)); 00909 return true; 00910 } 00911 00912 // If the condition of the branch is an equality comparison, we may be 00913 // able to infer the value. 00914 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()); 00915 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest)) 00916 return true; 00917 } 00918 } 00919 00920 // If the edge was formed by a switch on the value, then we may know exactly 00921 // what it is. 00922 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) { 00923 if (SI->getCondition() != Val) 00924 return false; 00925 00926 bool DefaultCase = SI->getDefaultDest() == BBTo; 00927 unsigned BitWidth = Val->getType()->getIntegerBitWidth(); 00928 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/); 00929 00930 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); 00931 i != e; ++i) { 00932 ConstantRange EdgeVal(i.getCaseValue()->getValue()); 00933 if (DefaultCase) { 00934 // It is possible that the default destination is the destination of 00935 // some cases. There is no need to perform difference for those cases. 00936 if (i.getCaseSuccessor() != BBTo) 00937 EdgesVals = EdgesVals.difference(EdgeVal); 00938 } else if (i.getCaseSuccessor() == BBTo) 00939 EdgesVals = EdgesVals.unionWith(EdgeVal); 00940 } 00941 Result = LVILatticeVal::getRange(EdgesVals); 00942 return true; 00943 } 00944 return false; 00945 } 00946 00947 /// \brief Compute the value of Val on the edge BBFrom -> BBTo, or the value at 00948 /// the basic block if the edge does not constraint Val. 00949 bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom, 00950 BasicBlock *BBTo, LVILatticeVal &Result, 00951 Instruction *CxtI) { 00952 // If already a constant, there is nothing to compute. 00953 if (Constant *VC = dyn_cast<Constant>(Val)) { 00954 Result = LVILatticeVal::get(VC); 00955 return true; 00956 } 00957 00958 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) { 00959 if (!Result.isConstantRange() || 00960 Result.getConstantRange().getSingleElement()) 00961 return true; 00962 00963 // FIXME: this check should be moved to the beginning of the function when 00964 // LVI better supports recursive values. Even for the single value case, we 00965 // can intersect to detect dead code (an empty range). 00966 if (!hasBlockValue(Val, BBFrom)) { 00967 BlockValueStack.push(std::make_pair(BBFrom, Val)); 00968 return false; 00969 } 00970 00971 // Try to intersect ranges of the BB and the constraint on the edge. 00972 LVILatticeVal InBlock = getBlockValue(Val, BBFrom); 00973 mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI); 00974 if (!InBlock.isConstantRange()) 00975 return true; 00976 00977 ConstantRange Range = 00978 Result.getConstantRange().intersectWith(InBlock.getConstantRange()); 00979 Result = LVILatticeVal::getRange(Range); 00980 return true; 00981 } 00982 00983 if (!hasBlockValue(Val, BBFrom)) { 00984 BlockValueStack.push(std::make_pair(BBFrom, Val)); 00985 return false; 00986 } 00987 00988 // if we couldn't compute the value on the edge, use the value from the BB 00989 Result = getBlockValue(Val, BBFrom); 00990 mergeAssumeBlockValueConstantRange(Val, Result, CxtI); 00991 return true; 00992 } 00993 00994 LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB, 00995 Instruction *CxtI) { 00996 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '" 00997 << BB->getName() << "'\n"); 00998 00999 BlockValueStack.push(std::make_pair(BB, V)); 01000 solve(); 01001 LVILatticeVal Result = getBlockValue(V, BB); 01002 mergeAssumeBlockValueConstantRange(V, Result, CxtI); 01003 01004 DEBUG(dbgs() << " Result = " << Result << "\n"); 01005 return Result; 01006 } 01007 01008 LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) { 01009 DEBUG(dbgs() << "LVI Getting value " << *V << " at '" 01010 << CxtI->getName() << "'\n"); 01011 01012 LVILatticeVal Result; 01013 mergeAssumeBlockValueConstantRange(V, Result, CxtI); 01014 01015 DEBUG(dbgs() << " Result = " << Result << "\n"); 01016 return Result; 01017 } 01018 01019 LVILatticeVal LazyValueInfoCache:: 01020 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, 01021 Instruction *CxtI) { 01022 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '" 01023 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n"); 01024 01025 LVILatticeVal Result; 01026 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) { 01027 solve(); 01028 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI); 01029 (void)WasFastQuery; 01030 assert(WasFastQuery && "More work to do after problem solved?"); 01031 } 01032 01033 DEBUG(dbgs() << " Result = " << Result << "\n"); 01034 return Result; 01035 } 01036 01037 void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, 01038 BasicBlock *NewSucc) { 01039 // When an edge in the graph has been threaded, values that we could not 01040 // determine a value for before (i.e. were marked overdefined) may be possible 01041 // to solve now. We do NOT try to proactively update these values. Instead, 01042 // we clear their entries from the cache, and allow lazy updating to recompute 01043 // them when needed. 01044 01045 // The updating process is fairly simple: we need to dropped cached info 01046 // for all values that were marked overdefined in OldSucc, and for those same 01047 // values in any successor of OldSucc (except NewSucc) in which they were 01048 // also marked overdefined. 01049 std::vector<BasicBlock*> worklist; 01050 worklist.push_back(OldSucc); 01051 01052 DenseSet<Value*> ClearSet; 01053 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(), 01054 E = OverDefinedCache.end(); I != E; ++I) { 01055 if (I->first == OldSucc) 01056 ClearSet.insert(I->second); 01057 } 01058 01059 // Use a worklist to perform a depth-first search of OldSucc's successors. 01060 // NOTE: We do not need a visited list since any blocks we have already 01061 // visited will have had their overdefined markers cleared already, and we 01062 // thus won't loop to their successors. 01063 while (!worklist.empty()) { 01064 BasicBlock *ToUpdate = worklist.back(); 01065 worklist.pop_back(); 01066 01067 // Skip blocks only accessible through NewSucc. 01068 if (ToUpdate == NewSucc) continue; 01069 01070 bool changed = false; 01071 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end(); 01072 I != E; ++I) { 01073 // If a value was marked overdefined in OldSucc, and is here too... 01074 DenseSet<OverDefinedPairTy>::iterator OI = 01075 OverDefinedCache.find(std::make_pair(ToUpdate, *I)); 01076 if (OI == OverDefinedCache.end()) continue; 01077 01078 // Remove it from the caches. 01079 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)]; 01080 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate); 01081 01082 assert(CI != Entry.end() && "Couldn't find entry to update?"); 01083 Entry.erase(CI); 01084 OverDefinedCache.erase(OI); 01085 01086 // If we removed anything, then we potentially need to update 01087 // blocks successors too. 01088 changed = true; 01089 } 01090 01091 if (!changed) continue; 01092 01093 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate)); 01094 } 01095 } 01096 01097 //===----------------------------------------------------------------------===// 01098 // LazyValueInfo Impl 01099 //===----------------------------------------------------------------------===// 01100 01101 /// getCache - This lazily constructs the LazyValueInfoCache. 01102 static LazyValueInfoCache &getCache(void *&PImpl, 01103 AssumptionTracker *AT, 01104 const DataLayout *DL = nullptr, 01105 DominatorTree *DT = nullptr) { 01106 if (!PImpl) 01107 PImpl = new LazyValueInfoCache(AT, DL, DT); 01108 return *static_cast<LazyValueInfoCache*>(PImpl); 01109 } 01110 01111 bool LazyValueInfo::runOnFunction(Function &F) { 01112 AT = &getAnalysis<AssumptionTracker>(); 01113 01114 DominatorTreeWrapperPass *DTWP = 01115 getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 01116 DT = DTWP ? &DTWP->getDomTree() : nullptr; 01117 01118 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); 01119 DL = DLP ? &DLP->getDataLayout() : nullptr; 01120 TLI = &getAnalysis<TargetLibraryInfo>(); 01121 01122 if (PImpl) 01123 getCache(PImpl, AT, DL, DT).clear(); 01124 01125 // Fully lazy. 01126 return false; 01127 } 01128 01129 void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const { 01130 AU.setPreservesAll(); 01131 AU.addRequired<AssumptionTracker>(); 01132 AU.addRequired<TargetLibraryInfo>(); 01133 } 01134 01135 void LazyValueInfo::releaseMemory() { 01136 // If the cache was allocated, free it. 01137 if (PImpl) { 01138 delete &getCache(PImpl, AT); 01139 PImpl = nullptr; 01140 } 01141 } 01142 01143 Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB, 01144 Instruction *CxtI) { 01145 LVILatticeVal Result = 01146 getCache(PImpl, AT, DL, DT).getValueInBlock(V, BB, CxtI); 01147 01148 if (Result.isConstant()) 01149 return Result.getConstant(); 01150 if (Result.isConstantRange()) { 01151 ConstantRange CR = Result.getConstantRange(); 01152 if (const APInt *SingleVal = CR.getSingleElement()) 01153 return ConstantInt::get(V->getContext(), *SingleVal); 01154 } 01155 return nullptr; 01156 } 01157 01158 /// getConstantOnEdge - Determine whether the specified value is known to be a 01159 /// constant on the specified edge. Return null if not. 01160 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB, 01161 BasicBlock *ToBB, 01162 Instruction *CxtI) { 01163 LVILatticeVal Result = 01164 getCache(PImpl, AT, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI); 01165 01166 if (Result.isConstant()) 01167 return Result.getConstant(); 01168 if (Result.isConstantRange()) { 01169 ConstantRange CR = Result.getConstantRange(); 01170 if (const APInt *SingleVal = CR.getSingleElement()) 01171 return ConstantInt::get(V->getContext(), *SingleVal); 01172 } 01173 return nullptr; 01174 } 01175 01176 static LazyValueInfo::Tristate 01177 getPredicateResult(unsigned Pred, Constant *C, LVILatticeVal &Result, 01178 const DataLayout *DL, TargetLibraryInfo *TLI) { 01179 01180 // If we know the value is a constant, evaluate the conditional. 01181 Constant *Res = nullptr; 01182 if (Result.isConstant()) { 01183 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL, 01184 TLI); 01185 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res)) 01186 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True; 01187 return LazyValueInfo::Unknown; 01188 } 01189 01190 if (Result.isConstantRange()) { 01191 ConstantInt *CI = dyn_cast<ConstantInt>(C); 01192 if (!CI) return LazyValueInfo::Unknown; 01193 01194 ConstantRange CR = Result.getConstantRange(); 01195 if (Pred == ICmpInst::ICMP_EQ) { 01196 if (!CR.contains(CI->getValue())) 01197 return LazyValueInfo::False; 01198 01199 if (CR.isSingleElement() && CR.contains(CI->getValue())) 01200 return LazyValueInfo::True; 01201 } else if (Pred == ICmpInst::ICMP_NE) { 01202 if (!CR.contains(CI->getValue())) 01203 return LazyValueInfo::True; 01204 01205 if (CR.isSingleElement() && CR.contains(CI->getValue())) 01206 return LazyValueInfo::False; 01207 } 01208 01209 // Handle more complex predicates. 01210 ConstantRange TrueValues = 01211 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue()); 01212 if (TrueValues.contains(CR)) 01213 return LazyValueInfo::True; 01214 if (TrueValues.inverse().contains(CR)) 01215 return LazyValueInfo::False; 01216 return LazyValueInfo::Unknown; 01217 } 01218 01219 if (Result.isNotConstant()) { 01220 // If this is an equality comparison, we can try to fold it knowing that 01221 // "V != C1". 01222 if (Pred == ICmpInst::ICMP_EQ) { 01223 // !C1 == C -> false iff C1 == C. 01224 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE, 01225 Result.getNotConstant(), C, DL, 01226 TLI); 01227 if (Res->isNullValue()) 01228 return LazyValueInfo::False; 01229 } else if (Pred == ICmpInst::ICMP_NE) { 01230 // !C1 != C -> true iff C1 == C. 01231 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE, 01232 Result.getNotConstant(), C, DL, 01233 TLI); 01234 if (Res->isNullValue()) 01235 return LazyValueInfo::True; 01236 } 01237 return LazyValueInfo::Unknown; 01238 } 01239 01240 return LazyValueInfo::Unknown; 01241 } 01242 01243 /// getPredicateOnEdge - Determine whether the specified value comparison 01244 /// with a constant is known to be true or false on the specified CFG edge. 01245 /// Pred is a CmpInst predicate. 01246 LazyValueInfo::Tristate 01247 LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C, 01248 BasicBlock *FromBB, BasicBlock *ToBB, 01249 Instruction *CxtI) { 01250 LVILatticeVal Result = 01251 getCache(PImpl, AT, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI); 01252 01253 return getPredicateResult(Pred, C, Result, DL, TLI); 01254 } 01255 01256 LazyValueInfo::Tristate 01257 LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C, 01258 Instruction *CxtI) { 01259 LVILatticeVal Result = 01260 getCache(PImpl, AT, DL, DT).getValueAt(V, CxtI); 01261 01262 return getPredicateResult(Pred, C, Result, DL, TLI); 01263 } 01264 01265 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, 01266 BasicBlock *NewSucc) { 01267 if (PImpl) getCache(PImpl, AT, DL, DT).threadEdge(PredBB, OldSucc, NewSucc); 01268 } 01269 01270 void LazyValueInfo::eraseBlock(BasicBlock *BB) { 01271 if (PImpl) getCache(PImpl, AT, DL, DT).eraseBlock(BB); 01272 }