1 //===- ValueTracking.cpp - Walk computations to compute properties --------===// 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 routines that help analyze properties that chains of 11 // computations have. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Analysis/ValueTracking.h" 16 #include "llvm/Analysis/InstructionSimplify.h" 17 #include "llvm/Constants.h" 18 #include "llvm/Instructions.h" 19 #include "llvm/GlobalVariable.h" 20 #include "llvm/GlobalAlias.h" 21 #include "llvm/IntrinsicInst.h" 22 #include "llvm/LLVMContext.h" 23 #include "llvm/Operator.h" 24 #include "llvm/Target/TargetData.h" 25 #include "llvm/Support/GetElementPtrTypeIterator.h" 26 #include "llvm/Support/MathExtras.h" 27 #include "llvm/Support/PatternMatch.h" 28 #include "llvm/ADT/SmallPtrSet.h" 29 #include <cstring> 30 using namespace llvm; 31 using namespace llvm::PatternMatch; 32 33 const unsigned MaxDepth = 6; 34 35 /// getBitWidth - Returns the bitwidth of the given scalar or pointer type (if 36 /// unknown returns 0). For vector types, returns the element type's bitwidth. 37 static unsigned getBitWidth(Type *Ty, const TargetData *TD) { 38 if (unsigned BitWidth = Ty->getScalarSizeInBits()) 39 return BitWidth; 40 assert(isa<PointerType>(Ty) && "Expected a pointer type!"); 41 return TD ? TD->getPointerSizeInBits() : 0; 42 } 43 44 /// ComputeMaskedBits - Determine which of the bits specified in Mask are 45 /// known to be either zero or one and return them in the KnownZero/KnownOne 46 /// bit sets. This code only analyzes bits in Mask, in order to short-circuit 47 /// processing. 48 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that 49 /// we cannot optimize based on the assumption that it is zero without changing 50 /// it to be an explicit zero. If we don't change it to zero, other code could 51 /// optimized based on the contradictory assumption that it is non-zero. 52 /// Because instcombine aggressively folds operations with undef args anyway, 53 /// this won't lose us code quality. 54 /// 55 /// This function is defined on values with integer type, values with pointer 56 /// type (but only if TD is non-null), and vectors of integers. In the case 57 /// where V is a vector, the mask, known zero, and known one values are the 58 /// same width as the vector element, and the bit is set only if it is true 59 /// for all of the elements in the vector. 60 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask, 61 APInt &KnownZero, APInt &KnownOne, 62 const TargetData *TD, unsigned Depth) { 63 assert(V && "No Value?"); 64 assert(Depth <= MaxDepth && "Limit Search Depth"); 65 unsigned BitWidth = Mask.getBitWidth(); 66 assert((V->getType()->isIntOrIntVectorTy() || 67 V->getType()->getScalarType()->isPointerTy()) && 68 "Not integer or pointer type!"); 69 assert((!TD || 70 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) && 71 (!V->getType()->isIntOrIntVectorTy() || 72 V->getType()->getScalarSizeInBits() == BitWidth) && 73 KnownZero.getBitWidth() == BitWidth && 74 KnownOne.getBitWidth() == BitWidth && 75 "V, Mask, KnownOne and KnownZero should have same BitWidth"); 76 77 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 78 // We know all of the bits for a constant! 79 KnownOne = CI->getValue() & Mask; 80 KnownZero = ~KnownOne & Mask; 81 return; 82 } 83 // Null and aggregate-zero are all-zeros. 84 if (isa<ConstantPointerNull>(V) || 85 isa<ConstantAggregateZero>(V)) { 86 KnownOne.clearAllBits(); 87 KnownZero = Mask; 88 return; 89 } 90 // Handle a constant vector by taking the intersection of the known bits of 91 // each element. 92 // FIXME: Remove. 93 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) { 94 KnownZero.setAllBits(); KnownOne.setAllBits(); 95 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) { 96 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0); 97 ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2, 98 TD, Depth); 99 KnownZero &= KnownZero2; 100 KnownOne &= KnownOne2; 101 } 102 return; 103 } 104 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) { 105 // We know that CDS must be a vector of integers. Take the intersection of 106 // each element. 107 KnownZero.setAllBits(); KnownOne.setAllBits(); 108 APInt Elt(KnownZero.getBitWidth(), 0); 109 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 110 Elt = CDS->getElementAsInteger(i); 111 KnownZero &= ~Elt; 112 KnownOne &= Elt; 113 } 114 return; 115 } 116 117 // The address of an aligned GlobalValue has trailing zeros. 118 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 119 unsigned Align = GV->getAlignment(); 120 if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) { 121 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) { 122 Type *ObjectType = GVar->getType()->getElementType(); 123 // If the object is defined in the current Module, we'll be giving 124 // it the preferred alignment. Otherwise, we have to assume that it 125 // may only have the minimum ABI alignment. 126 if (!GVar->isDeclaration() && !GVar->isWeakForLinker()) 127 Align = TD->getPreferredAlignment(GVar); 128 else 129 Align = TD->getABITypeAlignment(ObjectType); 130 } 131 } 132 if (Align > 0) 133 KnownZero = Mask & APInt::getLowBitsSet(BitWidth, 134 CountTrailingZeros_32(Align)); 135 else 136 KnownZero.clearAllBits(); 137 KnownOne.clearAllBits(); 138 return; 139 } 140 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has 141 // the bits of its aliasee. 142 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 143 if (GA->mayBeOverridden()) { 144 KnownZero.clearAllBits(); KnownOne.clearAllBits(); 145 } else { 146 ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne, 147 TD, Depth+1); 148 } 149 return; 150 } 151 152 if (Argument *A = dyn_cast<Argument>(V)) { 153 // Get alignment information off byval arguments if specified in the IR. 154 if (A->hasByValAttr()) 155 if (unsigned Align = A->getParamAlignment()) 156 KnownZero = Mask & APInt::getLowBitsSet(BitWidth, 157 CountTrailingZeros_32(Align)); 158 return; 159 } 160 161 // Start out not knowing anything. 162 KnownZero.clearAllBits(); KnownOne.clearAllBits(); 163 164 if (Depth == MaxDepth || Mask == 0) 165 return; // Limit search depth. 166 167 Operator *I = dyn_cast<Operator>(V); 168 if (!I) return; 169 170 APInt KnownZero2(KnownZero), KnownOne2(KnownOne); 171 switch (I->getOpcode()) { 172 default: break; 173 case Instruction::And: { 174 // If either the LHS or the RHS are Zero, the result is zero. 175 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1); 176 APInt Mask2(Mask & ~KnownZero); 177 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 178 Depth+1); 179 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 180 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 181 182 // Output known-1 bits are only known if set in both the LHS & RHS. 183 KnownOne &= KnownOne2; 184 // Output known-0 are known to be clear if zero in either the LHS | RHS. 185 KnownZero |= KnownZero2; 186 return; 187 } 188 case Instruction::Or: { 189 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1); 190 APInt Mask2(Mask & ~KnownOne); 191 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 192 Depth+1); 193 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 194 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 195 196 // Output known-0 bits are only known if clear in both the LHS & RHS. 197 KnownZero &= KnownZero2; 198 // Output known-1 are known to be set if set in either the LHS | RHS. 199 KnownOne |= KnownOne2; 200 return; 201 } 202 case Instruction::Xor: { 203 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1); 204 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD, 205 Depth+1); 206 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 207 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 208 209 // Output known-0 bits are known if clear or set in both the LHS & RHS. 210 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2); 211 // Output known-1 are known to be set if set in only one of the LHS, RHS. 212 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2); 213 KnownZero = KnownZeroOut; 214 return; 215 } 216 case Instruction::Mul: { 217 APInt Mask2 = APInt::getAllOnesValue(BitWidth); 218 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1); 219 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 220 Depth+1); 221 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 222 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 223 224 bool isKnownNegative = false; 225 bool isKnownNonNegative = false; 226 // If the multiplication is known not to overflow, compute the sign bit. 227 if (Mask.isNegative() && 228 cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap()) { 229 Value *Op1 = I->getOperand(1), *Op2 = I->getOperand(0); 230 if (Op1 == Op2) { 231 // The product of a number with itself is non-negative. 232 isKnownNonNegative = true; 233 } else { 234 bool isKnownNonNegative1 = KnownZero.isNegative(); 235 bool isKnownNonNegative2 = KnownZero2.isNegative(); 236 bool isKnownNegative1 = KnownOne.isNegative(); 237 bool isKnownNegative2 = KnownOne2.isNegative(); 238 // The product of two numbers with the same sign is non-negative. 239 isKnownNonNegative = (isKnownNegative1 && isKnownNegative2) || 240 (isKnownNonNegative1 && isKnownNonNegative2); 241 // The product of a negative number and a non-negative number is either 242 // negative or zero. 243 if (!isKnownNonNegative) 244 isKnownNegative = (isKnownNegative1 && isKnownNonNegative2 && 245 isKnownNonZero(Op2, TD, Depth)) || 246 (isKnownNegative2 && isKnownNonNegative1 && 247 isKnownNonZero(Op1, TD, Depth)); 248 } 249 } 250 251 // If low bits are zero in either operand, output low known-0 bits. 252 // Also compute a conserative estimate for high known-0 bits. 253 // More trickiness is possible, but this is sufficient for the 254 // interesting case of alignment computation. 255 KnownOne.clearAllBits(); 256 unsigned TrailZ = KnownZero.countTrailingOnes() + 257 KnownZero2.countTrailingOnes(); 258 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() + 259 KnownZero2.countLeadingOnes(), 260 BitWidth) - BitWidth; 261 262 TrailZ = std::min(TrailZ, BitWidth); 263 LeadZ = std::min(LeadZ, BitWidth); 264 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) | 265 APInt::getHighBitsSet(BitWidth, LeadZ); 266 KnownZero &= Mask; 267 268 // Only make use of no-wrap flags if we failed to compute the sign bit 269 // directly. This matters if the multiplication always overflows, in 270 // which case we prefer to follow the result of the direct computation, 271 // though as the program is invoking undefined behaviour we can choose 272 // whatever we like here. 273 if (isKnownNonNegative && !KnownOne.isNegative()) 274 KnownZero.setBit(BitWidth - 1); 275 else if (isKnownNegative && !KnownZero.isNegative()) 276 KnownOne.setBit(BitWidth - 1); 277 278 return; 279 } 280 case Instruction::UDiv: { 281 // For the purposes of computing leading zeros we can conservatively 282 // treat a udiv as a logical right shift by the power of 2 known to 283 // be less than the denominator. 284 APInt AllOnes = APInt::getAllOnesValue(BitWidth); 285 ComputeMaskedBits(I->getOperand(0), 286 AllOnes, KnownZero2, KnownOne2, TD, Depth+1); 287 unsigned LeadZ = KnownZero2.countLeadingOnes(); 288 289 KnownOne2.clearAllBits(); 290 KnownZero2.clearAllBits(); 291 ComputeMaskedBits(I->getOperand(1), 292 AllOnes, KnownZero2, KnownOne2, TD, Depth+1); 293 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros(); 294 if (RHSUnknownLeadingOnes != BitWidth) 295 LeadZ = std::min(BitWidth, 296 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1); 297 298 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask; 299 return; 300 } 301 case Instruction::Select: 302 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1); 303 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD, 304 Depth+1); 305 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 306 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 307 308 // Only known if known in both the LHS and RHS. 309 KnownOne &= KnownOne2; 310 KnownZero &= KnownZero2; 311 return; 312 case Instruction::FPTrunc: 313 case Instruction::FPExt: 314 case Instruction::FPToUI: 315 case Instruction::FPToSI: 316 case Instruction::SIToFP: 317 case Instruction::UIToFP: 318 return; // Can't work with floating point. 319 case Instruction::PtrToInt: 320 case Instruction::IntToPtr: 321 // We can't handle these if we don't know the pointer size. 322 if (!TD) return; 323 // FALL THROUGH and handle them the same as zext/trunc. 324 case Instruction::ZExt: 325 case Instruction::Trunc: { 326 Type *SrcTy = I->getOperand(0)->getType(); 327 328 unsigned SrcBitWidth; 329 // Note that we handle pointer operands here because of inttoptr/ptrtoint 330 // which fall through here. 331 if (SrcTy->isPointerTy()) 332 SrcBitWidth = TD->getTypeSizeInBits(SrcTy); 333 else 334 SrcBitWidth = SrcTy->getScalarSizeInBits(); 335 336 APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth); 337 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth); 338 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth); 339 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD, 340 Depth+1); 341 KnownZero = KnownZero.zextOrTrunc(BitWidth); 342 KnownOne = KnownOne.zextOrTrunc(BitWidth); 343 // Any top bits are known to be zero. 344 if (BitWidth > SrcBitWidth) 345 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth); 346 return; 347 } 348 case Instruction::BitCast: { 349 Type *SrcTy = I->getOperand(0)->getType(); 350 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 351 // TODO: For now, not handling conversions like: 352 // (bitcast i64 %x to <2 x i32>) 353 !I->getType()->isVectorTy()) { 354 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD, 355 Depth+1); 356 return; 357 } 358 break; 359 } 360 case Instruction::SExt: { 361 // Compute the bits in the result that are not present in the input. 362 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits(); 363 364 APInt MaskIn = Mask.trunc(SrcBitWidth); 365 KnownZero = KnownZero.trunc(SrcBitWidth); 366 KnownOne = KnownOne.trunc(SrcBitWidth); 367 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD, 368 Depth+1); 369 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 370 KnownZero = KnownZero.zext(BitWidth); 371 KnownOne = KnownOne.zext(BitWidth); 372 373 // If the sign bit of the input is known set or clear, then we know the 374 // top bits of the result. 375 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero 376 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth); 377 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set 378 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth); 379 return; 380 } 381 case Instruction::Shl: 382 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0 383 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { 384 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth); 385 APInt Mask2(Mask.lshr(ShiftAmt)); 386 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD, 387 Depth+1); 388 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 389 KnownZero <<= ShiftAmt; 390 KnownOne <<= ShiftAmt; 391 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0 392 return; 393 } 394 break; 395 case Instruction::LShr: 396 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0 397 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { 398 // Compute the new bits that are at the top now. 399 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth); 400 401 // Unsigned shift right. 402 APInt Mask2(Mask.shl(ShiftAmt)); 403 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD, 404 Depth+1); 405 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 406 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt); 407 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt); 408 // high bits known zero. 409 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt); 410 return; 411 } 412 break; 413 case Instruction::AShr: 414 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0 415 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { 416 // Compute the new bits that are at the top now. 417 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1); 418 419 // Signed shift right. 420 APInt Mask2(Mask.shl(ShiftAmt)); 421 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD, 422 Depth+1); 423 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 424 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt); 425 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt); 426 427 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt)); 428 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero. 429 KnownZero |= HighBits; 430 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one. 431 KnownOne |= HighBits; 432 return; 433 } 434 break; 435 case Instruction::Sub: { 436 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) { 437 // We know that the top bits of C-X are clear if X contains less bits 438 // than C (i.e. no wrap-around can happen). For example, 20-X is 439 // positive if we can prove that X is >= 0 and < 16. 440 if (!CLHS->getValue().isNegative()) { 441 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros(); 442 // NLZ can't be BitWidth with no sign bit 443 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1); 444 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2, 445 TD, Depth+1); 446 447 // If all of the MaskV bits are known to be zero, then we know the 448 // output top bits are zero, because we now know that the output is 449 // from [0-C]. 450 if ((KnownZero2 & MaskV) == MaskV) { 451 unsigned NLZ2 = CLHS->getValue().countLeadingZeros(); 452 // Top bits known zero. 453 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask; 454 } 455 } 456 } 457 } 458 // fall through 459 case Instruction::Add: { 460 // If one of the operands has trailing zeros, then the bits that the 461 // other operand has in those bit positions will be preserved in the 462 // result. For an add, this works with either operand. For a subtract, 463 // this only works if the known zeros are in the right operand. 464 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0); 465 APInt Mask2 = APInt::getLowBitsSet(BitWidth, 466 BitWidth - Mask.countLeadingZeros()); 467 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD, 468 Depth+1); 469 assert((LHSKnownZero & LHSKnownOne) == 0 && 470 "Bits known to be one AND zero?"); 471 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes(); 472 473 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD, 474 Depth+1); 475 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 476 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes(); 477 478 // Determine which operand has more trailing zeros, and use that 479 // many bits from the other operand. 480 if (LHSKnownZeroOut > RHSKnownZeroOut) { 481 if (I->getOpcode() == Instruction::Add) { 482 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut); 483 KnownZero |= KnownZero2 & Mask; 484 KnownOne |= KnownOne2 & Mask; 485 } else { 486 // If the known zeros are in the left operand for a subtract, 487 // fall back to the minimum known zeros in both operands. 488 KnownZero |= APInt::getLowBitsSet(BitWidth, 489 std::min(LHSKnownZeroOut, 490 RHSKnownZeroOut)); 491 } 492 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) { 493 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut); 494 KnownZero |= LHSKnownZero & Mask; 495 KnownOne |= LHSKnownOne & Mask; 496 } 497 498 // Are we still trying to solve for the sign bit? 499 if (Mask.isNegative() && !KnownZero.isNegative() && !KnownOne.isNegative()){ 500 OverflowingBinaryOperator *OBO = cast<OverflowingBinaryOperator>(I); 501 if (OBO->hasNoSignedWrap()) { 502 if (I->getOpcode() == Instruction::Add) { 503 // Adding two positive numbers can't wrap into negative 504 if (LHSKnownZero.isNegative() && KnownZero2.isNegative()) 505 KnownZero |= APInt::getSignBit(BitWidth); 506 // and adding two negative numbers can't wrap into positive. 507 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative()) 508 KnownOne |= APInt::getSignBit(BitWidth); 509 } else { 510 // Subtracting a negative number from a positive one can't wrap 511 if (LHSKnownZero.isNegative() && KnownOne2.isNegative()) 512 KnownZero |= APInt::getSignBit(BitWidth); 513 // neither can subtracting a positive number from a negative one. 514 else if (LHSKnownOne.isNegative() && KnownZero2.isNegative()) 515 KnownOne |= APInt::getSignBit(BitWidth); 516 } 517 } 518 } 519 520 return; 521 } 522 case Instruction::SRem: 523 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) { 524 APInt RA = Rem->getValue().abs(); 525 if (RA.isPowerOf2()) { 526 APInt LowBits = RA - 1; 527 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth); 528 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 529 Depth+1); 530 531 // The low bits of the first operand are unchanged by the srem. 532 KnownZero = KnownZero2 & LowBits; 533 KnownOne = KnownOne2 & LowBits; 534 535 // If the first operand is non-negative or has all low bits zero, then 536 // the upper bits are all zero. 537 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits)) 538 KnownZero |= ~LowBits; 539 540 // If the first operand is negative and not all low bits are zero, then 541 // the upper bits are all one. 542 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0)) 543 KnownOne |= ~LowBits; 544 545 KnownZero &= Mask; 546 KnownOne &= Mask; 547 548 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 549 } 550 } 551 552 // The sign bit is the LHS's sign bit, except when the result of the 553 // remainder is zero. 554 if (Mask.isNegative() && KnownZero.isNonNegative()) { 555 APInt Mask2 = APInt::getSignBit(BitWidth); 556 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0); 557 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD, 558 Depth+1); 559 // If it's known zero, our sign bit is also zero. 560 if (LHSKnownZero.isNegative()) 561 KnownZero |= LHSKnownZero; 562 } 563 564 break; 565 case Instruction::URem: { 566 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) { 567 APInt RA = Rem->getValue(); 568 if (RA.isPowerOf2()) { 569 APInt LowBits = (RA - 1); 570 APInt Mask2 = LowBits & Mask; 571 KnownZero |= ~LowBits & Mask; 572 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD, 573 Depth+1); 574 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 575 break; 576 } 577 } 578 579 // Since the result is less than or equal to either operand, any leading 580 // zero bits in either operand must also exist in the result. 581 APInt AllOnes = APInt::getAllOnesValue(BitWidth); 582 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne, 583 TD, Depth+1); 584 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2, 585 TD, Depth+1); 586 587 unsigned Leaders = std::max(KnownZero.countLeadingOnes(), 588 KnownZero2.countLeadingOnes()); 589 KnownOne.clearAllBits(); 590 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask; 591 break; 592 } 593 594 case Instruction::Alloca: { 595 AllocaInst *AI = cast<AllocaInst>(V); 596 unsigned Align = AI->getAlignment(); 597 if (Align == 0 && TD) 598 Align = TD->getABITypeAlignment(AI->getType()->getElementType()); 599 600 if (Align > 0) 601 KnownZero = Mask & APInt::getLowBitsSet(BitWidth, 602 CountTrailingZeros_32(Align)); 603 break; 604 } 605 case Instruction::GetElementPtr: { 606 // Analyze all of the subscripts of this getelementptr instruction 607 // to determine if we can prove known low zero bits. 608 APInt LocalMask = APInt::getAllOnesValue(BitWidth); 609 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0); 610 ComputeMaskedBits(I->getOperand(0), LocalMask, 611 LocalKnownZero, LocalKnownOne, TD, Depth+1); 612 unsigned TrailZ = LocalKnownZero.countTrailingOnes(); 613 614 gep_type_iterator GTI = gep_type_begin(I); 615 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) { 616 Value *Index = I->getOperand(i); 617 if (StructType *STy = dyn_cast<StructType>(*GTI)) { 618 // Handle struct member offset arithmetic. 619 if (!TD) return; 620 const StructLayout *SL = TD->getStructLayout(STy); 621 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue(); 622 uint64_t Offset = SL->getElementOffset(Idx); 623 TrailZ = std::min(TrailZ, 624 CountTrailingZeros_64(Offset)); 625 } else { 626 // Handle array index arithmetic. 627 Type *IndexedTy = GTI.getIndexedType(); 628 if (!IndexedTy->isSized()) return; 629 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits(); 630 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1; 631 LocalMask = APInt::getAllOnesValue(GEPOpiBits); 632 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0); 633 ComputeMaskedBits(Index, LocalMask, 634 LocalKnownZero, LocalKnownOne, TD, Depth+1); 635 TrailZ = std::min(TrailZ, 636 unsigned(CountTrailingZeros_64(TypeSize) + 637 LocalKnownZero.countTrailingOnes())); 638 } 639 } 640 641 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask; 642 break; 643 } 644 case Instruction::PHI: { 645 PHINode *P = cast<PHINode>(I); 646 // Handle the case of a simple two-predecessor recurrence PHI. 647 // There's a lot more that could theoretically be done here, but 648 // this is sufficient to catch some interesting cases. 649 if (P->getNumIncomingValues() == 2) { 650 for (unsigned i = 0; i != 2; ++i) { 651 Value *L = P->getIncomingValue(i); 652 Value *R = P->getIncomingValue(!i); 653 Operator *LU = dyn_cast<Operator>(L); 654 if (!LU) 655 continue; 656 unsigned Opcode = LU->getOpcode(); 657 // Check for operations that have the property that if 658 // both their operands have low zero bits, the result 659 // will have low zero bits. 660 if (Opcode == Instruction::Add || 661 Opcode == Instruction::Sub || 662 Opcode == Instruction::And || 663 Opcode == Instruction::Or || 664 Opcode == Instruction::Mul) { 665 Value *LL = LU->getOperand(0); 666 Value *LR = LU->getOperand(1); 667 // Find a recurrence. 668 if (LL == I) 669 L = LR; 670 else if (LR == I) 671 L = LL; 672 else 673 break; 674 // Ok, we have a PHI of the form L op= R. Check for low 675 // zero bits. 676 APInt Mask2 = APInt::getAllOnesValue(BitWidth); 677 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1); 678 Mask2 = APInt::getLowBitsSet(BitWidth, 679 KnownZero2.countTrailingOnes()); 680 681 // We need to take the minimum number of known bits 682 APInt KnownZero3(KnownZero), KnownOne3(KnownOne); 683 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1); 684 685 KnownZero = Mask & 686 APInt::getLowBitsSet(BitWidth, 687 std::min(KnownZero2.countTrailingOnes(), 688 KnownZero3.countTrailingOnes())); 689 break; 690 } 691 } 692 } 693 694 // Unreachable blocks may have zero-operand PHI nodes. 695 if (P->getNumIncomingValues() == 0) 696 return; 697 698 // Otherwise take the unions of the known bit sets of the operands, 699 // taking conservative care to avoid excessive recursion. 700 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) { 701 // Skip if every incoming value references to ourself. 702 if (P->hasConstantValue() == P) 703 break; 704 705 KnownZero = APInt::getAllOnesValue(BitWidth); 706 KnownOne = APInt::getAllOnesValue(BitWidth); 707 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) { 708 // Skip direct self references. 709 if (P->getIncomingValue(i) == P) continue; 710 711 KnownZero2 = APInt(BitWidth, 0); 712 KnownOne2 = APInt(BitWidth, 0); 713 // Recurse, but cap the recursion to one level, because we don't 714 // want to waste time spinning around in loops. 715 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne, 716 KnownZero2, KnownOne2, TD, MaxDepth-1); 717 KnownZero &= KnownZero2; 718 KnownOne &= KnownOne2; 719 // If all bits have been ruled out, there's no need to check 720 // more operands. 721 if (!KnownZero && !KnownOne) 722 break; 723 } 724 } 725 break; 726 } 727 case Instruction::Call: 728 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 729 switch (II->getIntrinsicID()) { 730 default: break; 731 case Intrinsic::ctlz: 732 case Intrinsic::cttz: { 733 unsigned LowBits = Log2_32(BitWidth)+1; 734 // If this call is undefined for 0, the result will be less than 2^n. 735 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext())) 736 LowBits -= 1; 737 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits); 738 break; 739 } 740 case Intrinsic::ctpop: { 741 unsigned LowBits = Log2_32(BitWidth)+1; 742 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits); 743 break; 744 } 745 case Intrinsic::x86_sse42_crc32_64_8: 746 case Intrinsic::x86_sse42_crc32_64_64: 747 KnownZero = APInt::getHighBitsSet(64, 32); 748 break; 749 } 750 } 751 break; 752 } 753 } 754 755 /// ComputeSignBit - Determine whether the sign bit is known to be zero or 756 /// one. Convenience wrapper around ComputeMaskedBits. 757 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne, 758 const TargetData *TD, unsigned Depth) { 759 unsigned BitWidth = getBitWidth(V->getType(), TD); 760 if (!BitWidth) { 761 KnownZero = false; 762 KnownOne = false; 763 return; 764 } 765 APInt ZeroBits(BitWidth, 0); 766 APInt OneBits(BitWidth, 0); 767 ComputeMaskedBits(V, APInt::getSignBit(BitWidth), ZeroBits, OneBits, TD, 768 Depth); 769 KnownOne = OneBits[BitWidth - 1]; 770 KnownZero = ZeroBits[BitWidth - 1]; 771 } 772 773 /// isPowerOfTwo - Return true if the given value is known to have exactly one 774 /// bit set when defined. For vectors return true if every element is known to 775 /// be a power of two when defined. Supports values with integer or pointer 776 /// types and vectors of integers. 777 bool llvm::isPowerOfTwo(Value *V, const TargetData *TD, bool OrZero, 778 unsigned Depth) { 779 if (Constant *C = dyn_cast<Constant>(V)) { 780 if (C->isNullValue()) 781 return OrZero; 782 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) 783 return CI->getValue().isPowerOf2(); 784 // TODO: Handle vector constants. 785 } 786 787 // 1 << X is clearly a power of two if the one is not shifted off the end. If 788 // it is shifted off the end then the result is undefined. 789 if (match(V, m_Shl(m_One(), m_Value()))) 790 return true; 791 792 // (signbit) >>l X is clearly a power of two if the one is not shifted off the 793 // bottom. If it is shifted off the bottom then the result is undefined. 794 if (match(V, m_LShr(m_SignBit(), m_Value()))) 795 return true; 796 797 // The remaining tests are all recursive, so bail out if we hit the limit. 798 if (Depth++ == MaxDepth) 799 return false; 800 801 Value *X = 0, *Y = 0; 802 // A shift of a power of two is a power of two or zero. 803 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) || 804 match(V, m_Shr(m_Value(X), m_Value())))) 805 return isPowerOfTwo(X, TD, /*OrZero*/true, Depth); 806 807 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V)) 808 return isPowerOfTwo(ZI->getOperand(0), TD, OrZero, Depth); 809 810 if (SelectInst *SI = dyn_cast<SelectInst>(V)) 811 return isPowerOfTwo(SI->getTrueValue(), TD, OrZero, Depth) && 812 isPowerOfTwo(SI->getFalseValue(), TD, OrZero, Depth); 813 814 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) { 815 // A power of two and'd with anything is a power of two or zero. 816 if (isPowerOfTwo(X, TD, /*OrZero*/true, Depth) || 817 isPowerOfTwo(Y, TD, /*OrZero*/true, Depth)) 818 return true; 819 // X & (-X) is always a power of two or zero. 820 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X)))) 821 return true; 822 return false; 823 } 824 825 // An exact divide or right shift can only shift off zero bits, so the result 826 // is a power of two only if the first operand is a power of two and not 827 // copying a sign bit (sdiv int_min, 2). 828 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) || 829 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) { 830 return isPowerOfTwo(cast<Operator>(V)->getOperand(0), TD, OrZero, Depth); 831 } 832 833 return false; 834 } 835 836 /// isKnownNonZero - Return true if the given value is known to be non-zero 837 /// when defined. For vectors return true if every element is known to be 838 /// non-zero when defined. Supports values with integer or pointer type and 839 /// vectors of integers. 840 bool llvm::isKnownNonZero(Value *V, const TargetData *TD, unsigned Depth) { 841 if (Constant *C = dyn_cast<Constant>(V)) { 842 if (C->isNullValue()) 843 return false; 844 if (isa<ConstantInt>(C)) 845 // Must be non-zero due to null test above. 846 return true; 847 // TODO: Handle vectors 848 return false; 849 } 850 851 // The remaining tests are all recursive, so bail out if we hit the limit. 852 if (Depth++ >= MaxDepth) 853 return false; 854 855 unsigned BitWidth = getBitWidth(V->getType(), TD); 856 857 // X | Y != 0 if X != 0 or Y != 0. 858 Value *X = 0, *Y = 0; 859 if (match(V, m_Or(m_Value(X), m_Value(Y)))) 860 return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth); 861 862 // ext X != 0 if X != 0. 863 if (isa<SExtInst>(V) || isa<ZExtInst>(V)) 864 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth); 865 866 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined 867 // if the lowest bit is shifted off the end. 868 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) { 869 // shl nuw can't remove any non-zero bits. 870 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V); 871 if (BO->hasNoUnsignedWrap()) 872 return isKnownNonZero(X, TD, Depth); 873 874 APInt KnownZero(BitWidth, 0); 875 APInt KnownOne(BitWidth, 0); 876 ComputeMaskedBits(X, APInt(BitWidth, 1), KnownZero, KnownOne, TD, Depth); 877 if (KnownOne[0]) 878 return true; 879 } 880 // shr X, Y != 0 if X is negative. Note that the value of the shift is not 881 // defined if the sign bit is shifted off the end. 882 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) { 883 // shr exact can only shift out zero bits. 884 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V); 885 if (BO->isExact()) 886 return isKnownNonZero(X, TD, Depth); 887 888 bool XKnownNonNegative, XKnownNegative; 889 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth); 890 if (XKnownNegative) 891 return true; 892 } 893 // div exact can only produce a zero if the dividend is zero. 894 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) { 895 return isKnownNonZero(X, TD, Depth); 896 } 897 // X + Y. 898 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) { 899 bool XKnownNonNegative, XKnownNegative; 900 bool YKnownNonNegative, YKnownNegative; 901 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth); 902 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth); 903 904 // If X and Y are both non-negative (as signed values) then their sum is not 905 // zero unless both X and Y are zero. 906 if (XKnownNonNegative && YKnownNonNegative) 907 if (isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth)) 908 return true; 909 910 // If X and Y are both negative (as signed values) then their sum is not 911 // zero unless both X and Y equal INT_MIN. 912 if (BitWidth && XKnownNegative && YKnownNegative) { 913 APInt KnownZero(BitWidth, 0); 914 APInt KnownOne(BitWidth, 0); 915 APInt Mask = APInt::getSignedMaxValue(BitWidth); 916 // The sign bit of X is set. If some other bit is set then X is not equal 917 // to INT_MIN. 918 ComputeMaskedBits(X, Mask, KnownZero, KnownOne, TD, Depth); 919 if ((KnownOne & Mask) != 0) 920 return true; 921 // The sign bit of Y is set. If some other bit is set then Y is not equal 922 // to INT_MIN. 923 ComputeMaskedBits(Y, Mask, KnownZero, KnownOne, TD, Depth); 924 if ((KnownOne & Mask) != 0) 925 return true; 926 } 927 928 // The sum of a non-negative number and a power of two is not zero. 929 if (XKnownNonNegative && isPowerOfTwo(Y, TD, /*OrZero*/false, Depth)) 930 return true; 931 if (YKnownNonNegative && isPowerOfTwo(X, TD, /*OrZero*/false, Depth)) 932 return true; 933 } 934 // X * Y. 935 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) { 936 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V); 937 // If X and Y are non-zero then so is X * Y as long as the multiplication 938 // does not overflow. 939 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) && 940 isKnownNonZero(X, TD, Depth) && isKnownNonZero(Y, TD, Depth)) 941 return true; 942 } 943 // (C ? X : Y) != 0 if X != 0 and Y != 0. 944 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) { 945 if (isKnownNonZero(SI->getTrueValue(), TD, Depth) && 946 isKnownNonZero(SI->getFalseValue(), TD, Depth)) 947 return true; 948 } 949 950 if (!BitWidth) return false; 951 APInt KnownZero(BitWidth, 0); 952 APInt KnownOne(BitWidth, 0); 953 ComputeMaskedBits(V, APInt::getAllOnesValue(BitWidth), KnownZero, KnownOne, 954 TD, Depth); 955 return KnownOne != 0; 956 } 957 958 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 959 /// this predicate to simplify operations downstream. Mask is known to be zero 960 /// for bits that V cannot have. 961 /// 962 /// This function is defined on values with integer type, values with pointer 963 /// type (but only if TD is non-null), and vectors of integers. In the case 964 /// where V is a vector, the mask, known zero, and known one values are the 965 /// same width as the vector element, and the bit is set only if it is true 966 /// for all of the elements in the vector. 967 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, 968 const TargetData *TD, unsigned Depth) { 969 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0); 970 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth); 971 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 972 return (KnownZero & Mask) == Mask; 973 } 974 975 976 977 /// ComputeNumSignBits - Return the number of times the sign bit of the 978 /// register is replicated into the other bits. We know that at least 1 bit 979 /// is always equal to the sign bit (itself), but other cases can give us 980 /// information. For example, immediately after an "ashr X, 2", we know that 981 /// the top 3 bits are all equal to each other, so we return 3. 982 /// 983 /// 'Op' must have a scalar integer type. 984 /// 985 unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD, 986 unsigned Depth) { 987 assert((TD || V->getType()->isIntOrIntVectorTy()) && 988 "ComputeNumSignBits requires a TargetData object to operate " 989 "on non-integer values!"); 990 Type *Ty = V->getType(); 991 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) : 992 Ty->getScalarSizeInBits(); 993 unsigned Tmp, Tmp2; 994 unsigned FirstAnswer = 1; 995 996 // Note that ConstantInt is handled by the general ComputeMaskedBits case 997 // below. 998 999 if (Depth == 6) 1000 return 1; // Limit search depth. 1001 1002 Operator *U = dyn_cast<Operator>(V); 1003 switch (Operator::getOpcode(V)) { 1004 default: break; 1005 case Instruction::SExt: 1006 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits(); 1007 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp; 1008 1009 case Instruction::AShr: { 1010 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1); 1011 // ashr X, C -> adds C sign bits. Vectors too. 1012 const APInt *ShAmt; 1013 if (match(U->getOperand(1), m_APInt(ShAmt))) { 1014 Tmp += ShAmt->getZExtValue(); 1015 if (Tmp > TyBits) Tmp = TyBits; 1016 } 1017 return Tmp; 1018 } 1019 case Instruction::Shl: { 1020 const APInt *ShAmt; 1021 if (match(U->getOperand(1), m_APInt(ShAmt))) { 1022 // shl destroys sign bits. 1023 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1); 1024 Tmp2 = ShAmt->getZExtValue(); 1025 if (Tmp2 >= TyBits || // Bad shift. 1026 Tmp2 >= Tmp) break; // Shifted all sign bits out. 1027 return Tmp - Tmp2; 1028 } 1029 break; 1030 } 1031 case Instruction::And: 1032 case Instruction::Or: 1033 case Instruction::Xor: // NOT is handled here. 1034 // Logical binary ops preserve the number of sign bits at the worst. 1035 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1); 1036 if (Tmp != 1) { 1037 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1); 1038 FirstAnswer = std::min(Tmp, Tmp2); 1039 // We computed what we know about the sign bits as our first 1040 // answer. Now proceed to the generic code that uses 1041 // ComputeMaskedBits, and pick whichever answer is better. 1042 } 1043 break; 1044 1045 case Instruction::Select: 1046 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1); 1047 if (Tmp == 1) return 1; // Early out. 1048 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1); 1049 return std::min(Tmp, Tmp2); 1050 1051 case Instruction::Add: 1052 // Add can have at most one carry bit. Thus we know that the output 1053 // is, at worst, one more bit than the inputs. 1054 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1); 1055 if (Tmp == 1) return 1; // Early out. 1056 1057 // Special case decrementing a value (ADD X, -1): 1058 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1))) 1059 if (CRHS->isAllOnesValue()) { 1060 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0); 1061 APInt Mask = APInt::getAllOnesValue(TyBits); 1062 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD, 1063 Depth+1); 1064 1065 // If the input is known to be 0 or 1, the output is 0/-1, which is all 1066 // sign bits set. 1067 if ((KnownZero | APInt(TyBits, 1)) == Mask) 1068 return TyBits; 1069 1070 // If we are subtracting one from a positive number, there is no carry 1071 // out of the result. 1072 if (KnownZero.isNegative()) 1073 return Tmp; 1074 } 1075 1076 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1); 1077 if (Tmp2 == 1) return 1; 1078 return std::min(Tmp, Tmp2)-1; 1079 1080 case Instruction::Sub: 1081 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1); 1082 if (Tmp2 == 1) return 1; 1083 1084 // Handle NEG. 1085 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0))) 1086 if (CLHS->isNullValue()) { 1087 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0); 1088 APInt Mask = APInt::getAllOnesValue(TyBits); 1089 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, 1090 TD, Depth+1); 1091 // If the input is known to be 0 or 1, the output is 0/-1, which is all 1092 // sign bits set. 1093 if ((KnownZero | APInt(TyBits, 1)) == Mask) 1094 return TyBits; 1095 1096 // If the input is known to be positive (the sign bit is known clear), 1097 // the output of the NEG has the same number of sign bits as the input. 1098 if (KnownZero.isNegative()) 1099 return Tmp2; 1100 1101 // Otherwise, we treat this like a SUB. 1102 } 1103 1104 // Sub can have at most one carry bit. Thus we know that the output 1105 // is, at worst, one more bit than the inputs. 1106 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1); 1107 if (Tmp == 1) return 1; // Early out. 1108 return std::min(Tmp, Tmp2)-1; 1109 1110 case Instruction::PHI: { 1111 PHINode *PN = cast<PHINode>(U); 1112 // Don't analyze large in-degree PHIs. 1113 if (PN->getNumIncomingValues() > 4) break; 1114 1115 // Take the minimum of all incoming values. This can't infinitely loop 1116 // because of our depth threshold. 1117 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1); 1118 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) { 1119 if (Tmp == 1) return Tmp; 1120 Tmp = std::min(Tmp, 1121 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1)); 1122 } 1123 return Tmp; 1124 } 1125 1126 case Instruction::Trunc: 1127 // FIXME: it's tricky to do anything useful for this, but it is an important 1128 // case for targets like X86. 1129 break; 1130 } 1131 1132 // Finally, if we can prove that the top bits of the result are 0's or 1's, 1133 // use this information. 1134 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0); 1135 APInt Mask = APInt::getAllOnesValue(TyBits); 1136 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth); 1137 1138 if (KnownZero.isNegative()) { // sign bit is 0 1139 Mask = KnownZero; 1140 } else if (KnownOne.isNegative()) { // sign bit is 1; 1141 Mask = KnownOne; 1142 } else { 1143 // Nothing known. 1144 return FirstAnswer; 1145 } 1146 1147 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine 1148 // the number of identical bits in the top of the input value. 1149 Mask = ~Mask; 1150 Mask <<= Mask.getBitWidth()-TyBits; 1151 // Return # leading zeros. We use 'min' here in case Val was zero before 1152 // shifting. We don't want to return '64' as for an i32 "0". 1153 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros())); 1154 } 1155 1156 /// ComputeMultiple - This function computes the integer multiple of Base that 1157 /// equals V. If successful, it returns true and returns the multiple in 1158 /// Multiple. If unsuccessful, it returns false. It looks 1159 /// through SExt instructions only if LookThroughSExt is true. 1160 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple, 1161 bool LookThroughSExt, unsigned Depth) { 1162 const unsigned MaxDepth = 6; 1163 1164 assert(V && "No Value?"); 1165 assert(Depth <= MaxDepth && "Limit Search Depth"); 1166 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!"); 1167 1168 Type *T = V->getType(); 1169 1170 ConstantInt *CI = dyn_cast<ConstantInt>(V); 1171 1172 if (Base == 0) 1173 return false; 1174 1175 if (Base == 1) { 1176 Multiple = V; 1177 return true; 1178 } 1179 1180 ConstantExpr *CO = dyn_cast<ConstantExpr>(V); 1181 Constant *BaseVal = ConstantInt::get(T, Base); 1182 if (CO && CO == BaseVal) { 1183 // Multiple is 1. 1184 Multiple = ConstantInt::get(T, 1); 1185 return true; 1186 } 1187 1188 if (CI && CI->getZExtValue() % Base == 0) { 1189 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base); 1190 return true; 1191 } 1192 1193 if (Depth == MaxDepth) return false; // Limit search depth. 1194 1195 Operator *I = dyn_cast<Operator>(V); 1196 if (!I) return false; 1197 1198 switch (I->getOpcode()) { 1199 default: break; 1200 case Instruction::SExt: 1201 if (!LookThroughSExt) return false; 1202 // otherwise fall through to ZExt 1203 case Instruction::ZExt: 1204 return ComputeMultiple(I->getOperand(0), Base, Multiple, 1205 LookThroughSExt, Depth+1); 1206 case Instruction::Shl: 1207 case Instruction::Mul: { 1208 Value *Op0 = I->getOperand(0); 1209 Value *Op1 = I->getOperand(1); 1210 1211 if (I->getOpcode() == Instruction::Shl) { 1212 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1); 1213 if (!Op1CI) return false; 1214 // Turn Op0 << Op1 into Op0 * 2^Op1 1215 APInt Op1Int = Op1CI->getValue(); 1216 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1); 1217 APInt API(Op1Int.getBitWidth(), 0); 1218 API.setBit(BitToSet); 1219 Op1 = ConstantInt::get(V->getContext(), API); 1220 } 1221 1222 Value *Mul0 = NULL; 1223 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) { 1224 if (Constant *Op1C = dyn_cast<Constant>(Op1)) 1225 if (Constant *MulC = dyn_cast<Constant>(Mul0)) { 1226 if (Op1C->getType()->getPrimitiveSizeInBits() < 1227 MulC->getType()->getPrimitiveSizeInBits()) 1228 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType()); 1229 if (Op1C->getType()->getPrimitiveSizeInBits() > 1230 MulC->getType()->getPrimitiveSizeInBits()) 1231 MulC = ConstantExpr::getZExt(MulC, Op1C->getType()); 1232 1233 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1) 1234 Multiple = ConstantExpr::getMul(MulC, Op1C); 1235 return true; 1236 } 1237 1238 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0)) 1239 if (Mul0CI->getValue() == 1) { 1240 // V == Base * Op1, so return Op1 1241 Multiple = Op1; 1242 return true; 1243 } 1244 } 1245 1246 Value *Mul1 = NULL; 1247 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) { 1248 if (Constant *Op0C = dyn_cast<Constant>(Op0)) 1249 if (Constant *MulC = dyn_cast<Constant>(Mul1)) { 1250 if (Op0C->getType()->getPrimitiveSizeInBits() < 1251 MulC->getType()->getPrimitiveSizeInBits()) 1252 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType()); 1253 if (Op0C->getType()->getPrimitiveSizeInBits() > 1254 MulC->getType()->getPrimitiveSizeInBits()) 1255 MulC = ConstantExpr::getZExt(MulC, Op0C->getType()); 1256 1257 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0) 1258 Multiple = ConstantExpr::getMul(MulC, Op0C); 1259 return true; 1260 } 1261 1262 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1)) 1263 if (Mul1CI->getValue() == 1) { 1264 // V == Base * Op0, so return Op0 1265 Multiple = Op0; 1266 return true; 1267 } 1268 } 1269 } 1270 } 1271 1272 // We could not determine if V is a multiple of Base. 1273 return false; 1274 } 1275 1276 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 1277 /// value is never equal to -0.0. 1278 /// 1279 /// NOTE: this function will need to be revisited when we support non-default 1280 /// rounding modes! 1281 /// 1282 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) { 1283 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) 1284 return !CFP->getValueAPF().isNegZero(); 1285 1286 if (Depth == 6) 1287 return 1; // Limit search depth. 1288 1289 const Operator *I = dyn_cast<Operator>(V); 1290 if (I == 0) return false; 1291 1292 // (add x, 0.0) is guaranteed to return +0.0, not -0.0. 1293 if (I->getOpcode() == Instruction::FAdd && 1294 isa<ConstantFP>(I->getOperand(1)) && 1295 cast<ConstantFP>(I->getOperand(1))->isNullValue()) 1296 return true; 1297 1298 // sitofp and uitofp turn into +0.0 for zero. 1299 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I)) 1300 return true; 1301 1302 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 1303 // sqrt(-0.0) = -0.0, no other negative results are possible. 1304 if (II->getIntrinsicID() == Intrinsic::sqrt) 1305 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1); 1306 1307 if (const CallInst *CI = dyn_cast<CallInst>(I)) 1308 if (const Function *F = CI->getCalledFunction()) { 1309 if (F->isDeclaration()) { 1310 // abs(x) != -0.0 1311 if (F->getName() == "abs") return true; 1312 // fabs[lf](x) != -0.0 1313 if (F->getName() == "fabs") return true; 1314 if (F->getName() == "fabsf") return true; 1315 if (F->getName() == "fabsl") return true; 1316 if (F->getName() == "sqrt" || F->getName() == "sqrtf" || 1317 F->getName() == "sqrtl") 1318 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1); 1319 } 1320 } 1321 1322 return false; 1323 } 1324 1325 /// isBytewiseValue - If the specified value can be set by repeating the same 1326 /// byte in memory, return the i8 value that it is represented with. This is 1327 /// true for all i8 values obviously, but is also true for i32 0, i32 -1, 1328 /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated 1329 /// byte store (e.g. i16 0x1234), return null. 1330 Value *llvm::isBytewiseValue(Value *V) { 1331 // All byte-wide stores are splatable, even of arbitrary variables. 1332 if (V->getType()->isIntegerTy(8)) return V; 1333 1334 // Handle 'null' ConstantArrayZero etc. 1335 if (Constant *C = dyn_cast<Constant>(V)) 1336 if (C->isNullValue()) 1337 return Constant::getNullValue(Type::getInt8Ty(V->getContext())); 1338 1339 // Constant float and double values can be handled as integer values if the 1340 // corresponding integer value is "byteable". An important case is 0.0. 1341 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) { 1342 if (CFP->getType()->isFloatTy()) 1343 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext())); 1344 if (CFP->getType()->isDoubleTy()) 1345 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext())); 1346 // Don't handle long double formats, which have strange constraints. 1347 } 1348 1349 // We can handle constant integers that are power of two in size and a 1350 // multiple of 8 bits. 1351 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 1352 unsigned Width = CI->getBitWidth(); 1353 if (isPowerOf2_32(Width) && Width > 8) { 1354 // We can handle this value if the recursive binary decomposition is the 1355 // same at all levels. 1356 APInt Val = CI->getValue(); 1357 APInt Val2; 1358 while (Val.getBitWidth() != 8) { 1359 unsigned NextWidth = Val.getBitWidth()/2; 1360 Val2 = Val.lshr(NextWidth); 1361 Val2 = Val2.trunc(Val.getBitWidth()/2); 1362 Val = Val.trunc(Val.getBitWidth()/2); 1363 1364 // If the top/bottom halves aren't the same, reject it. 1365 if (Val != Val2) 1366 return 0; 1367 } 1368 return ConstantInt::get(V->getContext(), Val); 1369 } 1370 } 1371 1372 // A ConstantArray is splatable if all its members are equal and also 1373 // splatable. 1374 if (ConstantArray *CA = dyn_cast<ConstantArray>(V)) { 1375 if (CA->getNumOperands() == 0) 1376 return 0; 1377 1378 Value *Val = isBytewiseValue(CA->getOperand(0)); 1379 if (!Val) 1380 return 0; 1381 1382 for (unsigned I = 1, E = CA->getNumOperands(); I != E; ++I) 1383 if (CA->getOperand(I-1) != CA->getOperand(I)) 1384 return 0; 1385 1386 return Val; 1387 } 1388 1389 // FIXME: Vector types (e.g., <4 x i32> <i32 -1, i32 -1, i32 -1, i32 -1>). 1390 1391 // Conceptually, we could handle things like: 1392 // %a = zext i8 %X to i16 1393 // %b = shl i16 %a, 8 1394 // %c = or i16 %a, %b 1395 // but until there is an example that actually needs this, it doesn't seem 1396 // worth worrying about. 1397 return 0; 1398 } 1399 1400 1401 // This is the recursive version of BuildSubAggregate. It takes a few different 1402 // arguments. Idxs is the index within the nested struct From that we are 1403 // looking at now (which is of type IndexedType). IdxSkip is the number of 1404 // indices from Idxs that should be left out when inserting into the resulting 1405 // struct. To is the result struct built so far, new insertvalue instructions 1406 // build on that. 1407 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType, 1408 SmallVector<unsigned, 10> &Idxs, 1409 unsigned IdxSkip, 1410 Instruction *InsertBefore) { 1411 llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType); 1412 if (STy) { 1413 // Save the original To argument so we can modify it 1414 Value *OrigTo = To; 1415 // General case, the type indexed by Idxs is a struct 1416 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1417 // Process each struct element recursively 1418 Idxs.push_back(i); 1419 Value *PrevTo = To; 1420 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip, 1421 InsertBefore); 1422 Idxs.pop_back(); 1423 if (!To) { 1424 // Couldn't find any inserted value for this index? Cleanup 1425 while (PrevTo != OrigTo) { 1426 InsertValueInst* Del = cast<InsertValueInst>(PrevTo); 1427 PrevTo = Del->getAggregateOperand(); 1428 Del->eraseFromParent(); 1429 } 1430 // Stop processing elements 1431 break; 1432 } 1433 } 1434 // If we successfully found a value for each of our subaggregates 1435 if (To) 1436 return To; 1437 } 1438 // Base case, the type indexed by SourceIdxs is not a struct, or not all of 1439 // the struct's elements had a value that was inserted directly. In the latter 1440 // case, perhaps we can't determine each of the subelements individually, but 1441 // we might be able to find the complete struct somewhere. 1442 1443 // Find the value that is at that particular spot 1444 Value *V = FindInsertedValue(From, Idxs); 1445 1446 if (!V) 1447 return NULL; 1448 1449 // Insert the value in the new (sub) aggregrate 1450 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip), 1451 "tmp", InsertBefore); 1452 } 1453 1454 // This helper takes a nested struct and extracts a part of it (which is again a 1455 // struct) into a new value. For example, given the struct: 1456 // { a, { b, { c, d }, e } } 1457 // and the indices "1, 1" this returns 1458 // { c, d }. 1459 // 1460 // It does this by inserting an insertvalue for each element in the resulting 1461 // struct, as opposed to just inserting a single struct. This will only work if 1462 // each of the elements of the substruct are known (ie, inserted into From by an 1463 // insertvalue instruction somewhere). 1464 // 1465 // All inserted insertvalue instructions are inserted before InsertBefore 1466 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range, 1467 Instruction *InsertBefore) { 1468 assert(InsertBefore && "Must have someplace to insert!"); 1469 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(), 1470 idx_range); 1471 Value *To = UndefValue::get(IndexedType); 1472 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end()); 1473 unsigned IdxSkip = Idxs.size(); 1474 1475 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore); 1476 } 1477 1478 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if 1479 /// the scalar value indexed is already around as a register, for example if it 1480 /// were inserted directly into the aggregrate. 1481 /// 1482 /// If InsertBefore is not null, this function will duplicate (modified) 1483 /// insertvalues when a part of a nested struct is extracted. 1484 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range, 1485 Instruction *InsertBefore) { 1486 // Nothing to index? Just return V then (this is useful at the end of our 1487 // recursion). 1488 if (idx_range.empty()) 1489 return V; 1490 // We have indices, so V should have an indexable type. 1491 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) && 1492 "Not looking at a struct or array?"); 1493 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) && 1494 "Invalid indices for type?"); 1495 1496 if (Constant *C = dyn_cast<Constant>(V)) { 1497 C = C->getAggregateElement(idx_range[0]); 1498 if (C == 0) return 0; 1499 return FindInsertedValue(C, idx_range.slice(1), InsertBefore); 1500 } 1501 1502 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) { 1503 // Loop the indices for the insertvalue instruction in parallel with the 1504 // requested indices 1505 const unsigned *req_idx = idx_range.begin(); 1506 for (const unsigned *i = I->idx_begin(), *e = I->idx_end(); 1507 i != e; ++i, ++req_idx) { 1508 if (req_idx == idx_range.end()) { 1509 // We can't handle this without inserting insertvalues 1510 if (!InsertBefore) 1511 return 0; 1512 1513 // The requested index identifies a part of a nested aggregate. Handle 1514 // this specially. For example, 1515 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0 1516 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1 1517 // %C = extractvalue {i32, { i32, i32 } } %B, 1 1518 // This can be changed into 1519 // %A = insertvalue {i32, i32 } undef, i32 10, 0 1520 // %C = insertvalue {i32, i32 } %A, i32 11, 1 1521 // which allows the unused 0,0 element from the nested struct to be 1522 // removed. 1523 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx), 1524 InsertBefore); 1525 } 1526 1527 // This insert value inserts something else than what we are looking for. 1528 // See if the (aggregrate) value inserted into has the value we are 1529 // looking for, then. 1530 if (*req_idx != *i) 1531 return FindInsertedValue(I->getAggregateOperand(), idx_range, 1532 InsertBefore); 1533 } 1534 // If we end up here, the indices of the insertvalue match with those 1535 // requested (though possibly only partially). Now we recursively look at 1536 // the inserted value, passing any remaining indices. 1537 return FindInsertedValue(I->getInsertedValueOperand(), 1538 makeArrayRef(req_idx, idx_range.end()), 1539 InsertBefore); 1540 } 1541 1542 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) { 1543 // If we're extracting a value from an aggregrate that was extracted from 1544 // something else, we can extract from that something else directly instead. 1545 // However, we will need to chain I's indices with the requested indices. 1546 1547 // Calculate the number of indices required 1548 unsigned size = I->getNumIndices() + idx_range.size(); 1549 // Allocate some space to put the new indices in 1550 SmallVector<unsigned, 5> Idxs; 1551 Idxs.reserve(size); 1552 // Add indices from the extract value instruction 1553 Idxs.append(I->idx_begin(), I->idx_end()); 1554 1555 // Add requested indices 1556 Idxs.append(idx_range.begin(), idx_range.end()); 1557 1558 assert(Idxs.size() == size 1559 && "Number of indices added not correct?"); 1560 1561 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore); 1562 } 1563 // Otherwise, we don't know (such as, extracting from a function return value 1564 // or load instruction) 1565 return 0; 1566 } 1567 1568 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if 1569 /// it can be expressed as a base pointer plus a constant offset. Return the 1570 /// base and offset to the caller. 1571 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, 1572 const TargetData &TD) { 1573 Operator *PtrOp = dyn_cast<Operator>(Ptr); 1574 if (PtrOp == 0 || Ptr->getType()->isVectorTy()) 1575 return Ptr; 1576 1577 // Just look through bitcasts. 1578 if (PtrOp->getOpcode() == Instruction::BitCast) 1579 return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD); 1580 1581 // If this is a GEP with constant indices, we can look through it. 1582 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp); 1583 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr; 1584 1585 gep_type_iterator GTI = gep_type_begin(GEP); 1586 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E; 1587 ++I, ++GTI) { 1588 ConstantInt *OpC = cast<ConstantInt>(*I); 1589 if (OpC->isZero()) continue; 1590 1591 // Handle a struct and array indices which add their offset to the pointer. 1592 if (StructType *STy = dyn_cast<StructType>(*GTI)) { 1593 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue()); 1594 } else { 1595 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()); 1596 Offset += OpC->getSExtValue()*Size; 1597 } 1598 } 1599 1600 // Re-sign extend from the pointer size if needed to get overflow edge cases 1601 // right. 1602 unsigned PtrSize = TD.getPointerSizeInBits(); 1603 if (PtrSize < 64) 1604 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize); 1605 1606 return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD); 1607 } 1608 1609 1610 /// GetConstantStringInfo - This function computes the length of a 1611 /// null-terminated C string pointed to by V. If successful, it returns true 1612 /// and returns the string in Str. If unsuccessful, it returns false. 1613 bool llvm::GetConstantStringInfo(const Value *V, std::string &Str, 1614 uint64_t Offset, bool StopAtNul) { 1615 // If V is NULL then return false; 1616 if (V == NULL) return false; 1617 1618 // Look through bitcast instructions. 1619 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V)) 1620 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul); 1621 1622 // If the value is not a GEP instruction nor a constant expression with a 1623 // GEP instruction, then return false because ConstantArray can't occur 1624 // any other way. 1625 const User *GEP = 0; 1626 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) { 1627 GEP = GEPI; 1628 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 1629 if (CE->getOpcode() == Instruction::BitCast) 1630 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul); 1631 if (CE->getOpcode() != Instruction::GetElementPtr) 1632 return false; 1633 GEP = CE; 1634 } 1635 1636 if (GEP) { 1637 // Make sure the GEP has exactly three arguments. 1638 if (GEP->getNumOperands() != 3) 1639 return false; 1640 1641 // Make sure the index-ee is a pointer to array of i8. 1642 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType()); 1643 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType()); 1644 if (AT == 0 || !AT->getElementType()->isIntegerTy(8)) 1645 return false; 1646 1647 // Check to make sure that the first operand of the GEP is an integer and 1648 // has value 0 so that we are sure we're indexing into the initializer. 1649 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1)); 1650 if (FirstIdx == 0 || !FirstIdx->isZero()) 1651 return false; 1652 1653 // If the second index isn't a ConstantInt, then this is a variable index 1654 // into the array. If this occurs, we can't say anything meaningful about 1655 // the string. 1656 uint64_t StartIdx = 0; 1657 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2))) 1658 StartIdx = CI->getZExtValue(); 1659 else 1660 return false; 1661 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset, 1662 StopAtNul); 1663 } 1664 1665 // The GEP instruction, constant or instruction, must reference a global 1666 // variable that is a constant and is initialized. The referenced constant 1667 // initializer is the array that we'll use for optimization. 1668 const GlobalVariable* GV = dyn_cast<GlobalVariable>(V); 1669 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer()) 1670 return false; 1671 const Constant *GlobalInit = GV->getInitializer(); 1672 1673 // Handle the all-zeros case 1674 if (GlobalInit->isNullValue()) { 1675 // This is a degenerate case. The initializer is constant zero so the 1676 // length of the string must be zero. 1677 Str.clear(); 1678 return true; 1679 } 1680 1681 // Must be a Constant Array 1682 const ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit); 1683 if (Array == 0 || !Array->getType()->getElementType()->isIntegerTy(8)) 1684 return false; 1685 1686 // Get the number of elements in the array 1687 uint64_t NumElts = Array->getType()->getNumElements(); 1688 1689 if (Offset > NumElts) 1690 return false; 1691 1692 // Traverse the constant array from 'Offset' which is the place the GEP refers 1693 // to in the array. 1694 Str.reserve(NumElts-Offset); 1695 for (unsigned i = Offset; i != NumElts; ++i) { 1696 const Constant *Elt = Array->getOperand(i); 1697 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt); 1698 if (!CI) // This array isn't suitable, non-int initializer. 1699 return false; 1700 if (StopAtNul && CI->isZero()) 1701 return true; // we found end of string, success! 1702 Str += (char)CI->getZExtValue(); 1703 } 1704 1705 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy. 1706 return true; 1707 } 1708 1709 // These next two are very similar to the above, but also look through PHI 1710 // nodes. 1711 // TODO: See if we can integrate these two together. 1712 1713 /// GetStringLengthH - If we can compute the length of the string pointed to by 1714 /// the specified pointer, return 'len+1'. If we can't, return 0. 1715 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) { 1716 // Look through noop bitcast instructions. 1717 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) 1718 return GetStringLengthH(BCI->getOperand(0), PHIs); 1719 1720 // If this is a PHI node, there are two cases: either we have already seen it 1721 // or we haven't. 1722 if (PHINode *PN = dyn_cast<PHINode>(V)) { 1723 if (!PHIs.insert(PN)) 1724 return ~0ULL; // already in the set. 1725 1726 // If it was new, see if all the input strings are the same length. 1727 uint64_t LenSoFar = ~0ULL; 1728 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1729 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs); 1730 if (Len == 0) return 0; // Unknown length -> unknown. 1731 1732 if (Len == ~0ULL) continue; 1733 1734 if (Len != LenSoFar && LenSoFar != ~0ULL) 1735 return 0; // Disagree -> unknown. 1736 LenSoFar = Len; 1737 } 1738 1739 // Success, all agree. 1740 return LenSoFar; 1741 } 1742 1743 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y) 1744 if (SelectInst *SI = dyn_cast<SelectInst>(V)) { 1745 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs); 1746 if (Len1 == 0) return 0; 1747 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs); 1748 if (Len2 == 0) return 0; 1749 if (Len1 == ~0ULL) return Len2; 1750 if (Len2 == ~0ULL) return Len1; 1751 if (Len1 != Len2) return 0; 1752 return Len1; 1753 } 1754 1755 // As a special-case, "@string = constant i8 0" is also a string with zero 1756 // length, not wrapped in a bitcast or GEP. 1757 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) { 1758 if (GV->isConstant() && GV->hasDefinitiveInitializer()) 1759 if (GV->getInitializer()->isNullValue()) return 1; 1760 return 0; 1761 } 1762 1763 // If the value is not a GEP instruction nor a constant expression with a 1764 // GEP instruction, then return unknown. 1765 User *GEP = 0; 1766 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) { 1767 GEP = GEPI; 1768 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 1769 if (CE->getOpcode() != Instruction::GetElementPtr) 1770 return 0; 1771 GEP = CE; 1772 } else { 1773 return 0; 1774 } 1775 1776 // Make sure the GEP has exactly three arguments. 1777 if (GEP->getNumOperands() != 3) 1778 return 0; 1779 1780 // Check to make sure that the first operand of the GEP is an integer and 1781 // has value 0 so that we are sure we're indexing into the initializer. 1782 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) { 1783 if (!Idx->isZero()) 1784 return 0; 1785 } else 1786 return 0; 1787 1788 // If the second index isn't a ConstantInt, then this is a variable index 1789 // into the array. If this occurs, we can't say anything meaningful about 1790 // the string. 1791 uint64_t StartIdx = 0; 1792 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2))) 1793 StartIdx = CI->getZExtValue(); 1794 else 1795 return 0; 1796 1797 // The GEP instruction, constant or instruction, must reference a global 1798 // variable that is a constant and is initialized. The referenced constant 1799 // initializer is the array that we'll use for optimization. 1800 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 1801 if (!GV || !GV->isConstant() || !GV->hasInitializer() || 1802 GV->mayBeOverridden()) 1803 return 0; 1804 Constant *GlobalInit = GV->getInitializer(); 1805 1806 // Handle the ConstantAggregateZero case, which is a degenerate case. The 1807 // initializer is constant zero so the length of the string must be zero. 1808 if (isa<ConstantAggregateZero>(GlobalInit)) 1809 return 1; // Len = 0 offset by 1. 1810 1811 // Must be a Constant Array 1812 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit); 1813 if (!Array || !Array->getType()->getElementType()->isIntegerTy(8)) 1814 return false; 1815 1816 // Get the number of elements in the array 1817 uint64_t NumElts = Array->getType()->getNumElements(); 1818 1819 // Traverse the constant array from StartIdx (derived above) which is 1820 // the place the GEP refers to in the array. 1821 for (unsigned i = StartIdx; i != NumElts; ++i) { 1822 Constant *Elt = Array->getOperand(i); 1823 ConstantInt *CI = dyn_cast<ConstantInt>(Elt); 1824 if (!CI) // This array isn't suitable, non-int initializer. 1825 return 0; 1826 if (CI->isZero()) 1827 return i-StartIdx+1; // We found end of string, success! 1828 } 1829 1830 return 0; // The array isn't null terminated, conservatively return 'unknown'. 1831 } 1832 1833 /// GetStringLength - If we can compute the length of the string pointed to by 1834 /// the specified pointer, return 'len+1'. If we can't, return 0. 1835 uint64_t llvm::GetStringLength(Value *V) { 1836 if (!V->getType()->isPointerTy()) return 0; 1837 1838 SmallPtrSet<PHINode*, 32> PHIs; 1839 uint64_t Len = GetStringLengthH(V, PHIs); 1840 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return 1841 // an empty string as a length. 1842 return Len == ~0ULL ? 1 : Len; 1843 } 1844 1845 Value * 1846 llvm::GetUnderlyingObject(Value *V, const TargetData *TD, unsigned MaxLookup) { 1847 if (!V->getType()->isPointerTy()) 1848 return V; 1849 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) { 1850 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 1851 V = GEP->getPointerOperand(); 1852 } else if (Operator::getOpcode(V) == Instruction::BitCast) { 1853 V = cast<Operator>(V)->getOperand(0); 1854 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 1855 if (GA->mayBeOverridden()) 1856 return V; 1857 V = GA->getAliasee(); 1858 } else { 1859 // See if InstructionSimplify knows any relevant tricks. 1860 if (Instruction *I = dyn_cast<Instruction>(V)) 1861 // TODO: Acquire a DominatorTree and use it. 1862 if (Value *Simplified = SimplifyInstruction(I, TD, 0)) { 1863 V = Simplified; 1864 continue; 1865 } 1866 1867 return V; 1868 } 1869 assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 1870 } 1871 return V; 1872 } 1873 1874 /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer 1875 /// are lifetime markers. 1876 /// 1877 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) { 1878 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end(); 1879 UI != UE; ++UI) { 1880 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI); 1881 if (!II) return false; 1882 1883 if (II->getIntrinsicID() != Intrinsic::lifetime_start && 1884 II->getIntrinsicID() != Intrinsic::lifetime_end) 1885 return false; 1886 } 1887 return true; 1888 } 1889 1890 bool llvm::isSafeToSpeculativelyExecute(const Value *V, 1891 const TargetData *TD) { 1892 const Operator *Inst = dyn_cast<Operator>(V); 1893 if (!Inst) 1894 return false; 1895 1896 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) 1897 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i))) 1898 if (C->canTrap()) 1899 return false; 1900 1901 switch (Inst->getOpcode()) { 1902 default: 1903 return true; 1904 case Instruction::UDiv: 1905 case Instruction::URem: 1906 // x / y is undefined if y == 0, but calcuations like x / 3 are safe. 1907 return isKnownNonZero(Inst->getOperand(1), TD); 1908 case Instruction::SDiv: 1909 case Instruction::SRem: { 1910 Value *Op = Inst->getOperand(1); 1911 // x / y is undefined if y == 0 1912 if (!isKnownNonZero(Op, TD)) 1913 return false; 1914 // x / y might be undefined if y == -1 1915 unsigned BitWidth = getBitWidth(Op->getType(), TD); 1916 if (BitWidth == 0) 1917 return false; 1918 APInt KnownZero(BitWidth, 0); 1919 APInt KnownOne(BitWidth, 0); 1920 ComputeMaskedBits(Op, APInt::getAllOnesValue(BitWidth), 1921 KnownZero, KnownOne, TD); 1922 return !!KnownZero; 1923 } 1924 case Instruction::Load: { 1925 const LoadInst *LI = cast<LoadInst>(Inst); 1926 if (!LI->isUnordered()) 1927 return false; 1928 return LI->getPointerOperand()->isDereferenceablePointer(); 1929 } 1930 case Instruction::Call: { 1931 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 1932 switch (II->getIntrinsicID()) { 1933 case Intrinsic::bswap: 1934 case Intrinsic::ctlz: 1935 case Intrinsic::ctpop: 1936 case Intrinsic::cttz: 1937 case Intrinsic::objectsize: 1938 case Intrinsic::sadd_with_overflow: 1939 case Intrinsic::smul_with_overflow: 1940 case Intrinsic::ssub_with_overflow: 1941 case Intrinsic::uadd_with_overflow: 1942 case Intrinsic::umul_with_overflow: 1943 case Intrinsic::usub_with_overflow: 1944 return true; 1945 // TODO: some fp intrinsics are marked as having the same error handling 1946 // as libm. They're safe to speculate when they won't error. 1947 // TODO: are convert_{from,to}_fp16 safe? 1948 // TODO: can we list target-specific intrinsics here? 1949 default: break; 1950 } 1951 } 1952 return false; // The called function could have undefined behavior or 1953 // side-effects, even if marked readnone nounwind. 1954 } 1955 case Instruction::VAArg: 1956 case Instruction::Alloca: 1957 case Instruction::Invoke: 1958 case Instruction::PHI: 1959 case Instruction::Store: 1960 case Instruction::Ret: 1961 case Instruction::Br: 1962 case Instruction::IndirectBr: 1963 case Instruction::Switch: 1964 case Instruction::Unwind: 1965 case Instruction::Unreachable: 1966 case Instruction::Fence: 1967 case Instruction::LandingPad: 1968 case Instruction::AtomicRMW: 1969 case Instruction::AtomicCmpXchg: 1970 case Instruction::Resume: 1971 return false; // Misc instructions which have effects 1972 } 1973 } 1974