1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===// 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 implements folding of constants for LLVM. This implements the 11 // (internal) ConstantFold.h interface, which is used by the 12 // ConstantExpr::get* methods to automatically fold constants when possible. 13 // 14 // The current constant folding implementation is implemented in two pieces: the 15 // pieces that don't need DataLayout, and the pieces that do. This is to avoid 16 // a dependence in IR on Target. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "ConstantFold.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/DerivedTypes.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/GetElementPtrTypeIterator.h" 26 #include "llvm/IR/GlobalAlias.h" 27 #include "llvm/IR/GlobalVariable.h" 28 #include "llvm/IR/Instructions.h" 29 #include "llvm/IR/Operator.h" 30 #include "llvm/Support/Compiler.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/ManagedStatic.h" 33 #include "llvm/Support/MathExtras.h" 34 #include <limits> 35 using namespace llvm; 36 37 //===----------------------------------------------------------------------===// 38 // ConstantFold*Instruction Implementations 39 //===----------------------------------------------------------------------===// 40 41 /// BitCastConstantVector - Convert the specified vector Constant node to the 42 /// specified vector type. At this point, we know that the elements of the 43 /// input vector constant are all simple integer or FP values. 44 static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) { 45 46 if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy); 47 if (CV->isNullValue()) return Constant::getNullValue(DstTy); 48 49 // If this cast changes element count then we can't handle it here: 50 // doing so requires endianness information. This should be handled by 51 // Analysis/ConstantFolding.cpp 52 unsigned NumElts = DstTy->getNumElements(); 53 if (NumElts != CV->getType()->getVectorNumElements()) 54 return nullptr; 55 56 Type *DstEltTy = DstTy->getElementType(); 57 58 SmallVector<Constant*, 16> Result; 59 Type *Ty = IntegerType::get(CV->getContext(), 32); 60 for (unsigned i = 0; i != NumElts; ++i) { 61 Constant *C = 62 ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i)); 63 C = ConstantExpr::getBitCast(C, DstEltTy); 64 Result.push_back(C); 65 } 66 67 return ConstantVector::get(Result); 68 } 69 70 /// This function determines which opcode to use to fold two constant cast 71 /// expressions together. It uses CastInst::isEliminableCastPair to determine 72 /// the opcode. Consequently its just a wrapper around that function. 73 /// @brief Determine if it is valid to fold a cast of a cast 74 static unsigned 75 foldConstantCastPair( 76 unsigned opc, ///< opcode of the second cast constant expression 77 ConstantExpr *Op, ///< the first cast constant expression 78 Type *DstTy ///< destination type of the first cast 79 ) { 80 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!"); 81 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type"); 82 assert(CastInst::isCast(opc) && "Invalid cast opcode"); 83 84 // The the types and opcodes for the two Cast constant expressions 85 Type *SrcTy = Op->getOperand(0)->getType(); 86 Type *MidTy = Op->getType(); 87 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode()); 88 Instruction::CastOps secondOp = Instruction::CastOps(opc); 89 90 // Assume that pointers are never more than 64 bits wide, and only use this 91 // for the middle type. Otherwise we could end up folding away illegal 92 // bitcasts between address spaces with different sizes. 93 IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext()); 94 95 // Let CastInst::isEliminableCastPair do the heavy lifting. 96 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy, 97 nullptr, FakeIntPtrTy, nullptr); 98 } 99 100 static Constant *FoldBitCast(Constant *V, Type *DestTy) { 101 Type *SrcTy = V->getType(); 102 if (SrcTy == DestTy) 103 return V; // no-op cast 104 105 // Check to see if we are casting a pointer to an aggregate to a pointer to 106 // the first element. If so, return the appropriate GEP instruction. 107 if (PointerType *PTy = dyn_cast<PointerType>(V->getType())) 108 if (PointerType *DPTy = dyn_cast<PointerType>(DestTy)) 109 if (PTy->getAddressSpace() == DPTy->getAddressSpace() 110 && DPTy->getElementType()->isSized()) { 111 SmallVector<Value*, 8> IdxList; 112 Value *Zero = 113 Constant::getNullValue(Type::getInt32Ty(DPTy->getContext())); 114 IdxList.push_back(Zero); 115 Type *ElTy = PTy->getElementType(); 116 while (ElTy != DPTy->getElementType()) { 117 if (StructType *STy = dyn_cast<StructType>(ElTy)) { 118 if (STy->getNumElements() == 0) break; 119 ElTy = STy->getElementType(0); 120 IdxList.push_back(Zero); 121 } else if (SequentialType *STy = 122 dyn_cast<SequentialType>(ElTy)) { 123 if (ElTy->isPointerTy()) break; // Can't index into pointers! 124 ElTy = STy->getElementType(); 125 IdxList.push_back(Zero); 126 } else { 127 break; 128 } 129 } 130 131 if (ElTy == DPTy->getElementType()) 132 // This GEP is inbounds because all indices are zero. 133 return ConstantExpr::getInBoundsGetElementPtr(V, IdxList); 134 } 135 136 // Handle casts from one vector constant to another. We know that the src 137 // and dest type have the same size (otherwise its an illegal cast). 138 if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) { 139 if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) { 140 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() && 141 "Not cast between same sized vectors!"); 142 SrcTy = nullptr; 143 // First, check for null. Undef is already handled. 144 if (isa<ConstantAggregateZero>(V)) 145 return Constant::getNullValue(DestTy); 146 147 // Handle ConstantVector and ConstantAggregateVector. 148 return BitCastConstantVector(V, DestPTy); 149 } 150 151 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts 152 // This allows for other simplifications (although some of them 153 // can only be handled by Analysis/ConstantFolding.cpp). 154 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) 155 return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy); 156 } 157 158 // Finally, implement bitcast folding now. The code below doesn't handle 159 // bitcast right. 160 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast. 161 return ConstantPointerNull::get(cast<PointerType>(DestTy)); 162 163 // Handle integral constant input. 164 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 165 if (DestTy->isIntegerTy()) 166 // Integral -> Integral. This is a no-op because the bit widths must 167 // be the same. Consequently, we just fold to V. 168 return V; 169 170 if (DestTy->isFloatingPointTy()) 171 return ConstantFP::get(DestTy->getContext(), 172 APFloat(DestTy->getFltSemantics(), 173 CI->getValue())); 174 175 // Otherwise, can't fold this (vector?) 176 return nullptr; 177 } 178 179 // Handle ConstantFP input: FP -> Integral. 180 if (ConstantFP *FP = dyn_cast<ConstantFP>(V)) 181 return ConstantInt::get(FP->getContext(), 182 FP->getValueAPF().bitcastToAPInt()); 183 184 return nullptr; 185 } 186 187 188 /// ExtractConstantBytes - V is an integer constant which only has a subset of 189 /// its bytes used. The bytes used are indicated by ByteStart (which is the 190 /// first byte used, counting from the least significant byte) and ByteSize, 191 /// which is the number of bytes used. 192 /// 193 /// This function analyzes the specified constant to see if the specified byte 194 /// range can be returned as a simplified constant. If so, the constant is 195 /// returned, otherwise null is returned. 196 /// 197 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart, 198 unsigned ByteSize) { 199 assert(C->getType()->isIntegerTy() && 200 (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 && 201 "Non-byte sized integer input"); 202 unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8; 203 assert(ByteSize && "Must be accessing some piece"); 204 assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input"); 205 assert(ByteSize != CSize && "Should not extract everything"); 206 207 // Constant Integers are simple. 208 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) { 209 APInt V = CI->getValue(); 210 if (ByteStart) 211 V = V.lshr(ByteStart*8); 212 V = V.trunc(ByteSize*8); 213 return ConstantInt::get(CI->getContext(), V); 214 } 215 216 // In the input is a constant expr, we might be able to recursively simplify. 217 // If not, we definitely can't do anything. 218 ConstantExpr *CE = dyn_cast<ConstantExpr>(C); 219 if (!CE) return nullptr; 220 221 switch (CE->getOpcode()) { 222 default: return nullptr; 223 case Instruction::Or: { 224 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize); 225 if (!RHS) 226 return nullptr; 227 228 // X | -1 -> -1. 229 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) 230 if (RHSC->isAllOnesValue()) 231 return RHSC; 232 233 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize); 234 if (!LHS) 235 return nullptr; 236 return ConstantExpr::getOr(LHS, RHS); 237 } 238 case Instruction::And: { 239 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize); 240 if (!RHS) 241 return nullptr; 242 243 // X & 0 -> 0. 244 if (RHS->isNullValue()) 245 return RHS; 246 247 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize); 248 if (!LHS) 249 return nullptr; 250 return ConstantExpr::getAnd(LHS, RHS); 251 } 252 case Instruction::LShr: { 253 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1)); 254 if (!Amt) 255 return nullptr; 256 unsigned ShAmt = Amt->getZExtValue(); 257 // Cannot analyze non-byte shifts. 258 if ((ShAmt & 7) != 0) 259 return nullptr; 260 ShAmt >>= 3; 261 262 // If the extract is known to be all zeros, return zero. 263 if (ByteStart >= CSize-ShAmt) 264 return Constant::getNullValue(IntegerType::get(CE->getContext(), 265 ByteSize*8)); 266 // If the extract is known to be fully in the input, extract it. 267 if (ByteStart+ByteSize+ShAmt <= CSize) 268 return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize); 269 270 // TODO: Handle the 'partially zero' case. 271 return nullptr; 272 } 273 274 case Instruction::Shl: { 275 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1)); 276 if (!Amt) 277 return nullptr; 278 unsigned ShAmt = Amt->getZExtValue(); 279 // Cannot analyze non-byte shifts. 280 if ((ShAmt & 7) != 0) 281 return nullptr; 282 ShAmt >>= 3; 283 284 // If the extract is known to be all zeros, return zero. 285 if (ByteStart+ByteSize <= ShAmt) 286 return Constant::getNullValue(IntegerType::get(CE->getContext(), 287 ByteSize*8)); 288 // If the extract is known to be fully in the input, extract it. 289 if (ByteStart >= ShAmt) 290 return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize); 291 292 // TODO: Handle the 'partially zero' case. 293 return nullptr; 294 } 295 296 case Instruction::ZExt: { 297 unsigned SrcBitSize = 298 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth(); 299 300 // If extracting something that is completely zero, return 0. 301 if (ByteStart*8 >= SrcBitSize) 302 return Constant::getNullValue(IntegerType::get(CE->getContext(), 303 ByteSize*8)); 304 305 // If exactly extracting the input, return it. 306 if (ByteStart == 0 && ByteSize*8 == SrcBitSize) 307 return CE->getOperand(0); 308 309 // If extracting something completely in the input, if if the input is a 310 // multiple of 8 bits, recurse. 311 if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize) 312 return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize); 313 314 // Otherwise, if extracting a subset of the input, which is not multiple of 315 // 8 bits, do a shift and trunc to get the bits. 316 if ((ByteStart+ByteSize)*8 < SrcBitSize) { 317 assert((SrcBitSize&7) && "Shouldn't get byte sized case here"); 318 Constant *Res = CE->getOperand(0); 319 if (ByteStart) 320 Res = ConstantExpr::getLShr(Res, 321 ConstantInt::get(Res->getType(), ByteStart*8)); 322 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(), 323 ByteSize*8)); 324 } 325 326 // TODO: Handle the 'partially zero' case. 327 return nullptr; 328 } 329 } 330 } 331 332 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof 333 /// on Ty, with any known factors factored out. If Folded is false, 334 /// return null if no factoring was possible, to avoid endlessly 335 /// bouncing an unfoldable expression back into the top-level folder. 336 /// 337 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy, 338 bool Folded) { 339 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 340 Constant *N = ConstantInt::get(DestTy, ATy->getNumElements()); 341 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true); 342 return ConstantExpr::getNUWMul(E, N); 343 } 344 345 if (StructType *STy = dyn_cast<StructType>(Ty)) 346 if (!STy->isPacked()) { 347 unsigned NumElems = STy->getNumElements(); 348 // An empty struct has size zero. 349 if (NumElems == 0) 350 return ConstantExpr::getNullValue(DestTy); 351 // Check for a struct with all members having the same size. 352 Constant *MemberSize = 353 getFoldedSizeOf(STy->getElementType(0), DestTy, true); 354 bool AllSame = true; 355 for (unsigned i = 1; i != NumElems; ++i) 356 if (MemberSize != 357 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) { 358 AllSame = false; 359 break; 360 } 361 if (AllSame) { 362 Constant *N = ConstantInt::get(DestTy, NumElems); 363 return ConstantExpr::getNUWMul(MemberSize, N); 364 } 365 } 366 367 // Pointer size doesn't depend on the pointee type, so canonicalize them 368 // to an arbitrary pointee. 369 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) 370 if (!PTy->getElementType()->isIntegerTy(1)) 371 return 372 getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1), 373 PTy->getAddressSpace()), 374 DestTy, true); 375 376 // If there's no interesting folding happening, bail so that we don't create 377 // a constant that looks like it needs folding but really doesn't. 378 if (!Folded) 379 return nullptr; 380 381 // Base case: Get a regular sizeof expression. 382 Constant *C = ConstantExpr::getSizeOf(Ty); 383 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 384 DestTy, false), 385 C, DestTy); 386 return C; 387 } 388 389 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof 390 /// on Ty, with any known factors factored out. If Folded is false, 391 /// return null if no factoring was possible, to avoid endlessly 392 /// bouncing an unfoldable expression back into the top-level folder. 393 /// 394 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy, 395 bool Folded) { 396 // The alignment of an array is equal to the alignment of the 397 // array element. Note that this is not always true for vectors. 398 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 399 Constant *C = ConstantExpr::getAlignOf(ATy->getElementType()); 400 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 401 DestTy, 402 false), 403 C, DestTy); 404 return C; 405 } 406 407 if (StructType *STy = dyn_cast<StructType>(Ty)) { 408 // Packed structs always have an alignment of 1. 409 if (STy->isPacked()) 410 return ConstantInt::get(DestTy, 1); 411 412 // Otherwise, struct alignment is the maximum alignment of any member. 413 // Without target data, we can't compare much, but we can check to see 414 // if all the members have the same alignment. 415 unsigned NumElems = STy->getNumElements(); 416 // An empty struct has minimal alignment. 417 if (NumElems == 0) 418 return ConstantInt::get(DestTy, 1); 419 // Check for a struct with all members having the same alignment. 420 Constant *MemberAlign = 421 getFoldedAlignOf(STy->getElementType(0), DestTy, true); 422 bool AllSame = true; 423 for (unsigned i = 1; i != NumElems; ++i) 424 if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) { 425 AllSame = false; 426 break; 427 } 428 if (AllSame) 429 return MemberAlign; 430 } 431 432 // Pointer alignment doesn't depend on the pointee type, so canonicalize them 433 // to an arbitrary pointee. 434 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) 435 if (!PTy->getElementType()->isIntegerTy(1)) 436 return 437 getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(), 438 1), 439 PTy->getAddressSpace()), 440 DestTy, true); 441 442 // If there's no interesting folding happening, bail so that we don't create 443 // a constant that looks like it needs folding but really doesn't. 444 if (!Folded) 445 return nullptr; 446 447 // Base case: Get a regular alignof expression. 448 Constant *C = ConstantExpr::getAlignOf(Ty); 449 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 450 DestTy, false), 451 C, DestTy); 452 return C; 453 } 454 455 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof 456 /// on Ty and FieldNo, with any known factors factored out. If Folded is false, 457 /// return null if no factoring was possible, to avoid endlessly 458 /// bouncing an unfoldable expression back into the top-level folder. 459 /// 460 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo, 461 Type *DestTy, 462 bool Folded) { 463 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 464 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false, 465 DestTy, false), 466 FieldNo, DestTy); 467 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true); 468 return ConstantExpr::getNUWMul(E, N); 469 } 470 471 if (StructType *STy = dyn_cast<StructType>(Ty)) 472 if (!STy->isPacked()) { 473 unsigned NumElems = STy->getNumElements(); 474 // An empty struct has no members. 475 if (NumElems == 0) 476 return nullptr; 477 // Check for a struct with all members having the same size. 478 Constant *MemberSize = 479 getFoldedSizeOf(STy->getElementType(0), DestTy, true); 480 bool AllSame = true; 481 for (unsigned i = 1; i != NumElems; ++i) 482 if (MemberSize != 483 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) { 484 AllSame = false; 485 break; 486 } 487 if (AllSame) { 488 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, 489 false, 490 DestTy, 491 false), 492 FieldNo, DestTy); 493 return ConstantExpr::getNUWMul(MemberSize, N); 494 } 495 } 496 497 // If there's no interesting folding happening, bail so that we don't create 498 // a constant that looks like it needs folding but really doesn't. 499 if (!Folded) 500 return nullptr; 501 502 // Base case: Get a regular offsetof expression. 503 Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo); 504 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 505 DestTy, false), 506 C, DestTy); 507 return C; 508 } 509 510 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V, 511 Type *DestTy) { 512 if (isa<UndefValue>(V)) { 513 // zext(undef) = 0, because the top bits will be zero. 514 // sext(undef) = 0, because the top bits will all be the same. 515 // [us]itofp(undef) = 0, because the result value is bounded. 516 if (opc == Instruction::ZExt || opc == Instruction::SExt || 517 opc == Instruction::UIToFP || opc == Instruction::SIToFP) 518 return Constant::getNullValue(DestTy); 519 return UndefValue::get(DestTy); 520 } 521 522 if (V->isNullValue() && !DestTy->isX86_MMXTy()) 523 return Constant::getNullValue(DestTy); 524 525 // If the cast operand is a constant expression, there's a few things we can 526 // do to try to simplify it. 527 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 528 if (CE->isCast()) { 529 // Try hard to fold cast of cast because they are often eliminable. 530 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy)) 531 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy); 532 } else if (CE->getOpcode() == Instruction::GetElementPtr && 533 // Do not fold addrspacecast (gep 0, .., 0). It might make the 534 // addrspacecast uncanonicalized. 535 opc != Instruction::AddrSpaceCast) { 536 // If all of the indexes in the GEP are null values, there is no pointer 537 // adjustment going on. We might as well cast the source pointer. 538 bool isAllNull = true; 539 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i) 540 if (!CE->getOperand(i)->isNullValue()) { 541 isAllNull = false; 542 break; 543 } 544 if (isAllNull) 545 // This is casting one pointer type to another, always BitCast 546 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy); 547 } 548 } 549 550 // If the cast operand is a constant vector, perform the cast by 551 // operating on each element. In the cast of bitcasts, the element 552 // count may be mismatched; don't attempt to handle that here. 553 if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) && 554 DestTy->isVectorTy() && 555 DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) { 556 SmallVector<Constant*, 16> res; 557 VectorType *DestVecTy = cast<VectorType>(DestTy); 558 Type *DstEltTy = DestVecTy->getElementType(); 559 Type *Ty = IntegerType::get(V->getContext(), 32); 560 for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) { 561 Constant *C = 562 ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i)); 563 res.push_back(ConstantExpr::getCast(opc, C, DstEltTy)); 564 } 565 return ConstantVector::get(res); 566 } 567 568 // We actually have to do a cast now. Perform the cast according to the 569 // opcode specified. 570 switch (opc) { 571 default: 572 llvm_unreachable("Failed to cast constant expression"); 573 case Instruction::FPTrunc: 574 case Instruction::FPExt: 575 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) { 576 bool ignored; 577 APFloat Val = FPC->getValueAPF(); 578 Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf : 579 DestTy->isFloatTy() ? APFloat::IEEEsingle : 580 DestTy->isDoubleTy() ? APFloat::IEEEdouble : 581 DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended : 582 DestTy->isFP128Ty() ? APFloat::IEEEquad : 583 DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble : 584 APFloat::Bogus, 585 APFloat::rmNearestTiesToEven, &ignored); 586 return ConstantFP::get(V->getContext(), Val); 587 } 588 return nullptr; // Can't fold. 589 case Instruction::FPToUI: 590 case Instruction::FPToSI: 591 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) { 592 const APFloat &V = FPC->getValueAPF(); 593 bool ignored; 594 uint64_t x[2]; 595 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 596 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI, 597 APFloat::rmTowardZero, &ignored); 598 APInt Val(DestBitWidth, x); 599 return ConstantInt::get(FPC->getContext(), Val); 600 } 601 return nullptr; // Can't fold. 602 case Instruction::IntToPtr: //always treated as unsigned 603 if (V->isNullValue()) // Is it an integral null value? 604 return ConstantPointerNull::get(cast<PointerType>(DestTy)); 605 return nullptr; // Other pointer types cannot be casted 606 case Instruction::PtrToInt: // always treated as unsigned 607 // Is it a null pointer value? 608 if (V->isNullValue()) 609 return ConstantInt::get(DestTy, 0); 610 // If this is a sizeof-like expression, pull out multiplications by 611 // known factors to expose them to subsequent folding. If it's an 612 // alignof-like expression, factor out known factors. 613 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 614 if (CE->getOpcode() == Instruction::GetElementPtr && 615 CE->getOperand(0)->isNullValue()) { 616 Type *Ty = 617 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 618 if (CE->getNumOperands() == 2) { 619 // Handle a sizeof-like expression. 620 Constant *Idx = CE->getOperand(1); 621 bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne(); 622 if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) { 623 Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true, 624 DestTy, false), 625 Idx, DestTy); 626 return ConstantExpr::getMul(C, Idx); 627 } 628 } else if (CE->getNumOperands() == 3 && 629 CE->getOperand(1)->isNullValue()) { 630 // Handle an alignof-like expression. 631 if (StructType *STy = dyn_cast<StructType>(Ty)) 632 if (!STy->isPacked()) { 633 ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2)); 634 if (CI->isOne() && 635 STy->getNumElements() == 2 && 636 STy->getElementType(0)->isIntegerTy(1)) { 637 return getFoldedAlignOf(STy->getElementType(1), DestTy, false); 638 } 639 } 640 // Handle an offsetof-like expression. 641 if (Ty->isStructTy() || Ty->isArrayTy()) { 642 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2), 643 DestTy, false)) 644 return C; 645 } 646 } 647 } 648 // Other pointer types cannot be casted 649 return nullptr; 650 case Instruction::UIToFP: 651 case Instruction::SIToFP: 652 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 653 APInt api = CI->getValue(); 654 APFloat apf(DestTy->getFltSemantics(), 655 APInt::getNullValue(DestTy->getPrimitiveSizeInBits())); 656 (void)apf.convertFromAPInt(api, 657 opc==Instruction::SIToFP, 658 APFloat::rmNearestTiesToEven); 659 return ConstantFP::get(V->getContext(), apf); 660 } 661 return nullptr; 662 case Instruction::ZExt: 663 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 664 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 665 return ConstantInt::get(V->getContext(), 666 CI->getValue().zext(BitWidth)); 667 } 668 return nullptr; 669 case Instruction::SExt: 670 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 671 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 672 return ConstantInt::get(V->getContext(), 673 CI->getValue().sext(BitWidth)); 674 } 675 return nullptr; 676 case Instruction::Trunc: { 677 if (V->getType()->isVectorTy()) 678 return nullptr; 679 680 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 681 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 682 return ConstantInt::get(V->getContext(), 683 CI->getValue().trunc(DestBitWidth)); 684 } 685 686 // The input must be a constantexpr. See if we can simplify this based on 687 // the bytes we are demanding. Only do this if the source and dest are an 688 // even multiple of a byte. 689 if ((DestBitWidth & 7) == 0 && 690 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0) 691 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8)) 692 return Res; 693 694 return nullptr; 695 } 696 case Instruction::BitCast: 697 return FoldBitCast(V, DestTy); 698 case Instruction::AddrSpaceCast: 699 return nullptr; 700 } 701 } 702 703 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond, 704 Constant *V1, Constant *V2) { 705 // Check for i1 and vector true/false conditions. 706 if (Cond->isNullValue()) return V2; 707 if (Cond->isAllOnesValue()) return V1; 708 709 // If the condition is a vector constant, fold the result elementwise. 710 if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) { 711 SmallVector<Constant*, 16> Result; 712 Type *Ty = IntegerType::get(CondV->getContext(), 32); 713 for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){ 714 Constant *V; 715 Constant *V1Element = ConstantExpr::getExtractElement(V1, 716 ConstantInt::get(Ty, i)); 717 Constant *V2Element = ConstantExpr::getExtractElement(V2, 718 ConstantInt::get(Ty, i)); 719 Constant *Cond = dyn_cast<Constant>(CondV->getOperand(i)); 720 if (V1Element == V2Element) { 721 V = V1Element; 722 } else if (isa<UndefValue>(Cond)) { 723 V = isa<UndefValue>(V1Element) ? V1Element : V2Element; 724 } else { 725 if (!isa<ConstantInt>(Cond)) break; 726 V = Cond->isNullValue() ? V2Element : V1Element; 727 } 728 Result.push_back(V); 729 } 730 731 // If we were able to build the vector, return it. 732 if (Result.size() == V1->getType()->getVectorNumElements()) 733 return ConstantVector::get(Result); 734 } 735 736 if (isa<UndefValue>(Cond)) { 737 if (isa<UndefValue>(V1)) return V1; 738 return V2; 739 } 740 if (isa<UndefValue>(V1)) return V2; 741 if (isa<UndefValue>(V2)) return V1; 742 if (V1 == V2) return V1; 743 744 if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) { 745 if (TrueVal->getOpcode() == Instruction::Select) 746 if (TrueVal->getOperand(0) == Cond) 747 return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2); 748 } 749 if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) { 750 if (FalseVal->getOpcode() == Instruction::Select) 751 if (FalseVal->getOperand(0) == Cond) 752 return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2)); 753 } 754 755 return nullptr; 756 } 757 758 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val, 759 Constant *Idx) { 760 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef 761 return UndefValue::get(Val->getType()->getVectorElementType()); 762 if (Val->isNullValue()) // ee(zero, x) -> zero 763 return Constant::getNullValue(Val->getType()->getVectorElementType()); 764 // ee({w,x,y,z}, undef) -> undef 765 if (isa<UndefValue>(Idx)) 766 return UndefValue::get(Val->getType()->getVectorElementType()); 767 768 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) { 769 uint64_t Index = CIdx->getZExtValue(); 770 // ee({w,x,y,z}, wrong_value) -> undef 771 if (Index >= Val->getType()->getVectorNumElements()) 772 return UndefValue::get(Val->getType()->getVectorElementType()); 773 return Val->getAggregateElement(Index); 774 } 775 return nullptr; 776 } 777 778 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val, 779 Constant *Elt, 780 Constant *Idx) { 781 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx); 782 if (!CIdx) return nullptr; 783 const APInt &IdxVal = CIdx->getValue(); 784 785 SmallVector<Constant*, 16> Result; 786 Type *Ty = IntegerType::get(Val->getContext(), 32); 787 for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){ 788 if (i == IdxVal) { 789 Result.push_back(Elt); 790 continue; 791 } 792 793 Constant *C = 794 ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i)); 795 Result.push_back(C); 796 } 797 798 return ConstantVector::get(Result); 799 } 800 801 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1, 802 Constant *V2, 803 Constant *Mask) { 804 unsigned MaskNumElts = Mask->getType()->getVectorNumElements(); 805 Type *EltTy = V1->getType()->getVectorElementType(); 806 807 // Undefined shuffle mask -> undefined value. 808 if (isa<UndefValue>(Mask)) 809 return UndefValue::get(VectorType::get(EltTy, MaskNumElts)); 810 811 // Don't break the bitcode reader hack. 812 if (isa<ConstantExpr>(Mask)) return nullptr; 813 814 unsigned SrcNumElts = V1->getType()->getVectorNumElements(); 815 816 // Loop over the shuffle mask, evaluating each element. 817 SmallVector<Constant*, 32> Result; 818 for (unsigned i = 0; i != MaskNumElts; ++i) { 819 int Elt = ShuffleVectorInst::getMaskValue(Mask, i); 820 if (Elt == -1) { 821 Result.push_back(UndefValue::get(EltTy)); 822 continue; 823 } 824 Constant *InElt; 825 if (unsigned(Elt) >= SrcNumElts*2) 826 InElt = UndefValue::get(EltTy); 827 else if (unsigned(Elt) >= SrcNumElts) { 828 Type *Ty = IntegerType::get(V2->getContext(), 32); 829 InElt = 830 ConstantExpr::getExtractElement(V2, 831 ConstantInt::get(Ty, Elt - SrcNumElts)); 832 } else { 833 Type *Ty = IntegerType::get(V1->getContext(), 32); 834 InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt)); 835 } 836 Result.push_back(InElt); 837 } 838 839 return ConstantVector::get(Result); 840 } 841 842 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg, 843 ArrayRef<unsigned> Idxs) { 844 // Base case: no indices, so return the entire value. 845 if (Idxs.empty()) 846 return Agg; 847 848 if (Constant *C = Agg->getAggregateElement(Idxs[0])) 849 return ConstantFoldExtractValueInstruction(C, Idxs.slice(1)); 850 851 return nullptr; 852 } 853 854 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg, 855 Constant *Val, 856 ArrayRef<unsigned> Idxs) { 857 // Base case: no indices, so replace the entire value. 858 if (Idxs.empty()) 859 return Val; 860 861 unsigned NumElts; 862 if (StructType *ST = dyn_cast<StructType>(Agg->getType())) 863 NumElts = ST->getNumElements(); 864 else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType())) 865 NumElts = AT->getNumElements(); 866 else 867 NumElts = Agg->getType()->getVectorNumElements(); 868 869 SmallVector<Constant*, 32> Result; 870 for (unsigned i = 0; i != NumElts; ++i) { 871 Constant *C = Agg->getAggregateElement(i); 872 if (!C) return nullptr; 873 874 if (Idxs[0] == i) 875 C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1)); 876 877 Result.push_back(C); 878 } 879 880 if (StructType *ST = dyn_cast<StructType>(Agg->getType())) 881 return ConstantStruct::get(ST, Result); 882 if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType())) 883 return ConstantArray::get(AT, Result); 884 return ConstantVector::get(Result); 885 } 886 887 888 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode, 889 Constant *C1, Constant *C2) { 890 // Handle UndefValue up front. 891 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) { 892 switch (Opcode) { 893 case Instruction::Xor: 894 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) 895 // Handle undef ^ undef -> 0 special case. This is a common 896 // idiom (misuse). 897 return Constant::getNullValue(C1->getType()); 898 // Fallthrough 899 case Instruction::Add: 900 case Instruction::Sub: 901 return UndefValue::get(C1->getType()); 902 case Instruction::And: 903 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef 904 return C1; 905 return Constant::getNullValue(C1->getType()); // undef & X -> 0 906 case Instruction::Mul: { 907 ConstantInt *CI; 908 // X * undef -> undef if X is odd or undef 909 if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) || 910 ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) || 911 (isa<UndefValue>(C1) && isa<UndefValue>(C2))) 912 return UndefValue::get(C1->getType()); 913 914 // X * undef -> 0 otherwise 915 return Constant::getNullValue(C1->getType()); 916 } 917 case Instruction::UDiv: 918 case Instruction::SDiv: 919 // undef / 1 -> undef 920 if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv) 921 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) 922 if (CI2->isOne()) 923 return C1; 924 // FALL THROUGH 925 case Instruction::URem: 926 case Instruction::SRem: 927 if (!isa<UndefValue>(C2)) // undef / X -> 0 928 return Constant::getNullValue(C1->getType()); 929 return C2; // X / undef -> undef 930 case Instruction::Or: // X | undef -> -1 931 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef 932 return C1; 933 return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0 934 case Instruction::LShr: 935 if (isa<UndefValue>(C2) && isa<UndefValue>(C1)) 936 return C1; // undef lshr undef -> undef 937 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0 938 // undef lshr X -> 0 939 case Instruction::AShr: 940 if (!isa<UndefValue>(C2)) // undef ashr X --> all ones 941 return Constant::getAllOnesValue(C1->getType()); 942 else if (isa<UndefValue>(C1)) 943 return C1; // undef ashr undef -> undef 944 else 945 return C1; // X ashr undef --> X 946 case Instruction::Shl: 947 if (isa<UndefValue>(C2) && isa<UndefValue>(C1)) 948 return C1; // undef shl undef -> undef 949 // undef << X -> 0 or X << undef -> 0 950 return Constant::getNullValue(C1->getType()); 951 } 952 } 953 954 // Handle simplifications when the RHS is a constant int. 955 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) { 956 switch (Opcode) { 957 case Instruction::Add: 958 if (CI2->equalsInt(0)) return C1; // X + 0 == X 959 break; 960 case Instruction::Sub: 961 if (CI2->equalsInt(0)) return C1; // X - 0 == X 962 break; 963 case Instruction::Mul: 964 if (CI2->equalsInt(0)) return C2; // X * 0 == 0 965 if (CI2->equalsInt(1)) 966 return C1; // X * 1 == X 967 break; 968 case Instruction::UDiv: 969 case Instruction::SDiv: 970 if (CI2->equalsInt(1)) 971 return C1; // X / 1 == X 972 if (CI2->equalsInt(0)) 973 return UndefValue::get(CI2->getType()); // X / 0 == undef 974 break; 975 case Instruction::URem: 976 case Instruction::SRem: 977 if (CI2->equalsInt(1)) 978 return Constant::getNullValue(CI2->getType()); // X % 1 == 0 979 if (CI2->equalsInt(0)) 980 return UndefValue::get(CI2->getType()); // X % 0 == undef 981 break; 982 case Instruction::And: 983 if (CI2->isZero()) return C2; // X & 0 == 0 984 if (CI2->isAllOnesValue()) 985 return C1; // X & -1 == X 986 987 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 988 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64) 989 if (CE1->getOpcode() == Instruction::ZExt) { 990 unsigned DstWidth = CI2->getType()->getBitWidth(); 991 unsigned SrcWidth = 992 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits(); 993 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth)); 994 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits) 995 return C1; 996 } 997 998 // If and'ing the address of a global with a constant, fold it. 999 if (CE1->getOpcode() == Instruction::PtrToInt && 1000 isa<GlobalValue>(CE1->getOperand(0))) { 1001 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0)); 1002 1003 // Functions are at least 4-byte aligned. 1004 unsigned GVAlign = GV->getAlignment(); 1005 if (isa<Function>(GV)) 1006 GVAlign = std::max(GVAlign, 4U); 1007 1008 if (GVAlign > 1) { 1009 unsigned DstWidth = CI2->getType()->getBitWidth(); 1010 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign)); 1011 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth)); 1012 1013 // If checking bits we know are clear, return zero. 1014 if ((CI2->getValue() & BitsNotSet) == CI2->getValue()) 1015 return Constant::getNullValue(CI2->getType()); 1016 } 1017 } 1018 } 1019 break; 1020 case Instruction::Or: 1021 if (CI2->equalsInt(0)) return C1; // X | 0 == X 1022 if (CI2->isAllOnesValue()) 1023 return C2; // X | -1 == -1 1024 break; 1025 case Instruction::Xor: 1026 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X 1027 1028 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 1029 switch (CE1->getOpcode()) { 1030 default: break; 1031 case Instruction::ICmp: 1032 case Instruction::FCmp: 1033 // cmp pred ^ true -> cmp !pred 1034 assert(CI2->equalsInt(1)); 1035 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate(); 1036 pred = CmpInst::getInversePredicate(pred); 1037 return ConstantExpr::getCompare(pred, CE1->getOperand(0), 1038 CE1->getOperand(1)); 1039 } 1040 } 1041 break; 1042 case Instruction::AShr: 1043 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2 1044 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) 1045 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero. 1046 return ConstantExpr::getLShr(C1, C2); 1047 break; 1048 } 1049 } else if (isa<ConstantInt>(C1)) { 1050 // If C1 is a ConstantInt and C2 is not, swap the operands. 1051 if (Instruction::isCommutative(Opcode)) 1052 return ConstantExpr::get(Opcode, C2, C1); 1053 } 1054 1055 // At this point we know neither constant is an UndefValue. 1056 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) { 1057 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) { 1058 const APInt &C1V = CI1->getValue(); 1059 const APInt &C2V = CI2->getValue(); 1060 switch (Opcode) { 1061 default: 1062 break; 1063 case Instruction::Add: 1064 return ConstantInt::get(CI1->getContext(), C1V + C2V); 1065 case Instruction::Sub: 1066 return ConstantInt::get(CI1->getContext(), C1V - C2V); 1067 case Instruction::Mul: 1068 return ConstantInt::get(CI1->getContext(), C1V * C2V); 1069 case Instruction::UDiv: 1070 assert(!CI2->isNullValue() && "Div by zero handled above"); 1071 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V)); 1072 case Instruction::SDiv: 1073 assert(!CI2->isNullValue() && "Div by zero handled above"); 1074 if (C2V.isAllOnesValue() && C1V.isMinSignedValue()) 1075 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef 1076 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V)); 1077 case Instruction::URem: 1078 assert(!CI2->isNullValue() && "Div by zero handled above"); 1079 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V)); 1080 case Instruction::SRem: 1081 assert(!CI2->isNullValue() && "Div by zero handled above"); 1082 if (C2V.isAllOnesValue() && C1V.isMinSignedValue()) 1083 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef 1084 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V)); 1085 case Instruction::And: 1086 return ConstantInt::get(CI1->getContext(), C1V & C2V); 1087 case Instruction::Or: 1088 return ConstantInt::get(CI1->getContext(), C1V | C2V); 1089 case Instruction::Xor: 1090 return ConstantInt::get(CI1->getContext(), C1V ^ C2V); 1091 case Instruction::Shl: { 1092 uint32_t shiftAmt = C2V.getZExtValue(); 1093 if (shiftAmt < C1V.getBitWidth()) 1094 return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt)); 1095 else 1096 return UndefValue::get(C1->getType()); // too big shift is undef 1097 } 1098 case Instruction::LShr: { 1099 uint32_t shiftAmt = C2V.getZExtValue(); 1100 if (shiftAmt < C1V.getBitWidth()) 1101 return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt)); 1102 else 1103 return UndefValue::get(C1->getType()); // too big shift is undef 1104 } 1105 case Instruction::AShr: { 1106 uint32_t shiftAmt = C2V.getZExtValue(); 1107 if (shiftAmt < C1V.getBitWidth()) 1108 return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt)); 1109 else 1110 return UndefValue::get(C1->getType()); // too big shift is undef 1111 } 1112 } 1113 } 1114 1115 switch (Opcode) { 1116 case Instruction::SDiv: 1117 case Instruction::UDiv: 1118 case Instruction::URem: 1119 case Instruction::SRem: 1120 case Instruction::LShr: 1121 case Instruction::AShr: 1122 case Instruction::Shl: 1123 if (CI1->equalsInt(0)) return C1; 1124 break; 1125 default: 1126 break; 1127 } 1128 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) { 1129 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) { 1130 APFloat C1V = CFP1->getValueAPF(); 1131 APFloat C2V = CFP2->getValueAPF(); 1132 APFloat C3V = C1V; // copy for modification 1133 switch (Opcode) { 1134 default: 1135 break; 1136 case Instruction::FAdd: 1137 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven); 1138 return ConstantFP::get(C1->getContext(), C3V); 1139 case Instruction::FSub: 1140 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven); 1141 return ConstantFP::get(C1->getContext(), C3V); 1142 case Instruction::FMul: 1143 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven); 1144 return ConstantFP::get(C1->getContext(), C3V); 1145 case Instruction::FDiv: 1146 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven); 1147 return ConstantFP::get(C1->getContext(), C3V); 1148 case Instruction::FRem: 1149 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven); 1150 return ConstantFP::get(C1->getContext(), C3V); 1151 } 1152 } 1153 } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) { 1154 // Perform elementwise folding. 1155 SmallVector<Constant*, 16> Result; 1156 Type *Ty = IntegerType::get(VTy->getContext(), 32); 1157 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 1158 Constant *LHS = 1159 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i)); 1160 Constant *RHS = 1161 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i)); 1162 1163 Result.push_back(ConstantExpr::get(Opcode, LHS, RHS)); 1164 } 1165 1166 return ConstantVector::get(Result); 1167 } 1168 1169 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 1170 // There are many possible foldings we could do here. We should probably 1171 // at least fold add of a pointer with an integer into the appropriate 1172 // getelementptr. This will improve alias analysis a bit. 1173 1174 // Given ((a + b) + c), if (b + c) folds to something interesting, return 1175 // (a + (b + c)). 1176 if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) { 1177 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2); 1178 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode) 1179 return ConstantExpr::get(Opcode, CE1->getOperand(0), T); 1180 } 1181 } else if (isa<ConstantExpr>(C2)) { 1182 // If C2 is a constant expr and C1 isn't, flop them around and fold the 1183 // other way if possible. 1184 if (Instruction::isCommutative(Opcode)) 1185 return ConstantFoldBinaryInstruction(Opcode, C2, C1); 1186 } 1187 1188 // i1 can be simplified in many cases. 1189 if (C1->getType()->isIntegerTy(1)) { 1190 switch (Opcode) { 1191 case Instruction::Add: 1192 case Instruction::Sub: 1193 return ConstantExpr::getXor(C1, C2); 1194 case Instruction::Mul: 1195 return ConstantExpr::getAnd(C1, C2); 1196 case Instruction::Shl: 1197 case Instruction::LShr: 1198 case Instruction::AShr: 1199 // We can assume that C2 == 0. If it were one the result would be 1200 // undefined because the shift value is as large as the bitwidth. 1201 return C1; 1202 case Instruction::SDiv: 1203 case Instruction::UDiv: 1204 // We can assume that C2 == 1. If it were zero the result would be 1205 // undefined through division by zero. 1206 return C1; 1207 case Instruction::URem: 1208 case Instruction::SRem: 1209 // We can assume that C2 == 1. If it were zero the result would be 1210 // undefined through division by zero. 1211 return ConstantInt::getFalse(C1->getContext()); 1212 default: 1213 break; 1214 } 1215 } 1216 1217 // We don't know how to fold this. 1218 return nullptr; 1219 } 1220 1221 /// isZeroSizedType - This type is zero sized if its an array or structure of 1222 /// zero sized types. The only leaf zero sized type is an empty structure. 1223 static bool isMaybeZeroSizedType(Type *Ty) { 1224 if (StructType *STy = dyn_cast<StructType>(Ty)) { 1225 if (STy->isOpaque()) return true; // Can't say. 1226 1227 // If all of elements have zero size, this does too. 1228 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 1229 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false; 1230 return true; 1231 1232 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1233 return isMaybeZeroSizedType(ATy->getElementType()); 1234 } 1235 return false; 1236 } 1237 1238 /// IdxCompare - Compare the two constants as though they were getelementptr 1239 /// indices. This allows coersion of the types to be the same thing. 1240 /// 1241 /// If the two constants are the "same" (after coersion), return 0. If the 1242 /// first is less than the second, return -1, if the second is less than the 1243 /// first, return 1. If the constants are not integral, return -2. 1244 /// 1245 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) { 1246 if (C1 == C2) return 0; 1247 1248 // Ok, we found a different index. If they are not ConstantInt, we can't do 1249 // anything with them. 1250 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2)) 1251 return -2; // don't know! 1252 1253 // Ok, we have two differing integer indices. Sign extend them to be the same 1254 // type. Long is always big enough, so we use it. 1255 if (!C1->getType()->isIntegerTy(64)) 1256 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext())); 1257 1258 if (!C2->getType()->isIntegerTy(64)) 1259 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext())); 1260 1261 if (C1 == C2) return 0; // They are equal 1262 1263 // If the type being indexed over is really just a zero sized type, there is 1264 // no pointer difference being made here. 1265 if (isMaybeZeroSizedType(ElTy)) 1266 return -2; // dunno. 1267 1268 // If they are really different, now that they are the same type, then we 1269 // found a difference! 1270 if (cast<ConstantInt>(C1)->getSExtValue() < 1271 cast<ConstantInt>(C2)->getSExtValue()) 1272 return -1; 1273 else 1274 return 1; 1275 } 1276 1277 /// evaluateFCmpRelation - This function determines if there is anything we can 1278 /// decide about the two constants provided. This doesn't need to handle simple 1279 /// things like ConstantFP comparisons, but should instead handle ConstantExprs. 1280 /// If we can determine that the two constants have a particular relation to 1281 /// each other, we should return the corresponding FCmpInst predicate, 1282 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in 1283 /// ConstantFoldCompareInstruction. 1284 /// 1285 /// To simplify this code we canonicalize the relation so that the first 1286 /// operand is always the most "complex" of the two. We consider ConstantFP 1287 /// to be the simplest, and ConstantExprs to be the most complex. 1288 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) { 1289 assert(V1->getType() == V2->getType() && 1290 "Cannot compare values of different types!"); 1291 1292 // Handle degenerate case quickly 1293 if (V1 == V2) return FCmpInst::FCMP_OEQ; 1294 1295 if (!isa<ConstantExpr>(V1)) { 1296 if (!isa<ConstantExpr>(V2)) { 1297 // We distilled thisUse the standard constant folder for a few cases 1298 ConstantInt *R = nullptr; 1299 R = dyn_cast<ConstantInt>( 1300 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2)); 1301 if (R && !R->isZero()) 1302 return FCmpInst::FCMP_OEQ; 1303 R = dyn_cast<ConstantInt>( 1304 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2)); 1305 if (R && !R->isZero()) 1306 return FCmpInst::FCMP_OLT; 1307 R = dyn_cast<ConstantInt>( 1308 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2)); 1309 if (R && !R->isZero()) 1310 return FCmpInst::FCMP_OGT; 1311 1312 // Nothing more we can do 1313 return FCmpInst::BAD_FCMP_PREDICATE; 1314 } 1315 1316 // If the first operand is simple and second is ConstantExpr, swap operands. 1317 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1); 1318 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE) 1319 return FCmpInst::getSwappedPredicate(SwappedRelation); 1320 } else { 1321 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a 1322 // constantexpr or a simple constant. 1323 ConstantExpr *CE1 = cast<ConstantExpr>(V1); 1324 switch (CE1->getOpcode()) { 1325 case Instruction::FPTrunc: 1326 case Instruction::FPExt: 1327 case Instruction::UIToFP: 1328 case Instruction::SIToFP: 1329 // We might be able to do something with these but we don't right now. 1330 break; 1331 default: 1332 break; 1333 } 1334 } 1335 // There are MANY other foldings that we could perform here. They will 1336 // probably be added on demand, as they seem needed. 1337 return FCmpInst::BAD_FCMP_PREDICATE; 1338 } 1339 1340 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1, 1341 const GlobalValue *GV2) { 1342 // Don't try to decide equality of aliases. 1343 if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2)) 1344 if (!GV1->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage()) 1345 return ICmpInst::ICMP_NE; 1346 return ICmpInst::BAD_ICMP_PREDICATE; 1347 } 1348 1349 /// evaluateICmpRelation - This function determines if there is anything we can 1350 /// decide about the two constants provided. This doesn't need to handle simple 1351 /// things like integer comparisons, but should instead handle ConstantExprs 1352 /// and GlobalValues. If we can determine that the two constants have a 1353 /// particular relation to each other, we should return the corresponding ICmp 1354 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE. 1355 /// 1356 /// To simplify this code we canonicalize the relation so that the first 1357 /// operand is always the most "complex" of the two. We consider simple 1358 /// constants (like ConstantInt) to be the simplest, followed by 1359 /// GlobalValues, followed by ConstantExpr's (the most complex). 1360 /// 1361 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2, 1362 bool isSigned) { 1363 assert(V1->getType() == V2->getType() && 1364 "Cannot compare different types of values!"); 1365 if (V1 == V2) return ICmpInst::ICMP_EQ; 1366 1367 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) && 1368 !isa<BlockAddress>(V1)) { 1369 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) && 1370 !isa<BlockAddress>(V2)) { 1371 // We distilled this down to a simple case, use the standard constant 1372 // folder. 1373 ConstantInt *R = nullptr; 1374 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ; 1375 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1376 if (R && !R->isZero()) 1377 return pred; 1378 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1379 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1380 if (R && !R->isZero()) 1381 return pred; 1382 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1383 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1384 if (R && !R->isZero()) 1385 return pred; 1386 1387 // If we couldn't figure it out, bail. 1388 return ICmpInst::BAD_ICMP_PREDICATE; 1389 } 1390 1391 // If the first operand is simple, swap operands. 1392 ICmpInst::Predicate SwappedRelation = 1393 evaluateICmpRelation(V2, V1, isSigned); 1394 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1395 return ICmpInst::getSwappedPredicate(SwappedRelation); 1396 1397 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) { 1398 if (isa<ConstantExpr>(V2)) { // Swap as necessary. 1399 ICmpInst::Predicate SwappedRelation = 1400 evaluateICmpRelation(V2, V1, isSigned); 1401 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1402 return ICmpInst::getSwappedPredicate(SwappedRelation); 1403 return ICmpInst::BAD_ICMP_PREDICATE; 1404 } 1405 1406 // Now we know that the RHS is a GlobalValue, BlockAddress or simple 1407 // constant (which, since the types must match, means that it's a 1408 // ConstantPointerNull). 1409 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) { 1410 return areGlobalsPotentiallyEqual(GV, GV2); 1411 } else if (isa<BlockAddress>(V2)) { 1412 return ICmpInst::ICMP_NE; // Globals never equal labels. 1413 } else { 1414 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!"); 1415 // GlobalVals can never be null unless they have external weak linkage. 1416 // We don't try to evaluate aliases here. 1417 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV)) 1418 return ICmpInst::ICMP_NE; 1419 } 1420 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) { 1421 if (isa<ConstantExpr>(V2)) { // Swap as necessary. 1422 ICmpInst::Predicate SwappedRelation = 1423 evaluateICmpRelation(V2, V1, isSigned); 1424 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1425 return ICmpInst::getSwappedPredicate(SwappedRelation); 1426 return ICmpInst::BAD_ICMP_PREDICATE; 1427 } 1428 1429 // Now we know that the RHS is a GlobalValue, BlockAddress or simple 1430 // constant (which, since the types must match, means that it is a 1431 // ConstantPointerNull). 1432 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) { 1433 // Block address in another function can't equal this one, but block 1434 // addresses in the current function might be the same if blocks are 1435 // empty. 1436 if (BA2->getFunction() != BA->getFunction()) 1437 return ICmpInst::ICMP_NE; 1438 } else { 1439 // Block addresses aren't null, don't equal the address of globals. 1440 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) && 1441 "Canonicalization guarantee!"); 1442 return ICmpInst::ICMP_NE; 1443 } 1444 } else { 1445 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a 1446 // constantexpr, a global, block address, or a simple constant. 1447 ConstantExpr *CE1 = cast<ConstantExpr>(V1); 1448 Constant *CE1Op0 = CE1->getOperand(0); 1449 1450 switch (CE1->getOpcode()) { 1451 case Instruction::Trunc: 1452 case Instruction::FPTrunc: 1453 case Instruction::FPExt: 1454 case Instruction::FPToUI: 1455 case Instruction::FPToSI: 1456 break; // We can't evaluate floating point casts or truncations. 1457 1458 case Instruction::UIToFP: 1459 case Instruction::SIToFP: 1460 case Instruction::BitCast: 1461 case Instruction::ZExt: 1462 case Instruction::SExt: 1463 // If the cast is not actually changing bits, and the second operand is a 1464 // null pointer, do the comparison with the pre-casted value. 1465 if (V2->isNullValue() && 1466 (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) { 1467 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false; 1468 if (CE1->getOpcode() == Instruction::SExt) isSigned = true; 1469 return evaluateICmpRelation(CE1Op0, 1470 Constant::getNullValue(CE1Op0->getType()), 1471 isSigned); 1472 } 1473 break; 1474 1475 case Instruction::GetElementPtr: { 1476 GEPOperator *CE1GEP = cast<GEPOperator>(CE1); 1477 // Ok, since this is a getelementptr, we know that the constant has a 1478 // pointer type. Check the various cases. 1479 if (isa<ConstantPointerNull>(V2)) { 1480 // If we are comparing a GEP to a null pointer, check to see if the base 1481 // of the GEP equals the null pointer. 1482 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) { 1483 if (GV->hasExternalWeakLinkage()) 1484 // Weak linkage GVals could be zero or not. We're comparing that 1485 // to null pointer so its greater-or-equal 1486 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 1487 else 1488 // If its not weak linkage, the GVal must have a non-zero address 1489 // so the result is greater-than 1490 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1491 } else if (isa<ConstantPointerNull>(CE1Op0)) { 1492 // If we are indexing from a null pointer, check to see if we have any 1493 // non-zero indices. 1494 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i) 1495 if (!CE1->getOperand(i)->isNullValue()) 1496 // Offsetting from null, must not be equal. 1497 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1498 // Only zero indexes from null, must still be zero. 1499 return ICmpInst::ICMP_EQ; 1500 } 1501 // Otherwise, we can't really say if the first operand is null or not. 1502 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) { 1503 if (isa<ConstantPointerNull>(CE1Op0)) { 1504 if (GV2->hasExternalWeakLinkage()) 1505 // Weak linkage GVals could be zero or not. We're comparing it to 1506 // a null pointer, so its less-or-equal 1507 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 1508 else 1509 // If its not weak linkage, the GVal must have a non-zero address 1510 // so the result is less-than 1511 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1512 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) { 1513 if (GV == GV2) { 1514 // If this is a getelementptr of the same global, then it must be 1515 // different. Because the types must match, the getelementptr could 1516 // only have at most one index, and because we fold getelementptr's 1517 // with a single zero index, it must be nonzero. 1518 assert(CE1->getNumOperands() == 2 && 1519 !CE1->getOperand(1)->isNullValue() && 1520 "Surprising getelementptr!"); 1521 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1522 } else { 1523 if (CE1GEP->hasAllZeroIndices()) 1524 return areGlobalsPotentiallyEqual(GV, GV2); 1525 return ICmpInst::BAD_ICMP_PREDICATE; 1526 } 1527 } 1528 } else { 1529 ConstantExpr *CE2 = cast<ConstantExpr>(V2); 1530 Constant *CE2Op0 = CE2->getOperand(0); 1531 1532 // There are MANY other foldings that we could perform here. They will 1533 // probably be added on demand, as they seem needed. 1534 switch (CE2->getOpcode()) { 1535 default: break; 1536 case Instruction::GetElementPtr: 1537 // By far the most common case to handle is when the base pointers are 1538 // obviously to the same global. 1539 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) { 1540 // Don't know relative ordering, but check for inequality. 1541 if (CE1Op0 != CE2Op0) { 1542 GEPOperator *CE2GEP = cast<GEPOperator>(CE2); 1543 if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices()) 1544 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0), 1545 cast<GlobalValue>(CE2Op0)); 1546 return ICmpInst::BAD_ICMP_PREDICATE; 1547 } 1548 // Ok, we know that both getelementptr instructions are based on the 1549 // same global. From this, we can precisely determine the relative 1550 // ordering of the resultant pointers. 1551 unsigned i = 1; 1552 1553 // The logic below assumes that the result of the comparison 1554 // can be determined by finding the first index that differs. 1555 // This doesn't work if there is over-indexing in any 1556 // subsequent indices, so check for that case first. 1557 if (!CE1->isGEPWithNoNotionalOverIndexing() || 1558 !CE2->isGEPWithNoNotionalOverIndexing()) 1559 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1560 1561 // Compare all of the operands the GEP's have in common. 1562 gep_type_iterator GTI = gep_type_begin(CE1); 1563 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands(); 1564 ++i, ++GTI) 1565 switch (IdxCompare(CE1->getOperand(i), 1566 CE2->getOperand(i), GTI.getIndexedType())) { 1567 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT; 1568 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT; 1569 case -2: return ICmpInst::BAD_ICMP_PREDICATE; 1570 } 1571 1572 // Ok, we ran out of things they have in common. If any leftovers 1573 // are non-zero then we have a difference, otherwise we are equal. 1574 for (; i < CE1->getNumOperands(); ++i) 1575 if (!CE1->getOperand(i)->isNullValue()) { 1576 if (isa<ConstantInt>(CE1->getOperand(i))) 1577 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1578 else 1579 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1580 } 1581 1582 for (; i < CE2->getNumOperands(); ++i) 1583 if (!CE2->getOperand(i)->isNullValue()) { 1584 if (isa<ConstantInt>(CE2->getOperand(i))) 1585 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1586 else 1587 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1588 } 1589 return ICmpInst::ICMP_EQ; 1590 } 1591 } 1592 } 1593 } 1594 default: 1595 break; 1596 } 1597 } 1598 1599 return ICmpInst::BAD_ICMP_PREDICATE; 1600 } 1601 1602 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 1603 Constant *C1, Constant *C2) { 1604 Type *ResultTy; 1605 if (VectorType *VT = dyn_cast<VectorType>(C1->getType())) 1606 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()), 1607 VT->getNumElements()); 1608 else 1609 ResultTy = Type::getInt1Ty(C1->getContext()); 1610 1611 // Fold FCMP_FALSE/FCMP_TRUE unconditionally. 1612 if (pred == FCmpInst::FCMP_FALSE) 1613 return Constant::getNullValue(ResultTy); 1614 1615 if (pred == FCmpInst::FCMP_TRUE) 1616 return Constant::getAllOnesValue(ResultTy); 1617 1618 // Handle some degenerate cases first 1619 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) { 1620 // For EQ and NE, we can always pick a value for the undef to make the 1621 // predicate pass or fail, so we can return undef. 1622 // Also, if both operands are undef, we can return undef. 1623 if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) || 1624 (isa<UndefValue>(C1) && isa<UndefValue>(C2))) 1625 return UndefValue::get(ResultTy); 1626 // Otherwise, pick the same value as the non-undef operand, and fold 1627 // it to true or false. 1628 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred)); 1629 } 1630 1631 // icmp eq/ne(null,GV) -> false/true 1632 if (C1->isNullValue()) { 1633 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2)) 1634 // Don't try to evaluate aliases. External weak GV can be null. 1635 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) { 1636 if (pred == ICmpInst::ICMP_EQ) 1637 return ConstantInt::getFalse(C1->getContext()); 1638 else if (pred == ICmpInst::ICMP_NE) 1639 return ConstantInt::getTrue(C1->getContext()); 1640 } 1641 // icmp eq/ne(GV,null) -> false/true 1642 } else if (C2->isNullValue()) { 1643 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1)) 1644 // Don't try to evaluate aliases. External weak GV can be null. 1645 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) { 1646 if (pred == ICmpInst::ICMP_EQ) 1647 return ConstantInt::getFalse(C1->getContext()); 1648 else if (pred == ICmpInst::ICMP_NE) 1649 return ConstantInt::getTrue(C1->getContext()); 1650 } 1651 } 1652 1653 // If the comparison is a comparison between two i1's, simplify it. 1654 if (C1->getType()->isIntegerTy(1)) { 1655 switch(pred) { 1656 case ICmpInst::ICMP_EQ: 1657 if (isa<ConstantInt>(C2)) 1658 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2)); 1659 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2); 1660 case ICmpInst::ICMP_NE: 1661 return ConstantExpr::getXor(C1, C2); 1662 default: 1663 break; 1664 } 1665 } 1666 1667 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) { 1668 APInt V1 = cast<ConstantInt>(C1)->getValue(); 1669 APInt V2 = cast<ConstantInt>(C2)->getValue(); 1670 switch (pred) { 1671 default: llvm_unreachable("Invalid ICmp Predicate"); 1672 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2); 1673 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2); 1674 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2)); 1675 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2)); 1676 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2)); 1677 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2)); 1678 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2)); 1679 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2)); 1680 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2)); 1681 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2)); 1682 } 1683 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) { 1684 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF(); 1685 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF(); 1686 APFloat::cmpResult R = C1V.compare(C2V); 1687 switch (pred) { 1688 default: llvm_unreachable("Invalid FCmp Predicate"); 1689 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy); 1690 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy); 1691 case FCmpInst::FCMP_UNO: 1692 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered); 1693 case FCmpInst::FCMP_ORD: 1694 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered); 1695 case FCmpInst::FCMP_UEQ: 1696 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1697 R==APFloat::cmpEqual); 1698 case FCmpInst::FCMP_OEQ: 1699 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual); 1700 case FCmpInst::FCMP_UNE: 1701 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual); 1702 case FCmpInst::FCMP_ONE: 1703 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan || 1704 R==APFloat::cmpGreaterThan); 1705 case FCmpInst::FCMP_ULT: 1706 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1707 R==APFloat::cmpLessThan); 1708 case FCmpInst::FCMP_OLT: 1709 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan); 1710 case FCmpInst::FCMP_UGT: 1711 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1712 R==APFloat::cmpGreaterThan); 1713 case FCmpInst::FCMP_OGT: 1714 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan); 1715 case FCmpInst::FCMP_ULE: 1716 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan); 1717 case FCmpInst::FCMP_OLE: 1718 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan || 1719 R==APFloat::cmpEqual); 1720 case FCmpInst::FCMP_UGE: 1721 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan); 1722 case FCmpInst::FCMP_OGE: 1723 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan || 1724 R==APFloat::cmpEqual); 1725 } 1726 } else if (C1->getType()->isVectorTy()) { 1727 // If we can constant fold the comparison of each element, constant fold 1728 // the whole vector comparison. 1729 SmallVector<Constant*, 4> ResElts; 1730 Type *Ty = IntegerType::get(C1->getContext(), 32); 1731 // Compare the elements, producing an i1 result or constant expr. 1732 for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){ 1733 Constant *C1E = 1734 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i)); 1735 Constant *C2E = 1736 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i)); 1737 1738 ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E)); 1739 } 1740 1741 return ConstantVector::get(ResElts); 1742 } 1743 1744 if (C1->getType()->isFloatingPointTy()) { 1745 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true. 1746 switch (evaluateFCmpRelation(C1, C2)) { 1747 default: llvm_unreachable("Unknown relation!"); 1748 case FCmpInst::FCMP_UNO: 1749 case FCmpInst::FCMP_ORD: 1750 case FCmpInst::FCMP_UEQ: 1751 case FCmpInst::FCMP_UNE: 1752 case FCmpInst::FCMP_ULT: 1753 case FCmpInst::FCMP_UGT: 1754 case FCmpInst::FCMP_ULE: 1755 case FCmpInst::FCMP_UGE: 1756 case FCmpInst::FCMP_TRUE: 1757 case FCmpInst::FCMP_FALSE: 1758 case FCmpInst::BAD_FCMP_PREDICATE: 1759 break; // Couldn't determine anything about these constants. 1760 case FCmpInst::FCMP_OEQ: // We know that C1 == C2 1761 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ || 1762 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE || 1763 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE); 1764 break; 1765 case FCmpInst::FCMP_OLT: // We know that C1 < C2 1766 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE || 1767 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT || 1768 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE); 1769 break; 1770 case FCmpInst::FCMP_OGT: // We know that C1 > C2 1771 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE || 1772 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT || 1773 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE); 1774 break; 1775 case FCmpInst::FCMP_OLE: // We know that C1 <= C2 1776 // We can only partially decide this relation. 1777 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 1778 Result = 0; 1779 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 1780 Result = 1; 1781 break; 1782 case FCmpInst::FCMP_OGE: // We known that C1 >= C2 1783 // We can only partially decide this relation. 1784 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 1785 Result = 0; 1786 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 1787 Result = 1; 1788 break; 1789 case FCmpInst::FCMP_ONE: // We know that C1 != C2 1790 // We can only partially decide this relation. 1791 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 1792 Result = 0; 1793 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 1794 Result = 1; 1795 break; 1796 } 1797 1798 // If we evaluated the result, return it now. 1799 if (Result != -1) 1800 return ConstantInt::get(ResultTy, Result); 1801 1802 } else { 1803 // Evaluate the relation between the two constants, per the predicate. 1804 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true. 1805 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) { 1806 default: llvm_unreachable("Unknown relational!"); 1807 case ICmpInst::BAD_ICMP_PREDICATE: 1808 break; // Couldn't determine anything about these constants. 1809 case ICmpInst::ICMP_EQ: // We know the constants are equal! 1810 // If we know the constants are equal, we can decide the result of this 1811 // computation precisely. 1812 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred); 1813 break; 1814 case ICmpInst::ICMP_ULT: 1815 switch (pred) { 1816 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE: 1817 Result = 1; break; 1818 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE: 1819 Result = 0; break; 1820 } 1821 break; 1822 case ICmpInst::ICMP_SLT: 1823 switch (pred) { 1824 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE: 1825 Result = 1; break; 1826 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE: 1827 Result = 0; break; 1828 } 1829 break; 1830 case ICmpInst::ICMP_UGT: 1831 switch (pred) { 1832 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE: 1833 Result = 1; break; 1834 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE: 1835 Result = 0; break; 1836 } 1837 break; 1838 case ICmpInst::ICMP_SGT: 1839 switch (pred) { 1840 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE: 1841 Result = 1; break; 1842 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE: 1843 Result = 0; break; 1844 } 1845 break; 1846 case ICmpInst::ICMP_ULE: 1847 if (pred == ICmpInst::ICMP_UGT) Result = 0; 1848 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1; 1849 break; 1850 case ICmpInst::ICMP_SLE: 1851 if (pred == ICmpInst::ICMP_SGT) Result = 0; 1852 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1; 1853 break; 1854 case ICmpInst::ICMP_UGE: 1855 if (pred == ICmpInst::ICMP_ULT) Result = 0; 1856 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1; 1857 break; 1858 case ICmpInst::ICMP_SGE: 1859 if (pred == ICmpInst::ICMP_SLT) Result = 0; 1860 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1; 1861 break; 1862 case ICmpInst::ICMP_NE: 1863 if (pred == ICmpInst::ICMP_EQ) Result = 0; 1864 if (pred == ICmpInst::ICMP_NE) Result = 1; 1865 break; 1866 } 1867 1868 // If we evaluated the result, return it now. 1869 if (Result != -1) 1870 return ConstantInt::get(ResultTy, Result); 1871 1872 // If the right hand side is a bitcast, try using its inverse to simplify 1873 // it by moving it to the left hand side. We can't do this if it would turn 1874 // a vector compare into a scalar compare or visa versa. 1875 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) { 1876 Constant *CE2Op0 = CE2->getOperand(0); 1877 if (CE2->getOpcode() == Instruction::BitCast && 1878 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) { 1879 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType()); 1880 return ConstantExpr::getICmp(pred, Inverse, CE2Op0); 1881 } 1882 } 1883 1884 // If the left hand side is an extension, try eliminating it. 1885 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 1886 if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) || 1887 (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){ 1888 Constant *CE1Op0 = CE1->getOperand(0); 1889 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType()); 1890 if (CE1Inverse == CE1Op0) { 1891 // Check whether we can safely truncate the right hand side. 1892 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType()); 1893 if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse, 1894 C2->getType()) == C2) 1895 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse); 1896 } 1897 } 1898 } 1899 1900 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) || 1901 (C1->isNullValue() && !C2->isNullValue())) { 1902 // If C2 is a constant expr and C1 isn't, flip them around and fold the 1903 // other way if possible. 1904 // Also, if C1 is null and C2 isn't, flip them around. 1905 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred); 1906 return ConstantExpr::getICmp(pred, C2, C1); 1907 } 1908 } 1909 return nullptr; 1910 } 1911 1912 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices 1913 /// is "inbounds". 1914 template<typename IndexTy> 1915 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) { 1916 // No indices means nothing that could be out of bounds. 1917 if (Idxs.empty()) return true; 1918 1919 // If the first index is zero, it's in bounds. 1920 if (cast<Constant>(Idxs[0])->isNullValue()) return true; 1921 1922 // If the first index is one and all the rest are zero, it's in bounds, 1923 // by the one-past-the-end rule. 1924 if (!cast<ConstantInt>(Idxs[0])->isOne()) 1925 return false; 1926 for (unsigned i = 1, e = Idxs.size(); i != e; ++i) 1927 if (!cast<Constant>(Idxs[i])->isNullValue()) 1928 return false; 1929 return true; 1930 } 1931 1932 /// \brief Test whether a given ConstantInt is in-range for a SequentialType. 1933 static bool isIndexInRangeOfSequentialType(const SequentialType *STy, 1934 const ConstantInt *CI) { 1935 if (const PointerType *PTy = dyn_cast<PointerType>(STy)) 1936 // Only handle pointers to sized types, not pointers to functions. 1937 return PTy->getElementType()->isSized(); 1938 1939 uint64_t NumElements = 0; 1940 // Determine the number of elements in our sequential type. 1941 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy)) 1942 NumElements = ATy->getNumElements(); 1943 else if (const VectorType *VTy = dyn_cast<VectorType>(STy)) 1944 NumElements = VTy->getNumElements(); 1945 1946 assert((isa<ArrayType>(STy) || NumElements > 0) && 1947 "didn't expect non-array type to have zero elements!"); 1948 1949 // We cannot bounds check the index if it doesn't fit in an int64_t. 1950 if (CI->getValue().getActiveBits() > 64) 1951 return false; 1952 1953 // A negative index or an index past the end of our sequential type is 1954 // considered out-of-range. 1955 int64_t IndexVal = CI->getSExtValue(); 1956 if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements)) 1957 return false; 1958 1959 // Otherwise, it is in-range. 1960 return true; 1961 } 1962 1963 template<typename IndexTy> 1964 static Constant *ConstantFoldGetElementPtrImpl(Constant *C, 1965 bool inBounds, 1966 ArrayRef<IndexTy> Idxs) { 1967 if (Idxs.empty()) return C; 1968 Constant *Idx0 = cast<Constant>(Idxs[0]); 1969 if ((Idxs.size() == 1 && Idx0->isNullValue())) 1970 return C; 1971 1972 if (isa<UndefValue>(C)) { 1973 PointerType *Ptr = cast<PointerType>(C->getType()); 1974 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs); 1975 assert(Ty && "Invalid indices for GEP!"); 1976 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace())); 1977 } 1978 1979 if (C->isNullValue()) { 1980 bool isNull = true; 1981 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) 1982 if (!cast<Constant>(Idxs[i])->isNullValue()) { 1983 isNull = false; 1984 break; 1985 } 1986 if (isNull) { 1987 PointerType *Ptr = cast<PointerType>(C->getType()); 1988 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs); 1989 assert(Ty && "Invalid indices for GEP!"); 1990 return ConstantPointerNull::get(PointerType::get(Ty, 1991 Ptr->getAddressSpace())); 1992 } 1993 } 1994 1995 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1996 // Combine Indices - If the source pointer to this getelementptr instruction 1997 // is a getelementptr instruction, combine the indices of the two 1998 // getelementptr instructions into a single instruction. 1999 // 2000 if (CE->getOpcode() == Instruction::GetElementPtr) { 2001 Type *LastTy = nullptr; 2002 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE); 2003 I != E; ++I) 2004 LastTy = *I; 2005 2006 // We cannot combine indices if doing so would take us outside of an 2007 // array or vector. Doing otherwise could trick us if we evaluated such a 2008 // GEP as part of a load. 2009 // 2010 // e.g. Consider if the original GEP was: 2011 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c, 2012 // i32 0, i32 0, i64 0) 2013 // 2014 // If we then tried to offset it by '8' to get to the third element, 2015 // an i8, we should *not* get: 2016 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c, 2017 // i32 0, i32 0, i64 8) 2018 // 2019 // This GEP tries to index array element '8 which runs out-of-bounds. 2020 // Subsequent evaluation would get confused and produce erroneous results. 2021 // 2022 // The following prohibits such a GEP from being formed by checking to see 2023 // if the index is in-range with respect to an array or vector. 2024 bool PerformFold = false; 2025 if (Idx0->isNullValue()) 2026 PerformFold = true; 2027 else if (SequentialType *STy = dyn_cast_or_null<SequentialType>(LastTy)) 2028 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0)) 2029 PerformFold = isIndexInRangeOfSequentialType(STy, CI); 2030 2031 if (PerformFold) { 2032 SmallVector<Value*, 16> NewIndices; 2033 NewIndices.reserve(Idxs.size() + CE->getNumOperands()); 2034 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i) 2035 NewIndices.push_back(CE->getOperand(i)); 2036 2037 // Add the last index of the source with the first index of the new GEP. 2038 // Make sure to handle the case when they are actually different types. 2039 Constant *Combined = CE->getOperand(CE->getNumOperands()-1); 2040 // Otherwise it must be an array. 2041 if (!Idx0->isNullValue()) { 2042 Type *IdxTy = Combined->getType(); 2043 if (IdxTy != Idx0->getType()) { 2044 Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext()); 2045 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty); 2046 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty); 2047 Combined = ConstantExpr::get(Instruction::Add, C1, C2); 2048 } else { 2049 Combined = 2050 ConstantExpr::get(Instruction::Add, Idx0, Combined); 2051 } 2052 } 2053 2054 NewIndices.push_back(Combined); 2055 NewIndices.append(Idxs.begin() + 1, Idxs.end()); 2056 return 2057 ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices, 2058 inBounds && 2059 cast<GEPOperator>(CE)->isInBounds()); 2060 } 2061 } 2062 2063 // Attempt to fold casts to the same type away. For example, folding: 2064 // 2065 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*), 2066 // i64 0, i64 0) 2067 // into: 2068 // 2069 // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0) 2070 // 2071 // Don't fold if the cast is changing address spaces. 2072 if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) { 2073 PointerType *SrcPtrTy = 2074 dyn_cast<PointerType>(CE->getOperand(0)->getType()); 2075 PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType()); 2076 if (SrcPtrTy && DstPtrTy) { 2077 ArrayType *SrcArrayTy = 2078 dyn_cast<ArrayType>(SrcPtrTy->getElementType()); 2079 ArrayType *DstArrayTy = 2080 dyn_cast<ArrayType>(DstPtrTy->getElementType()); 2081 if (SrcArrayTy && DstArrayTy 2082 && SrcArrayTy->getElementType() == DstArrayTy->getElementType() 2083 && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace()) 2084 return ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0), 2085 Idxs, inBounds); 2086 } 2087 } 2088 } 2089 2090 // Check to see if any array indices are not within the corresponding 2091 // notional array or vector bounds. If so, try to determine if they can be 2092 // factored out into preceding dimensions. 2093 bool Unknown = false; 2094 SmallVector<Constant *, 8> NewIdxs; 2095 Type *Ty = C->getType(); 2096 Type *Prev = nullptr; 2097 for (unsigned i = 0, e = Idxs.size(); i != e; 2098 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) { 2099 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) { 2100 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty)) 2101 if (CI->getSExtValue() > 0 && 2102 !isIndexInRangeOfSequentialType(cast<SequentialType>(Ty), CI)) { 2103 if (isa<SequentialType>(Prev)) { 2104 // It's out of range, but we can factor it into the prior 2105 // dimension. 2106 NewIdxs.resize(Idxs.size()); 2107 uint64_t NumElements = 0; 2108 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) 2109 NumElements = ATy->getNumElements(); 2110 else 2111 NumElements = cast<VectorType>(Ty)->getNumElements(); 2112 2113 ConstantInt *Factor = ConstantInt::get(CI->getType(), NumElements); 2114 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor); 2115 2116 Constant *PrevIdx = cast<Constant>(Idxs[i-1]); 2117 Constant *Div = ConstantExpr::getSDiv(CI, Factor); 2118 2119 // Before adding, extend both operands to i64 to avoid 2120 // overflow trouble. 2121 if (!PrevIdx->getType()->isIntegerTy(64)) 2122 PrevIdx = ConstantExpr::getSExt(PrevIdx, 2123 Type::getInt64Ty(Div->getContext())); 2124 if (!Div->getType()->isIntegerTy(64)) 2125 Div = ConstantExpr::getSExt(Div, 2126 Type::getInt64Ty(Div->getContext())); 2127 2128 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div); 2129 } else { 2130 // It's out of range, but the prior dimension is a struct 2131 // so we can't do anything about it. 2132 Unknown = true; 2133 } 2134 } 2135 } else { 2136 // We don't know if it's in range or not. 2137 Unknown = true; 2138 } 2139 } 2140 2141 // If we did any factoring, start over with the adjusted indices. 2142 if (!NewIdxs.empty()) { 2143 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) 2144 if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]); 2145 return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds); 2146 } 2147 2148 // If all indices are known integers and normalized, we can do a simple 2149 // check for the "inbounds" property. 2150 if (!Unknown && !inBounds) 2151 if (auto *GV = dyn_cast<GlobalVariable>(C)) 2152 if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs)) 2153 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs); 2154 2155 return nullptr; 2156 } 2157 2158 Constant *llvm::ConstantFoldGetElementPtr(Constant *C, 2159 bool inBounds, 2160 ArrayRef<Constant *> Idxs) { 2161 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs); 2162 } 2163 2164 Constant *llvm::ConstantFoldGetElementPtr(Constant *C, 2165 bool inBounds, 2166 ArrayRef<Value *> Idxs) { 2167 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs); 2168 } 2169