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