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 GVAlign = GV->getPointerAlignment(TheModule->getDataLayout()); 1214 1215 // If the function alignment is not specified then assume that it 1216 // is 4. 1217 // This is dangerous; on x86, the alignment of the pointer 1218 // corresponds to the alignment of the function, but might be less 1219 // than 4 if it isn't explicitly specified. 1220 // However, a fix for this behaviour was reverted because it 1221 // increased code size (see https://reviews.llvm.org/D55115) 1222 // FIXME: This code should be deleted once existing targets have 1223 // appropriate defaults 1224 if (!GVAlign && isa<Function>(GV)) 1225 GVAlign = Align(4); 1226 } else if (isa<Function>(GV)) { 1227 // Without a datalayout we have to assume the worst case: that the 1228 // function pointer isn't aligned at all. 1229 GVAlign = llvm::None; 1230 } else { 1231 GVAlign = MaybeAlign(GV->getAlignment()); 1232 } 1233 1234 if (GVAlign && *GVAlign > 1) { 1235 unsigned DstWidth = CI2->getType()->getBitWidth(); 1236 unsigned SrcWidth = std::min(DstWidth, Log2(*GVAlign)); 1237 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth)); 1238 1239 // If checking bits we know are clear, return zero. 1240 if ((CI2->getValue() & BitsNotSet) == CI2->getValue()) 1241 return Constant::getNullValue(CI2->getType()); 1242 } 1243 } 1244 } 1245 break; 1246 case Instruction::Or: 1247 if (CI2->isZero()) return C1; // X | 0 == X 1248 if (CI2->isMinusOne()) 1249 return C2; // X | -1 == -1 1250 break; 1251 case Instruction::Xor: 1252 if (CI2->isZero()) return C1; // X ^ 0 == X 1253 1254 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 1255 switch (CE1->getOpcode()) { 1256 default: break; 1257 case Instruction::ICmp: 1258 case Instruction::FCmp: 1259 // cmp pred ^ true -> cmp !pred 1260 assert(CI2->isOne()); 1261 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate(); 1262 pred = CmpInst::getInversePredicate(pred); 1263 return ConstantExpr::getCompare(pred, CE1->getOperand(0), 1264 CE1->getOperand(1)); 1265 } 1266 } 1267 break; 1268 case Instruction::AShr: 1269 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2 1270 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) 1271 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero. 1272 return ConstantExpr::getLShr(C1, C2); 1273 break; 1274 } 1275 } else if (isa<ConstantInt>(C1)) { 1276 // If C1 is a ConstantInt and C2 is not, swap the operands. 1277 if (Instruction::isCommutative(Opcode)) 1278 return ConstantExpr::get(Opcode, C2, C1); 1279 } 1280 1281 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) { 1282 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) { 1283 const APInt &C1V = CI1->getValue(); 1284 const APInt &C2V = CI2->getValue(); 1285 switch (Opcode) { 1286 default: 1287 break; 1288 case Instruction::Add: 1289 return ConstantInt::get(CI1->getContext(), C1V + C2V); 1290 case Instruction::Sub: 1291 return ConstantInt::get(CI1->getContext(), C1V - C2V); 1292 case Instruction::Mul: 1293 return ConstantInt::get(CI1->getContext(), C1V * C2V); 1294 case Instruction::UDiv: 1295 assert(!CI2->isZero() && "Div by zero handled above"); 1296 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V)); 1297 case Instruction::SDiv: 1298 assert(!CI2->isZero() && "Div by zero handled above"); 1299 if (C2V.isAllOnesValue() && C1V.isMinSignedValue()) 1300 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef 1301 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V)); 1302 case Instruction::URem: 1303 assert(!CI2->isZero() && "Div by zero handled above"); 1304 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V)); 1305 case Instruction::SRem: 1306 assert(!CI2->isZero() && "Div by zero handled above"); 1307 if (C2V.isAllOnesValue() && C1V.isMinSignedValue()) 1308 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef 1309 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V)); 1310 case Instruction::And: 1311 return ConstantInt::get(CI1->getContext(), C1V & C2V); 1312 case Instruction::Or: 1313 return ConstantInt::get(CI1->getContext(), C1V | C2V); 1314 case Instruction::Xor: 1315 return ConstantInt::get(CI1->getContext(), C1V ^ C2V); 1316 case Instruction::Shl: 1317 if (C2V.ult(C1V.getBitWidth())) 1318 return ConstantInt::get(CI1->getContext(), C1V.shl(C2V)); 1319 return UndefValue::get(C1->getType()); // too big shift is undef 1320 case Instruction::LShr: 1321 if (C2V.ult(C1V.getBitWidth())) 1322 return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V)); 1323 return UndefValue::get(C1->getType()); // too big shift is undef 1324 case Instruction::AShr: 1325 if (C2V.ult(C1V.getBitWidth())) 1326 return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V)); 1327 return UndefValue::get(C1->getType()); // too big shift is undef 1328 } 1329 } 1330 1331 switch (Opcode) { 1332 case Instruction::SDiv: 1333 case Instruction::UDiv: 1334 case Instruction::URem: 1335 case Instruction::SRem: 1336 case Instruction::LShr: 1337 case Instruction::AShr: 1338 case Instruction::Shl: 1339 if (CI1->isZero()) return C1; 1340 break; 1341 default: 1342 break; 1343 } 1344 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) { 1345 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) { 1346 const APFloat &C1V = CFP1->getValueAPF(); 1347 const APFloat &C2V = CFP2->getValueAPF(); 1348 APFloat C3V = C1V; // copy for modification 1349 switch (Opcode) { 1350 default: 1351 break; 1352 case Instruction::FAdd: 1353 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven); 1354 return ConstantFP::get(C1->getContext(), C3V); 1355 case Instruction::FSub: 1356 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven); 1357 return ConstantFP::get(C1->getContext(), C3V); 1358 case Instruction::FMul: 1359 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven); 1360 return ConstantFP::get(C1->getContext(), C3V); 1361 case Instruction::FDiv: 1362 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven); 1363 return ConstantFP::get(C1->getContext(), C3V); 1364 case Instruction::FRem: 1365 (void)C3V.mod(C2V); 1366 return ConstantFP::get(C1->getContext(), C3V); 1367 } 1368 } 1369 } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) { 1370 // Do not iterate on scalable vector. The number of elements is unknown at 1371 // compile-time. 1372 if (IsScalableVector) 1373 return nullptr; 1374 // Fast path for splatted constants. 1375 if (Constant *C2Splat = C2->getSplatValue()) { 1376 if (Instruction::isIntDivRem(Opcode) && C2Splat->isNullValue()) 1377 return UndefValue::get(VTy); 1378 if (Constant *C1Splat = C1->getSplatValue()) { 1379 return ConstantVector::getSplat( 1380 VTy->getElementCount(), 1381 ConstantExpr::get(Opcode, C1Splat, C2Splat)); 1382 } 1383 } 1384 1385 // Fold each element and create a vector constant from those constants. 1386 SmallVector<Constant*, 16> Result; 1387 Type *Ty = IntegerType::get(VTy->getContext(), 32); 1388 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 1389 Constant *ExtractIdx = ConstantInt::get(Ty, i); 1390 Constant *LHS = ConstantExpr::getExtractElement(C1, ExtractIdx); 1391 Constant *RHS = ConstantExpr::getExtractElement(C2, ExtractIdx); 1392 1393 // If any element of a divisor vector is zero, the whole op is undef. 1394 if (Instruction::isIntDivRem(Opcode) && RHS->isNullValue()) 1395 return UndefValue::get(VTy); 1396 1397 Result.push_back(ConstantExpr::get(Opcode, LHS, RHS)); 1398 } 1399 1400 return ConstantVector::get(Result); 1401 } 1402 1403 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 1404 // There are many possible foldings we could do here. We should probably 1405 // at least fold add of a pointer with an integer into the appropriate 1406 // getelementptr. This will improve alias analysis a bit. 1407 1408 // Given ((a + b) + c), if (b + c) folds to something interesting, return 1409 // (a + (b + c)). 1410 if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) { 1411 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2); 1412 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode) 1413 return ConstantExpr::get(Opcode, CE1->getOperand(0), T); 1414 } 1415 } else if (isa<ConstantExpr>(C2)) { 1416 // If C2 is a constant expr and C1 isn't, flop them around and fold the 1417 // other way if possible. 1418 if (Instruction::isCommutative(Opcode)) 1419 return ConstantFoldBinaryInstruction(Opcode, C2, C1); 1420 } 1421 1422 // i1 can be simplified in many cases. 1423 if (C1->getType()->isIntegerTy(1)) { 1424 switch (Opcode) { 1425 case Instruction::Add: 1426 case Instruction::Sub: 1427 return ConstantExpr::getXor(C1, C2); 1428 case Instruction::Mul: 1429 return ConstantExpr::getAnd(C1, C2); 1430 case Instruction::Shl: 1431 case Instruction::LShr: 1432 case Instruction::AShr: 1433 // We can assume that C2 == 0. If it were one the result would be 1434 // undefined because the shift value is as large as the bitwidth. 1435 return C1; 1436 case Instruction::SDiv: 1437 case Instruction::UDiv: 1438 // We can assume that C2 == 1. If it were zero the result would be 1439 // undefined through division by zero. 1440 return C1; 1441 case Instruction::URem: 1442 case Instruction::SRem: 1443 // We can assume that C2 == 1. If it were zero the result would be 1444 // undefined through division by zero. 1445 return ConstantInt::getFalse(C1->getContext()); 1446 default: 1447 break; 1448 } 1449 } 1450 1451 // We don't know how to fold this. 1452 return nullptr; 1453 } 1454 1455 /// This type is zero-sized if it's an array or structure of zero-sized types. 1456 /// The only leaf zero-sized type is an empty structure. 1457 static bool isMaybeZeroSizedType(Type *Ty) { 1458 if (StructType *STy = dyn_cast<StructType>(Ty)) { 1459 if (STy->isOpaque()) return true; // Can't say. 1460 1461 // If all of elements have zero size, this does too. 1462 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 1463 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false; 1464 return true; 1465 1466 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1467 return isMaybeZeroSizedType(ATy->getElementType()); 1468 } 1469 return false; 1470 } 1471 1472 /// Compare the two constants as though they were getelementptr indices. 1473 /// This allows coercion of the types to be the same thing. 1474 /// 1475 /// If the two constants are the "same" (after coercion), return 0. If the 1476 /// first is less than the second, return -1, if the second is less than the 1477 /// first, return 1. If the constants are not integral, return -2. 1478 /// 1479 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) { 1480 if (C1 == C2) return 0; 1481 1482 // Ok, we found a different index. If they are not ConstantInt, we can't do 1483 // anything with them. 1484 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2)) 1485 return -2; // don't know! 1486 1487 // We cannot compare the indices if they don't fit in an int64_t. 1488 if (cast<ConstantInt>(C1)->getValue().getActiveBits() > 64 || 1489 cast<ConstantInt>(C2)->getValue().getActiveBits() > 64) 1490 return -2; // don't know! 1491 1492 // Ok, we have two differing integer indices. Sign extend them to be the same 1493 // type. 1494 int64_t C1Val = cast<ConstantInt>(C1)->getSExtValue(); 1495 int64_t C2Val = cast<ConstantInt>(C2)->getSExtValue(); 1496 1497 if (C1Val == C2Val) return 0; // They are equal 1498 1499 // If the type being indexed over is really just a zero sized type, there is 1500 // no pointer difference being made here. 1501 if (isMaybeZeroSizedType(ElTy)) 1502 return -2; // dunno. 1503 1504 // If they are really different, now that they are the same type, then we 1505 // found a difference! 1506 if (C1Val < C2Val) 1507 return -1; 1508 else 1509 return 1; 1510 } 1511 1512 /// This function determines if there is anything we can decide about the two 1513 /// constants provided. This doesn't need to handle simple things like 1514 /// ConstantFP comparisons, but should instead handle ConstantExprs. 1515 /// If we can determine that the two constants have a particular relation to 1516 /// each other, we should return the corresponding FCmpInst predicate, 1517 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in 1518 /// ConstantFoldCompareInstruction. 1519 /// 1520 /// To simplify this code we canonicalize the relation so that the first 1521 /// operand is always the most "complex" of the two. We consider ConstantFP 1522 /// to be the simplest, and ConstantExprs to be the most complex. 1523 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) { 1524 assert(V1->getType() == V2->getType() && 1525 "Cannot compare values of different types!"); 1526 1527 // We do not know if a constant expression will evaluate to a number or NaN. 1528 // Therefore, we can only say that the relation is unordered or equal. 1529 if (V1 == V2) return FCmpInst::FCMP_UEQ; 1530 1531 if (!isa<ConstantExpr>(V1)) { 1532 if (!isa<ConstantExpr>(V2)) { 1533 // Simple case, use the standard constant folder. 1534 ConstantInt *R = nullptr; 1535 R = dyn_cast<ConstantInt>( 1536 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2)); 1537 if (R && !R->isZero()) 1538 return FCmpInst::FCMP_OEQ; 1539 R = dyn_cast<ConstantInt>( 1540 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2)); 1541 if (R && !R->isZero()) 1542 return FCmpInst::FCMP_OLT; 1543 R = dyn_cast<ConstantInt>( 1544 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2)); 1545 if (R && !R->isZero()) 1546 return FCmpInst::FCMP_OGT; 1547 1548 // Nothing more we can do 1549 return FCmpInst::BAD_FCMP_PREDICATE; 1550 } 1551 1552 // If the first operand is simple and second is ConstantExpr, swap operands. 1553 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1); 1554 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE) 1555 return FCmpInst::getSwappedPredicate(SwappedRelation); 1556 } else { 1557 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a 1558 // constantexpr or a simple constant. 1559 ConstantExpr *CE1 = cast<ConstantExpr>(V1); 1560 switch (CE1->getOpcode()) { 1561 case Instruction::FPTrunc: 1562 case Instruction::FPExt: 1563 case Instruction::UIToFP: 1564 case Instruction::SIToFP: 1565 // We might be able to do something with these but we don't right now. 1566 break; 1567 default: 1568 break; 1569 } 1570 } 1571 // There are MANY other foldings that we could perform here. They will 1572 // probably be added on demand, as they seem needed. 1573 return FCmpInst::BAD_FCMP_PREDICATE; 1574 } 1575 1576 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1, 1577 const GlobalValue *GV2) { 1578 auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) { 1579 if (GV->hasExternalWeakLinkage() || GV->hasWeakAnyLinkage()) 1580 return true; 1581 if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) { 1582 Type *Ty = GVar->getValueType(); 1583 // A global with opaque type might end up being zero sized. 1584 if (!Ty->isSized()) 1585 return true; 1586 // A global with an empty type might lie at the address of any other 1587 // global. 1588 if (Ty->isEmptyTy()) 1589 return true; 1590 } 1591 return false; 1592 }; 1593 // Don't try to decide equality of aliases. 1594 if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2)) 1595 if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2)) 1596 return ICmpInst::ICMP_NE; 1597 return ICmpInst::BAD_ICMP_PREDICATE; 1598 } 1599 1600 /// This function determines if there is anything we can decide about the two 1601 /// constants provided. This doesn't need to handle simple things like integer 1602 /// comparisons, but should instead handle ConstantExprs and GlobalValues. 1603 /// If we can determine that the two constants have a particular relation to 1604 /// each other, we should return the corresponding ICmp predicate, otherwise 1605 /// return ICmpInst::BAD_ICMP_PREDICATE. 1606 /// 1607 /// To simplify this code we canonicalize the relation so that the first 1608 /// operand is always the most "complex" of the two. We consider simple 1609 /// constants (like ConstantInt) to be the simplest, followed by 1610 /// GlobalValues, followed by ConstantExpr's (the most complex). 1611 /// 1612 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2, 1613 bool isSigned) { 1614 assert(V1->getType() == V2->getType() && 1615 "Cannot compare different types of values!"); 1616 if (V1 == V2) return ICmpInst::ICMP_EQ; 1617 1618 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) && 1619 !isa<BlockAddress>(V1)) { 1620 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) && 1621 !isa<BlockAddress>(V2)) { 1622 // We distilled this down to a simple case, use the standard constant 1623 // folder. 1624 ConstantInt *R = nullptr; 1625 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ; 1626 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1627 if (R && !R->isZero()) 1628 return pred; 1629 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1630 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1631 if (R && !R->isZero()) 1632 return pred; 1633 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1634 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1635 if (R && !R->isZero()) 1636 return pred; 1637 1638 // If we couldn't figure it out, bail. 1639 return ICmpInst::BAD_ICMP_PREDICATE; 1640 } 1641 1642 // If the first operand is simple, swap operands. 1643 ICmpInst::Predicate SwappedRelation = 1644 evaluateICmpRelation(V2, V1, isSigned); 1645 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1646 return ICmpInst::getSwappedPredicate(SwappedRelation); 1647 1648 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) { 1649 if (isa<ConstantExpr>(V2)) { // Swap as necessary. 1650 ICmpInst::Predicate SwappedRelation = 1651 evaluateICmpRelation(V2, V1, isSigned); 1652 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1653 return ICmpInst::getSwappedPredicate(SwappedRelation); 1654 return ICmpInst::BAD_ICMP_PREDICATE; 1655 } 1656 1657 // Now we know that the RHS is a GlobalValue, BlockAddress or simple 1658 // constant (which, since the types must match, means that it's a 1659 // ConstantPointerNull). 1660 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) { 1661 return areGlobalsPotentiallyEqual(GV, GV2); 1662 } else if (isa<BlockAddress>(V2)) { 1663 return ICmpInst::ICMP_NE; // Globals never equal labels. 1664 } else { 1665 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!"); 1666 // GlobalVals can never be null unless they have external weak linkage. 1667 // We don't try to evaluate aliases here. 1668 // NOTE: We should not be doing this constant folding if null pointer 1669 // is considered valid for the function. But currently there is no way to 1670 // query it from the Constant type. 1671 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV) && 1672 !NullPointerIsDefined(nullptr /* F */, 1673 GV->getType()->getAddressSpace())) 1674 return ICmpInst::ICMP_NE; 1675 } 1676 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) { 1677 if (isa<ConstantExpr>(V2)) { // Swap as necessary. 1678 ICmpInst::Predicate SwappedRelation = 1679 evaluateICmpRelation(V2, V1, isSigned); 1680 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1681 return ICmpInst::getSwappedPredicate(SwappedRelation); 1682 return ICmpInst::BAD_ICMP_PREDICATE; 1683 } 1684 1685 // Now we know that the RHS is a GlobalValue, BlockAddress or simple 1686 // constant (which, since the types must match, means that it is a 1687 // ConstantPointerNull). 1688 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) { 1689 // Block address in another function can't equal this one, but block 1690 // addresses in the current function might be the same if blocks are 1691 // empty. 1692 if (BA2->getFunction() != BA->getFunction()) 1693 return ICmpInst::ICMP_NE; 1694 } else { 1695 // Block addresses aren't null, don't equal the address of globals. 1696 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) && 1697 "Canonicalization guarantee!"); 1698 return ICmpInst::ICMP_NE; 1699 } 1700 } else { 1701 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a 1702 // constantexpr, a global, block address, or a simple constant. 1703 ConstantExpr *CE1 = cast<ConstantExpr>(V1); 1704 Constant *CE1Op0 = CE1->getOperand(0); 1705 1706 switch (CE1->getOpcode()) { 1707 case Instruction::Trunc: 1708 case Instruction::FPTrunc: 1709 case Instruction::FPExt: 1710 case Instruction::FPToUI: 1711 case Instruction::FPToSI: 1712 break; // We can't evaluate floating point casts or truncations. 1713 1714 case Instruction::UIToFP: 1715 case Instruction::SIToFP: 1716 case Instruction::BitCast: 1717 case Instruction::ZExt: 1718 case Instruction::SExt: 1719 // We can't evaluate floating point casts or truncations. 1720 if (CE1Op0->getType()->isFPOrFPVectorTy()) 1721 break; 1722 1723 // If the cast is not actually changing bits, and the second operand is a 1724 // null pointer, do the comparison with the pre-casted value. 1725 if (V2->isNullValue() && CE1->getType()->isIntOrPtrTy()) { 1726 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false; 1727 if (CE1->getOpcode() == Instruction::SExt) isSigned = true; 1728 return evaluateICmpRelation(CE1Op0, 1729 Constant::getNullValue(CE1Op0->getType()), 1730 isSigned); 1731 } 1732 break; 1733 1734 case Instruction::GetElementPtr: { 1735 GEPOperator *CE1GEP = cast<GEPOperator>(CE1); 1736 // Ok, since this is a getelementptr, we know that the constant has a 1737 // pointer type. Check the various cases. 1738 if (isa<ConstantPointerNull>(V2)) { 1739 // If we are comparing a GEP to a null pointer, check to see if the base 1740 // of the GEP equals the null pointer. 1741 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) { 1742 if (GV->hasExternalWeakLinkage()) 1743 // Weak linkage GVals could be zero or not. We're comparing that 1744 // to null pointer so its greater-or-equal 1745 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 1746 else 1747 // If its not weak linkage, the GVal must have a non-zero address 1748 // so the result is greater-than 1749 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1750 } else if (isa<ConstantPointerNull>(CE1Op0)) { 1751 // If we are indexing from a null pointer, check to see if we have any 1752 // non-zero indices. 1753 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i) 1754 if (!CE1->getOperand(i)->isNullValue()) 1755 // Offsetting from null, must not be equal. 1756 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1757 // Only zero indexes from null, must still be zero. 1758 return ICmpInst::ICMP_EQ; 1759 } 1760 // Otherwise, we can't really say if the first operand is null or not. 1761 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) { 1762 if (isa<ConstantPointerNull>(CE1Op0)) { 1763 if (GV2->hasExternalWeakLinkage()) 1764 // Weak linkage GVals could be zero or not. We're comparing it to 1765 // a null pointer, so its less-or-equal 1766 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 1767 else 1768 // If its not weak linkage, the GVal must have a non-zero address 1769 // so the result is less-than 1770 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1771 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) { 1772 if (GV == GV2) { 1773 // If this is a getelementptr of the same global, then it must be 1774 // different. Because the types must match, the getelementptr could 1775 // only have at most one index, and because we fold getelementptr's 1776 // with a single zero index, it must be nonzero. 1777 assert(CE1->getNumOperands() == 2 && 1778 !CE1->getOperand(1)->isNullValue() && 1779 "Surprising getelementptr!"); 1780 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1781 } else { 1782 if (CE1GEP->hasAllZeroIndices()) 1783 return areGlobalsPotentiallyEqual(GV, GV2); 1784 return ICmpInst::BAD_ICMP_PREDICATE; 1785 } 1786 } 1787 } else { 1788 ConstantExpr *CE2 = cast<ConstantExpr>(V2); 1789 Constant *CE2Op0 = CE2->getOperand(0); 1790 1791 // There are MANY other foldings that we could perform here. They will 1792 // probably be added on demand, as they seem needed. 1793 switch (CE2->getOpcode()) { 1794 default: break; 1795 case Instruction::GetElementPtr: 1796 // By far the most common case to handle is when the base pointers are 1797 // obviously to the same global. 1798 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) { 1799 // Don't know relative ordering, but check for inequality. 1800 if (CE1Op0 != CE2Op0) { 1801 GEPOperator *CE2GEP = cast<GEPOperator>(CE2); 1802 if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices()) 1803 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0), 1804 cast<GlobalValue>(CE2Op0)); 1805 return ICmpInst::BAD_ICMP_PREDICATE; 1806 } 1807 // Ok, we know that both getelementptr instructions are based on the 1808 // same global. From this, we can precisely determine the relative 1809 // ordering of the resultant pointers. 1810 unsigned i = 1; 1811 1812 // The logic below assumes that the result of the comparison 1813 // can be determined by finding the first index that differs. 1814 // This doesn't work if there is over-indexing in any 1815 // subsequent indices, so check for that case first. 1816 if (!CE1->isGEPWithNoNotionalOverIndexing() || 1817 !CE2->isGEPWithNoNotionalOverIndexing()) 1818 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1819 1820 // Compare all of the operands the GEP's have in common. 1821 gep_type_iterator GTI = gep_type_begin(CE1); 1822 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands(); 1823 ++i, ++GTI) 1824 switch (IdxCompare(CE1->getOperand(i), 1825 CE2->getOperand(i), GTI.getIndexedType())) { 1826 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT; 1827 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT; 1828 case -2: return ICmpInst::BAD_ICMP_PREDICATE; 1829 } 1830 1831 // Ok, we ran out of things they have in common. If any leftovers 1832 // are non-zero then we have a difference, otherwise we are equal. 1833 for (; i < CE1->getNumOperands(); ++i) 1834 if (!CE1->getOperand(i)->isNullValue()) { 1835 if (isa<ConstantInt>(CE1->getOperand(i))) 1836 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1837 else 1838 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1839 } 1840 1841 for (; i < CE2->getNumOperands(); ++i) 1842 if (!CE2->getOperand(i)->isNullValue()) { 1843 if (isa<ConstantInt>(CE2->getOperand(i))) 1844 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1845 else 1846 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1847 } 1848 return ICmpInst::ICMP_EQ; 1849 } 1850 } 1851 } 1852 break; 1853 } 1854 default: 1855 break; 1856 } 1857 } 1858 1859 return ICmpInst::BAD_ICMP_PREDICATE; 1860 } 1861 1862 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 1863 Constant *C1, Constant *C2) { 1864 Type *ResultTy; 1865 if (VectorType *VT = dyn_cast<VectorType>(C1->getType())) 1866 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()), 1867 VT->getElementCount()); 1868 else 1869 ResultTy = Type::getInt1Ty(C1->getContext()); 1870 1871 // Fold FCMP_FALSE/FCMP_TRUE unconditionally. 1872 if (pred == FCmpInst::FCMP_FALSE) 1873 return Constant::getNullValue(ResultTy); 1874 1875 if (pred == FCmpInst::FCMP_TRUE) 1876 return Constant::getAllOnesValue(ResultTy); 1877 1878 // Handle some degenerate cases first 1879 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) { 1880 CmpInst::Predicate Predicate = CmpInst::Predicate(pred); 1881 bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate); 1882 // For EQ and NE, we can always pick a value for the undef to make the 1883 // predicate pass or fail, so we can return undef. 1884 // Also, if both operands are undef, we can return undef for int comparison. 1885 if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2)) 1886 return UndefValue::get(ResultTy); 1887 1888 // Otherwise, for integer compare, pick the same value as the non-undef 1889 // operand, and fold it to true or false. 1890 if (isIntegerPredicate) 1891 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(Predicate)); 1892 1893 // Choosing NaN for the undef will always make unordered comparison succeed 1894 // and ordered comparison fails. 1895 return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate)); 1896 } 1897 1898 // icmp eq/ne(null,GV) -> false/true 1899 if (C1->isNullValue()) { 1900 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2)) 1901 // Don't try to evaluate aliases. External weak GV can be null. 1902 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() && 1903 !NullPointerIsDefined(nullptr /* F */, 1904 GV->getType()->getAddressSpace())) { 1905 if (pred == ICmpInst::ICMP_EQ) 1906 return ConstantInt::getFalse(C1->getContext()); 1907 else if (pred == ICmpInst::ICMP_NE) 1908 return ConstantInt::getTrue(C1->getContext()); 1909 } 1910 // icmp eq/ne(GV,null) -> false/true 1911 } else if (C2->isNullValue()) { 1912 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1)) 1913 // Don't try to evaluate aliases. External weak GV can be null. 1914 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() && 1915 !NullPointerIsDefined(nullptr /* F */, 1916 GV->getType()->getAddressSpace())) { 1917 if (pred == ICmpInst::ICMP_EQ) 1918 return ConstantInt::getFalse(C1->getContext()); 1919 else if (pred == ICmpInst::ICMP_NE) 1920 return ConstantInt::getTrue(C1->getContext()); 1921 } 1922 } 1923 1924 // If the comparison is a comparison between two i1's, simplify it. 1925 if (C1->getType()->isIntegerTy(1)) { 1926 switch(pred) { 1927 case ICmpInst::ICMP_EQ: 1928 if (isa<ConstantInt>(C2)) 1929 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2)); 1930 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2); 1931 case ICmpInst::ICMP_NE: 1932 return ConstantExpr::getXor(C1, C2); 1933 default: 1934 break; 1935 } 1936 } 1937 1938 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) { 1939 const APInt &V1 = cast<ConstantInt>(C1)->getValue(); 1940 const APInt &V2 = cast<ConstantInt>(C2)->getValue(); 1941 switch (pred) { 1942 default: llvm_unreachable("Invalid ICmp Predicate"); 1943 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2); 1944 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2); 1945 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2)); 1946 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2)); 1947 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2)); 1948 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2)); 1949 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2)); 1950 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2)); 1951 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2)); 1952 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2)); 1953 } 1954 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) { 1955 const APFloat &C1V = cast<ConstantFP>(C1)->getValueAPF(); 1956 const APFloat &C2V = cast<ConstantFP>(C2)->getValueAPF(); 1957 APFloat::cmpResult R = C1V.compare(C2V); 1958 switch (pred) { 1959 default: llvm_unreachable("Invalid FCmp Predicate"); 1960 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy); 1961 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy); 1962 case FCmpInst::FCMP_UNO: 1963 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered); 1964 case FCmpInst::FCMP_ORD: 1965 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered); 1966 case FCmpInst::FCMP_UEQ: 1967 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1968 R==APFloat::cmpEqual); 1969 case FCmpInst::FCMP_OEQ: 1970 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual); 1971 case FCmpInst::FCMP_UNE: 1972 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual); 1973 case FCmpInst::FCMP_ONE: 1974 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan || 1975 R==APFloat::cmpGreaterThan); 1976 case FCmpInst::FCMP_ULT: 1977 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1978 R==APFloat::cmpLessThan); 1979 case FCmpInst::FCMP_OLT: 1980 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan); 1981 case FCmpInst::FCMP_UGT: 1982 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1983 R==APFloat::cmpGreaterThan); 1984 case FCmpInst::FCMP_OGT: 1985 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan); 1986 case FCmpInst::FCMP_ULE: 1987 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan); 1988 case FCmpInst::FCMP_OLE: 1989 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan || 1990 R==APFloat::cmpEqual); 1991 case FCmpInst::FCMP_UGE: 1992 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan); 1993 case FCmpInst::FCMP_OGE: 1994 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan || 1995 R==APFloat::cmpEqual); 1996 } 1997 } else if (auto *C1VTy = dyn_cast<VectorType>(C1->getType())) { 1998 1999 // Do not iterate on scalable vector. The number of elements is unknown at 2000 // compile-time. 2001 if (isa<ScalableVectorType>(C1VTy)) 2002 return nullptr; 2003 2004 // Fast path for splatted constants. 2005 if (Constant *C1Splat = C1->getSplatValue()) 2006 if (Constant *C2Splat = C2->getSplatValue()) 2007 return ConstantVector::getSplat( 2008 C1VTy->getElementCount(), 2009 ConstantExpr::getCompare(pred, C1Splat, C2Splat)); 2010 2011 // If we can constant fold the comparison of each element, constant fold 2012 // the whole vector comparison. 2013 SmallVector<Constant*, 4> ResElts; 2014 Type *Ty = IntegerType::get(C1->getContext(), 32); 2015 // Compare the elements, producing an i1 result or constant expr. 2016 for (unsigned i = 0, e = C1VTy->getNumElements(); i != e; ++i) { 2017 Constant *C1E = 2018 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i)); 2019 Constant *C2E = 2020 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i)); 2021 2022 ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E)); 2023 } 2024 2025 return ConstantVector::get(ResElts); 2026 } 2027 2028 if (C1->getType()->isFloatingPointTy() && 2029 // Only call evaluateFCmpRelation if we have a constant expr to avoid 2030 // infinite recursive loop 2031 (isa<ConstantExpr>(C1) || isa<ConstantExpr>(C2))) { 2032 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true. 2033 switch (evaluateFCmpRelation(C1, C2)) { 2034 default: llvm_unreachable("Unknown relation!"); 2035 case FCmpInst::FCMP_UNO: 2036 case FCmpInst::FCMP_ORD: 2037 case FCmpInst::FCMP_UNE: 2038 case FCmpInst::FCMP_ULT: 2039 case FCmpInst::FCMP_UGT: 2040 case FCmpInst::FCMP_ULE: 2041 case FCmpInst::FCMP_UGE: 2042 case FCmpInst::FCMP_TRUE: 2043 case FCmpInst::FCMP_FALSE: 2044 case FCmpInst::BAD_FCMP_PREDICATE: 2045 break; // Couldn't determine anything about these constants. 2046 case FCmpInst::FCMP_OEQ: // We know that C1 == C2 2047 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ || 2048 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE || 2049 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE); 2050 break; 2051 case FCmpInst::FCMP_OLT: // We know that C1 < C2 2052 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE || 2053 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT || 2054 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE); 2055 break; 2056 case FCmpInst::FCMP_OGT: // We know that C1 > C2 2057 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE || 2058 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT || 2059 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE); 2060 break; 2061 case FCmpInst::FCMP_OLE: // We know that C1 <= C2 2062 // We can only partially decide this relation. 2063 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 2064 Result = 0; 2065 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 2066 Result = 1; 2067 break; 2068 case FCmpInst::FCMP_OGE: // We known that C1 >= C2 2069 // We can only partially decide this relation. 2070 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 2071 Result = 0; 2072 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 2073 Result = 1; 2074 break; 2075 case FCmpInst::FCMP_ONE: // We know that C1 != C2 2076 // We can only partially decide this relation. 2077 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 2078 Result = 0; 2079 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 2080 Result = 1; 2081 break; 2082 case FCmpInst::FCMP_UEQ: // We know that C1 == C2 || isUnordered(C1, C2). 2083 // We can only partially decide this relation. 2084 if (pred == FCmpInst::FCMP_ONE) 2085 Result = 0; 2086 else if (pred == FCmpInst::FCMP_UEQ) 2087 Result = 1; 2088 break; 2089 } 2090 2091 // If we evaluated the result, return it now. 2092 if (Result != -1) 2093 return ConstantInt::get(ResultTy, Result); 2094 2095 } else { 2096 // Evaluate the relation between the two constants, per the predicate. 2097 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true. 2098 switch (evaluateICmpRelation(C1, C2, 2099 CmpInst::isSigned((CmpInst::Predicate)pred))) { 2100 default: llvm_unreachable("Unknown relational!"); 2101 case ICmpInst::BAD_ICMP_PREDICATE: 2102 break; // Couldn't determine anything about these constants. 2103 case ICmpInst::ICMP_EQ: // We know the constants are equal! 2104 // If we know the constants are equal, we can decide the result of this 2105 // computation precisely. 2106 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred); 2107 break; 2108 case ICmpInst::ICMP_ULT: 2109 switch (pred) { 2110 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE: 2111 Result = 1; break; 2112 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE: 2113 Result = 0; break; 2114 } 2115 break; 2116 case ICmpInst::ICMP_SLT: 2117 switch (pred) { 2118 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE: 2119 Result = 1; break; 2120 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE: 2121 Result = 0; break; 2122 } 2123 break; 2124 case ICmpInst::ICMP_UGT: 2125 switch (pred) { 2126 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE: 2127 Result = 1; break; 2128 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE: 2129 Result = 0; break; 2130 } 2131 break; 2132 case ICmpInst::ICMP_SGT: 2133 switch (pred) { 2134 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE: 2135 Result = 1; break; 2136 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE: 2137 Result = 0; break; 2138 } 2139 break; 2140 case ICmpInst::ICMP_ULE: 2141 if (pred == ICmpInst::ICMP_UGT) Result = 0; 2142 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1; 2143 break; 2144 case ICmpInst::ICMP_SLE: 2145 if (pred == ICmpInst::ICMP_SGT) Result = 0; 2146 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1; 2147 break; 2148 case ICmpInst::ICMP_UGE: 2149 if (pred == ICmpInst::ICMP_ULT) Result = 0; 2150 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1; 2151 break; 2152 case ICmpInst::ICMP_SGE: 2153 if (pred == ICmpInst::ICMP_SLT) Result = 0; 2154 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1; 2155 break; 2156 case ICmpInst::ICMP_NE: 2157 if (pred == ICmpInst::ICMP_EQ) Result = 0; 2158 if (pred == ICmpInst::ICMP_NE) Result = 1; 2159 break; 2160 } 2161 2162 // If we evaluated the result, return it now. 2163 if (Result != -1) 2164 return ConstantInt::get(ResultTy, Result); 2165 2166 // If the right hand side is a bitcast, try using its inverse to simplify 2167 // it by moving it to the left hand side. We can't do this if it would turn 2168 // a vector compare into a scalar compare or visa versa, or if it would turn 2169 // the operands into FP values. 2170 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) { 2171 Constant *CE2Op0 = CE2->getOperand(0); 2172 if (CE2->getOpcode() == Instruction::BitCast && 2173 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy() && 2174 !CE2Op0->getType()->isFPOrFPVectorTy()) { 2175 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType()); 2176 return ConstantExpr::getICmp(pred, Inverse, CE2Op0); 2177 } 2178 } 2179 2180 // If the left hand side is an extension, try eliminating it. 2181 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 2182 if ((CE1->getOpcode() == Instruction::SExt && 2183 ICmpInst::isSigned((ICmpInst::Predicate)pred)) || 2184 (CE1->getOpcode() == Instruction::ZExt && 2185 !ICmpInst::isSigned((ICmpInst::Predicate)pred))){ 2186 Constant *CE1Op0 = CE1->getOperand(0); 2187 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType()); 2188 if (CE1Inverse == CE1Op0) { 2189 // Check whether we can safely truncate the right hand side. 2190 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType()); 2191 if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse, 2192 C2->getType()) == C2) 2193 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse); 2194 } 2195 } 2196 } 2197 2198 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) || 2199 (C1->isNullValue() && !C2->isNullValue())) { 2200 // If C2 is a constant expr and C1 isn't, flip them around and fold the 2201 // other way if possible. 2202 // Also, if C1 is null and C2 isn't, flip them around. 2203 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred); 2204 return ConstantExpr::getICmp(pred, C2, C1); 2205 } 2206 } 2207 return nullptr; 2208 } 2209 2210 /// Test whether the given sequence of *normalized* indices is "inbounds". 2211 template<typename IndexTy> 2212 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) { 2213 // No indices means nothing that could be out of bounds. 2214 if (Idxs.empty()) return true; 2215 2216 // If the first index is zero, it's in bounds. 2217 if (cast<Constant>(Idxs[0])->isNullValue()) return true; 2218 2219 // If the first index is one and all the rest are zero, it's in bounds, 2220 // by the one-past-the-end rule. 2221 if (auto *CI = dyn_cast<ConstantInt>(Idxs[0])) { 2222 if (!CI->isOne()) 2223 return false; 2224 } else { 2225 auto *CV = cast<ConstantDataVector>(Idxs[0]); 2226 CI = dyn_cast_or_null<ConstantInt>(CV->getSplatValue()); 2227 if (!CI || !CI->isOne()) 2228 return false; 2229 } 2230 2231 for (unsigned i = 1, e = Idxs.size(); i != e; ++i) 2232 if (!cast<Constant>(Idxs[i])->isNullValue()) 2233 return false; 2234 return true; 2235 } 2236 2237 /// Test whether a given ConstantInt is in-range for a SequentialType. 2238 static bool isIndexInRangeOfArrayType(uint64_t NumElements, 2239 const ConstantInt *CI) { 2240 // We cannot bounds check the index if it doesn't fit in an int64_t. 2241 if (CI->getValue().getMinSignedBits() > 64) 2242 return false; 2243 2244 // A negative index or an index past the end of our sequential type is 2245 // considered out-of-range. 2246 int64_t IndexVal = CI->getSExtValue(); 2247 if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements)) 2248 return false; 2249 2250 // Otherwise, it is in-range. 2251 return true; 2252 } 2253 2254 Constant *llvm::ConstantFoldGetElementPtr(Type *PointeeTy, Constant *C, 2255 bool InBounds, 2256 Optional<unsigned> InRangeIndex, 2257 ArrayRef<Value *> Idxs) { 2258 if (Idxs.empty()) return C; 2259 2260 Type *GEPTy = GetElementPtrInst::getGEPReturnType( 2261 PointeeTy, C, makeArrayRef((Value *const *)Idxs.data(), Idxs.size())); 2262 2263 if (isa<UndefValue>(C)) 2264 return UndefValue::get(GEPTy); 2265 2266 Constant *Idx0 = cast<Constant>(Idxs[0]); 2267 if (Idxs.size() == 1 && (Idx0->isNullValue() || isa<UndefValue>(Idx0))) 2268 return GEPTy->isVectorTy() && !C->getType()->isVectorTy() 2269 ? ConstantVector::getSplat( 2270 cast<VectorType>(GEPTy)->getElementCount(), C) 2271 : C; 2272 2273 if (C->isNullValue()) { 2274 bool isNull = true; 2275 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) 2276 if (!isa<UndefValue>(Idxs[i]) && 2277 !cast<Constant>(Idxs[i])->isNullValue()) { 2278 isNull = false; 2279 break; 2280 } 2281 if (isNull) { 2282 PointerType *PtrTy = cast<PointerType>(C->getType()->getScalarType()); 2283 Type *Ty = GetElementPtrInst::getIndexedType(PointeeTy, Idxs); 2284 2285 assert(Ty && "Invalid indices for GEP!"); 2286 Type *OrigGEPTy = PointerType::get(Ty, PtrTy->getAddressSpace()); 2287 Type *GEPTy = PointerType::get(Ty, PtrTy->getAddressSpace()); 2288 if (VectorType *VT = dyn_cast<VectorType>(C->getType())) 2289 GEPTy = VectorType::get(OrigGEPTy, VT->getNumElements()); 2290 2291 // The GEP returns a vector of pointers when one of more of 2292 // its arguments is a vector. 2293 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) { 2294 if (auto *VT = dyn_cast<VectorType>(Idxs[i]->getType())) { 2295 GEPTy = VectorType::get(OrigGEPTy, VT->getNumElements()); 2296 break; 2297 } 2298 } 2299 2300 return Constant::getNullValue(GEPTy); 2301 } 2302 } 2303 2304 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2305 // Combine Indices - If the source pointer to this getelementptr instruction 2306 // is a getelementptr instruction, combine the indices of the two 2307 // getelementptr instructions into a single instruction. 2308 // 2309 if (CE->getOpcode() == Instruction::GetElementPtr) { 2310 gep_type_iterator LastI = gep_type_end(CE); 2311 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE); 2312 I != E; ++I) 2313 LastI = I; 2314 2315 // We cannot combine indices if doing so would take us outside of an 2316 // array or vector. Doing otherwise could trick us if we evaluated such a 2317 // GEP as part of a load. 2318 // 2319 // e.g. Consider if the original GEP was: 2320 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c, 2321 // i32 0, i32 0, i64 0) 2322 // 2323 // If we then tried to offset it by '8' to get to the third element, 2324 // an i8, we should *not* get: 2325 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c, 2326 // i32 0, i32 0, i64 8) 2327 // 2328 // This GEP tries to index array element '8 which runs out-of-bounds. 2329 // Subsequent evaluation would get confused and produce erroneous results. 2330 // 2331 // The following prohibits such a GEP from being formed by checking to see 2332 // if the index is in-range with respect to an array. 2333 // TODO: This code may be extended to handle vectors as well. 2334 bool PerformFold = false; 2335 if (Idx0->isNullValue()) 2336 PerformFold = true; 2337 else if (LastI.isSequential()) 2338 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0)) 2339 PerformFold = (!LastI.isBoundedSequential() || 2340 isIndexInRangeOfArrayType( 2341 LastI.getSequentialNumElements(), CI)) && 2342 !CE->getOperand(CE->getNumOperands() - 1) 2343 ->getType() 2344 ->isVectorTy(); 2345 2346 if (PerformFold) { 2347 SmallVector<Value*, 16> NewIndices; 2348 NewIndices.reserve(Idxs.size() + CE->getNumOperands()); 2349 NewIndices.append(CE->op_begin() + 1, CE->op_end() - 1); 2350 2351 // Add the last index of the source with the first index of the new GEP. 2352 // Make sure to handle the case when they are actually different types. 2353 Constant *Combined = CE->getOperand(CE->getNumOperands()-1); 2354 // Otherwise it must be an array. 2355 if (!Idx0->isNullValue()) { 2356 Type *IdxTy = Combined->getType(); 2357 if (IdxTy != Idx0->getType()) { 2358 unsigned CommonExtendedWidth = 2359 std::max(IdxTy->getIntegerBitWidth(), 2360 Idx0->getType()->getIntegerBitWidth()); 2361 CommonExtendedWidth = std::max(CommonExtendedWidth, 64U); 2362 2363 Type *CommonTy = 2364 Type::getIntNTy(IdxTy->getContext(), CommonExtendedWidth); 2365 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, CommonTy); 2366 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, CommonTy); 2367 Combined = ConstantExpr::get(Instruction::Add, C1, C2); 2368 } else { 2369 Combined = 2370 ConstantExpr::get(Instruction::Add, Idx0, Combined); 2371 } 2372 } 2373 2374 NewIndices.push_back(Combined); 2375 NewIndices.append(Idxs.begin() + 1, Idxs.end()); 2376 2377 // The combined GEP normally inherits its index inrange attribute from 2378 // the inner GEP, but if the inner GEP's last index was adjusted by the 2379 // outer GEP, any inbounds attribute on that index is invalidated. 2380 Optional<unsigned> IRIndex = cast<GEPOperator>(CE)->getInRangeIndex(); 2381 if (IRIndex && *IRIndex == CE->getNumOperands() - 2 && !Idx0->isNullValue()) 2382 IRIndex = None; 2383 2384 return ConstantExpr::getGetElementPtr( 2385 cast<GEPOperator>(CE)->getSourceElementType(), CE->getOperand(0), 2386 NewIndices, InBounds && cast<GEPOperator>(CE)->isInBounds(), 2387 IRIndex); 2388 } 2389 } 2390 2391 // Attempt to fold casts to the same type away. For example, folding: 2392 // 2393 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*), 2394 // i64 0, i64 0) 2395 // into: 2396 // 2397 // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0) 2398 // 2399 // Don't fold if the cast is changing address spaces. 2400 if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) { 2401 PointerType *SrcPtrTy = 2402 dyn_cast<PointerType>(CE->getOperand(0)->getType()); 2403 PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType()); 2404 if (SrcPtrTy && DstPtrTy) { 2405 ArrayType *SrcArrayTy = 2406 dyn_cast<ArrayType>(SrcPtrTy->getElementType()); 2407 ArrayType *DstArrayTy = 2408 dyn_cast<ArrayType>(DstPtrTy->getElementType()); 2409 if (SrcArrayTy && DstArrayTy 2410 && SrcArrayTy->getElementType() == DstArrayTy->getElementType() 2411 && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace()) 2412 return ConstantExpr::getGetElementPtr(SrcArrayTy, 2413 (Constant *)CE->getOperand(0), 2414 Idxs, InBounds, InRangeIndex); 2415 } 2416 } 2417 } 2418 2419 // Check to see if any array indices are not within the corresponding 2420 // notional array or vector bounds. If so, try to determine if they can be 2421 // factored out into preceding dimensions. 2422 SmallVector<Constant *, 8> NewIdxs; 2423 Type *Ty = PointeeTy; 2424 Type *Prev = C->getType(); 2425 auto GEPIter = gep_type_begin(PointeeTy, Idxs); 2426 bool Unknown = 2427 !isa<ConstantInt>(Idxs[0]) && !isa<ConstantDataVector>(Idxs[0]); 2428 for (unsigned i = 1, e = Idxs.size(); i != e; 2429 Prev = Ty, Ty = (++GEPIter).getIndexedType(), ++i) { 2430 if (!isa<ConstantInt>(Idxs[i]) && !isa<ConstantDataVector>(Idxs[i])) { 2431 // We don't know if it's in range or not. 2432 Unknown = true; 2433 continue; 2434 } 2435 if (!isa<ConstantInt>(Idxs[i - 1]) && !isa<ConstantDataVector>(Idxs[i - 1])) 2436 // Skip if the type of the previous index is not supported. 2437 continue; 2438 if (InRangeIndex && i == *InRangeIndex + 1) { 2439 // If an index is marked inrange, we cannot apply this canonicalization to 2440 // the following index, as that will cause the inrange index to point to 2441 // the wrong element. 2442 continue; 2443 } 2444 if (isa<StructType>(Ty)) { 2445 // The verify makes sure that GEPs into a struct are in range. 2446 continue; 2447 } 2448 if (isa<VectorType>(Ty)) { 2449 // There can be awkward padding in after a non-power of two vector. 2450 Unknown = true; 2451 continue; 2452 } 2453 auto *STy = cast<ArrayType>(Ty); 2454 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) { 2455 if (isIndexInRangeOfArrayType(STy->getNumElements(), CI)) 2456 // It's in range, skip to the next index. 2457 continue; 2458 if (CI->getSExtValue() < 0) { 2459 // It's out of range and negative, don't try to factor it. 2460 Unknown = true; 2461 continue; 2462 } 2463 } else { 2464 auto *CV = cast<ConstantDataVector>(Idxs[i]); 2465 bool InRange = true; 2466 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) { 2467 auto *CI = cast<ConstantInt>(CV->getElementAsConstant(I)); 2468 InRange &= isIndexInRangeOfArrayType(STy->getNumElements(), CI); 2469 if (CI->getSExtValue() < 0) { 2470 Unknown = true; 2471 break; 2472 } 2473 } 2474 if (InRange || Unknown) 2475 // It's in range, skip to the next index. 2476 // It's out of range and negative, don't try to factor it. 2477 continue; 2478 } 2479 if (isa<StructType>(Prev)) { 2480 // It's out of range, but the prior dimension is a struct 2481 // so we can't do anything about it. 2482 Unknown = true; 2483 continue; 2484 } 2485 // It's out of range, but we can factor it into the prior 2486 // dimension. 2487 NewIdxs.resize(Idxs.size()); 2488 // Determine the number of elements in our sequential type. 2489 uint64_t NumElements = STy->getArrayNumElements(); 2490 2491 // Expand the current index or the previous index to a vector from a scalar 2492 // if necessary. 2493 Constant *CurrIdx = cast<Constant>(Idxs[i]); 2494 auto *PrevIdx = 2495 NewIdxs[i - 1] ? NewIdxs[i - 1] : cast<Constant>(Idxs[i - 1]); 2496 bool IsCurrIdxVector = CurrIdx->getType()->isVectorTy(); 2497 bool IsPrevIdxVector = PrevIdx->getType()->isVectorTy(); 2498 bool UseVector = IsCurrIdxVector || IsPrevIdxVector; 2499 2500 if (!IsCurrIdxVector && IsPrevIdxVector) 2501 CurrIdx = ConstantDataVector::getSplat( 2502 cast<VectorType>(PrevIdx->getType())->getNumElements(), CurrIdx); 2503 2504 if (!IsPrevIdxVector && IsCurrIdxVector) 2505 PrevIdx = ConstantDataVector::getSplat( 2506 cast<VectorType>(CurrIdx->getType())->getNumElements(), PrevIdx); 2507 2508 Constant *Factor = 2509 ConstantInt::get(CurrIdx->getType()->getScalarType(), NumElements); 2510 if (UseVector) 2511 Factor = ConstantDataVector::getSplat( 2512 IsPrevIdxVector 2513 ? cast<VectorType>(PrevIdx->getType())->getNumElements() 2514 : cast<VectorType>(CurrIdx->getType())->getNumElements(), 2515 Factor); 2516 2517 NewIdxs[i] = ConstantExpr::getSRem(CurrIdx, Factor); 2518 2519 Constant *Div = ConstantExpr::getSDiv(CurrIdx, Factor); 2520 2521 unsigned CommonExtendedWidth = 2522 std::max(PrevIdx->getType()->getScalarSizeInBits(), 2523 Div->getType()->getScalarSizeInBits()); 2524 CommonExtendedWidth = std::max(CommonExtendedWidth, 64U); 2525 2526 // Before adding, extend both operands to i64 to avoid 2527 // overflow trouble. 2528 Type *ExtendedTy = Type::getIntNTy(Div->getContext(), CommonExtendedWidth); 2529 if (UseVector) 2530 ExtendedTy = VectorType::get( 2531 ExtendedTy, 2532 IsPrevIdxVector 2533 ? cast<VectorType>(PrevIdx->getType())->getNumElements() 2534 : cast<VectorType>(CurrIdx->getType())->getNumElements()); 2535 2536 if (!PrevIdx->getType()->isIntOrIntVectorTy(CommonExtendedWidth)) 2537 PrevIdx = ConstantExpr::getSExt(PrevIdx, ExtendedTy); 2538 2539 if (!Div->getType()->isIntOrIntVectorTy(CommonExtendedWidth)) 2540 Div = ConstantExpr::getSExt(Div, ExtendedTy); 2541 2542 NewIdxs[i - 1] = ConstantExpr::getAdd(PrevIdx, Div); 2543 } 2544 2545 // If we did any factoring, start over with the adjusted indices. 2546 if (!NewIdxs.empty()) { 2547 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) 2548 if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]); 2549 return ConstantExpr::getGetElementPtr(PointeeTy, C, NewIdxs, InBounds, 2550 InRangeIndex); 2551 } 2552 2553 // If all indices are known integers and normalized, we can do a simple 2554 // check for the "inbounds" property. 2555 if (!Unknown && !InBounds) 2556 if (auto *GV = dyn_cast<GlobalVariable>(C)) 2557 if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs)) 2558 return ConstantExpr::getGetElementPtr(PointeeTy, C, Idxs, 2559 /*InBounds=*/true, InRangeIndex); 2560 2561 return nullptr; 2562 } 2563