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