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