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