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