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 UndefValue::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::getNullValue(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 // Lane < Splat minimum vector width => extractelt Splat(x), Lane -> x 671 if (CIdx->getValue().ult(ValVTy->getElementCount().getKnownMinValue())) { 672 if (Constant *SplatVal = Val->getSplatValue()) 673 return SplatVal; 674 } 675 676 return Val->getAggregateElement(CIdx); 677 } 678 679 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val, 680 Constant *Elt, 681 Constant *Idx) { 682 if (isa<UndefValue>(Idx)) 683 return PoisonValue::get(Val->getType()); 684 685 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx); 686 if (!CIdx) return nullptr; 687 688 // Do not iterate on scalable vector. The num of elements is unknown at 689 // compile-time. 690 if (isa<ScalableVectorType>(Val->getType())) 691 return nullptr; 692 693 auto *ValTy = cast<FixedVectorType>(Val->getType()); 694 695 unsigned NumElts = ValTy->getNumElements(); 696 if (CIdx->uge(NumElts)) 697 return UndefValue::get(Val->getType()); 698 699 SmallVector<Constant*, 16> Result; 700 Result.reserve(NumElts); 701 auto *Ty = Type::getInt32Ty(Val->getContext()); 702 uint64_t IdxVal = CIdx->getZExtValue(); 703 for (unsigned i = 0; i != NumElts; ++i) { 704 if (i == IdxVal) { 705 Result.push_back(Elt); 706 continue; 707 } 708 709 Constant *C = ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i)); 710 Result.push_back(C); 711 } 712 713 return ConstantVector::get(Result); 714 } 715 716 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2, 717 ArrayRef<int> Mask) { 718 auto *V1VTy = cast<VectorType>(V1->getType()); 719 unsigned MaskNumElts = Mask.size(); 720 auto MaskEltCount = 721 ElementCount::get(MaskNumElts, isa<ScalableVectorType>(V1VTy)); 722 Type *EltTy = V1VTy->getElementType(); 723 724 // Undefined shuffle mask -> undefined value. 725 if (all_of(Mask, [](int Elt) { return Elt == UndefMaskElem; })) { 726 return UndefValue::get(FixedVectorType::get(EltTy, MaskNumElts)); 727 } 728 729 // If the mask is all zeros this is a splat, no need to go through all 730 // elements. 731 if (all_of(Mask, [](int Elt) { return Elt == 0; }) && 732 !MaskEltCount.isScalable()) { 733 Type *Ty = IntegerType::get(V1->getContext(), 32); 734 Constant *Elt = 735 ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, 0)); 736 return ConstantVector::getSplat(MaskEltCount, Elt); 737 } 738 // Do not iterate on scalable vector. The num of elements is unknown at 739 // compile-time. 740 if (isa<ScalableVectorType>(V1VTy)) 741 return nullptr; 742 743 unsigned SrcNumElts = V1VTy->getElementCount().getKnownMinValue(); 744 745 // Loop over the shuffle mask, evaluating each element. 746 SmallVector<Constant*, 32> Result; 747 for (unsigned i = 0; i != MaskNumElts; ++i) { 748 int Elt = Mask[i]; 749 if (Elt == -1) { 750 Result.push_back(UndefValue::get(EltTy)); 751 continue; 752 } 753 Constant *InElt; 754 if (unsigned(Elt) >= SrcNumElts*2) 755 InElt = UndefValue::get(EltTy); 756 else if (unsigned(Elt) >= SrcNumElts) { 757 Type *Ty = IntegerType::get(V2->getContext(), 32); 758 InElt = 759 ConstantExpr::getExtractElement(V2, 760 ConstantInt::get(Ty, Elt - SrcNumElts)); 761 } else { 762 Type *Ty = IntegerType::get(V1->getContext(), 32); 763 InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt)); 764 } 765 Result.push_back(InElt); 766 } 767 768 return ConstantVector::get(Result); 769 } 770 771 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg, 772 ArrayRef<unsigned> Idxs) { 773 // Base case: no indices, so return the entire value. 774 if (Idxs.empty()) 775 return Agg; 776 777 if (Constant *C = Agg->getAggregateElement(Idxs[0])) 778 return ConstantFoldExtractValueInstruction(C, Idxs.slice(1)); 779 780 return nullptr; 781 } 782 783 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg, 784 Constant *Val, 785 ArrayRef<unsigned> Idxs) { 786 // Base case: no indices, so replace the entire value. 787 if (Idxs.empty()) 788 return Val; 789 790 unsigned NumElts; 791 if (StructType *ST = dyn_cast<StructType>(Agg->getType())) 792 NumElts = ST->getNumElements(); 793 else 794 NumElts = cast<ArrayType>(Agg->getType())->getNumElements(); 795 796 SmallVector<Constant*, 32> Result; 797 for (unsigned i = 0; i != NumElts; ++i) { 798 Constant *C = Agg->getAggregateElement(i); 799 if (!C) return nullptr; 800 801 if (Idxs[0] == i) 802 C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1)); 803 804 Result.push_back(C); 805 } 806 807 if (StructType *ST = dyn_cast<StructType>(Agg->getType())) 808 return ConstantStruct::get(ST, Result); 809 return ConstantArray::get(cast<ArrayType>(Agg->getType()), Result); 810 } 811 812 Constant *llvm::ConstantFoldUnaryInstruction(unsigned Opcode, Constant *C) { 813 assert(Instruction::isUnaryOp(Opcode) && "Non-unary instruction detected"); 814 815 // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length 816 // vectors are always evaluated per element. 817 bool IsScalableVector = isa<ScalableVectorType>(C->getType()); 818 bool HasScalarUndefOrScalableVectorUndef = 819 (!C->getType()->isVectorTy() || IsScalableVector) && isa<UndefValue>(C); 820 821 if (HasScalarUndefOrScalableVectorUndef) { 822 switch (static_cast<Instruction::UnaryOps>(Opcode)) { 823 case Instruction::FNeg: 824 return C; // -undef -> undef 825 case Instruction::UnaryOpsEnd: 826 llvm_unreachable("Invalid UnaryOp"); 827 } 828 } 829 830 // Constant should not be UndefValue, unless these are vector constants. 831 assert(!HasScalarUndefOrScalableVectorUndef && "Unexpected UndefValue"); 832 // We only have FP UnaryOps right now. 833 assert(!isa<ConstantInt>(C) && "Unexpected Integer UnaryOp"); 834 835 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 836 const APFloat &CV = CFP->getValueAPF(); 837 switch (Opcode) { 838 default: 839 break; 840 case Instruction::FNeg: 841 return ConstantFP::get(C->getContext(), neg(CV)); 842 } 843 } else if (auto *VTy = dyn_cast<FixedVectorType>(C->getType())) { 844 845 Type *Ty = IntegerType::get(VTy->getContext(), 32); 846 // Fast path for splatted constants. 847 if (Constant *Splat = C->getSplatValue()) { 848 Constant *Elt = ConstantExpr::get(Opcode, Splat); 849 return ConstantVector::getSplat(VTy->getElementCount(), Elt); 850 } 851 852 // Fold each element and create a vector constant from those constants. 853 SmallVector<Constant *, 16> Result; 854 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 855 Constant *ExtractIdx = ConstantInt::get(Ty, i); 856 Constant *Elt = ConstantExpr::getExtractElement(C, ExtractIdx); 857 858 Result.push_back(ConstantExpr::get(Opcode, Elt)); 859 } 860 861 return ConstantVector::get(Result); 862 } 863 864 // We don't know how to fold this. 865 return nullptr; 866 } 867 868 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode, Constant *C1, 869 Constant *C2) { 870 assert(Instruction::isBinaryOp(Opcode) && "Non-binary instruction detected"); 871 872 // Simplify BinOps with their identity values first. They are no-ops and we 873 // can always return the other value, including undef or poison values. 874 // FIXME: remove unnecessary duplicated identity patterns below. 875 // FIXME: Use AllowRHSConstant with getBinOpIdentity to handle additional ops, 876 // like X << 0 = X. 877 Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, C1->getType()); 878 if (Identity) { 879 if (C1 == Identity) 880 return C2; 881 if (C2 == Identity) 882 return C1; 883 } 884 885 // Binary operations propagate poison. 886 if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2)) 887 return PoisonValue::get(C1->getType()); 888 889 // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length 890 // vectors are always evaluated per element. 891 bool IsScalableVector = isa<ScalableVectorType>(C1->getType()); 892 bool HasScalarUndefOrScalableVectorUndef = 893 (!C1->getType()->isVectorTy() || IsScalableVector) && 894 (isa<UndefValue>(C1) || isa<UndefValue>(C2)); 895 if (HasScalarUndefOrScalableVectorUndef) { 896 switch (static_cast<Instruction::BinaryOps>(Opcode)) { 897 case Instruction::Xor: 898 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) 899 // Handle undef ^ undef -> 0 special case. This is a common 900 // idiom (misuse). 901 return Constant::getNullValue(C1->getType()); 902 LLVM_FALLTHROUGH; 903 case Instruction::Add: 904 case Instruction::Sub: 905 return UndefValue::get(C1->getType()); 906 case Instruction::And: 907 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef 908 return C1; 909 return Constant::getNullValue(C1->getType()); // undef & X -> 0 910 case Instruction::Mul: { 911 // undef * undef -> undef 912 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) 913 return C1; 914 const APInt *CV; 915 // X * undef -> undef if X is odd 916 if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV))) 917 if ((*CV)[0]) 918 return UndefValue::get(C1->getType()); 919 920 // X * undef -> 0 otherwise 921 return Constant::getNullValue(C1->getType()); 922 } 923 case Instruction::SDiv: 924 case Instruction::UDiv: 925 // X / undef -> undef 926 if (isa<UndefValue>(C2)) 927 return C2; 928 // undef / 0 -> undef 929 // undef / 1 -> undef 930 if (match(C2, m_Zero()) || match(C2, m_One())) 931 return C1; 932 // undef / X -> 0 otherwise 933 return Constant::getNullValue(C1->getType()); 934 case Instruction::URem: 935 case Instruction::SRem: 936 // X % undef -> undef 937 if (match(C2, m_Undef())) 938 return C2; 939 // undef % 0 -> undef 940 if (match(C2, m_Zero())) 941 return C1; 942 // undef % X -> 0 otherwise 943 return Constant::getNullValue(C1->getType()); 944 case Instruction::Or: // X | undef -> -1 945 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef 946 return C1; 947 return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0 948 case Instruction::LShr: 949 // X >>l undef -> undef 950 if (isa<UndefValue>(C2)) 951 return C2; 952 // undef >>l 0 -> undef 953 if (match(C2, m_Zero())) 954 return C1; 955 // undef >>l X -> 0 956 return Constant::getNullValue(C1->getType()); 957 case Instruction::AShr: 958 // X >>a undef -> undef 959 if (isa<UndefValue>(C2)) 960 return C2; 961 // undef >>a 0 -> undef 962 if (match(C2, m_Zero())) 963 return C1; 964 // TODO: undef >>a X -> undef if the shift is exact 965 // undef >>a X -> 0 966 return Constant::getNullValue(C1->getType()); 967 case Instruction::Shl: 968 // X << undef -> undef 969 if (isa<UndefValue>(C2)) 970 return C2; 971 // undef << 0 -> undef 972 if (match(C2, m_Zero())) 973 return C1; 974 // undef << X -> 0 975 return Constant::getNullValue(C1->getType()); 976 case Instruction::FSub: 977 // -0.0 - undef --> undef (consistent with "fneg undef") 978 if (match(C1, m_NegZeroFP()) && isa<UndefValue>(C2)) 979 return C2; 980 LLVM_FALLTHROUGH; 981 case Instruction::FAdd: 982 case Instruction::FMul: 983 case Instruction::FDiv: 984 case Instruction::FRem: 985 // [any flop] undef, undef -> undef 986 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) 987 return C1; 988 // [any flop] C, undef -> NaN 989 // [any flop] undef, C -> NaN 990 // We could potentially specialize NaN/Inf constants vs. 'normal' 991 // constants (possibly differently depending on opcode and operand). This 992 // would allow returning undef sometimes. But it is always safe to fold to 993 // NaN because we can choose the undef operand as NaN, and any FP opcode 994 // with a NaN operand will propagate NaN. 995 return ConstantFP::getNaN(C1->getType()); 996 case Instruction::BinaryOpsEnd: 997 llvm_unreachable("Invalid BinaryOp"); 998 } 999 } 1000 1001 // Neither constant should be UndefValue, unless these are vector constants. 1002 assert((!HasScalarUndefOrScalableVectorUndef) && "Unexpected UndefValue"); 1003 1004 // Handle simplifications when the RHS is a constant int. 1005 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) { 1006 switch (Opcode) { 1007 case Instruction::Add: 1008 if (CI2->isZero()) return C1; // X + 0 == X 1009 break; 1010 case Instruction::Sub: 1011 if (CI2->isZero()) return C1; // X - 0 == X 1012 break; 1013 case Instruction::Mul: 1014 if (CI2->isZero()) return C2; // X * 0 == 0 1015 if (CI2->isOne()) 1016 return C1; // X * 1 == X 1017 break; 1018 case Instruction::UDiv: 1019 case Instruction::SDiv: 1020 if (CI2->isOne()) 1021 return C1; // X / 1 == X 1022 if (CI2->isZero()) 1023 return UndefValue::get(CI2->getType()); // X / 0 == undef 1024 break; 1025 case Instruction::URem: 1026 case Instruction::SRem: 1027 if (CI2->isOne()) 1028 return Constant::getNullValue(CI2->getType()); // X % 1 == 0 1029 if (CI2->isZero()) 1030 return UndefValue::get(CI2->getType()); // X % 0 == undef 1031 break; 1032 case Instruction::And: 1033 if (CI2->isZero()) return C2; // X & 0 == 0 1034 if (CI2->isMinusOne()) 1035 return C1; // X & -1 == X 1036 1037 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 1038 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64) 1039 if (CE1->getOpcode() == Instruction::ZExt) { 1040 unsigned DstWidth = CI2->getType()->getBitWidth(); 1041 unsigned SrcWidth = 1042 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits(); 1043 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth)); 1044 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits) 1045 return C1; 1046 } 1047 1048 // If and'ing the address of a global with a constant, fold it. 1049 if (CE1->getOpcode() == Instruction::PtrToInt && 1050 isa<GlobalValue>(CE1->getOperand(0))) { 1051 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0)); 1052 1053 MaybeAlign GVAlign; 1054 1055 if (Module *TheModule = GV->getParent()) { 1056 const DataLayout &DL = TheModule->getDataLayout(); 1057 GVAlign = GV->getPointerAlignment(DL); 1058 1059 // If the function alignment is not specified then assume that it 1060 // is 4. 1061 // This is dangerous; on x86, the alignment of the pointer 1062 // corresponds to the alignment of the function, but might be less 1063 // than 4 if it isn't explicitly specified. 1064 // However, a fix for this behaviour was reverted because it 1065 // increased code size (see https://reviews.llvm.org/D55115) 1066 // FIXME: This code should be deleted once existing targets have 1067 // appropriate defaults 1068 if (isa<Function>(GV) && !DL.getFunctionPtrAlign()) 1069 GVAlign = Align(4); 1070 } else if (isa<Function>(GV)) { 1071 // Without a datalayout we have to assume the worst case: that the 1072 // function pointer isn't aligned at all. 1073 GVAlign = llvm::None; 1074 } else if (isa<GlobalVariable>(GV)) { 1075 GVAlign = cast<GlobalVariable>(GV)->getAlign(); 1076 } 1077 1078 if (GVAlign && *GVAlign > 1) { 1079 unsigned DstWidth = CI2->getType()->getBitWidth(); 1080 unsigned SrcWidth = std::min(DstWidth, Log2(*GVAlign)); 1081 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth)); 1082 1083 // If checking bits we know are clear, return zero. 1084 if ((CI2->getValue() & BitsNotSet) == CI2->getValue()) 1085 return Constant::getNullValue(CI2->getType()); 1086 } 1087 } 1088 } 1089 break; 1090 case Instruction::Or: 1091 if (CI2->isZero()) return C1; // X | 0 == X 1092 if (CI2->isMinusOne()) 1093 return C2; // X | -1 == -1 1094 break; 1095 case Instruction::Xor: 1096 if (CI2->isZero()) return C1; // X ^ 0 == X 1097 1098 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 1099 switch (CE1->getOpcode()) { 1100 default: break; 1101 case Instruction::ICmp: 1102 case Instruction::FCmp: 1103 // cmp pred ^ true -> cmp !pred 1104 assert(CI2->isOne()); 1105 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate(); 1106 pred = CmpInst::getInversePredicate(pred); 1107 return ConstantExpr::getCompare(pred, CE1->getOperand(0), 1108 CE1->getOperand(1)); 1109 } 1110 } 1111 break; 1112 case Instruction::AShr: 1113 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2 1114 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) 1115 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero. 1116 return ConstantExpr::getLShr(C1, C2); 1117 break; 1118 } 1119 } else if (isa<ConstantInt>(C1)) { 1120 // If C1 is a ConstantInt and C2 is not, swap the operands. 1121 if (Instruction::isCommutative(Opcode)) 1122 return ConstantExpr::get(Opcode, C2, C1); 1123 } 1124 1125 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) { 1126 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) { 1127 const APInt &C1V = CI1->getValue(); 1128 const APInt &C2V = CI2->getValue(); 1129 switch (Opcode) { 1130 default: 1131 break; 1132 case Instruction::Add: 1133 return ConstantInt::get(CI1->getContext(), C1V + C2V); 1134 case Instruction::Sub: 1135 return ConstantInt::get(CI1->getContext(), C1V - C2V); 1136 case Instruction::Mul: 1137 return ConstantInt::get(CI1->getContext(), C1V * C2V); 1138 case Instruction::UDiv: 1139 assert(!CI2->isZero() && "Div by zero handled above"); 1140 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V)); 1141 case Instruction::SDiv: 1142 assert(!CI2->isZero() && "Div by zero handled above"); 1143 if (C2V.isAllOnesValue() && C1V.isMinSignedValue()) 1144 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef 1145 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V)); 1146 case Instruction::URem: 1147 assert(!CI2->isZero() && "Div by zero handled above"); 1148 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V)); 1149 case Instruction::SRem: 1150 assert(!CI2->isZero() && "Div by zero handled above"); 1151 if (C2V.isAllOnesValue() && C1V.isMinSignedValue()) 1152 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef 1153 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V)); 1154 case Instruction::And: 1155 return ConstantInt::get(CI1->getContext(), C1V & C2V); 1156 case Instruction::Or: 1157 return ConstantInt::get(CI1->getContext(), C1V | C2V); 1158 case Instruction::Xor: 1159 return ConstantInt::get(CI1->getContext(), C1V ^ C2V); 1160 case Instruction::Shl: 1161 if (C2V.ult(C1V.getBitWidth())) 1162 return ConstantInt::get(CI1->getContext(), C1V.shl(C2V)); 1163 return UndefValue::get(C1->getType()); // too big shift is undef 1164 case Instruction::LShr: 1165 if (C2V.ult(C1V.getBitWidth())) 1166 return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V)); 1167 return UndefValue::get(C1->getType()); // too big shift is undef 1168 case Instruction::AShr: 1169 if (C2V.ult(C1V.getBitWidth())) 1170 return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V)); 1171 return UndefValue::get(C1->getType()); // too big shift is undef 1172 } 1173 } 1174 1175 switch (Opcode) { 1176 case Instruction::SDiv: 1177 case Instruction::UDiv: 1178 case Instruction::URem: 1179 case Instruction::SRem: 1180 case Instruction::LShr: 1181 case Instruction::AShr: 1182 case Instruction::Shl: 1183 if (CI1->isZero()) return C1; 1184 break; 1185 default: 1186 break; 1187 } 1188 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) { 1189 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) { 1190 const APFloat &C1V = CFP1->getValueAPF(); 1191 const APFloat &C2V = CFP2->getValueAPF(); 1192 APFloat C3V = C1V; // copy for modification 1193 switch (Opcode) { 1194 default: 1195 break; 1196 case Instruction::FAdd: 1197 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven); 1198 return ConstantFP::get(C1->getContext(), C3V); 1199 case Instruction::FSub: 1200 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven); 1201 return ConstantFP::get(C1->getContext(), C3V); 1202 case Instruction::FMul: 1203 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven); 1204 return ConstantFP::get(C1->getContext(), C3V); 1205 case Instruction::FDiv: 1206 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven); 1207 return ConstantFP::get(C1->getContext(), C3V); 1208 case Instruction::FRem: 1209 (void)C3V.mod(C2V); 1210 return ConstantFP::get(C1->getContext(), C3V); 1211 } 1212 } 1213 } else if (auto *VTy = dyn_cast<VectorType>(C1->getType())) { 1214 // Fast path for splatted constants. 1215 if (Constant *C2Splat = C2->getSplatValue()) { 1216 if (Instruction::isIntDivRem(Opcode) && C2Splat->isNullValue()) 1217 return UndefValue::get(VTy); 1218 if (Constant *C1Splat = C1->getSplatValue()) { 1219 return ConstantVector::getSplat( 1220 VTy->getElementCount(), 1221 ConstantExpr::get(Opcode, C1Splat, C2Splat)); 1222 } 1223 } 1224 1225 if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) { 1226 // Fold each element and create a vector constant from those constants. 1227 SmallVector<Constant*, 16> Result; 1228 Type *Ty = IntegerType::get(FVTy->getContext(), 32); 1229 for (unsigned i = 0, e = FVTy->getNumElements(); i != e; ++i) { 1230 Constant *ExtractIdx = ConstantInt::get(Ty, i); 1231 Constant *LHS = ConstantExpr::getExtractElement(C1, ExtractIdx); 1232 Constant *RHS = ConstantExpr::getExtractElement(C2, ExtractIdx); 1233 1234 // If any element of a divisor vector is zero, the whole op is undef. 1235 if (Instruction::isIntDivRem(Opcode) && RHS->isNullValue()) 1236 return UndefValue::get(VTy); 1237 1238 Result.push_back(ConstantExpr::get(Opcode, LHS, RHS)); 1239 } 1240 1241 return ConstantVector::get(Result); 1242 } 1243 } 1244 1245 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 1246 // There are many possible foldings we could do here. We should probably 1247 // at least fold add of a pointer with an integer into the appropriate 1248 // getelementptr. This will improve alias analysis a bit. 1249 1250 // Given ((a + b) + c), if (b + c) folds to something interesting, return 1251 // (a + (b + c)). 1252 if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) { 1253 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2); 1254 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode) 1255 return ConstantExpr::get(Opcode, CE1->getOperand(0), T); 1256 } 1257 } else if (isa<ConstantExpr>(C2)) { 1258 // If C2 is a constant expr and C1 isn't, flop them around and fold the 1259 // other way if possible. 1260 if (Instruction::isCommutative(Opcode)) 1261 return ConstantFoldBinaryInstruction(Opcode, C2, C1); 1262 } 1263 1264 // i1 can be simplified in many cases. 1265 if (C1->getType()->isIntegerTy(1)) { 1266 switch (Opcode) { 1267 case Instruction::Add: 1268 case Instruction::Sub: 1269 return ConstantExpr::getXor(C1, C2); 1270 case Instruction::Mul: 1271 return ConstantExpr::getAnd(C1, C2); 1272 case Instruction::Shl: 1273 case Instruction::LShr: 1274 case Instruction::AShr: 1275 // We can assume that C2 == 0. If it were one the result would be 1276 // undefined because the shift value is as large as the bitwidth. 1277 return C1; 1278 case Instruction::SDiv: 1279 case Instruction::UDiv: 1280 // We can assume that C2 == 1. If it were zero the result would be 1281 // undefined through division by zero. 1282 return C1; 1283 case Instruction::URem: 1284 case Instruction::SRem: 1285 // We can assume that C2 == 1. If it were zero the result would be 1286 // undefined through division by zero. 1287 return ConstantInt::getFalse(C1->getContext()); 1288 default: 1289 break; 1290 } 1291 } 1292 1293 // We don't know how to fold this. 1294 return nullptr; 1295 } 1296 1297 /// This type is zero-sized if it's an array or structure of zero-sized types. 1298 /// The only leaf zero-sized type is an empty structure. 1299 static bool isMaybeZeroSizedType(Type *Ty) { 1300 if (StructType *STy = dyn_cast<StructType>(Ty)) { 1301 if (STy->isOpaque()) return true; // Can't say. 1302 1303 // If all of elements have zero size, this does too. 1304 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 1305 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false; 1306 return true; 1307 1308 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1309 return isMaybeZeroSizedType(ATy->getElementType()); 1310 } 1311 return false; 1312 } 1313 1314 /// Compare the two constants as though they were getelementptr indices. 1315 /// This allows coercion of the types to be the same thing. 1316 /// 1317 /// If the two constants are the "same" (after coercion), return 0. If the 1318 /// first is less than the second, return -1, if the second is less than the 1319 /// first, return 1. If the constants are not integral, return -2. 1320 /// 1321 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) { 1322 if (C1 == C2) return 0; 1323 1324 // Ok, we found a different index. If they are not ConstantInt, we can't do 1325 // anything with them. 1326 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2)) 1327 return -2; // don't know! 1328 1329 // We cannot compare the indices if they don't fit in an int64_t. 1330 if (cast<ConstantInt>(C1)->getValue().getActiveBits() > 64 || 1331 cast<ConstantInt>(C2)->getValue().getActiveBits() > 64) 1332 return -2; // don't know! 1333 1334 // Ok, we have two differing integer indices. Sign extend them to be the same 1335 // type. 1336 int64_t C1Val = cast<ConstantInt>(C1)->getSExtValue(); 1337 int64_t C2Val = cast<ConstantInt>(C2)->getSExtValue(); 1338 1339 if (C1Val == C2Val) return 0; // They are equal 1340 1341 // If the type being indexed over is really just a zero sized type, there is 1342 // no pointer difference being made here. 1343 if (isMaybeZeroSizedType(ElTy)) 1344 return -2; // dunno. 1345 1346 // If they are really different, now that they are the same type, then we 1347 // found a difference! 1348 if (C1Val < C2Val) 1349 return -1; 1350 else 1351 return 1; 1352 } 1353 1354 /// This function determines if there is anything we can decide about the two 1355 /// constants provided. This doesn't need to handle simple things like 1356 /// ConstantFP comparisons, but should instead handle ConstantExprs. 1357 /// If we can determine that the two constants have a particular relation to 1358 /// each other, we should return the corresponding FCmpInst predicate, 1359 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in 1360 /// ConstantFoldCompareInstruction. 1361 /// 1362 /// To simplify this code we canonicalize the relation so that the first 1363 /// operand is always the most "complex" of the two. We consider ConstantFP 1364 /// to be the simplest, and ConstantExprs to be the most complex. 1365 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) { 1366 assert(V1->getType() == V2->getType() && 1367 "Cannot compare values of different types!"); 1368 1369 // We do not know if a constant expression will evaluate to a number or NaN. 1370 // Therefore, we can only say that the relation is unordered or equal. 1371 if (V1 == V2) return FCmpInst::FCMP_UEQ; 1372 1373 if (!isa<ConstantExpr>(V1)) { 1374 if (!isa<ConstantExpr>(V2)) { 1375 // Simple case, use the standard constant folder. 1376 ConstantInt *R = nullptr; 1377 R = dyn_cast<ConstantInt>( 1378 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2)); 1379 if (R && !R->isZero()) 1380 return FCmpInst::FCMP_OEQ; 1381 R = dyn_cast<ConstantInt>( 1382 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2)); 1383 if (R && !R->isZero()) 1384 return FCmpInst::FCMP_OLT; 1385 R = dyn_cast<ConstantInt>( 1386 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2)); 1387 if (R && !R->isZero()) 1388 return FCmpInst::FCMP_OGT; 1389 1390 // Nothing more we can do 1391 return FCmpInst::BAD_FCMP_PREDICATE; 1392 } 1393 1394 // If the first operand is simple and second is ConstantExpr, swap operands. 1395 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1); 1396 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE) 1397 return FCmpInst::getSwappedPredicate(SwappedRelation); 1398 } else { 1399 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a 1400 // constantexpr or a simple constant. 1401 ConstantExpr *CE1 = cast<ConstantExpr>(V1); 1402 switch (CE1->getOpcode()) { 1403 case Instruction::FPTrunc: 1404 case Instruction::FPExt: 1405 case Instruction::UIToFP: 1406 case Instruction::SIToFP: 1407 // We might be able to do something with these but we don't right now. 1408 break; 1409 default: 1410 break; 1411 } 1412 } 1413 // There are MANY other foldings that we could perform here. They will 1414 // probably be added on demand, as they seem needed. 1415 return FCmpInst::BAD_FCMP_PREDICATE; 1416 } 1417 1418 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1, 1419 const GlobalValue *GV2) { 1420 auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) { 1421 if (GV->isInterposable() || GV->hasGlobalUnnamedAddr()) 1422 return true; 1423 if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) { 1424 Type *Ty = GVar->getValueType(); 1425 // A global with opaque type might end up being zero sized. 1426 if (!Ty->isSized()) 1427 return true; 1428 // A global with an empty type might lie at the address of any other 1429 // global. 1430 if (Ty->isEmptyTy()) 1431 return true; 1432 } 1433 return false; 1434 }; 1435 // Don't try to decide equality of aliases. 1436 if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2)) 1437 if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2)) 1438 return ICmpInst::ICMP_NE; 1439 return ICmpInst::BAD_ICMP_PREDICATE; 1440 } 1441 1442 /// This function determines if there is anything we can decide about the two 1443 /// constants provided. This doesn't need to handle simple things like integer 1444 /// comparisons, but should instead handle ConstantExprs and GlobalValues. 1445 /// If we can determine that the two constants have a particular relation to 1446 /// each other, we should return the corresponding ICmp predicate, otherwise 1447 /// return ICmpInst::BAD_ICMP_PREDICATE. 1448 /// 1449 /// To simplify this code we canonicalize the relation so that the first 1450 /// operand is always the most "complex" of the two. We consider simple 1451 /// constants (like ConstantInt) to be the simplest, followed by 1452 /// GlobalValues, followed by ConstantExpr's (the most complex). 1453 /// 1454 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2, 1455 bool isSigned) { 1456 assert(V1->getType() == V2->getType() && 1457 "Cannot compare different types of values!"); 1458 if (V1 == V2) return ICmpInst::ICMP_EQ; 1459 1460 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) && 1461 !isa<BlockAddress>(V1)) { 1462 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) && 1463 !isa<BlockAddress>(V2)) { 1464 // We distilled this down to a simple case, use the standard constant 1465 // folder. 1466 ConstantInt *R = nullptr; 1467 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ; 1468 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1469 if (R && !R->isZero()) 1470 return pred; 1471 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1472 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1473 if (R && !R->isZero()) 1474 return pred; 1475 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1476 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 1477 if (R && !R->isZero()) 1478 return pred; 1479 1480 // If we couldn't figure it out, bail. 1481 return ICmpInst::BAD_ICMP_PREDICATE; 1482 } 1483 1484 // If the first operand is simple, swap operands. 1485 ICmpInst::Predicate SwappedRelation = 1486 evaluateICmpRelation(V2, V1, isSigned); 1487 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1488 return ICmpInst::getSwappedPredicate(SwappedRelation); 1489 1490 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) { 1491 if (isa<ConstantExpr>(V2)) { // Swap as necessary. 1492 ICmpInst::Predicate SwappedRelation = 1493 evaluateICmpRelation(V2, V1, isSigned); 1494 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1495 return ICmpInst::getSwappedPredicate(SwappedRelation); 1496 return ICmpInst::BAD_ICMP_PREDICATE; 1497 } 1498 1499 // Now we know that the RHS is a GlobalValue, BlockAddress or simple 1500 // constant (which, since the types must match, means that it's a 1501 // ConstantPointerNull). 1502 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) { 1503 return areGlobalsPotentiallyEqual(GV, GV2); 1504 } else if (isa<BlockAddress>(V2)) { 1505 return ICmpInst::ICMP_NE; // Globals never equal labels. 1506 } else { 1507 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!"); 1508 // GlobalVals can never be null unless they have external weak linkage. 1509 // We don't try to evaluate aliases here. 1510 // NOTE: We should not be doing this constant folding if null pointer 1511 // is considered valid for the function. But currently there is no way to 1512 // query it from the Constant type. 1513 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV) && 1514 !NullPointerIsDefined(nullptr /* F */, 1515 GV->getType()->getAddressSpace())) 1516 return ICmpInst::ICMP_UGT; 1517 } 1518 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) { 1519 if (isa<ConstantExpr>(V2)) { // Swap as necessary. 1520 ICmpInst::Predicate SwappedRelation = 1521 evaluateICmpRelation(V2, V1, isSigned); 1522 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 1523 return ICmpInst::getSwappedPredicate(SwappedRelation); 1524 return ICmpInst::BAD_ICMP_PREDICATE; 1525 } 1526 1527 // Now we know that the RHS is a GlobalValue, BlockAddress or simple 1528 // constant (which, since the types must match, means that it is a 1529 // ConstantPointerNull). 1530 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) { 1531 // Block address in another function can't equal this one, but block 1532 // addresses in the current function might be the same if blocks are 1533 // empty. 1534 if (BA2->getFunction() != BA->getFunction()) 1535 return ICmpInst::ICMP_NE; 1536 } else { 1537 // Block addresses aren't null, don't equal the address of globals. 1538 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) && 1539 "Canonicalization guarantee!"); 1540 return ICmpInst::ICMP_NE; 1541 } 1542 } else { 1543 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a 1544 // constantexpr, a global, block address, or a simple constant. 1545 ConstantExpr *CE1 = cast<ConstantExpr>(V1); 1546 Constant *CE1Op0 = CE1->getOperand(0); 1547 1548 switch (CE1->getOpcode()) { 1549 case Instruction::Trunc: 1550 case Instruction::FPTrunc: 1551 case Instruction::FPExt: 1552 case Instruction::FPToUI: 1553 case Instruction::FPToSI: 1554 break; // We can't evaluate floating point casts or truncations. 1555 1556 case Instruction::BitCast: 1557 // If this is a global value cast, check to see if the RHS is also a 1558 // GlobalValue. 1559 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) 1560 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) 1561 return areGlobalsPotentiallyEqual(GV, GV2); 1562 LLVM_FALLTHROUGH; 1563 case Instruction::UIToFP: 1564 case Instruction::SIToFP: 1565 case Instruction::ZExt: 1566 case Instruction::SExt: 1567 // We can't evaluate floating point casts or truncations. 1568 if (CE1Op0->getType()->isFPOrFPVectorTy()) 1569 break; 1570 1571 // If the cast is not actually changing bits, and the second operand is a 1572 // null pointer, do the comparison with the pre-casted value. 1573 if (V2->isNullValue() && CE1->getType()->isIntOrPtrTy()) { 1574 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false; 1575 if (CE1->getOpcode() == Instruction::SExt) isSigned = true; 1576 return evaluateICmpRelation(CE1Op0, 1577 Constant::getNullValue(CE1Op0->getType()), 1578 isSigned); 1579 } 1580 break; 1581 1582 case Instruction::GetElementPtr: { 1583 GEPOperator *CE1GEP = cast<GEPOperator>(CE1); 1584 // Ok, since this is a getelementptr, we know that the constant has a 1585 // pointer type. Check the various cases. 1586 if (isa<ConstantPointerNull>(V2)) { 1587 // If we are comparing a GEP to a null pointer, check to see if the base 1588 // of the GEP equals the null pointer. 1589 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) { 1590 // If its not weak linkage, the GVal must have a non-zero address 1591 // so the result is greater-than 1592 if (!GV->hasExternalWeakLinkage()) 1593 return ICmpInst::ICMP_UGT; 1594 } else if (isa<ConstantPointerNull>(CE1Op0)) { 1595 // If we are indexing from a null pointer, check to see if we have any 1596 // non-zero indices. 1597 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i) 1598 if (!CE1->getOperand(i)->isNullValue()) 1599 // Offsetting from null, must not be equal. 1600 return ICmpInst::ICMP_UGT; 1601 // Only zero indexes from null, must still be zero. 1602 return ICmpInst::ICMP_EQ; 1603 } 1604 // Otherwise, we can't really say if the first operand is null or not. 1605 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) { 1606 if (isa<ConstantPointerNull>(CE1Op0)) { 1607 // If its not weak linkage, the GVal must have a non-zero address 1608 // so the result is less-than 1609 if (!GV2->hasExternalWeakLinkage()) 1610 return ICmpInst::ICMP_ULT; 1611 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) { 1612 if (GV == GV2) { 1613 // If this is a getelementptr of the same global, then it must be 1614 // different. Because the types must match, the getelementptr could 1615 // only have at most one index, and because we fold getelementptr's 1616 // with a single zero index, it must be nonzero. 1617 assert(CE1->getNumOperands() == 2 && 1618 !CE1->getOperand(1)->isNullValue() && 1619 "Surprising getelementptr!"); 1620 return ICmpInst::ICMP_UGT; 1621 } else { 1622 if (CE1GEP->hasAllZeroIndices()) 1623 return areGlobalsPotentiallyEqual(GV, GV2); 1624 return ICmpInst::BAD_ICMP_PREDICATE; 1625 } 1626 } 1627 } else { 1628 ConstantExpr *CE2 = cast<ConstantExpr>(V2); 1629 Constant *CE2Op0 = CE2->getOperand(0); 1630 1631 // There are MANY other foldings that we could perform here. They will 1632 // probably be added on demand, as they seem needed. 1633 switch (CE2->getOpcode()) { 1634 default: break; 1635 case Instruction::GetElementPtr: 1636 // By far the most common case to handle is when the base pointers are 1637 // obviously to the same global. 1638 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) { 1639 // Don't know relative ordering, but check for inequality. 1640 if (CE1Op0 != CE2Op0) { 1641 GEPOperator *CE2GEP = cast<GEPOperator>(CE2); 1642 if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices()) 1643 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0), 1644 cast<GlobalValue>(CE2Op0)); 1645 return ICmpInst::BAD_ICMP_PREDICATE; 1646 } 1647 // Ok, we know that both getelementptr instructions are based on the 1648 // same global. From this, we can precisely determine the relative 1649 // ordering of the resultant pointers. 1650 unsigned i = 1; 1651 1652 // The logic below assumes that the result of the comparison 1653 // can be determined by finding the first index that differs. 1654 // This doesn't work if there is over-indexing in any 1655 // subsequent indices, so check for that case first. 1656 if (!CE1->isGEPWithNoNotionalOverIndexing() || 1657 !CE2->isGEPWithNoNotionalOverIndexing()) 1658 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1659 1660 // Compare all of the operands the GEP's have in common. 1661 gep_type_iterator GTI = gep_type_begin(CE1); 1662 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands(); 1663 ++i, ++GTI) 1664 switch (IdxCompare(CE1->getOperand(i), 1665 CE2->getOperand(i), GTI.getIndexedType())) { 1666 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT; 1667 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT; 1668 case -2: return ICmpInst::BAD_ICMP_PREDICATE; 1669 } 1670 1671 // Ok, we ran out of things they have in common. If any leftovers 1672 // are non-zero then we have a difference, otherwise we are equal. 1673 for (; i < CE1->getNumOperands(); ++i) 1674 if (!CE1->getOperand(i)->isNullValue()) { 1675 if (isa<ConstantInt>(CE1->getOperand(i))) 1676 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 1677 else 1678 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1679 } 1680 1681 for (; i < CE2->getNumOperands(); ++i) 1682 if (!CE2->getOperand(i)->isNullValue()) { 1683 if (isa<ConstantInt>(CE2->getOperand(i))) 1684 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 1685 else 1686 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 1687 } 1688 return ICmpInst::ICMP_EQ; 1689 } 1690 } 1691 } 1692 break; 1693 } 1694 default: 1695 break; 1696 } 1697 } 1698 1699 return ICmpInst::BAD_ICMP_PREDICATE; 1700 } 1701 1702 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 1703 Constant *C1, Constant *C2) { 1704 Type *ResultTy; 1705 if (VectorType *VT = dyn_cast<VectorType>(C1->getType())) 1706 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()), 1707 VT->getElementCount()); 1708 else 1709 ResultTy = Type::getInt1Ty(C1->getContext()); 1710 1711 // Fold FCMP_FALSE/FCMP_TRUE unconditionally. 1712 if (pred == FCmpInst::FCMP_FALSE) 1713 return Constant::getNullValue(ResultTy); 1714 1715 if (pred == FCmpInst::FCMP_TRUE) 1716 return Constant::getAllOnesValue(ResultTy); 1717 1718 // Handle some degenerate cases first 1719 if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2)) 1720 return PoisonValue::get(ResultTy); 1721 1722 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) { 1723 CmpInst::Predicate Predicate = CmpInst::Predicate(pred); 1724 bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate); 1725 // For EQ and NE, we can always pick a value for the undef to make the 1726 // predicate pass or fail, so we can return undef. 1727 // Also, if both operands are undef, we can return undef for int comparison. 1728 if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2)) 1729 return UndefValue::get(ResultTy); 1730 1731 // Otherwise, for integer compare, pick the same value as the non-undef 1732 // operand, and fold it to true or false. 1733 if (isIntegerPredicate) 1734 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(Predicate)); 1735 1736 // Choosing NaN for the undef will always make unordered comparison succeed 1737 // and ordered comparison fails. 1738 return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate)); 1739 } 1740 1741 // icmp eq/ne(null,GV) -> false/true 1742 if (C1->isNullValue()) { 1743 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2)) 1744 // Don't try to evaluate aliases. External weak GV can be null. 1745 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() && 1746 !NullPointerIsDefined(nullptr /* F */, 1747 GV->getType()->getAddressSpace())) { 1748 if (pred == ICmpInst::ICMP_EQ) 1749 return ConstantInt::getFalse(C1->getContext()); 1750 else if (pred == ICmpInst::ICMP_NE) 1751 return ConstantInt::getTrue(C1->getContext()); 1752 } 1753 // icmp eq/ne(GV,null) -> false/true 1754 } else if (C2->isNullValue()) { 1755 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1)) { 1756 // Don't try to evaluate aliases. External weak GV can be null. 1757 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() && 1758 !NullPointerIsDefined(nullptr /* F */, 1759 GV->getType()->getAddressSpace())) { 1760 if (pred == ICmpInst::ICMP_EQ) 1761 return ConstantInt::getFalse(C1->getContext()); 1762 else if (pred == ICmpInst::ICMP_NE) 1763 return ConstantInt::getTrue(C1->getContext()); 1764 } 1765 } 1766 1767 // The caller is expected to commute the operands if the constant expression 1768 // is C2. 1769 // C1 >= 0 --> true 1770 if (pred == ICmpInst::ICMP_UGE) 1771 return Constant::getAllOnesValue(ResultTy); 1772 // C1 < 0 --> false 1773 if (pred == ICmpInst::ICMP_ULT) 1774 return Constant::getNullValue(ResultTy); 1775 } 1776 1777 // If the comparison is a comparison between two i1's, simplify it. 1778 if (C1->getType()->isIntegerTy(1)) { 1779 switch(pred) { 1780 case ICmpInst::ICMP_EQ: 1781 if (isa<ConstantInt>(C2)) 1782 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2)); 1783 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2); 1784 case ICmpInst::ICMP_NE: 1785 return ConstantExpr::getXor(C1, C2); 1786 default: 1787 break; 1788 } 1789 } 1790 1791 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) { 1792 const APInt &V1 = cast<ConstantInt>(C1)->getValue(); 1793 const APInt &V2 = cast<ConstantInt>(C2)->getValue(); 1794 switch (pred) { 1795 default: llvm_unreachable("Invalid ICmp Predicate"); 1796 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2); 1797 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2); 1798 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2)); 1799 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2)); 1800 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2)); 1801 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2)); 1802 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2)); 1803 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2)); 1804 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2)); 1805 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2)); 1806 } 1807 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) { 1808 const APFloat &C1V = cast<ConstantFP>(C1)->getValueAPF(); 1809 const APFloat &C2V = cast<ConstantFP>(C2)->getValueAPF(); 1810 APFloat::cmpResult R = C1V.compare(C2V); 1811 switch (pred) { 1812 default: llvm_unreachable("Invalid FCmp Predicate"); 1813 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy); 1814 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy); 1815 case FCmpInst::FCMP_UNO: 1816 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered); 1817 case FCmpInst::FCMP_ORD: 1818 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered); 1819 case FCmpInst::FCMP_UEQ: 1820 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1821 R==APFloat::cmpEqual); 1822 case FCmpInst::FCMP_OEQ: 1823 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual); 1824 case FCmpInst::FCMP_UNE: 1825 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual); 1826 case FCmpInst::FCMP_ONE: 1827 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan || 1828 R==APFloat::cmpGreaterThan); 1829 case FCmpInst::FCMP_ULT: 1830 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1831 R==APFloat::cmpLessThan); 1832 case FCmpInst::FCMP_OLT: 1833 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan); 1834 case FCmpInst::FCMP_UGT: 1835 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 1836 R==APFloat::cmpGreaterThan); 1837 case FCmpInst::FCMP_OGT: 1838 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan); 1839 case FCmpInst::FCMP_ULE: 1840 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan); 1841 case FCmpInst::FCMP_OLE: 1842 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan || 1843 R==APFloat::cmpEqual); 1844 case FCmpInst::FCMP_UGE: 1845 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan); 1846 case FCmpInst::FCMP_OGE: 1847 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan || 1848 R==APFloat::cmpEqual); 1849 } 1850 } else if (auto *C1VTy = dyn_cast<VectorType>(C1->getType())) { 1851 1852 // Fast path for splatted constants. 1853 if (Constant *C1Splat = C1->getSplatValue()) 1854 if (Constant *C2Splat = C2->getSplatValue()) 1855 return ConstantVector::getSplat( 1856 C1VTy->getElementCount(), 1857 ConstantExpr::getCompare(pred, C1Splat, C2Splat)); 1858 1859 // Do not iterate on scalable vector. The number of elements is unknown at 1860 // compile-time. 1861 if (isa<ScalableVectorType>(C1VTy)) 1862 return nullptr; 1863 1864 // If we can constant fold the comparison of each element, constant fold 1865 // the whole vector comparison. 1866 SmallVector<Constant*, 4> ResElts; 1867 Type *Ty = IntegerType::get(C1->getContext(), 32); 1868 // Compare the elements, producing an i1 result or constant expr. 1869 for (unsigned I = 0, E = C1VTy->getElementCount().getKnownMinValue(); 1870 I != E; ++I) { 1871 Constant *C1E = 1872 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, I)); 1873 Constant *C2E = 1874 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, I)); 1875 1876 ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E)); 1877 } 1878 1879 return ConstantVector::get(ResElts); 1880 } 1881 1882 if (C1->getType()->isFloatingPointTy() && 1883 // Only call evaluateFCmpRelation if we have a constant expr to avoid 1884 // infinite recursive loop 1885 (isa<ConstantExpr>(C1) || isa<ConstantExpr>(C2))) { 1886 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true. 1887 switch (evaluateFCmpRelation(C1, C2)) { 1888 default: llvm_unreachable("Unknown relation!"); 1889 case FCmpInst::FCMP_UNO: 1890 case FCmpInst::FCMP_ORD: 1891 case FCmpInst::FCMP_UNE: 1892 case FCmpInst::FCMP_ULT: 1893 case FCmpInst::FCMP_UGT: 1894 case FCmpInst::FCMP_ULE: 1895 case FCmpInst::FCMP_UGE: 1896 case FCmpInst::FCMP_TRUE: 1897 case FCmpInst::FCMP_FALSE: 1898 case FCmpInst::BAD_FCMP_PREDICATE: 1899 break; // Couldn't determine anything about these constants. 1900 case FCmpInst::FCMP_OEQ: // We know that C1 == C2 1901 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ || 1902 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE || 1903 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE); 1904 break; 1905 case FCmpInst::FCMP_OLT: // We know that C1 < C2 1906 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE || 1907 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT || 1908 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE); 1909 break; 1910 case FCmpInst::FCMP_OGT: // We know that C1 > C2 1911 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE || 1912 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT || 1913 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE); 1914 break; 1915 case FCmpInst::FCMP_OLE: // We know that C1 <= C2 1916 // We can only partially decide this relation. 1917 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 1918 Result = 0; 1919 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 1920 Result = 1; 1921 break; 1922 case FCmpInst::FCMP_OGE: // We known that C1 >= C2 1923 // We can only partially decide this relation. 1924 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 1925 Result = 0; 1926 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 1927 Result = 1; 1928 break; 1929 case FCmpInst::FCMP_ONE: // We know that C1 != C2 1930 // We can only partially decide this relation. 1931 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 1932 Result = 0; 1933 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 1934 Result = 1; 1935 break; 1936 case FCmpInst::FCMP_UEQ: // We know that C1 == C2 || isUnordered(C1, C2). 1937 // We can only partially decide this relation. 1938 if (pred == FCmpInst::FCMP_ONE) 1939 Result = 0; 1940 else if (pred == FCmpInst::FCMP_UEQ) 1941 Result = 1; 1942 break; 1943 } 1944 1945 // If we evaluated the result, return it now. 1946 if (Result != -1) 1947 return ConstantInt::get(ResultTy, Result); 1948 1949 } else { 1950 // Evaluate the relation between the two constants, per the predicate. 1951 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true. 1952 switch (evaluateICmpRelation(C1, C2, 1953 CmpInst::isSigned((CmpInst::Predicate)pred))) { 1954 default: llvm_unreachable("Unknown relational!"); 1955 case ICmpInst::BAD_ICMP_PREDICATE: 1956 break; // Couldn't determine anything about these constants. 1957 case ICmpInst::ICMP_EQ: // We know the constants are equal! 1958 // If we know the constants are equal, we can decide the result of this 1959 // computation precisely. 1960 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred); 1961 break; 1962 case ICmpInst::ICMP_ULT: 1963 switch (pred) { 1964 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE: 1965 Result = 1; break; 1966 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE: 1967 Result = 0; break; 1968 } 1969 break; 1970 case ICmpInst::ICMP_SLT: 1971 switch (pred) { 1972 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE: 1973 Result = 1; break; 1974 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE: 1975 Result = 0; break; 1976 } 1977 break; 1978 case ICmpInst::ICMP_UGT: 1979 switch (pred) { 1980 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE: 1981 Result = 1; break; 1982 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE: 1983 Result = 0; break; 1984 } 1985 break; 1986 case ICmpInst::ICMP_SGT: 1987 switch (pred) { 1988 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE: 1989 Result = 1; break; 1990 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE: 1991 Result = 0; break; 1992 } 1993 break; 1994 case ICmpInst::ICMP_ULE: 1995 if (pred == ICmpInst::ICMP_UGT) Result = 0; 1996 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1; 1997 break; 1998 case ICmpInst::ICMP_SLE: 1999 if (pred == ICmpInst::ICMP_SGT) Result = 0; 2000 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1; 2001 break; 2002 case ICmpInst::ICMP_UGE: 2003 if (pred == ICmpInst::ICMP_ULT) Result = 0; 2004 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1; 2005 break; 2006 case ICmpInst::ICMP_SGE: 2007 if (pred == ICmpInst::ICMP_SLT) Result = 0; 2008 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1; 2009 break; 2010 case ICmpInst::ICMP_NE: 2011 if (pred == ICmpInst::ICMP_EQ) Result = 0; 2012 if (pred == ICmpInst::ICMP_NE) Result = 1; 2013 break; 2014 } 2015 2016 // If we evaluated the result, return it now. 2017 if (Result != -1) 2018 return ConstantInt::get(ResultTy, Result); 2019 2020 // If the right hand side is a bitcast, try using its inverse to simplify 2021 // it by moving it to the left hand side. We can't do this if it would turn 2022 // a vector compare into a scalar compare or visa versa, or if it would turn 2023 // the operands into FP values. 2024 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) { 2025 Constant *CE2Op0 = CE2->getOperand(0); 2026 if (CE2->getOpcode() == Instruction::BitCast && 2027 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy() && 2028 !CE2Op0->getType()->isFPOrFPVectorTy()) { 2029 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType()); 2030 return ConstantExpr::getICmp(pred, Inverse, CE2Op0); 2031 } 2032 } 2033 2034 // If the left hand side is an extension, try eliminating it. 2035 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 2036 if ((CE1->getOpcode() == Instruction::SExt && 2037 ICmpInst::isSigned((ICmpInst::Predicate)pred)) || 2038 (CE1->getOpcode() == Instruction::ZExt && 2039 !ICmpInst::isSigned((ICmpInst::Predicate)pred))){ 2040 Constant *CE1Op0 = CE1->getOperand(0); 2041 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType()); 2042 if (CE1Inverse == CE1Op0) { 2043 // Check whether we can safely truncate the right hand side. 2044 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType()); 2045 if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse, 2046 C2->getType()) == C2) 2047 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse); 2048 } 2049 } 2050 } 2051 2052 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) || 2053 (C1->isNullValue() && !C2->isNullValue())) { 2054 // If C2 is a constant expr and C1 isn't, flip them around and fold the 2055 // other way if possible. 2056 // Also, if C1 is null and C2 isn't, flip them around. 2057 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred); 2058 return ConstantExpr::getICmp(pred, C2, C1); 2059 } 2060 } 2061 return nullptr; 2062 } 2063 2064 /// Test whether the given sequence of *normalized* indices is "inbounds". 2065 template<typename IndexTy> 2066 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) { 2067 // No indices means nothing that could be out of bounds. 2068 if (Idxs.empty()) return true; 2069 2070 // If the first index is zero, it's in bounds. 2071 if (cast<Constant>(Idxs[0])->isNullValue()) return true; 2072 2073 // If the first index is one and all the rest are zero, it's in bounds, 2074 // by the one-past-the-end rule. 2075 if (auto *CI = dyn_cast<ConstantInt>(Idxs[0])) { 2076 if (!CI->isOne()) 2077 return false; 2078 } else { 2079 auto *CV = cast<ConstantDataVector>(Idxs[0]); 2080 CI = dyn_cast_or_null<ConstantInt>(CV->getSplatValue()); 2081 if (!CI || !CI->isOne()) 2082 return false; 2083 } 2084 2085 for (unsigned i = 1, e = Idxs.size(); i != e; ++i) 2086 if (!cast<Constant>(Idxs[i])->isNullValue()) 2087 return false; 2088 return true; 2089 } 2090 2091 /// Test whether a given ConstantInt is in-range for a SequentialType. 2092 static bool isIndexInRangeOfArrayType(uint64_t NumElements, 2093 const ConstantInt *CI) { 2094 // We cannot bounds check the index if it doesn't fit in an int64_t. 2095 if (CI->getValue().getMinSignedBits() > 64) 2096 return false; 2097 2098 // A negative index or an index past the end of our sequential type is 2099 // considered out-of-range. 2100 int64_t IndexVal = CI->getSExtValue(); 2101 if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements)) 2102 return false; 2103 2104 // Otherwise, it is in-range. 2105 return true; 2106 } 2107 2108 // Combine Indices - If the source pointer to this getelementptr instruction 2109 // is a getelementptr instruction, combine the indices of the two 2110 // getelementptr instructions into a single instruction. 2111 static Constant *foldGEPOfGEP(GEPOperator *GEP, Type *PointeeTy, bool InBounds, 2112 ArrayRef<Value *> Idxs) { 2113 if (PointeeTy != GEP->getResultElementType()) 2114 return nullptr; 2115 2116 Constant *Idx0 = cast<Constant>(Idxs[0]); 2117 if (Idx0->isNullValue()) { 2118 // Handle the simple case of a zero index. 2119 SmallVector<Value*, 16> NewIndices; 2120 NewIndices.reserve(Idxs.size() + GEP->getNumIndices()); 2121 NewIndices.append(GEP->idx_begin(), GEP->idx_end()); 2122 NewIndices.append(Idxs.begin() + 1, Idxs.end()); 2123 return ConstantExpr::getGetElementPtr( 2124 GEP->getSourceElementType(), cast<Constant>(GEP->getPointerOperand()), 2125 NewIndices, InBounds && GEP->isInBounds(), GEP->getInRangeIndex()); 2126 } 2127 2128 gep_type_iterator LastI = gep_type_end(GEP); 2129 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP); 2130 I != E; ++I) 2131 LastI = I; 2132 2133 // We cannot combine indices if doing so would take us outside of an 2134 // array or vector. Doing otherwise could trick us if we evaluated such a 2135 // GEP as part of a load. 2136 // 2137 // e.g. Consider if the original GEP was: 2138 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c, 2139 // i32 0, i32 0, i64 0) 2140 // 2141 // If we then tried to offset it by '8' to get to the third element, 2142 // an i8, we should *not* get: 2143 // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c, 2144 // i32 0, i32 0, i64 8) 2145 // 2146 // This GEP tries to index array element '8 which runs out-of-bounds. 2147 // Subsequent evaluation would get confused and produce erroneous results. 2148 // 2149 // The following prohibits such a GEP from being formed by checking to see 2150 // if the index is in-range with respect to an array. 2151 if (!LastI.isSequential()) 2152 return nullptr; 2153 ConstantInt *CI = dyn_cast<ConstantInt>(Idx0); 2154 if (!CI) 2155 return nullptr; 2156 if (LastI.isBoundedSequential() && 2157 !isIndexInRangeOfArrayType(LastI.getSequentialNumElements(), CI)) 2158 return nullptr; 2159 2160 // TODO: This code may be extended to handle vectors as well. 2161 auto *LastIdx = cast<Constant>(GEP->getOperand(GEP->getNumOperands()-1)); 2162 Type *LastIdxTy = LastIdx->getType(); 2163 if (LastIdxTy->isVectorTy()) 2164 return nullptr; 2165 2166 SmallVector<Value*, 16> NewIndices; 2167 NewIndices.reserve(Idxs.size() + GEP->getNumIndices()); 2168 NewIndices.append(GEP->idx_begin(), GEP->idx_end() - 1); 2169 2170 // Add the last index of the source with the first index of the new GEP. 2171 // Make sure to handle the case when they are actually different types. 2172 if (LastIdxTy != Idx0->getType()) { 2173 unsigned CommonExtendedWidth = 2174 std::max(LastIdxTy->getIntegerBitWidth(), 2175 Idx0->getType()->getIntegerBitWidth()); 2176 CommonExtendedWidth = std::max(CommonExtendedWidth, 64U); 2177 2178 Type *CommonTy = 2179 Type::getIntNTy(LastIdxTy->getContext(), CommonExtendedWidth); 2180 Idx0 = ConstantExpr::getSExtOrBitCast(Idx0, CommonTy); 2181 LastIdx = ConstantExpr::getSExtOrBitCast(LastIdx, CommonTy); 2182 } 2183 2184 NewIndices.push_back(ConstantExpr::get(Instruction::Add, Idx0, LastIdx)); 2185 NewIndices.append(Idxs.begin() + 1, Idxs.end()); 2186 2187 // The combined GEP normally inherits its index inrange attribute from 2188 // the inner GEP, but if the inner GEP's last index was adjusted by the 2189 // outer GEP, any inbounds attribute on that index is invalidated. 2190 Optional<unsigned> IRIndex = GEP->getInRangeIndex(); 2191 if (IRIndex && *IRIndex == GEP->getNumIndices() - 1) 2192 IRIndex = None; 2193 2194 return ConstantExpr::getGetElementPtr( 2195 GEP->getSourceElementType(), cast<Constant>(GEP->getPointerOperand()), 2196 NewIndices, InBounds && GEP->isInBounds(), IRIndex); 2197 } 2198 2199 Constant *llvm::ConstantFoldGetElementPtr(Type *PointeeTy, Constant *C, 2200 bool InBounds, 2201 Optional<unsigned> InRangeIndex, 2202 ArrayRef<Value *> Idxs) { 2203 if (Idxs.empty()) return C; 2204 2205 Type *GEPTy = GetElementPtrInst::getGEPReturnType( 2206 PointeeTy, C, makeArrayRef((Value *const *)Idxs.data(), Idxs.size())); 2207 2208 if (isa<PoisonValue>(C)) 2209 return PoisonValue::get(GEPTy); 2210 2211 if (isa<UndefValue>(C)) 2212 return UndefValue::get(GEPTy); 2213 2214 Constant *Idx0 = cast<Constant>(Idxs[0]); 2215 if (Idxs.size() == 1 && (Idx0->isNullValue() || isa<UndefValue>(Idx0))) 2216 return GEPTy->isVectorTy() && !C->getType()->isVectorTy() 2217 ? ConstantVector::getSplat( 2218 cast<VectorType>(GEPTy)->getElementCount(), C) 2219 : C; 2220 2221 if (C->isNullValue()) { 2222 bool isNull = true; 2223 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) 2224 if (!isa<UndefValue>(Idxs[i]) && 2225 !cast<Constant>(Idxs[i])->isNullValue()) { 2226 isNull = false; 2227 break; 2228 } 2229 if (isNull) { 2230 PointerType *PtrTy = cast<PointerType>(C->getType()->getScalarType()); 2231 Type *Ty = GetElementPtrInst::getIndexedType(PointeeTy, Idxs); 2232 2233 assert(Ty && "Invalid indices for GEP!"); 2234 Type *OrigGEPTy = PointerType::get(Ty, PtrTy->getAddressSpace()); 2235 Type *GEPTy = PointerType::get(Ty, PtrTy->getAddressSpace()); 2236 if (VectorType *VT = dyn_cast<VectorType>(C->getType())) 2237 GEPTy = VectorType::get(OrigGEPTy, VT->getElementCount()); 2238 2239 // The GEP returns a vector of pointers when one of more of 2240 // its arguments is a vector. 2241 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) { 2242 if (auto *VT = dyn_cast<VectorType>(Idxs[i]->getType())) { 2243 assert((!isa<VectorType>(GEPTy) || isa<ScalableVectorType>(GEPTy) == 2244 isa<ScalableVectorType>(VT)) && 2245 "Mismatched GEPTy vector types"); 2246 GEPTy = VectorType::get(OrigGEPTy, VT->getElementCount()); 2247 break; 2248 } 2249 } 2250 2251 return Constant::getNullValue(GEPTy); 2252 } 2253 } 2254 2255 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2256 if (auto *GEP = dyn_cast<GEPOperator>(CE)) 2257 if (Constant *C = foldGEPOfGEP(GEP, PointeeTy, InBounds, Idxs)) 2258 return C; 2259 2260 // Attempt to fold casts to the same type away. For example, folding: 2261 // 2262 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*), 2263 // i64 0, i64 0) 2264 // into: 2265 // 2266 // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0) 2267 // 2268 // Don't fold if the cast is changing address spaces. 2269 if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) { 2270 PointerType *SrcPtrTy = 2271 dyn_cast<PointerType>(CE->getOperand(0)->getType()); 2272 PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType()); 2273 if (SrcPtrTy && DstPtrTy) { 2274 ArrayType *SrcArrayTy = 2275 dyn_cast<ArrayType>(SrcPtrTy->getElementType()); 2276 ArrayType *DstArrayTy = 2277 dyn_cast<ArrayType>(DstPtrTy->getElementType()); 2278 if (SrcArrayTy && DstArrayTy 2279 && SrcArrayTy->getElementType() == DstArrayTy->getElementType() 2280 && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace()) 2281 return ConstantExpr::getGetElementPtr(SrcArrayTy, 2282 (Constant *)CE->getOperand(0), 2283 Idxs, InBounds, InRangeIndex); 2284 } 2285 } 2286 } 2287 2288 // Check to see if any array indices are not within the corresponding 2289 // notional array or vector bounds. If so, try to determine if they can be 2290 // factored out into preceding dimensions. 2291 SmallVector<Constant *, 8> NewIdxs; 2292 Type *Ty = PointeeTy; 2293 Type *Prev = C->getType(); 2294 auto GEPIter = gep_type_begin(PointeeTy, Idxs); 2295 bool Unknown = 2296 !isa<ConstantInt>(Idxs[0]) && !isa<ConstantDataVector>(Idxs[0]); 2297 for (unsigned i = 1, e = Idxs.size(); i != e; 2298 Prev = Ty, Ty = (++GEPIter).getIndexedType(), ++i) { 2299 if (!isa<ConstantInt>(Idxs[i]) && !isa<ConstantDataVector>(Idxs[i])) { 2300 // We don't know if it's in range or not. 2301 Unknown = true; 2302 continue; 2303 } 2304 if (!isa<ConstantInt>(Idxs[i - 1]) && !isa<ConstantDataVector>(Idxs[i - 1])) 2305 // Skip if the type of the previous index is not supported. 2306 continue; 2307 if (InRangeIndex && i == *InRangeIndex + 1) { 2308 // If an index is marked inrange, we cannot apply this canonicalization to 2309 // the following index, as that will cause the inrange index to point to 2310 // the wrong element. 2311 continue; 2312 } 2313 if (isa<StructType>(Ty)) { 2314 // The verify makes sure that GEPs into a struct are in range. 2315 continue; 2316 } 2317 if (isa<VectorType>(Ty)) { 2318 // There can be awkward padding in after a non-power of two vector. 2319 Unknown = true; 2320 continue; 2321 } 2322 auto *STy = cast<ArrayType>(Ty); 2323 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) { 2324 if (isIndexInRangeOfArrayType(STy->getNumElements(), CI)) 2325 // It's in range, skip to the next index. 2326 continue; 2327 if (CI->getSExtValue() < 0) { 2328 // It's out of range and negative, don't try to factor it. 2329 Unknown = true; 2330 continue; 2331 } 2332 } else { 2333 auto *CV = cast<ConstantDataVector>(Idxs[i]); 2334 bool InRange = true; 2335 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) { 2336 auto *CI = cast<ConstantInt>(CV->getElementAsConstant(I)); 2337 InRange &= isIndexInRangeOfArrayType(STy->getNumElements(), CI); 2338 if (CI->getSExtValue() < 0) { 2339 Unknown = true; 2340 break; 2341 } 2342 } 2343 if (InRange || Unknown) 2344 // It's in range, skip to the next index. 2345 // It's out of range and negative, don't try to factor it. 2346 continue; 2347 } 2348 if (isa<StructType>(Prev)) { 2349 // It's out of range, but the prior dimension is a struct 2350 // so we can't do anything about it. 2351 Unknown = true; 2352 continue; 2353 } 2354 // It's out of range, but we can factor it into the prior 2355 // dimension. 2356 NewIdxs.resize(Idxs.size()); 2357 // Determine the number of elements in our sequential type. 2358 uint64_t NumElements = STy->getArrayNumElements(); 2359 2360 // Expand the current index or the previous index to a vector from a scalar 2361 // if necessary. 2362 Constant *CurrIdx = cast<Constant>(Idxs[i]); 2363 auto *PrevIdx = 2364 NewIdxs[i - 1] ? NewIdxs[i - 1] : cast<Constant>(Idxs[i - 1]); 2365 bool IsCurrIdxVector = CurrIdx->getType()->isVectorTy(); 2366 bool IsPrevIdxVector = PrevIdx->getType()->isVectorTy(); 2367 bool UseVector = IsCurrIdxVector || IsPrevIdxVector; 2368 2369 if (!IsCurrIdxVector && IsPrevIdxVector) 2370 CurrIdx = ConstantDataVector::getSplat( 2371 cast<FixedVectorType>(PrevIdx->getType())->getNumElements(), CurrIdx); 2372 2373 if (!IsPrevIdxVector && IsCurrIdxVector) 2374 PrevIdx = ConstantDataVector::getSplat( 2375 cast<FixedVectorType>(CurrIdx->getType())->getNumElements(), PrevIdx); 2376 2377 Constant *Factor = 2378 ConstantInt::get(CurrIdx->getType()->getScalarType(), NumElements); 2379 if (UseVector) 2380 Factor = ConstantDataVector::getSplat( 2381 IsPrevIdxVector 2382 ? cast<FixedVectorType>(PrevIdx->getType())->getNumElements() 2383 : cast<FixedVectorType>(CurrIdx->getType())->getNumElements(), 2384 Factor); 2385 2386 NewIdxs[i] = ConstantExpr::getSRem(CurrIdx, Factor); 2387 2388 Constant *Div = ConstantExpr::getSDiv(CurrIdx, Factor); 2389 2390 unsigned CommonExtendedWidth = 2391 std::max(PrevIdx->getType()->getScalarSizeInBits(), 2392 Div->getType()->getScalarSizeInBits()); 2393 CommonExtendedWidth = std::max(CommonExtendedWidth, 64U); 2394 2395 // Before adding, extend both operands to i64 to avoid 2396 // overflow trouble. 2397 Type *ExtendedTy = Type::getIntNTy(Div->getContext(), CommonExtendedWidth); 2398 if (UseVector) 2399 ExtendedTy = FixedVectorType::get( 2400 ExtendedTy, 2401 IsPrevIdxVector 2402 ? cast<FixedVectorType>(PrevIdx->getType())->getNumElements() 2403 : cast<FixedVectorType>(CurrIdx->getType())->getNumElements()); 2404 2405 if (!PrevIdx->getType()->isIntOrIntVectorTy(CommonExtendedWidth)) 2406 PrevIdx = ConstantExpr::getSExt(PrevIdx, ExtendedTy); 2407 2408 if (!Div->getType()->isIntOrIntVectorTy(CommonExtendedWidth)) 2409 Div = ConstantExpr::getSExt(Div, ExtendedTy); 2410 2411 NewIdxs[i - 1] = ConstantExpr::getAdd(PrevIdx, Div); 2412 } 2413 2414 // If we did any factoring, start over with the adjusted indices. 2415 if (!NewIdxs.empty()) { 2416 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) 2417 if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]); 2418 return ConstantExpr::getGetElementPtr(PointeeTy, C, NewIdxs, InBounds, 2419 InRangeIndex); 2420 } 2421 2422 // If all indices are known integers and normalized, we can do a simple 2423 // check for the "inbounds" property. 2424 if (!Unknown && !InBounds) 2425 if (auto *GV = dyn_cast<GlobalVariable>(C)) 2426 if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs)) 2427 return ConstantExpr::getGetElementPtr(PointeeTy, C, Idxs, 2428 /*InBounds=*/true, InRangeIndex); 2429 2430 return nullptr; 2431 } 2432