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 if (APFloat::opInvalidOp == 597 V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI, 598 APFloat::rmTowardZero, &ignored)) { 599 // Undefined behavior invoked - the destination type can't represent 600 // the input constant. 601 return UndefValue::get(DestTy); 602 } 603 APInt Val(DestBitWidth, x); 604 return ConstantInt::get(FPC->getContext(), Val); 605 } 606 return nullptr; // Can't fold. 607 case Instruction::IntToPtr: //always treated as unsigned 608 if (V->isNullValue()) // Is it an integral null value? 609 return ConstantPointerNull::get(cast<PointerType>(DestTy)); 610 return nullptr; // Other pointer types cannot be casted 611 case Instruction::PtrToInt: // always treated as unsigned 612 // Is it a null pointer value? 613 if (V->isNullValue()) 614 return ConstantInt::get(DestTy, 0); 615 // If this is a sizeof-like expression, pull out multiplications by 616 // known factors to expose them to subsequent folding. If it's an 617 // alignof-like expression, factor out known factors. 618 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 619 if (CE->getOpcode() == Instruction::GetElementPtr && 620 CE->getOperand(0)->isNullValue()) { 621 Type *Ty = 622 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 623 if (CE->getNumOperands() == 2) { 624 // Handle a sizeof-like expression. 625 Constant *Idx = CE->getOperand(1); 626 bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne(); 627 if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) { 628 Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true, 629 DestTy, false), 630 Idx, DestTy); 631 return ConstantExpr::getMul(C, Idx); 632 } 633 } else if (CE->getNumOperands() == 3 && 634 CE->getOperand(1)->isNullValue()) { 635 // Handle an alignof-like expression. 636 if (StructType *STy = dyn_cast<StructType>(Ty)) 637 if (!STy->isPacked()) { 638 ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2)); 639 if (CI->isOne() && 640 STy->getNumElements() == 2 && 641 STy->getElementType(0)->isIntegerTy(1)) { 642 return getFoldedAlignOf(STy->getElementType(1), DestTy, false); 643 } 644 } 645 // Handle an offsetof-like expression. 646 if (Ty->isStructTy() || Ty->isArrayTy()) { 647 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2), 648 DestTy, false)) 649 return C; 650 } 651 } 652 } 653 // Other pointer types cannot be casted 654 return nullptr; 655 case Instruction::UIToFP: 656 case Instruction::SIToFP: 657 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 658 APInt api = CI->getValue(); 659 APFloat apf(DestTy->getFltSemantics(), 660 APInt::getNullValue(DestTy->getPrimitiveSizeInBits())); 661 if (APFloat::opOverflow & 662 apf.convertFromAPInt(api, opc==Instruction::SIToFP, 663 APFloat::rmNearestTiesToEven)) { 664 // Undefined behavior invoked - the destination type can't represent 665 // the input constant. 666 return UndefValue::get(DestTy); 667 } 668 return ConstantFP::get(V->getContext(), apf); 669 } 670 return nullptr; 671 case Instruction::ZExt: 672 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 673 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 674 return ConstantInt::get(V->getContext(), 675 CI->getValue().zext(BitWidth)); 676 } 677 return nullptr; 678 case Instruction::SExt: 679 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 680 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 681 return ConstantInt::get(V->getContext(), 682 CI->getValue().sext(BitWidth)); 683 } 684 return nullptr; 685 case Instruction::Trunc: { 686 if (V->getType()->isVectorTy()) 687 return nullptr; 688 689 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 690 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 691 return ConstantInt::get(V->getContext(), 692 CI->getValue().trunc(DestBitWidth)); 693 } 694 695 // The input must be a constantexpr. See if we can simplify this based on 696 // the bytes we are demanding. Only do this if the source and dest are an 697 // even multiple of a byte. 698 if ((DestBitWidth & 7) == 0 && 699 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0) 700 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8)) 701 return Res; 702 703 return nullptr; 704 } 705 case Instruction::BitCast: 706 return FoldBitCast(V, DestTy); 707 case Instruction::AddrSpaceCast: 708 return nullptr; 709 } 710 } 711 712 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond, 713 Constant *V1, Constant *V2) { 714 // Check for i1 and vector true/false conditions. 715 if (Cond->isNullValue()) return V2; 716 if (Cond->isAllOnesValue()) return V1; 717 718 // If the condition is a vector constant, fold the result elementwise. 719 if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) { 720 SmallVector<Constant*, 16> Result; 721 Type *Ty = IntegerType::get(CondV->getContext(), 32); 722 for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){ 723 Constant *V; 724 Constant *V1Element = ConstantExpr::getExtractElement(V1, 725 ConstantInt::get(Ty, i)); 726 Constant *V2Element = ConstantExpr::getExtractElement(V2, 727 ConstantInt::get(Ty, i)); 728 Constant *Cond = dyn_cast<Constant>(CondV->getOperand(i)); 729 if (V1Element == V2Element) { 730 V = V1Element; 731 } else if (isa<UndefValue>(Cond)) { 732 V = isa<UndefValue>(V1Element) ? V1Element : V2Element; 733 } else { 734 if (!isa<ConstantInt>(Cond)) break; 735 V = Cond->isNullValue() ? V2Element : V1Element; 736 } 737 Result.push_back(V); 738 } 739 740 // If we were able to build the vector, return it. 741 if (Result.size() == V1->getType()->getVectorNumElements()) 742 return ConstantVector::get(Result); 743 } 744 745 if (isa<UndefValue>(Cond)) { 746 if (isa<UndefValue>(V1)) return V1; 747 return V2; 748 } 749 if (isa<UndefValue>(V1)) return V2; 750 if (isa<UndefValue>(V2)) return V1; 751 if (V1 == V2) return V1; 752 753 if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) { 754 if (TrueVal->getOpcode() == Instruction::Select) 755 if (TrueVal->getOperand(0) == Cond) 756 return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2); 757 } 758 if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) { 759 if (FalseVal->getOpcode() == Instruction::Select) 760 if (FalseVal->getOperand(0) == Cond) 761 return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2)); 762 } 763 764 return nullptr; 765 } 766 767 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val, 768 Constant *Idx) { 769 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef 770 return UndefValue::get(Val->getType()->getVectorElementType()); 771 if (Val->isNullValue()) // ee(zero, x) -> zero 772 return Constant::getNullValue(Val->getType()->getVectorElementType()); 773 // ee({w,x,y,z}, undef) -> undef 774 if (isa<UndefValue>(Idx)) 775 return UndefValue::get(Val->getType()->getVectorElementType()); 776 777 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) { 778 uint64_t Index = CIdx->getZExtValue(); 779 // ee({w,x,y,z}, wrong_value) -> undef 780 if (Index >= Val->getType()->getVectorNumElements()) 781 return UndefValue::get(Val->getType()->getVectorElementType()); 782 return Val->getAggregateElement(Index); 783 } 784 return nullptr; 785 } 786 787 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val, 788 Constant *Elt, 789 Constant *Idx) { 790 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx); 791 if (!CIdx) return nullptr; 792 const APInt &IdxVal = CIdx->getValue(); 793 794 SmallVector<Constant*, 16> Result; 795 Type *Ty = IntegerType::get(Val->getContext(), 32); 796 for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){ 797 if (i == IdxVal) { 798 Result.push_back(Elt); 799 continue; 800 } 801 802 Constant *C = 803 ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i)); 804 Result.push_back(C); 805 } 806 807 return ConstantVector::get(Result); 808 } 809 810 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1, 811 Constant *V2, 812 Constant *Mask) { 813 unsigned MaskNumElts = Mask->getType()->getVectorNumElements(); 814 Type *EltTy = V1->getType()->getVectorElementType(); 815 816 // Undefined shuffle mask -> undefined value. 817 if (isa<UndefValue>(Mask)) 818 return UndefValue::get(VectorType::get(EltTy, MaskNumElts)); 819 820 // Don't break the bitcode reader hack. 821 if (isa<ConstantExpr>(Mask)) return nullptr; 822 823 unsigned SrcNumElts = V1->getType()->getVectorNumElements(); 824 825 // Loop over the shuffle mask, evaluating each element. 826 SmallVector<Constant*, 32> Result; 827 for (unsigned i = 0; i != MaskNumElts; ++i) { 828 int Elt = ShuffleVectorInst::getMaskValue(Mask, i); 829 if (Elt == -1) { 830 Result.push_back(UndefValue::get(EltTy)); 831 continue; 832 } 833 Constant *InElt; 834 if (unsigned(Elt) >= SrcNumElts*2) 835 InElt = UndefValue::get(EltTy); 836 else if (unsigned(Elt) >= SrcNumElts) { 837 Type *Ty = IntegerType::get(V2->getContext(), 32); 838 InElt = 839 ConstantExpr::getExtractElement(V2, 840 ConstantInt::get(Ty, Elt - SrcNumElts)); 841 } else { 842 Type *Ty = IntegerType::get(V1->getContext(), 32); 843 InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt)); 844 } 845 Result.push_back(InElt); 846 } 847 848 return ConstantVector::get(Result); 849 } 850 851 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg, 852 ArrayRef<unsigned> Idxs) { 853 // Base case: no indices, so return the entire value. 854 if (Idxs.empty()) 855 return Agg; 856 857 if (Constant *C = Agg->getAggregateElement(Idxs[0])) 858 return ConstantFoldExtractValueInstruction(C, Idxs.slice(1)); 859 860 return nullptr; 861 } 862 863 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg, 864 Constant *Val, 865 ArrayRef<unsigned> Idxs) { 866 // Base case: no indices, so replace the entire value. 867 if (Idxs.empty()) 868 return Val; 869 870 unsigned NumElts; 871 if (StructType *ST = dyn_cast<StructType>(Agg->getType())) 872 NumElts = ST->getNumElements(); 873 else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType())) 874 NumElts = AT->getNumElements(); 875 else 876 NumElts = Agg->getType()->getVectorNumElements(); 877 878 SmallVector<Constant*, 32> Result; 879 for (unsigned i = 0; i != NumElts; ++i) { 880 Constant *C = Agg->getAggregateElement(i); 881 if (!C) return nullptr; 882 883 if (Idxs[0] == i) 884 C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1)); 885 886 Result.push_back(C); 887 } 888 889 if (StructType *ST = dyn_cast<StructType>(Agg->getType())) 890 return ConstantStruct::get(ST, Result); 891 if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType())) 892 return ConstantArray::get(AT, Result); 893 return ConstantVector::get(Result); 894 } 895 896 897 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode, 898 Constant *C1, Constant *C2) { 899 // Handle UndefValue up front. 900 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) { 901 switch (Opcode) { 902 case Instruction::Xor: 903 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) 904 // Handle undef ^ undef -> 0 special case. This is a common 905 // idiom (misuse). 906 return Constant::getNullValue(C1->getType()); 907 // Fallthrough 908 case Instruction::Add: 909 case Instruction::Sub: 910 return UndefValue::get(C1->getType()); 911 case Instruction::And: 912 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef 913 return C1; 914 return Constant::getNullValue(C1->getType()); // undef & X -> 0 915 case Instruction::Mul: { 916 ConstantInt *CI; 917 // X * undef -> undef if X is odd or undef 918 if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) || 919 ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) || 920 (isa<UndefValue>(C1) && isa<UndefValue>(C2))) 921 return UndefValue::get(C1->getType()); 922 923 // X * undef -> 0 otherwise 924 return Constant::getNullValue(C1->getType()); 925 } 926 case Instruction::UDiv: 927 case Instruction::SDiv: 928 // undef / 1 -> undef 929 if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv) 930 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) 931 if (CI2->isOne()) 932 return C1; 933 // FALL THROUGH 934 case Instruction::URem: 935 case Instruction::SRem: 936 if (!isa<UndefValue>(C2)) // undef / X -> 0 937 return Constant::getNullValue(C1->getType()); 938 return C2; // X / undef -> undef 939 case Instruction::Or: // X | undef -> -1 940 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef 941 return C1; 942 return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0 943 case Instruction::LShr: 944 if (isa<UndefValue>(C2) && isa<UndefValue>(C1)) 945 return C1; // undef lshr undef -> undef 946 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0 947 // undef lshr X -> 0 948 case Instruction::AShr: 949 if (!isa<UndefValue>(C2)) // undef ashr X --> all ones 950 return Constant::getAllOnesValue(C1->getType()); 951 else if (isa<UndefValue>(C1)) 952 return C1; // undef ashr undef -> undef 953 else 954 return C1; // X ashr undef --> X 955 case Instruction::Shl: 956 if (isa<UndefValue>(C2) && isa<UndefValue>(C1)) 957 return C1; // undef shl undef -> undef 958 // undef << X -> 0 or X << undef -> 0 959 return Constant::getNullValue(C1->getType()); 960 } 961 } 962 963 // Handle simplifications when the RHS is a constant int. 964 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) { 965 switch (Opcode) { 966 case Instruction::Add: 967 if (CI2->equalsInt(0)) return C1; // X + 0 == X 968 break; 969 case Instruction::Sub: 970 if (CI2->equalsInt(0)) return C1; // X - 0 == X 971 break; 972 case Instruction::Mul: 973 if (CI2->equalsInt(0)) return C2; // X * 0 == 0 974 if (CI2->equalsInt(1)) 975 return C1; // X * 1 == X 976 break; 977 case Instruction::UDiv: 978 case Instruction::SDiv: 979 if (CI2->equalsInt(1)) 980 return C1; // X / 1 == X 981 if (CI2->equalsInt(0)) 982 return UndefValue::get(CI2->getType()); // X / 0 == undef 983 break; 984 case Instruction::URem: 985 case Instruction::SRem: 986 if (CI2->equalsInt(1)) 987 return Constant::getNullValue(CI2->getType()); // X % 1 == 0 988 if (CI2->equalsInt(0)) 989 return UndefValue::get(CI2->getType()); // X % 0 == undef 990 break; 991 case Instruction::And: 992 if (CI2->isZero()) return C2; // X & 0 == 0 993 if (CI2->isAllOnesValue()) 994 return C1; // X & -1 == X 995 996 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 997 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64) 998 if (CE1->getOpcode() == Instruction::ZExt) { 999 unsigned DstWidth = CI2->getType()->getBitWidth(); 1000 unsigned SrcWidth = 1001 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits(); 1002 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth)); 1003 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits) 1004 return C1; 1005 } 1006 1007 // If and'ing the address of a global with a constant, fold it. 1008 if (CE1->getOpcode() == Instruction::PtrToInt && 1009 isa<GlobalValue>(CE1->getOperand(0))) { 1010 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0)); 1011 1012 // Functions are at least 4-byte aligned. 1013 unsigned GVAlign = GV->getAlignment(); 1014 if (isa<Function>(GV)) 1015 GVAlign = std::max(GVAlign, 4U); 1016 1017 if (GVAlign > 1) { 1018 unsigned DstWidth = CI2->getType()->getBitWidth(); 1019 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign)); 1020 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth)); 1021 1022 // If checking bits we know are clear, return zero. 1023 if ((CI2->getValue() & BitsNotSet) == CI2->getValue()) 1024 return Constant::getNullValue(CI2->getType()); 1025 } 1026 } 1027 } 1028 break; 1029 case Instruction::Or: 1030 if (CI2->equalsInt(0)) return C1; // X | 0 == X 1031 if (CI2->isAllOnesValue()) 1032 return C2; // X | -1 == -1 1033 break; 1034 case Instruction::Xor: 1035 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X 1036 1037 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 1038 switch (CE1->getOpcode()) { 1039 default: break; 1040 case Instruction::ICmp: 1041 case Instruction::FCmp: 1042 // cmp pred ^ true -> cmp !pred 1043 assert(CI2->equalsInt(1)); 1044 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate(); 1045 pred = CmpInst::getInversePredicate(pred); 1046 return ConstantExpr::getCompare(pred, CE1->getOperand(0), 1047 CE1->getOperand(1)); 1048 } 1049 } 1050 break; 1051 case Instruction::AShr: 1052 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2 1053 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) 1054 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero. 1055 return ConstantExpr::getLShr(C1, C2); 1056 break; 1057 } 1058 } else if (isa<ConstantInt>(C1)) { 1059 // If C1 is a ConstantInt and C2 is not, swap the operands. 1060 if (Instruction::isCommutative(Opcode)) 1061 return ConstantExpr::get(Opcode, C2, C1); 1062 } 1063 1064 // At this point we know neither constant is an UndefValue. 1065 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) { 1066 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) { 1067 const APInt &C1V = CI1->getValue(); 1068 const APInt &C2V = CI2->getValue(); 1069 switch (Opcode) { 1070 default: 1071 break; 1072 case Instruction::Add: 1073 return ConstantInt::get(CI1->getContext(), C1V + C2V); 1074 case Instruction::Sub: 1075 return ConstantInt::get(CI1->getContext(), C1V - C2V); 1076 case Instruction::Mul: 1077 return ConstantInt::get(CI1->getContext(), C1V * C2V); 1078 case Instruction::UDiv: 1079 assert(!CI2->isNullValue() && "Div by zero handled above"); 1080 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V)); 1081 case Instruction::SDiv: 1082 assert(!CI2->isNullValue() && "Div by zero handled above"); 1083 if (C2V.isAllOnesValue() && C1V.isMinSignedValue()) 1084 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef 1085 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V)); 1086 case Instruction::URem: 1087 assert(!CI2->isNullValue() && "Div by zero handled above"); 1088 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V)); 1089 case Instruction::SRem: 1090 assert(!CI2->isNullValue() && "Div by zero handled above"); 1091 if (C2V.isAllOnesValue() && C1V.isMinSignedValue()) 1092 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef 1093 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V)); 1094 case Instruction::And: 1095 return ConstantInt::get(CI1->getContext(), C1V & C2V); 1096 case Instruction::Or: 1097 return ConstantInt::get(CI1->getContext(), C1V | C2V); 1098 case Instruction::Xor: 1099 return ConstantInt::get(CI1->getContext(), C1V ^ C2V); 1100 case Instruction::Shl: { 1101 uint32_t shiftAmt = C2V.getZExtValue(); 1102 if (shiftAmt < C1V.getBitWidth()) 1103 return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt)); 1104 else 1105 return UndefValue::get(C1->getType()); // too big shift is undef 1106 } 1107 case Instruction::LShr: { 1108 uint32_t shiftAmt = C2V.getZExtValue(); 1109 if (shiftAmt < C1V.getBitWidth()) 1110 return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt)); 1111 else 1112 return UndefValue::get(C1->getType()); // too big shift is undef 1113 } 1114 case Instruction::AShr: { 1115 uint32_t shiftAmt = C2V.getZExtValue(); 1116 if (shiftAmt < C1V.getBitWidth()) 1117 return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt)); 1118 else 1119 return UndefValue::get(C1->getType()); // too big shift is undef 1120 } 1121 } 1122 } 1123 1124 switch (Opcode) { 1125 case Instruction::SDiv: 1126 case Instruction::UDiv: 1127 case Instruction::URem: 1128 case Instruction::SRem: 1129 case Instruction::LShr: 1130 case Instruction::AShr: 1131 case Instruction::Shl: 1132 if (CI1->equalsInt(0)) return C1; 1133 break; 1134 default: 1135 break; 1136 } 1137 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) { 1138 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) { 1139 APFloat C1V = CFP1->getValueAPF(); 1140 APFloat C2V = CFP2->getValueAPF(); 1141 APFloat C3V = C1V; // copy for modification 1142 switch (Opcode) { 1143 default: 1144 break; 1145 case Instruction::FAdd: 1146 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven); 1147 return ConstantFP::get(C1->getContext(), C3V); 1148 case Instruction::FSub: 1149 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven); 1150 return ConstantFP::get(C1->getContext(), C3V); 1151 case Instruction::FMul: 1152 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven); 1153 return ConstantFP::get(C1->getContext(), C3V); 1154 case Instruction::FDiv: 1155 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven); 1156 return ConstantFP::get(C1->getContext(), C3V); 1157 case Instruction::FRem: 1158 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven); 1159 return ConstantFP::get(C1->getContext(), C3V); 1160 } 1161 } 1162 } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) { 1163 // Perform elementwise folding. 1164 SmallVector<Constant*, 16> Result; 1165 Type *Ty = IntegerType::get(VTy->getContext(), 32); 1166 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 1167 Constant *LHS = 1168 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i)); 1169 Constant *RHS = 1170 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i)); 1171 1172 Result.push_back(ConstantExpr::get(Opcode, LHS, RHS)); 1173 } 1174 1175 return ConstantVector::get(Result); 1176 } 1177 1178 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 1179 // There are many possible foldings we could do here. We should probably 1180 // at least fold add of a pointer with an integer into the appropriate 1181 // getelementptr. This will improve alias analysis a bit. 1182 1183 // Given ((a + b) + c), if (b + c) folds to something interesting, return 1184 // (a + (b + c)). 1185 if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) { 1186 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2); 1187 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode) 1188 return ConstantExpr::get(Opcode, CE1->getOperand(0), T); 1189 } 1190 } else if (isa<ConstantExpr>(C2)) { 1191 // If C2 is a constant expr and C1 isn't, flop them around and fold the 1192 // other way if possible. 1193 if (Instruction::isCommutative(Opcode)) 1194 return ConstantFoldBinaryInstruction(Opcode, C2, C1); 1195 } 1196 1197 // i1 can be simplified in many cases. 1198 if (C1->getType()->isIntegerTy(1)) { 1199 switch (Opcode) { 1200 case Instruction::Add: 1201 case Instruction::Sub: 1202 return ConstantExpr::getXor(C1, C2); 1203 case Instruction::Mul: 1204 return ConstantExpr::getAnd(C1, C2); 1205 case Instruction::Shl: 1206 case Instruction::LShr: 1207 case Instruction::AShr: 1208 // We can assume that C2 == 0. If it were one the result would be 1209 // undefined because the shift value is as large as the bitwidth. 1210 return C1; 1211 case Instruction::SDiv: 1212 case Instruction::UDiv: 1213 // We can assume that C2 == 1. If it were zero the result would be 1214 // undefined through division by zero. 1215 return C1; 1216 case Instruction::URem: 1217 case Instruction::SRem: 1218 // We can assume that C2 == 1. If it were zero the result would be 1219 // undefined through division by zero. 1220 return ConstantInt::getFalse(C1->getContext()); 1221 default: 1222 break; 1223 } 1224 } 1225 1226 // We don't know how to fold this. 1227 return nullptr; 1228 } 1229 1230 /// isZeroSizedType - This type is zero sized if its an array or structure of 1231 /// zero sized types. The only leaf zero sized type is an empty structure. 1232 static bool isMaybeZeroSizedType(Type *Ty) { 1233 if (StructType *STy = dyn_cast<StructType>(Ty)) { 1234 if (STy->isOpaque()) return true; // Can't say. 1235 1236 // If all of elements have zero size, this does too. 1237 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 1238 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false; 1239 return true; 1240 1241 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1242 return isMaybeZeroSizedType(ATy->getElementType()); 1243 } 1244 return false; 1245 } 1246 1247 /// IdxCompare - Compare the two constants as though they were getelementptr 1248 /// indices. This allows coersion of the types to be the same thing. 1249 /// 1250 /// If the two constants are the "same" (after coersion), return 0. If the 1251 /// first is less than the second, return -1, if the second is less than the 1252 /// first, return 1. If the constants are not integral, return -2. 1253 /// 1254 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) { 1255 if (C1 == C2) return 0; 1256 1257 // Ok, we found a different index. If they are not ConstantInt, we can't do 1258 // anything with them. 1259 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2)) 1260 return -2; // don't know! 1261 1262 // Ok, we have two differing integer indices. Sign extend them to be the same 1263 // type. Long is always big enough, so we use it. 1264 if (!C1->getType()->isIntegerTy(64)) 1265 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext())); 1266 1267 if (!C2->getType()->isIntegerTy(64)) 1268 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext())); 1269 1270 if (C1 == C2) return 0; // They are equal 1271 1272 // If the type being indexed over is really just a zero sized type, there is 1273 // no pointer difference being made here. 1274 if (isMaybeZeroSizedType(ElTy)) 1275 return -2; // dunno. 1276 1277 // If they are really different, now that they are the same type, then we 1278 // found a difference! 1279 if (cast<ConstantInt>(C1)->getSExtValue() < 1280 cast<ConstantInt>(C2)->getSExtValue()) 1281 return -1; 1282 else 1283 return 1; 1284 } 1285 1286 /// evaluateFCmpRelation - This function determines if there is anything we can 1287 /// decide about the two constants provided. This doesn't need to handle simple 1288 /// things like ConstantFP comparisons, but should instead handle ConstantExprs. 1289 /// If we can determine that the two constants have a particular relation to 1290 /// each other, we should return the corresponding FCmpInst predicate, 1291 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in 1292 /// ConstantFoldCompareInstruction. 1293 /// 1294 /// To simplify this code we canonicalize the relation so that the first 1295 /// operand is always the most "complex" of the two. We consider ConstantFP 1296 /// to be the simplest, and ConstantExprs to be the most complex. 1297 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) { 1298 assert(V1->getType() == V2->getType() && 1299 "Cannot compare values of different types!"); 1300 1301 // Handle degenerate case quickly 1302 if (V1 == V2) return FCmpInst::FCMP_OEQ; 1303 1304 if (!isa<ConstantExpr>(V1)) { 1305 if (!isa<ConstantExpr>(V2)) { 1306 // We distilled thisUse the standard constant folder for a few cases 1307 ConstantInt *R = nullptr; 1308 R = dyn_cast<ConstantInt>( 1309 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2)); 1310 if (R && !R->isZero()) 1311 return FCmpInst::FCMP_OEQ; 1312 R = dyn_cast<ConstantInt>( 1313 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2)); 1314 if (R && !R->isZero()) 1315 return FCmpInst::FCMP_OLT; 1316 R = dyn_cast<ConstantInt>( 1317 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2)); 1318 if (R && !R->isZero()) 1319 return FCmpInst::FCMP_OGT; 1320 1321 // Nothing more we can do 1322 return FCmpInst::BAD_FCMP_PREDICATE; 1323 } 1324 1325 // If the first operand is simple and second is ConstantExpr, swap operands. 1326 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1); 1327 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE) 1328 return FCmpInst::getSwappedPredicate(SwappedRelation); 1329 } else { 1330 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a 1331 // constantexpr or a simple constant. 1332 ConstantExpr *CE1 = cast<ConstantExpr>(V1); 1333 switch (CE1->getOpcode()) { 1334 case Instruction::FPTrunc: 1335 case Instruction::FPExt: 1336 case Instruction::UIToFP: 1337 case Instruction::SIToFP: 1338 // We might be able to do something with these but we don't right now. 1339 break; 1340 default: 1341 break; 1342 } 1343 } 1344 // There are MANY other foldings that we could perform here. They will 1345 // probably be added on demand, as they seem needed. 1346 return FCmpInst::BAD_FCMP_PREDICATE; 1347 } 1348 1349 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1, 1350 const GlobalValue *GV2) { 1351 // Don't try to decide equality of aliases. 1352 if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2)) 1353 if (!GV1->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage()) 1354 return ICmpInst::ICMP_NE; 1355 return ICmpInst::BAD_ICMP_PREDICATE; 1356 } 1357 1358 /// evaluateICmpRelation - This function determines if there is anything we can 1359 /// decide about the two constants provided. This doesn't need to handle simple 1360 /// things like integer comparisons, but should instead handle ConstantExprs 1361 /// and GlobalValues. If we can determine that the two constants have a 1362 /// particular relation to each other, we should return the corresponding ICmp 1363 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE. 1364 /// 1365 /// To simplify this code we canonicalize the relation so that the first 1366 /// operand is always the most "complex" of the two. We consider simple 1367 /// constants (like ConstantInt) to be the simplest, followed by 1368 /// GlobalValues, followed by ConstantExpr's (the most complex). 1369 /// 1370 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2, 1371 bool isSigned) { 1372 assert(V1->getType() == V2->getType() && 1373 "Cannot compare different types of values!"); 1374 if (V1 == V2) return ICmpInst::ICMP_EQ; 1375 1376 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) && 1377 !isa<BlockAddress>(V1)) { 1378 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) && 1379 !isa<BlockAddress>(V2)) { 1380 // We distilled this down to a simple case, use the standard constant 1381 // folder. 1382 ConstantInt *R = nullptr; 1383 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ; 1384 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1385 if (R && !R->isZero()) 1386 return pred; 1387 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1388 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1389 if (R && !R->isZero()) 1390 return pred; 1391 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1392 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1393 if (R && !R->isZero()) 1394 return pred; 1395 1396 // If we couldn't figure it out, bail. 1397 return ICmpInst::BAD_ICMP_PREDICATE; 1398 } 1399 1400 // If the first operand is simple, swap operands. 1401 ICmpInst::Predicate SwappedRelation = 1402 evaluateICmpRelation(V2, V1, isSigned); 1403 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1404 return ICmpInst::getSwappedPredicate(SwappedRelation); 1405 1406 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) { 1407 if (isa<ConstantExpr>(V2)) { // Swap as necessary. 1408 ICmpInst::Predicate SwappedRelation = 1409 evaluateICmpRelation(V2, V1, isSigned); 1410 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1411 return ICmpInst::getSwappedPredicate(SwappedRelation); 1412 return ICmpInst::BAD_ICMP_PREDICATE; 1413 } 1414 1415 // Now we know that the RHS is a GlobalValue, BlockAddress or simple 1416 // constant (which, since the types must match, means that it's a 1417 // ConstantPointerNull). 1418 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) { 1419 return areGlobalsPotentiallyEqual(GV, GV2); 1420 } else if (isa<BlockAddress>(V2)) { 1421 return ICmpInst::ICMP_NE; // Globals never equal labels. 1422 } else { 1423 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!"); 1424 // GlobalVals can never be null unless they have external weak linkage. 1425 // We don't try to evaluate aliases here. 1426 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV)) 1427 return ICmpInst::ICMP_NE; 1428 } 1429 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) { 1430 if (isa<ConstantExpr>(V2)) { // Swap as necessary. 1431 ICmpInst::Predicate SwappedRelation = 1432 evaluateICmpRelation(V2, V1, isSigned); 1433 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1434 return ICmpInst::getSwappedPredicate(SwappedRelation); 1435 return ICmpInst::BAD_ICMP_PREDICATE; 1436 } 1437 1438 // Now we know that the RHS is a GlobalValue, BlockAddress or simple 1439 // constant (which, since the types must match, means that it is a 1440 // ConstantPointerNull). 1441 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) { 1442 // Block address in another function can't equal this one, but block 1443 // addresses in the current function might be the same if blocks are 1444 // empty. 1445 if (BA2->getFunction() != BA->getFunction()) 1446 return ICmpInst::ICMP_NE; 1447 } else { 1448 // Block addresses aren't null, don't equal the address of globals. 1449 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) && 1450 "Canonicalization guarantee!"); 1451 return ICmpInst::ICMP_NE; 1452 } 1453 } else { 1454 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a 1455 // constantexpr, a global, block address, or a simple constant. 1456 ConstantExpr *CE1 = cast<ConstantExpr>(V1); 1457 Constant *CE1Op0 = CE1->getOperand(0); 1458 1459 switch (CE1->getOpcode()) { 1460 case Instruction::Trunc: 1461 case Instruction::FPTrunc: 1462 case Instruction::FPExt: 1463 case Instruction::FPToUI: 1464 case Instruction::FPToSI: 1465 break; // We can't evaluate floating point casts or truncations. 1466 1467 case Instruction::UIToFP: 1468 case Instruction::SIToFP: 1469 case Instruction::BitCast: 1470 case Instruction::ZExt: 1471 case Instruction::SExt: 1472 // If the cast is not actually changing bits, and the second operand is a 1473 // null pointer, do the comparison with the pre-casted value. 1474 if (V2->isNullValue() && 1475 (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) { 1476 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false; 1477 if (CE1->getOpcode() == Instruction::SExt) isSigned = true; 1478 return evaluateICmpRelation(CE1Op0, 1479 Constant::getNullValue(CE1Op0->getType()), 1480 isSigned); 1481 } 1482 break; 1483 1484 case Instruction::GetElementPtr: { 1485 GEPOperator *CE1GEP = cast<GEPOperator>(CE1); 1486 // Ok, since this is a getelementptr, we know that the constant has a 1487 // pointer type. Check the various cases. 1488 if (isa<ConstantPointerNull>(V2)) { 1489 // If we are comparing a GEP to a null pointer, check to see if the base 1490 // of the GEP equals the null pointer. 1491 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) { 1492 if (GV->hasExternalWeakLinkage()) 1493 // Weak linkage GVals could be zero or not. We're comparing that 1494 // to null pointer so its greater-or-equal 1495 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 1496 else 1497 // If its not weak linkage, the GVal must have a non-zero address 1498 // so the result is greater-than 1499 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1500 } else if (isa<ConstantPointerNull>(CE1Op0)) { 1501 // If we are indexing from a null pointer, check to see if we have any 1502 // non-zero indices. 1503 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i) 1504 if (!CE1->getOperand(i)->isNullValue()) 1505 // Offsetting from null, must not be equal. 1506 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1507 // Only zero indexes from null, must still be zero. 1508 return ICmpInst::ICMP_EQ; 1509 } 1510 // Otherwise, we can't really say if the first operand is null or not. 1511 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) { 1512 if (isa<ConstantPointerNull>(CE1Op0)) { 1513 if (GV2->hasExternalWeakLinkage()) 1514 // Weak linkage GVals could be zero or not. We're comparing it to 1515 // a null pointer, so its less-or-equal 1516 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 1517 else 1518 // If its not weak linkage, the GVal must have a non-zero address 1519 // so the result is less-than 1520 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1521 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) { 1522 if (GV == GV2) { 1523 // If this is a getelementptr of the same global, then it must be 1524 // different. Because the types must match, the getelementptr could 1525 // only have at most one index, and because we fold getelementptr's 1526 // with a single zero index, it must be nonzero. 1527 assert(CE1->getNumOperands() == 2 && 1528 !CE1->getOperand(1)->isNullValue() && 1529 "Surprising getelementptr!"); 1530 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1531 } else { 1532 if (CE1GEP->hasAllZeroIndices()) 1533 return areGlobalsPotentiallyEqual(GV, GV2); 1534 return ICmpInst::BAD_ICMP_PREDICATE; 1535 } 1536 } 1537 } else { 1538 ConstantExpr *CE2 = cast<ConstantExpr>(V2); 1539 Constant *CE2Op0 = CE2->getOperand(0); 1540 1541 // There are MANY other foldings that we could perform here. They will 1542 // probably be added on demand, as they seem needed. 1543 switch (CE2->getOpcode()) { 1544 default: break; 1545 case Instruction::GetElementPtr: 1546 // By far the most common case to handle is when the base pointers are 1547 // obviously to the same global. 1548 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) { 1549 // Don't know relative ordering, but check for inequality. 1550 if (CE1Op0 != CE2Op0) { 1551 GEPOperator *CE2GEP = cast<GEPOperator>(CE2); 1552 if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices()) 1553 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0), 1554 cast<GlobalValue>(CE2Op0)); 1555 return ICmpInst::BAD_ICMP_PREDICATE; 1556 } 1557 // Ok, we know that both getelementptr instructions are based on the 1558 // same global. From this, we can precisely determine the relative 1559 // ordering of the resultant pointers. 1560 unsigned i = 1; 1561 1562 // The logic below assumes that the result of the comparison 1563 // can be determined by finding the first index that differs. 1564 // This doesn't work if there is over-indexing in any 1565 // subsequent indices, so check for that case first. 1566 if (!CE1->isGEPWithNoNotionalOverIndexing() || 1567 !CE2->isGEPWithNoNotionalOverIndexing()) 1568 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1569 1570 // Compare all of the operands the GEP's have in common. 1571 gep_type_iterator GTI = gep_type_begin(CE1); 1572 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands(); 1573 ++i, ++GTI) 1574 switch (IdxCompare(CE1->getOperand(i), 1575 CE2->getOperand(i), GTI.getIndexedType())) { 1576 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT; 1577 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT; 1578 case -2: return ICmpInst::BAD_ICMP_PREDICATE; 1579 } 1580 1581 // Ok, we ran out of things they have in common. If any leftovers 1582 // are non-zero then we have a difference, otherwise we are equal. 1583 for (; i < CE1->getNumOperands(); ++i) 1584 if (!CE1->getOperand(i)->isNullValue()) { 1585 if (isa<ConstantInt>(CE1->getOperand(i))) 1586 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1587 else 1588 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1589 } 1590 1591 for (; i < CE2->getNumOperands(); ++i) 1592 if (!CE2->getOperand(i)->isNullValue()) { 1593 if (isa<ConstantInt>(CE2->getOperand(i))) 1594 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1595 else 1596 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1597 } 1598 return ICmpInst::ICMP_EQ; 1599 } 1600 } 1601 } 1602 } 1603 default: 1604 break; 1605 } 1606 } 1607 1608 return ICmpInst::BAD_ICMP_PREDICATE; 1609 } 1610 1611 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 1612 Constant *C1, Constant *C2) { 1613 Type *ResultTy; 1614 if (VectorType *VT = dyn_cast<VectorType>(C1->getType())) 1615 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()), 1616 VT->getNumElements()); 1617 else 1618 ResultTy = Type::getInt1Ty(C1->getContext()); 1619 1620 // Fold FCMP_FALSE/FCMP_TRUE unconditionally. 1621 if (pred == FCmpInst::FCMP_FALSE) 1622 return Constant::getNullValue(ResultTy); 1623 1624 if (pred == FCmpInst::FCMP_TRUE) 1625 return Constant::getAllOnesValue(ResultTy); 1626 1627 // Handle some degenerate cases first 1628 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) { 1629 // For EQ and NE, we can always pick a value for the undef to make the 1630 // predicate pass or fail, so we can return undef. 1631 // Also, if both operands are undef, we can return undef. 1632 if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) || 1633 (isa<UndefValue>(C1) && isa<UndefValue>(C2))) 1634 return UndefValue::get(ResultTy); 1635 // Otherwise, pick the same value as the non-undef operand, and fold 1636 // it to true or false. 1637 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred)); 1638 } 1639 1640 // icmp eq/ne(null,GV) -> false/true 1641 if (C1->isNullValue()) { 1642 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2)) 1643 // Don't try to evaluate aliases. External weak GV can be null. 1644 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) { 1645 if (pred == ICmpInst::ICMP_EQ) 1646 return ConstantInt::getFalse(C1->getContext()); 1647 else if (pred == ICmpInst::ICMP_NE) 1648 return ConstantInt::getTrue(C1->getContext()); 1649 } 1650 // icmp eq/ne(GV,null) -> false/true 1651 } else if (C2->isNullValue()) { 1652 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1)) 1653 // Don't try to evaluate aliases. External weak GV can be null. 1654 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) { 1655 if (pred == ICmpInst::ICMP_EQ) 1656 return ConstantInt::getFalse(C1->getContext()); 1657 else if (pred == ICmpInst::ICMP_NE) 1658 return ConstantInt::getTrue(C1->getContext()); 1659 } 1660 } 1661 1662 // If the comparison is a comparison between two i1's, simplify it. 1663 if (C1->getType()->isIntegerTy(1)) { 1664 switch(pred) { 1665 case ICmpInst::ICMP_EQ: 1666 if (isa<ConstantInt>(C2)) 1667 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2)); 1668 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2); 1669 case ICmpInst::ICMP_NE: 1670 return ConstantExpr::getXor(C1, C2); 1671 default: 1672 break; 1673 } 1674 } 1675 1676 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) { 1677 APInt V1 = cast<ConstantInt>(C1)->getValue(); 1678 APInt V2 = cast<ConstantInt>(C2)->getValue(); 1679 switch (pred) { 1680 default: llvm_unreachable("Invalid ICmp Predicate"); 1681 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2); 1682 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2); 1683 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2)); 1684 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2)); 1685 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2)); 1686 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2)); 1687 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2)); 1688 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2)); 1689 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2)); 1690 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2)); 1691 } 1692 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) { 1693 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF(); 1694 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF(); 1695 APFloat::cmpResult R = C1V.compare(C2V); 1696 switch (pred) { 1697 default: llvm_unreachable("Invalid FCmp Predicate"); 1698 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy); 1699 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy); 1700 case FCmpInst::FCMP_UNO: 1701 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered); 1702 case FCmpInst::FCMP_ORD: 1703 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered); 1704 case FCmpInst::FCMP_UEQ: 1705 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1706 R==APFloat::cmpEqual); 1707 case FCmpInst::FCMP_OEQ: 1708 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual); 1709 case FCmpInst::FCMP_UNE: 1710 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual); 1711 case FCmpInst::FCMP_ONE: 1712 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan || 1713 R==APFloat::cmpGreaterThan); 1714 case FCmpInst::FCMP_ULT: 1715 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1716 R==APFloat::cmpLessThan); 1717 case FCmpInst::FCMP_OLT: 1718 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan); 1719 case FCmpInst::FCMP_UGT: 1720 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1721 R==APFloat::cmpGreaterThan); 1722 case FCmpInst::FCMP_OGT: 1723 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan); 1724 case FCmpInst::FCMP_ULE: 1725 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan); 1726 case FCmpInst::FCMP_OLE: 1727 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan || 1728 R==APFloat::cmpEqual); 1729 case FCmpInst::FCMP_UGE: 1730 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan); 1731 case FCmpInst::FCMP_OGE: 1732 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan || 1733 R==APFloat::cmpEqual); 1734 } 1735 } else if (C1->getType()->isVectorTy()) { 1736 // If we can constant fold the comparison of each element, constant fold 1737 // the whole vector comparison. 1738 SmallVector<Constant*, 4> ResElts; 1739 Type *Ty = IntegerType::get(C1->getContext(), 32); 1740 // Compare the elements, producing an i1 result or constant expr. 1741 for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){ 1742 Constant *C1E = 1743 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i)); 1744 Constant *C2E = 1745 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i)); 1746 1747 ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E)); 1748 } 1749 1750 return ConstantVector::get(ResElts); 1751 } 1752 1753 if (C1->getType()->isFloatingPointTy()) { 1754 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true. 1755 switch (evaluateFCmpRelation(C1, C2)) { 1756 default: llvm_unreachable("Unknown relation!"); 1757 case FCmpInst::FCMP_UNO: 1758 case FCmpInst::FCMP_ORD: 1759 case FCmpInst::FCMP_UEQ: 1760 case FCmpInst::FCMP_UNE: 1761 case FCmpInst::FCMP_ULT: 1762 case FCmpInst::FCMP_UGT: 1763 case FCmpInst::FCMP_ULE: 1764 case FCmpInst::FCMP_UGE: 1765 case FCmpInst::FCMP_TRUE: 1766 case FCmpInst::FCMP_FALSE: 1767 case FCmpInst::BAD_FCMP_PREDICATE: 1768 break; // Couldn't determine anything about these constants. 1769 case FCmpInst::FCMP_OEQ: // We know that C1 == C2 1770 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ || 1771 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE || 1772 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE); 1773 break; 1774 case FCmpInst::FCMP_OLT: // We know that C1 < C2 1775 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE || 1776 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT || 1777 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE); 1778 break; 1779 case FCmpInst::FCMP_OGT: // We know that C1 > C2 1780 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE || 1781 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT || 1782 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE); 1783 break; 1784 case FCmpInst::FCMP_OLE: // We know that C1 <= C2 1785 // We can only partially decide this relation. 1786 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 1787 Result = 0; 1788 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 1789 Result = 1; 1790 break; 1791 case FCmpInst::FCMP_OGE: // We known that C1 >= C2 1792 // We can only partially decide this relation. 1793 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 1794 Result = 0; 1795 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 1796 Result = 1; 1797 break; 1798 case FCmpInst::FCMP_ONE: // We know that C1 != C2 1799 // We can only partially decide this relation. 1800 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 1801 Result = 0; 1802 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 1803 Result = 1; 1804 break; 1805 } 1806 1807 // If we evaluated the result, return it now. 1808 if (Result != -1) 1809 return ConstantInt::get(ResultTy, Result); 1810 1811 } else { 1812 // Evaluate the relation between the two constants, per the predicate. 1813 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true. 1814 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) { 1815 default: llvm_unreachable("Unknown relational!"); 1816 case ICmpInst::BAD_ICMP_PREDICATE: 1817 break; // Couldn't determine anything about these constants. 1818 case ICmpInst::ICMP_EQ: // We know the constants are equal! 1819 // If we know the constants are equal, we can decide the result of this 1820 // computation precisely. 1821 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred); 1822 break; 1823 case ICmpInst::ICMP_ULT: 1824 switch (pred) { 1825 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE: 1826 Result = 1; break; 1827 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE: 1828 Result = 0; break; 1829 } 1830 break; 1831 case ICmpInst::ICMP_SLT: 1832 switch (pred) { 1833 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE: 1834 Result = 1; break; 1835 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE: 1836 Result = 0; break; 1837 } 1838 break; 1839 case ICmpInst::ICMP_UGT: 1840 switch (pred) { 1841 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE: 1842 Result = 1; break; 1843 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE: 1844 Result = 0; break; 1845 } 1846 break; 1847 case ICmpInst::ICMP_SGT: 1848 switch (pred) { 1849 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE: 1850 Result = 1; break; 1851 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE: 1852 Result = 0; break; 1853 } 1854 break; 1855 case ICmpInst::ICMP_ULE: 1856 if (pred == ICmpInst::ICMP_UGT) Result = 0; 1857 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1; 1858 break; 1859 case ICmpInst::ICMP_SLE: 1860 if (pred == ICmpInst::ICMP_SGT) Result = 0; 1861 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1; 1862 break; 1863 case ICmpInst::ICMP_UGE: 1864 if (pred == ICmpInst::ICMP_ULT) Result = 0; 1865 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1; 1866 break; 1867 case ICmpInst::ICMP_SGE: 1868 if (pred == ICmpInst::ICMP_SLT) Result = 0; 1869 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1; 1870 break; 1871 case ICmpInst::ICMP_NE: 1872 if (pred == ICmpInst::ICMP_EQ) Result = 0; 1873 if (pred == ICmpInst::ICMP_NE) Result = 1; 1874 break; 1875 } 1876 1877 // If we evaluated the result, return it now. 1878 if (Result != -1) 1879 return ConstantInt::get(ResultTy, Result); 1880 1881 // If the right hand side is a bitcast, try using its inverse to simplify 1882 // it by moving it to the left hand side. We can't do this if it would turn 1883 // a vector compare into a scalar compare or visa versa. 1884 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) { 1885 Constant *CE2Op0 = CE2->getOperand(0); 1886 if (CE2->getOpcode() == Instruction::BitCast && 1887 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) { 1888 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType()); 1889 return ConstantExpr::getICmp(pred, Inverse, CE2Op0); 1890 } 1891 } 1892 1893 // If the left hand side is an extension, try eliminating it. 1894 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 1895 if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) || 1896 (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){ 1897 Constant *CE1Op0 = CE1->getOperand(0); 1898 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType()); 1899 if (CE1Inverse == CE1Op0) { 1900 // Check whether we can safely truncate the right hand side. 1901 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType()); 1902 if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse, 1903 C2->getType()) == C2) 1904 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse); 1905 } 1906 } 1907 } 1908 1909 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) || 1910 (C1->isNullValue() && !C2->isNullValue())) { 1911 // If C2 is a constant expr and C1 isn't, flip them around and fold the 1912 // other way if possible. 1913 // Also, if C1 is null and C2 isn't, flip them around. 1914 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred); 1915 return ConstantExpr::getICmp(pred, C2, C1); 1916 } 1917 } 1918 return nullptr; 1919 } 1920 1921 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices 1922 /// is "inbounds". 1923 template<typename IndexTy> 1924 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) { 1925 // No indices means nothing that could be out of bounds. 1926 if (Idxs.empty()) return true; 1927 1928 // If the first index is zero, it's in bounds. 1929 if (cast<Constant>(Idxs[0])->isNullValue()) return true; 1930 1931 // If the first index is one and all the rest are zero, it's in bounds, 1932 // by the one-past-the-end rule. 1933 if (!cast<ConstantInt>(Idxs[0])->isOne()) 1934 return false; 1935 for (unsigned i = 1, e = Idxs.size(); i != e; ++i) 1936 if (!cast<Constant>(Idxs[i])->isNullValue()) 1937 return false; 1938 return true; 1939 } 1940 1941 /// \brief Test whether a given ConstantInt is in-range for a SequentialType. 1942 static bool isIndexInRangeOfSequentialType(const SequentialType *STy, 1943 const ConstantInt *CI) { 1944 if (const PointerType *PTy = dyn_cast<PointerType>(STy)) 1945 // Only handle pointers to sized types, not pointers to functions. 1946 return PTy->getElementType()->isSized(); 1947 1948 uint64_t NumElements = 0; 1949 // Determine the number of elements in our sequential type. 1950 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy)) 1951 NumElements = ATy->getNumElements(); 1952 else if (const VectorType *VTy = dyn_cast<VectorType>(STy)) 1953 NumElements = VTy->getNumElements(); 1954 1955 assert((isa<ArrayType>(STy) || NumElements > 0) && 1956 "didn't expect non-array type to have zero elements!"); 1957 1958 // We cannot bounds check the index if it doesn't fit in an int64_t. 1959 if (CI->getValue().getActiveBits() > 64) 1960 return false; 1961 1962 // A negative index or an index past the end of our sequential type is 1963 // considered out-of-range. 1964 int64_t IndexVal = CI->getSExtValue(); 1965 if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements)) 1966 return false; 1967 1968 // Otherwise, it is in-range. 1969 return true; 1970 } 1971 1972 template<typename IndexTy> 1973 static Constant *ConstantFoldGetElementPtrImpl(Constant *C, 1974 bool inBounds, 1975 ArrayRef<IndexTy> Idxs) { 1976 if (Idxs.empty()) return C; 1977 Constant *Idx0 = cast<Constant>(Idxs[0]); 1978 if ((Idxs.size() == 1 && Idx0->isNullValue())) 1979 return C; 1980 1981 if (isa<UndefValue>(C)) { 1982 PointerType *Ptr = cast<PointerType>(C->getType()); 1983 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs); 1984 assert(Ty && "Invalid indices for GEP!"); 1985 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace())); 1986 } 1987 1988 if (C->isNullValue()) { 1989 bool isNull = true; 1990 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) 1991 if (!cast<Constant>(Idxs[i])->isNullValue()) { 1992 isNull = false; 1993 break; 1994 } 1995 if (isNull) { 1996 PointerType *Ptr = cast<PointerType>(C->getType()); 1997 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs); 1998 assert(Ty && "Invalid indices for GEP!"); 1999 return ConstantPointerNull::get(PointerType::get(Ty, 2000 Ptr->getAddressSpace())); 2001 } 2002 } 2003 2004 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2005 // Combine Indices - If the source pointer to this getelementptr instruction 2006 // is a getelementptr instruction, combine the indices of the two 2007 // getelementptr instructions into a single instruction. 2008 // 2009 if (CE->getOpcode() == Instruction::GetElementPtr) { 2010 Type *LastTy = nullptr; 2011 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE); 2012 I != E; ++I) 2013 LastTy = *I; 2014 2015 // We cannot combine indices if doing so would take us outside of an 2016 // array or vector. Doing otherwise could trick us if we evaluated such a 2017 // GEP as part of a load. 2018 // 2019 // e.g. Consider if the original GEP was: 2020 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c, 2021 // i32 0, i32 0, i64 0) 2022 // 2023 // If we then tried to offset it by '8' to get to the third element, 2024 // an i8, we should *not* get: 2025 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c, 2026 // i32 0, i32 0, i64 8) 2027 // 2028 // This GEP tries to index array element '8 which runs out-of-bounds. 2029 // Subsequent evaluation would get confused and produce erroneous results. 2030 // 2031 // The following prohibits such a GEP from being formed by checking to see 2032 // if the index is in-range with respect to an array or vector. 2033 bool PerformFold = false; 2034 if (Idx0->isNullValue()) 2035 PerformFold = true; 2036 else if (SequentialType *STy = dyn_cast_or_null<SequentialType>(LastTy)) 2037 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0)) 2038 PerformFold = isIndexInRangeOfSequentialType(STy, CI); 2039 2040 if (PerformFold) { 2041 SmallVector<Value*, 16> NewIndices; 2042 NewIndices.reserve(Idxs.size() + CE->getNumOperands()); 2043 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i) 2044 NewIndices.push_back(CE->getOperand(i)); 2045 2046 // Add the last index of the source with the first index of the new GEP. 2047 // Make sure to handle the case when they are actually different types. 2048 Constant *Combined = CE->getOperand(CE->getNumOperands()-1); 2049 // Otherwise it must be an array. 2050 if (!Idx0->isNullValue()) { 2051 Type *IdxTy = Combined->getType(); 2052 if (IdxTy != Idx0->getType()) { 2053 Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext()); 2054 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty); 2055 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty); 2056 Combined = ConstantExpr::get(Instruction::Add, C1, C2); 2057 } else { 2058 Combined = 2059 ConstantExpr::get(Instruction::Add, Idx0, Combined); 2060 } 2061 } 2062 2063 NewIndices.push_back(Combined); 2064 NewIndices.append(Idxs.begin() + 1, Idxs.end()); 2065 return 2066 ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices, 2067 inBounds && 2068 cast<GEPOperator>(CE)->isInBounds()); 2069 } 2070 } 2071 2072 // Attempt to fold casts to the same type away. For example, folding: 2073 // 2074 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*), 2075 // i64 0, i64 0) 2076 // into: 2077 // 2078 // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0) 2079 // 2080 // Don't fold if the cast is changing address spaces. 2081 if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) { 2082 PointerType *SrcPtrTy = 2083 dyn_cast<PointerType>(CE->getOperand(0)->getType()); 2084 PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType()); 2085 if (SrcPtrTy && DstPtrTy) { 2086 ArrayType *SrcArrayTy = 2087 dyn_cast<ArrayType>(SrcPtrTy->getElementType()); 2088 ArrayType *DstArrayTy = 2089 dyn_cast<ArrayType>(DstPtrTy->getElementType()); 2090 if (SrcArrayTy && DstArrayTy 2091 && SrcArrayTy->getElementType() == DstArrayTy->getElementType() 2092 && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace()) 2093 return ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0), 2094 Idxs, inBounds); 2095 } 2096 } 2097 } 2098 2099 // Check to see if any array indices are not within the corresponding 2100 // notional array or vector bounds. If so, try to determine if they can be 2101 // factored out into preceding dimensions. 2102 bool Unknown = false; 2103 SmallVector<Constant *, 8> NewIdxs; 2104 Type *Ty = C->getType(); 2105 Type *Prev = nullptr; 2106 for (unsigned i = 0, e = Idxs.size(); i != e; 2107 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) { 2108 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) { 2109 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty)) 2110 if (CI->getSExtValue() > 0 && 2111 !isIndexInRangeOfSequentialType(cast<SequentialType>(Ty), CI)) { 2112 if (isa<SequentialType>(Prev)) { 2113 // It's out of range, but we can factor it into the prior 2114 // dimension. 2115 NewIdxs.resize(Idxs.size()); 2116 uint64_t NumElements = 0; 2117 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) 2118 NumElements = ATy->getNumElements(); 2119 else 2120 NumElements = cast<VectorType>(Ty)->getNumElements(); 2121 2122 ConstantInt *Factor = ConstantInt::get(CI->getType(), NumElements); 2123 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor); 2124 2125 Constant *PrevIdx = cast<Constant>(Idxs[i-1]); 2126 Constant *Div = ConstantExpr::getSDiv(CI, Factor); 2127 2128 // Before adding, extend both operands to i64 to avoid 2129 // overflow trouble. 2130 if (!PrevIdx->getType()->isIntegerTy(64)) 2131 PrevIdx = ConstantExpr::getSExt(PrevIdx, 2132 Type::getInt64Ty(Div->getContext())); 2133 if (!Div->getType()->isIntegerTy(64)) 2134 Div = ConstantExpr::getSExt(Div, 2135 Type::getInt64Ty(Div->getContext())); 2136 2137 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div); 2138 } else { 2139 // It's out of range, but the prior dimension is a struct 2140 // so we can't do anything about it. 2141 Unknown = true; 2142 } 2143 } 2144 } else { 2145 // We don't know if it's in range or not. 2146 Unknown = true; 2147 } 2148 } 2149 2150 // If we did any factoring, start over with the adjusted indices. 2151 if (!NewIdxs.empty()) { 2152 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) 2153 if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]); 2154 return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds); 2155 } 2156 2157 // If all indices are known integers and normalized, we can do a simple 2158 // check for the "inbounds" property. 2159 if (!Unknown && !inBounds) 2160 if (auto *GV = dyn_cast<GlobalVariable>(C)) 2161 if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs)) 2162 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs); 2163 2164 return nullptr; 2165 } 2166 2167 Constant *llvm::ConstantFoldGetElementPtr(Constant *C, 2168 bool inBounds, 2169 ArrayRef<Constant *> Idxs) { 2170 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs); 2171 } 2172 2173 Constant *llvm::ConstantFoldGetElementPtr(Constant *C, 2174 bool inBounds, 2175 ArrayRef<Value *> Idxs) { 2176 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs); 2177 } 2178