1 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===// 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 defines routines for folding instructions into constants. 10 // 11 // Also, to supplement the basic IR ConstantExpr simplifications, 12 // this file defines some additional folding routines that can make use of 13 // DataLayout information. These functions cannot go in IR due to library 14 // dependency issues. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/Analysis/ConstantFolding.h" 19 #include "llvm/ADT/APFloat.h" 20 #include "llvm/ADT/APInt.h" 21 #include "llvm/ADT/ArrayRef.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/StringRef.h" 26 #include "llvm/Analysis/TargetLibraryInfo.h" 27 #include "llvm/Analysis/ValueTracking.h" 28 #include "llvm/Analysis/VectorUtils.h" 29 #include "llvm/Config/config.h" 30 #include "llvm/IR/Constant.h" 31 #include "llvm/IR/Constants.h" 32 #include "llvm/IR/DataLayout.h" 33 #include "llvm/IR/DerivedTypes.h" 34 #include "llvm/IR/Function.h" 35 #include "llvm/IR/GlobalValue.h" 36 #include "llvm/IR/GlobalVariable.h" 37 #include "llvm/IR/InstrTypes.h" 38 #include "llvm/IR/Instruction.h" 39 #include "llvm/IR/Instructions.h" 40 #include "llvm/IR/Intrinsics.h" 41 #include "llvm/IR/IntrinsicsX86.h" 42 #include "llvm/IR/Operator.h" 43 #include "llvm/IR/Type.h" 44 #include "llvm/IR/Value.h" 45 #include "llvm/Support/Casting.h" 46 #include "llvm/Support/ErrorHandling.h" 47 #include "llvm/Support/KnownBits.h" 48 #include "llvm/Support/MathExtras.h" 49 #include <cassert> 50 #include <cerrno> 51 #include <cfenv> 52 #include <cmath> 53 #include <cstddef> 54 #include <cstdint> 55 56 using namespace llvm; 57 58 namespace { 59 60 //===----------------------------------------------------------------------===// 61 // Constant Folding internal helper functions 62 //===----------------------------------------------------------------------===// 63 64 static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy, 65 Constant *C, Type *SrcEltTy, 66 unsigned NumSrcElts, 67 const DataLayout &DL) { 68 // Now that we know that the input value is a vector of integers, just shift 69 // and insert them into our result. 70 unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy); 71 for (unsigned i = 0; i != NumSrcElts; ++i) { 72 Constant *Element; 73 if (DL.isLittleEndian()) 74 Element = C->getAggregateElement(NumSrcElts - i - 1); 75 else 76 Element = C->getAggregateElement(i); 77 78 if (Element && isa<UndefValue>(Element)) { 79 Result <<= BitShift; 80 continue; 81 } 82 83 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element); 84 if (!ElementCI) 85 return ConstantExpr::getBitCast(C, DestTy); 86 87 Result <<= BitShift; 88 Result |= ElementCI->getValue().zextOrSelf(Result.getBitWidth()); 89 } 90 91 return nullptr; 92 } 93 94 /// Constant fold bitcast, symbolically evaluating it with DataLayout. 95 /// This always returns a non-null constant, but it may be a 96 /// ConstantExpr if unfoldable. 97 Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) { 98 assert(CastInst::castIsValid(Instruction::BitCast, C, DestTy) && 99 "Invalid constantexpr bitcast!"); 100 101 // Catch the obvious splat cases. 102 if (C->isNullValue() && !DestTy->isX86_MMXTy()) 103 return Constant::getNullValue(DestTy); 104 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() && 105 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types! 106 return Constant::getAllOnesValue(DestTy); 107 108 if (auto *VTy = dyn_cast<VectorType>(C->getType())) { 109 // Handle a vector->scalar integer/fp cast. 110 if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) { 111 unsigned NumSrcElts = VTy->getNumElements(); 112 Type *SrcEltTy = VTy->getElementType(); 113 114 // If the vector is a vector of floating point, convert it to vector of int 115 // to simplify things. 116 if (SrcEltTy->isFloatingPointTy()) { 117 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits(); 118 Type *SrcIVTy = 119 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts); 120 // Ask IR to do the conversion now that #elts line up. 121 C = ConstantExpr::getBitCast(C, SrcIVTy); 122 } 123 124 APInt Result(DL.getTypeSizeInBits(DestTy), 0); 125 if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C, 126 SrcEltTy, NumSrcElts, DL)) 127 return CE; 128 129 if (isa<IntegerType>(DestTy)) 130 return ConstantInt::get(DestTy, Result); 131 132 APFloat FP(DestTy->getFltSemantics(), Result); 133 return ConstantFP::get(DestTy->getContext(), FP); 134 } 135 } 136 137 // The code below only handles casts to vectors currently. 138 auto *DestVTy = dyn_cast<VectorType>(DestTy); 139 if (!DestVTy) 140 return ConstantExpr::getBitCast(C, DestTy); 141 142 // If this is a scalar -> vector cast, convert the input into a <1 x scalar> 143 // vector so the code below can handle it uniformly. 144 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) { 145 Constant *Ops = C; // don't take the address of C! 146 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL); 147 } 148 149 // If this is a bitcast from constant vector -> vector, fold it. 150 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C)) 151 return ConstantExpr::getBitCast(C, DestTy); 152 153 // If the element types match, IR can fold it. 154 unsigned NumDstElt = DestVTy->getNumElements(); 155 unsigned NumSrcElt = C->getType()->getVectorNumElements(); 156 if (NumDstElt == NumSrcElt) 157 return ConstantExpr::getBitCast(C, DestTy); 158 159 Type *SrcEltTy = C->getType()->getVectorElementType(); 160 Type *DstEltTy = DestVTy->getElementType(); 161 162 // Otherwise, we're changing the number of elements in a vector, which 163 // requires endianness information to do the right thing. For example, 164 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>) 165 // folds to (little endian): 166 // <4 x i32> <i32 0, i32 0, i32 1, i32 0> 167 // and to (big endian): 168 // <4 x i32> <i32 0, i32 0, i32 0, i32 1> 169 170 // First thing is first. We only want to think about integer here, so if 171 // we have something in FP form, recast it as integer. 172 if (DstEltTy->isFloatingPointTy()) { 173 // Fold to an vector of integers with same size as our FP type. 174 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits(); 175 Type *DestIVTy = 176 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt); 177 // Recursively handle this integer conversion, if possible. 178 C = FoldBitCast(C, DestIVTy, DL); 179 180 // Finally, IR can handle this now that #elts line up. 181 return ConstantExpr::getBitCast(C, DestTy); 182 } 183 184 // Okay, we know the destination is integer, if the input is FP, convert 185 // it to integer first. 186 if (SrcEltTy->isFloatingPointTy()) { 187 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits(); 188 Type *SrcIVTy = 189 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt); 190 // Ask IR to do the conversion now that #elts line up. 191 C = ConstantExpr::getBitCast(C, SrcIVTy); 192 // If IR wasn't able to fold it, bail out. 193 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector. 194 !isa<ConstantDataVector>(C)) 195 return C; 196 } 197 198 // Now we know that the input and output vectors are both integer vectors 199 // of the same size, and that their #elements is not the same. Do the 200 // conversion here, which depends on whether the input or output has 201 // more elements. 202 bool isLittleEndian = DL.isLittleEndian(); 203 204 SmallVector<Constant*, 32> Result; 205 if (NumDstElt < NumSrcElt) { 206 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>) 207 Constant *Zero = Constant::getNullValue(DstEltTy); 208 unsigned Ratio = NumSrcElt/NumDstElt; 209 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits(); 210 unsigned SrcElt = 0; 211 for (unsigned i = 0; i != NumDstElt; ++i) { 212 // Build each element of the result. 213 Constant *Elt = Zero; 214 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1); 215 for (unsigned j = 0; j != Ratio; ++j) { 216 Constant *Src = C->getAggregateElement(SrcElt++); 217 if (Src && isa<UndefValue>(Src)) 218 Src = Constant::getNullValue(C->getType()->getVectorElementType()); 219 else 220 Src = dyn_cast_or_null<ConstantInt>(Src); 221 if (!Src) // Reject constantexpr elements. 222 return ConstantExpr::getBitCast(C, DestTy); 223 224 // Zero extend the element to the right size. 225 Src = ConstantExpr::getZExt(Src, Elt->getType()); 226 227 // Shift it to the right place, depending on endianness. 228 Src = ConstantExpr::getShl(Src, 229 ConstantInt::get(Src->getType(), ShiftAmt)); 230 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize; 231 232 // Mix it in. 233 Elt = ConstantExpr::getOr(Elt, Src); 234 } 235 Result.push_back(Elt); 236 } 237 return ConstantVector::get(Result); 238 } 239 240 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>) 241 unsigned Ratio = NumDstElt/NumSrcElt; 242 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy); 243 244 // Loop over each source value, expanding into multiple results. 245 for (unsigned i = 0; i != NumSrcElt; ++i) { 246 auto *Element = C->getAggregateElement(i); 247 248 if (!Element) // Reject constantexpr elements. 249 return ConstantExpr::getBitCast(C, DestTy); 250 251 if (isa<UndefValue>(Element)) { 252 // Correctly Propagate undef values. 253 Result.append(Ratio, UndefValue::get(DstEltTy)); 254 continue; 255 } 256 257 auto *Src = dyn_cast<ConstantInt>(Element); 258 if (!Src) 259 return ConstantExpr::getBitCast(C, DestTy); 260 261 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1); 262 for (unsigned j = 0; j != Ratio; ++j) { 263 // Shift the piece of the value into the right place, depending on 264 // endianness. 265 Constant *Elt = ConstantExpr::getLShr(Src, 266 ConstantInt::get(Src->getType(), ShiftAmt)); 267 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize; 268 269 // Truncate the element to an integer with the same pointer size and 270 // convert the element back to a pointer using a inttoptr. 271 if (DstEltTy->isPointerTy()) { 272 IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize); 273 Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy); 274 Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy)); 275 continue; 276 } 277 278 // Truncate and remember this piece. 279 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy)); 280 } 281 } 282 283 return ConstantVector::get(Result); 284 } 285 286 } // end anonymous namespace 287 288 /// If this constant is a constant offset from a global, return the global and 289 /// the constant. Because of constantexprs, this function is recursive. 290 bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, 291 APInt &Offset, const DataLayout &DL) { 292 // Trivial case, constant is the global. 293 if ((GV = dyn_cast<GlobalValue>(C))) { 294 unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType()); 295 Offset = APInt(BitWidth, 0); 296 return true; 297 } 298 299 // Otherwise, if this isn't a constant expr, bail out. 300 auto *CE = dyn_cast<ConstantExpr>(C); 301 if (!CE) return false; 302 303 // Look through ptr->int and ptr->ptr casts. 304 if (CE->getOpcode() == Instruction::PtrToInt || 305 CE->getOpcode() == Instruction::BitCast) 306 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL); 307 308 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5) 309 auto *GEP = dyn_cast<GEPOperator>(CE); 310 if (!GEP) 311 return false; 312 313 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType()); 314 APInt TmpOffset(BitWidth, 0); 315 316 // If the base isn't a global+constant, we aren't either. 317 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL)) 318 return false; 319 320 // Otherwise, add any offset that our operands provide. 321 if (!GEP->accumulateConstantOffset(DL, TmpOffset)) 322 return false; 323 324 Offset = TmpOffset; 325 return true; 326 } 327 328 Constant *llvm::ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy, 329 const DataLayout &DL) { 330 do { 331 Type *SrcTy = C->getType(); 332 333 // If the type sizes are the same and a cast is legal, just directly 334 // cast the constant. 335 if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) { 336 Instruction::CastOps Cast = Instruction::BitCast; 337 // If we are going from a pointer to int or vice versa, we spell the cast 338 // differently. 339 if (SrcTy->isIntegerTy() && DestTy->isPointerTy()) 340 Cast = Instruction::IntToPtr; 341 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy()) 342 Cast = Instruction::PtrToInt; 343 344 if (CastInst::castIsValid(Cast, C, DestTy)) 345 return ConstantExpr::getCast(Cast, C, DestTy); 346 } 347 348 // If this isn't an aggregate type, there is nothing we can do to drill down 349 // and find a bitcastable constant. 350 if (!SrcTy->isAggregateType()) 351 return nullptr; 352 353 // We're simulating a load through a pointer that was bitcast to point to 354 // a different type, so we can try to walk down through the initial 355 // elements of an aggregate to see if some part of the aggregate is 356 // castable to implement the "load" semantic model. 357 if (SrcTy->isStructTy()) { 358 // Struct types might have leading zero-length elements like [0 x i32], 359 // which are certainly not what we are looking for, so skip them. 360 unsigned Elem = 0; 361 Constant *ElemC; 362 do { 363 ElemC = C->getAggregateElement(Elem++); 364 } while (ElemC && DL.getTypeSizeInBits(ElemC->getType()) == 0); 365 C = ElemC; 366 } else { 367 C = C->getAggregateElement(0u); 368 } 369 } while (C); 370 371 return nullptr; 372 } 373 374 namespace { 375 376 /// Recursive helper to read bits out of global. C is the constant being copied 377 /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy 378 /// results into and BytesLeft is the number of bytes left in 379 /// the CurPtr buffer. DL is the DataLayout. 380 bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr, 381 unsigned BytesLeft, const DataLayout &DL) { 382 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) && 383 "Out of range access"); 384 385 // If this element is zero or undefined, we can just return since *CurPtr is 386 // zero initialized. 387 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) 388 return true; 389 390 if (auto *CI = dyn_cast<ConstantInt>(C)) { 391 if (CI->getBitWidth() > 64 || 392 (CI->getBitWidth() & 7) != 0) 393 return false; 394 395 uint64_t Val = CI->getZExtValue(); 396 unsigned IntBytes = unsigned(CI->getBitWidth()/8); 397 398 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) { 399 int n = ByteOffset; 400 if (!DL.isLittleEndian()) 401 n = IntBytes - n - 1; 402 CurPtr[i] = (unsigned char)(Val >> (n * 8)); 403 ++ByteOffset; 404 } 405 return true; 406 } 407 408 if (auto *CFP = dyn_cast<ConstantFP>(C)) { 409 if (CFP->getType()->isDoubleTy()) { 410 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL); 411 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL); 412 } 413 if (CFP->getType()->isFloatTy()){ 414 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL); 415 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL); 416 } 417 if (CFP->getType()->isHalfTy()){ 418 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL); 419 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL); 420 } 421 return false; 422 } 423 424 if (auto *CS = dyn_cast<ConstantStruct>(C)) { 425 const StructLayout *SL = DL.getStructLayout(CS->getType()); 426 unsigned Index = SL->getElementContainingOffset(ByteOffset); 427 uint64_t CurEltOffset = SL->getElementOffset(Index); 428 ByteOffset -= CurEltOffset; 429 430 while (true) { 431 // If the element access is to the element itself and not to tail padding, 432 // read the bytes from the element. 433 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType()); 434 435 if (ByteOffset < EltSize && 436 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr, 437 BytesLeft, DL)) 438 return false; 439 440 ++Index; 441 442 // Check to see if we read from the last struct element, if so we're done. 443 if (Index == CS->getType()->getNumElements()) 444 return true; 445 446 // If we read all of the bytes we needed from this element we're done. 447 uint64_t NextEltOffset = SL->getElementOffset(Index); 448 449 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset) 450 return true; 451 452 // Move to the next element of the struct. 453 CurPtr += NextEltOffset - CurEltOffset - ByteOffset; 454 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset; 455 ByteOffset = 0; 456 CurEltOffset = NextEltOffset; 457 } 458 // not reached. 459 } 460 461 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) || 462 isa<ConstantDataSequential>(C)) { 463 Type *EltTy = C->getType()->getSequentialElementType(); 464 uint64_t EltSize = DL.getTypeAllocSize(EltTy); 465 uint64_t Index = ByteOffset / EltSize; 466 uint64_t Offset = ByteOffset - Index * EltSize; 467 uint64_t NumElts; 468 if (auto *AT = dyn_cast<ArrayType>(C->getType())) 469 NumElts = AT->getNumElements(); 470 else 471 NumElts = C->getType()->getVectorNumElements(); 472 473 for (; Index != NumElts; ++Index) { 474 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr, 475 BytesLeft, DL)) 476 return false; 477 478 uint64_t BytesWritten = EltSize - Offset; 479 assert(BytesWritten <= EltSize && "Not indexing into this element?"); 480 if (BytesWritten >= BytesLeft) 481 return true; 482 483 Offset = 0; 484 BytesLeft -= BytesWritten; 485 CurPtr += BytesWritten; 486 } 487 return true; 488 } 489 490 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 491 if (CE->getOpcode() == Instruction::IntToPtr && 492 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) { 493 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr, 494 BytesLeft, DL); 495 } 496 } 497 498 // Otherwise, unknown initializer type. 499 return false; 500 } 501 502 Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy, 503 const DataLayout &DL) { 504 auto *PTy = cast<PointerType>(C->getType()); 505 auto *IntType = dyn_cast<IntegerType>(LoadTy); 506 507 // If this isn't an integer load we can't fold it directly. 508 if (!IntType) { 509 unsigned AS = PTy->getAddressSpace(); 510 511 // If this is a float/double load, we can try folding it as an int32/64 load 512 // and then bitcast the result. This can be useful for union cases. Note 513 // that address spaces don't matter here since we're not going to result in 514 // an actual new load. 515 Type *MapTy; 516 if (LoadTy->isHalfTy()) 517 MapTy = Type::getInt16Ty(C->getContext()); 518 else if (LoadTy->isFloatTy()) 519 MapTy = Type::getInt32Ty(C->getContext()); 520 else if (LoadTy->isDoubleTy()) 521 MapTy = Type::getInt64Ty(C->getContext()); 522 else if (LoadTy->isVectorTy()) { 523 MapTy = PointerType::getIntNTy(C->getContext(), 524 DL.getTypeSizeInBits(LoadTy)); 525 } else 526 return nullptr; 527 528 C = FoldBitCast(C, MapTy->getPointerTo(AS), DL); 529 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL)) { 530 if (Res->isNullValue() && !LoadTy->isX86_MMXTy()) 531 // Materializing a zero can be done trivially without a bitcast 532 return Constant::getNullValue(LoadTy); 533 Type *CastTy = LoadTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(LoadTy) : LoadTy; 534 Res = FoldBitCast(Res, CastTy, DL); 535 if (LoadTy->isPtrOrPtrVectorTy()) { 536 // For vector of pointer, we needed to first convert to a vector of integer, then do vector inttoptr 537 if (Res->isNullValue() && !LoadTy->isX86_MMXTy()) 538 return Constant::getNullValue(LoadTy); 539 if (DL.isNonIntegralPointerType(LoadTy->getScalarType())) 540 // Be careful not to replace a load of an addrspace value with an inttoptr here 541 return nullptr; 542 Res = ConstantExpr::getCast(Instruction::IntToPtr, Res, LoadTy); 543 } 544 return Res; 545 } 546 return nullptr; 547 } 548 549 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8; 550 if (BytesLoaded > 32 || BytesLoaded == 0) 551 return nullptr; 552 553 GlobalValue *GVal; 554 APInt OffsetAI; 555 if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL)) 556 return nullptr; 557 558 auto *GV = dyn_cast<GlobalVariable>(GVal); 559 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 560 !GV->getInitializer()->getType()->isSized()) 561 return nullptr; 562 563 int64_t Offset = OffsetAI.getSExtValue(); 564 int64_t InitializerSize = DL.getTypeAllocSize(GV->getInitializer()->getType()); 565 566 // If we're not accessing anything in this constant, the result is undefined. 567 if (Offset <= -1 * static_cast<int64_t>(BytesLoaded)) 568 return UndefValue::get(IntType); 569 570 // If we're not accessing anything in this constant, the result is undefined. 571 if (Offset >= InitializerSize) 572 return UndefValue::get(IntType); 573 574 unsigned char RawBytes[32] = {0}; 575 unsigned char *CurPtr = RawBytes; 576 unsigned BytesLeft = BytesLoaded; 577 578 // If we're loading off the beginning of the global, some bytes may be valid. 579 if (Offset < 0) { 580 CurPtr += -Offset; 581 BytesLeft += Offset; 582 Offset = 0; 583 } 584 585 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL)) 586 return nullptr; 587 588 APInt ResultVal = APInt(IntType->getBitWidth(), 0); 589 if (DL.isLittleEndian()) { 590 ResultVal = RawBytes[BytesLoaded - 1]; 591 for (unsigned i = 1; i != BytesLoaded; ++i) { 592 ResultVal <<= 8; 593 ResultVal |= RawBytes[BytesLoaded - 1 - i]; 594 } 595 } else { 596 ResultVal = RawBytes[0]; 597 for (unsigned i = 1; i != BytesLoaded; ++i) { 598 ResultVal <<= 8; 599 ResultVal |= RawBytes[i]; 600 } 601 } 602 603 return ConstantInt::get(IntType->getContext(), ResultVal); 604 } 605 606 Constant *ConstantFoldLoadThroughBitcastExpr(ConstantExpr *CE, Type *DestTy, 607 const DataLayout &DL) { 608 auto *SrcPtr = CE->getOperand(0); 609 auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType()); 610 if (!SrcPtrTy) 611 return nullptr; 612 Type *SrcTy = SrcPtrTy->getPointerElementType(); 613 614 Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL); 615 if (!C) 616 return nullptr; 617 618 return llvm::ConstantFoldLoadThroughBitcast(C, DestTy, DL); 619 } 620 621 } // end anonymous namespace 622 623 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, 624 const DataLayout &DL) { 625 // First, try the easy cases: 626 if (auto *GV = dyn_cast<GlobalVariable>(C)) 627 if (GV->isConstant() && GV->hasDefinitiveInitializer()) 628 return GV->getInitializer(); 629 630 if (auto *GA = dyn_cast<GlobalAlias>(C)) 631 if (GA->getAliasee() && !GA->isInterposable()) 632 return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL); 633 634 // If the loaded value isn't a constant expr, we can't handle it. 635 auto *CE = dyn_cast<ConstantExpr>(C); 636 if (!CE) 637 return nullptr; 638 639 if (CE->getOpcode() == Instruction::GetElementPtr) { 640 if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) { 641 if (GV->isConstant() && GV->hasDefinitiveInitializer()) { 642 if (Constant *V = 643 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) 644 return V; 645 } 646 } 647 } 648 649 if (CE->getOpcode() == Instruction::BitCast) 650 if (Constant *LoadedC = ConstantFoldLoadThroughBitcastExpr(CE, Ty, DL)) 651 return LoadedC; 652 653 // Instead of loading constant c string, use corresponding integer value 654 // directly if string length is small enough. 655 StringRef Str; 656 if (getConstantStringInfo(CE, Str) && !Str.empty()) { 657 size_t StrLen = Str.size(); 658 unsigned NumBits = Ty->getPrimitiveSizeInBits(); 659 // Replace load with immediate integer if the result is an integer or fp 660 // value. 661 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 && 662 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) { 663 APInt StrVal(NumBits, 0); 664 APInt SingleChar(NumBits, 0); 665 if (DL.isLittleEndian()) { 666 for (unsigned char C : reverse(Str.bytes())) { 667 SingleChar = static_cast<uint64_t>(C); 668 StrVal = (StrVal << 8) | SingleChar; 669 } 670 } else { 671 for (unsigned char C : Str.bytes()) { 672 SingleChar = static_cast<uint64_t>(C); 673 StrVal = (StrVal << 8) | SingleChar; 674 } 675 // Append NULL at the end. 676 SingleChar = 0; 677 StrVal = (StrVal << 8) | SingleChar; 678 } 679 680 Constant *Res = ConstantInt::get(CE->getContext(), StrVal); 681 if (Ty->isFloatingPointTy()) 682 Res = ConstantExpr::getBitCast(Res, Ty); 683 return Res; 684 } 685 } 686 687 // If this load comes from anywhere in a constant global, and if the global 688 // is all undef or zero, we know what it loads. 689 if (auto *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) { 690 if (GV->isConstant() && GV->hasDefinitiveInitializer()) { 691 if (GV->getInitializer()->isNullValue()) 692 return Constant::getNullValue(Ty); 693 if (isa<UndefValue>(GV->getInitializer())) 694 return UndefValue::get(Ty); 695 } 696 } 697 698 // Try hard to fold loads from bitcasted strange and non-type-safe things. 699 return FoldReinterpretLoadFromConstPtr(CE, Ty, DL); 700 } 701 702 namespace { 703 704 Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) { 705 if (LI->isVolatile()) return nullptr; 706 707 if (auto *C = dyn_cast<Constant>(LI->getOperand(0))) 708 return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL); 709 710 return nullptr; 711 } 712 713 /// One of Op0/Op1 is a constant expression. 714 /// Attempt to symbolically evaluate the result of a binary operator merging 715 /// these together. If target data info is available, it is provided as DL, 716 /// otherwise DL is null. 717 Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1, 718 const DataLayout &DL) { 719 // SROA 720 721 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl. 722 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute 723 // bits. 724 725 if (Opc == Instruction::And) { 726 KnownBits Known0 = computeKnownBits(Op0, DL); 727 KnownBits Known1 = computeKnownBits(Op1, DL); 728 if ((Known1.One | Known0.Zero).isAllOnesValue()) { 729 // All the bits of Op0 that the 'and' could be masking are already zero. 730 return Op0; 731 } 732 if ((Known0.One | Known1.Zero).isAllOnesValue()) { 733 // All the bits of Op1 that the 'and' could be masking are already zero. 734 return Op1; 735 } 736 737 Known0.Zero |= Known1.Zero; 738 Known0.One &= Known1.One; 739 if (Known0.isConstant()) 740 return ConstantInt::get(Op0->getType(), Known0.getConstant()); 741 } 742 743 // If the constant expr is something like &A[123] - &A[4].f, fold this into a 744 // constant. This happens frequently when iterating over a global array. 745 if (Opc == Instruction::Sub) { 746 GlobalValue *GV1, *GV2; 747 APInt Offs1, Offs2; 748 749 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL)) 750 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) { 751 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType()); 752 753 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow. 754 // PtrToInt may change the bitwidth so we have convert to the right size 755 // first. 756 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) - 757 Offs2.zextOrTrunc(OpSize)); 758 } 759 } 760 761 return nullptr; 762 } 763 764 /// If array indices are not pointer-sized integers, explicitly cast them so 765 /// that they aren't implicitly casted by the getelementptr. 766 Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops, 767 Type *ResultTy, Optional<unsigned> InRangeIndex, 768 const DataLayout &DL, const TargetLibraryInfo *TLI) { 769 Type *IntIdxTy = DL.getIndexType(ResultTy); 770 Type *IntIdxScalarTy = IntIdxTy->getScalarType(); 771 772 bool Any = false; 773 SmallVector<Constant*, 32> NewIdxs; 774 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 775 if ((i == 1 || 776 !isa<StructType>(GetElementPtrInst::getIndexedType( 777 SrcElemTy, Ops.slice(1, i - 1)))) && 778 Ops[i]->getType()->getScalarType() != IntIdxScalarTy) { 779 Any = true; 780 Type *NewType = Ops[i]->getType()->isVectorTy() 781 ? IntIdxTy 782 : IntIdxScalarTy; 783 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i], 784 true, 785 NewType, 786 true), 787 Ops[i], NewType)); 788 } else 789 NewIdxs.push_back(Ops[i]); 790 } 791 792 if (!Any) 793 return nullptr; 794 795 Constant *C = ConstantExpr::getGetElementPtr( 796 SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex); 797 if (Constant *Folded = ConstantFoldConstant(C, DL, TLI)) 798 C = Folded; 799 800 return C; 801 } 802 803 /// Strip the pointer casts, but preserve the address space information. 804 Constant *StripPtrCastKeepAS(Constant *Ptr, Type *&ElemTy) { 805 assert(Ptr->getType()->isPointerTy() && "Not a pointer type"); 806 auto *OldPtrTy = cast<PointerType>(Ptr->getType()); 807 Ptr = cast<Constant>(Ptr->stripPointerCasts()); 808 auto *NewPtrTy = cast<PointerType>(Ptr->getType()); 809 810 ElemTy = NewPtrTy->getPointerElementType(); 811 812 // Preserve the address space number of the pointer. 813 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) { 814 NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace()); 815 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy); 816 } 817 return Ptr; 818 } 819 820 /// If we can symbolically evaluate the GEP constant expression, do so. 821 Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP, 822 ArrayRef<Constant *> Ops, 823 const DataLayout &DL, 824 const TargetLibraryInfo *TLI) { 825 const GEPOperator *InnermostGEP = GEP; 826 bool InBounds = GEP->isInBounds(); 827 828 Type *SrcElemTy = GEP->getSourceElementType(); 829 Type *ResElemTy = GEP->getResultElementType(); 830 Type *ResTy = GEP->getType(); 831 if (!SrcElemTy->isSized() || 832 (SrcElemTy->isVectorTy() && SrcElemTy->getVectorIsScalable())) 833 return nullptr; 834 835 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy, 836 GEP->getInRangeIndex(), DL, TLI)) 837 return C; 838 839 Constant *Ptr = Ops[0]; 840 if (!Ptr->getType()->isPointerTy()) 841 return nullptr; 842 843 Type *IntIdxTy = DL.getIndexType(Ptr->getType()); 844 845 // If this is a constant expr gep that is effectively computing an 846 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12' 847 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 848 if (!isa<ConstantInt>(Ops[i])) { 849 850 // If this is "gep i8* Ptr, (sub 0, V)", fold this as: 851 // "inttoptr (sub (ptrtoint Ptr), V)" 852 if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) { 853 auto *CE = dyn_cast<ConstantExpr>(Ops[1]); 854 assert((!CE || CE->getType() == IntIdxTy) && 855 "CastGEPIndices didn't canonicalize index types!"); 856 if (CE && CE->getOpcode() == Instruction::Sub && 857 CE->getOperand(0)->isNullValue()) { 858 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType()); 859 Res = ConstantExpr::getSub(Res, CE->getOperand(1)); 860 Res = ConstantExpr::getIntToPtr(Res, ResTy); 861 if (auto *FoldedRes = ConstantFoldConstant(Res, DL, TLI)) 862 Res = FoldedRes; 863 return Res; 864 } 865 } 866 return nullptr; 867 } 868 869 unsigned BitWidth = DL.getTypeSizeInBits(IntIdxTy); 870 APInt Offset = 871 APInt(BitWidth, 872 DL.getIndexedOffsetInType( 873 SrcElemTy, 874 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1))); 875 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy); 876 877 // If this is a GEP of a GEP, fold it all into a single GEP. 878 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) { 879 InnermostGEP = GEP; 880 InBounds &= GEP->isInBounds(); 881 882 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end()); 883 884 // Do not try the incorporate the sub-GEP if some index is not a number. 885 bool AllConstantInt = true; 886 for (Value *NestedOp : NestedOps) 887 if (!isa<ConstantInt>(NestedOp)) { 888 AllConstantInt = false; 889 break; 890 } 891 if (!AllConstantInt) 892 break; 893 894 Ptr = cast<Constant>(GEP->getOperand(0)); 895 SrcElemTy = GEP->getSourceElementType(); 896 Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps)); 897 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy); 898 } 899 900 // If the base value for this address is a literal integer value, fold the 901 // getelementptr to the resulting integer value casted to the pointer type. 902 APInt BasePtr(BitWidth, 0); 903 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) { 904 if (CE->getOpcode() == Instruction::IntToPtr) { 905 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) 906 BasePtr = Base->getValue().zextOrTrunc(BitWidth); 907 } 908 } 909 910 auto *PTy = cast<PointerType>(Ptr->getType()); 911 if ((Ptr->isNullValue() || BasePtr != 0) && 912 !DL.isNonIntegralPointerType(PTy)) { 913 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr); 914 return ConstantExpr::getIntToPtr(C, ResTy); 915 } 916 917 // Otherwise form a regular getelementptr. Recompute the indices so that 918 // we eliminate over-indexing of the notional static type array bounds. 919 // This makes it easy to determine if the getelementptr is "inbounds". 920 // Also, this helps GlobalOpt do SROA on GlobalVariables. 921 Type *Ty = PTy; 922 SmallVector<Constant *, 32> NewIdxs; 923 924 do { 925 if (!Ty->isStructTy()) { 926 if (Ty->isPointerTy()) { 927 // The only pointer indexing we'll do is on the first index of the GEP. 928 if (!NewIdxs.empty()) 929 break; 930 931 Ty = SrcElemTy; 932 933 // Only handle pointers to sized types, not pointers to functions. 934 if (!Ty->isSized()) 935 return nullptr; 936 } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) { 937 Ty = ATy->getElementType(); 938 } else { 939 // We've reached some non-indexable type. 940 break; 941 } 942 943 // Determine which element of the array the offset points into. 944 APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty)); 945 if (ElemSize == 0) { 946 // The element size is 0. This may be [0 x Ty]*, so just use a zero 947 // index for this level and proceed to the next level to see if it can 948 // accommodate the offset. 949 NewIdxs.push_back(ConstantInt::get(IntIdxTy, 0)); 950 } else { 951 // The element size is non-zero divide the offset by the element 952 // size (rounding down), to compute the index at this level. 953 bool Overflow; 954 APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow); 955 if (Overflow) 956 break; 957 Offset -= NewIdx * ElemSize; 958 NewIdxs.push_back(ConstantInt::get(IntIdxTy, NewIdx)); 959 } 960 } else { 961 auto *STy = cast<StructType>(Ty); 962 // If we end up with an offset that isn't valid for this struct type, we 963 // can't re-form this GEP in a regular form, so bail out. The pointer 964 // operand likely went through casts that are necessary to make the GEP 965 // sensible. 966 const StructLayout &SL = *DL.getStructLayout(STy); 967 if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes())) 968 break; 969 970 // Determine which field of the struct the offset points into. The 971 // getZExtValue is fine as we've already ensured that the offset is 972 // within the range representable by the StructLayout API. 973 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue()); 974 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 975 ElIdx)); 976 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx)); 977 Ty = STy->getTypeAtIndex(ElIdx); 978 } 979 } while (Ty != ResElemTy); 980 981 // If we haven't used up the entire offset by descending the static 982 // type, then the offset is pointing into the middle of an indivisible 983 // member, so we can't simplify it. 984 if (Offset != 0) 985 return nullptr; 986 987 // Preserve the inrange index from the innermost GEP if possible. We must 988 // have calculated the same indices up to and including the inrange index. 989 Optional<unsigned> InRangeIndex; 990 if (Optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex()) 991 if (SrcElemTy == InnermostGEP->getSourceElementType() && 992 NewIdxs.size() > *LastIRIndex) { 993 InRangeIndex = LastIRIndex; 994 for (unsigned I = 0; I <= *LastIRIndex; ++I) 995 if (NewIdxs[I] != InnermostGEP->getOperand(I + 1)) 996 return nullptr; 997 } 998 999 // Create a GEP. 1000 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs, 1001 InBounds, InRangeIndex); 1002 assert(C->getType()->getPointerElementType() == Ty && 1003 "Computed GetElementPtr has unexpected type!"); 1004 1005 // If we ended up indexing a member with a type that doesn't match 1006 // the type of what the original indices indexed, add a cast. 1007 if (Ty != ResElemTy) 1008 C = FoldBitCast(C, ResTy, DL); 1009 1010 return C; 1011 } 1012 1013 /// Attempt to constant fold an instruction with the 1014 /// specified opcode and operands. If successful, the constant result is 1015 /// returned, if not, null is returned. Note that this function can fail when 1016 /// attempting to fold instructions like loads and stores, which have no 1017 /// constant expression form. 1018 Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode, 1019 ArrayRef<Constant *> Ops, 1020 const DataLayout &DL, 1021 const TargetLibraryInfo *TLI) { 1022 Type *DestTy = InstOrCE->getType(); 1023 1024 if (Instruction::isUnaryOp(Opcode)) 1025 return ConstantFoldUnaryOpOperand(Opcode, Ops[0], DL); 1026 1027 if (Instruction::isBinaryOp(Opcode)) 1028 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL); 1029 1030 if (Instruction::isCast(Opcode)) 1031 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL); 1032 1033 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) { 1034 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI)) 1035 return C; 1036 1037 return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), Ops[0], 1038 Ops.slice(1), GEP->isInBounds(), 1039 GEP->getInRangeIndex()); 1040 } 1041 1042 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE)) 1043 return CE->getWithOperands(Ops); 1044 1045 switch (Opcode) { 1046 default: return nullptr; 1047 case Instruction::ICmp: 1048 case Instruction::FCmp: llvm_unreachable("Invalid for compares"); 1049 case Instruction::Call: 1050 if (auto *F = dyn_cast<Function>(Ops.back())) { 1051 const auto *Call = cast<CallBase>(InstOrCE); 1052 if (canConstantFoldCallTo(Call, F)) 1053 return ConstantFoldCall(Call, F, Ops.slice(0, Ops.size() - 1), TLI); 1054 } 1055 return nullptr; 1056 case Instruction::Select: 1057 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]); 1058 case Instruction::ExtractElement: 1059 return ConstantExpr::getExtractElement(Ops[0], Ops[1]); 1060 case Instruction::ExtractValue: 1061 return ConstantExpr::getExtractValue( 1062 Ops[0], cast<ExtractValueInst>(InstOrCE)->getIndices()); 1063 case Instruction::InsertElement: 1064 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]); 1065 case Instruction::ShuffleVector: 1066 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]); 1067 } 1068 } 1069 1070 } // end anonymous namespace 1071 1072 //===----------------------------------------------------------------------===// 1073 // Constant Folding public APIs 1074 //===----------------------------------------------------------------------===// 1075 1076 namespace { 1077 1078 Constant * 1079 ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL, 1080 const TargetLibraryInfo *TLI, 1081 SmallDenseMap<Constant *, Constant *> &FoldedOps) { 1082 if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C)) 1083 return nullptr; 1084 1085 SmallVector<Constant *, 8> Ops; 1086 for (const Use &NewU : C->operands()) { 1087 auto *NewC = cast<Constant>(&NewU); 1088 // Recursively fold the ConstantExpr's operands. If we have already folded 1089 // a ConstantExpr, we don't have to process it again. 1090 if (isa<ConstantVector>(NewC) || isa<ConstantExpr>(NewC)) { 1091 auto It = FoldedOps.find(NewC); 1092 if (It == FoldedOps.end()) { 1093 if (auto *FoldedC = 1094 ConstantFoldConstantImpl(NewC, DL, TLI, FoldedOps)) { 1095 FoldedOps.insert({NewC, FoldedC}); 1096 NewC = FoldedC; 1097 } else { 1098 FoldedOps.insert({NewC, NewC}); 1099 } 1100 } else { 1101 NewC = It->second; 1102 } 1103 } 1104 Ops.push_back(NewC); 1105 } 1106 1107 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 1108 if (CE->isCompare()) 1109 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1], 1110 DL, TLI); 1111 1112 return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI); 1113 } 1114 1115 assert(isa<ConstantVector>(C)); 1116 return ConstantVector::get(Ops); 1117 } 1118 1119 } // end anonymous namespace 1120 1121 Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL, 1122 const TargetLibraryInfo *TLI) { 1123 // Handle PHI nodes quickly here... 1124 if (auto *PN = dyn_cast<PHINode>(I)) { 1125 Constant *CommonValue = nullptr; 1126 1127 SmallDenseMap<Constant *, Constant *> FoldedOps; 1128 for (Value *Incoming : PN->incoming_values()) { 1129 // If the incoming value is undef then skip it. Note that while we could 1130 // skip the value if it is equal to the phi node itself we choose not to 1131 // because that would break the rule that constant folding only applies if 1132 // all operands are constants. 1133 if (isa<UndefValue>(Incoming)) 1134 continue; 1135 // If the incoming value is not a constant, then give up. 1136 auto *C = dyn_cast<Constant>(Incoming); 1137 if (!C) 1138 return nullptr; 1139 // Fold the PHI's operands. 1140 if (auto *FoldedC = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps)) 1141 C = FoldedC; 1142 // If the incoming value is a different constant to 1143 // the one we saw previously, then give up. 1144 if (CommonValue && C != CommonValue) 1145 return nullptr; 1146 CommonValue = C; 1147 } 1148 1149 // If we reach here, all incoming values are the same constant or undef. 1150 return CommonValue ? CommonValue : UndefValue::get(PN->getType()); 1151 } 1152 1153 // Scan the operand list, checking to see if they are all constants, if so, 1154 // hand off to ConstantFoldInstOperandsImpl. 1155 if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); })) 1156 return nullptr; 1157 1158 SmallDenseMap<Constant *, Constant *> FoldedOps; 1159 SmallVector<Constant *, 8> Ops; 1160 for (const Use &OpU : I->operands()) { 1161 auto *Op = cast<Constant>(&OpU); 1162 // Fold the Instruction's operands. 1163 if (auto *FoldedOp = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps)) 1164 Op = FoldedOp; 1165 1166 Ops.push_back(Op); 1167 } 1168 1169 if (const auto *CI = dyn_cast<CmpInst>(I)) 1170 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1], 1171 DL, TLI); 1172 1173 if (const auto *LI = dyn_cast<LoadInst>(I)) 1174 return ConstantFoldLoadInst(LI, DL); 1175 1176 if (auto *IVI = dyn_cast<InsertValueInst>(I)) { 1177 return ConstantExpr::getInsertValue( 1178 cast<Constant>(IVI->getAggregateOperand()), 1179 cast<Constant>(IVI->getInsertedValueOperand()), 1180 IVI->getIndices()); 1181 } 1182 1183 if (auto *EVI = dyn_cast<ExtractValueInst>(I)) { 1184 return ConstantExpr::getExtractValue( 1185 cast<Constant>(EVI->getAggregateOperand()), 1186 EVI->getIndices()); 1187 } 1188 1189 return ConstantFoldInstOperands(I, Ops, DL, TLI); 1190 } 1191 1192 Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL, 1193 const TargetLibraryInfo *TLI) { 1194 SmallDenseMap<Constant *, Constant *> FoldedOps; 1195 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps); 1196 } 1197 1198 Constant *llvm::ConstantFoldInstOperands(Instruction *I, 1199 ArrayRef<Constant *> Ops, 1200 const DataLayout &DL, 1201 const TargetLibraryInfo *TLI) { 1202 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI); 1203 } 1204 1205 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate, 1206 Constant *Ops0, Constant *Ops1, 1207 const DataLayout &DL, 1208 const TargetLibraryInfo *TLI) { 1209 // fold: icmp (inttoptr x), null -> icmp x, 0 1210 // fold: icmp null, (inttoptr x) -> icmp 0, x 1211 // fold: icmp (ptrtoint x), 0 -> icmp x, null 1212 // fold: icmp 0, (ptrtoint x) -> icmp null, x 1213 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y 1214 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y 1215 // 1216 // FIXME: The following comment is out of data and the DataLayout is here now. 1217 // ConstantExpr::getCompare cannot do this, because it doesn't have DL 1218 // around to know if bit truncation is happening. 1219 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) { 1220 if (Ops1->isNullValue()) { 1221 if (CE0->getOpcode() == Instruction::IntToPtr) { 1222 Type *IntPtrTy = DL.getIntPtrType(CE0->getType()); 1223 // Convert the integer value to the right size to ensure we get the 1224 // proper extension or truncation. 1225 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0), 1226 IntPtrTy, false); 1227 Constant *Null = Constant::getNullValue(C->getType()); 1228 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI); 1229 } 1230 1231 // Only do this transformation if the int is intptrty in size, otherwise 1232 // there is a truncation or extension that we aren't modeling. 1233 if (CE0->getOpcode() == Instruction::PtrToInt) { 1234 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType()); 1235 if (CE0->getType() == IntPtrTy) { 1236 Constant *C = CE0->getOperand(0); 1237 Constant *Null = Constant::getNullValue(C->getType()); 1238 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI); 1239 } 1240 } 1241 } 1242 1243 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) { 1244 if (CE0->getOpcode() == CE1->getOpcode()) { 1245 if (CE0->getOpcode() == Instruction::IntToPtr) { 1246 Type *IntPtrTy = DL.getIntPtrType(CE0->getType()); 1247 1248 // Convert the integer value to the right size to ensure we get the 1249 // proper extension or truncation. 1250 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0), 1251 IntPtrTy, false); 1252 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0), 1253 IntPtrTy, false); 1254 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI); 1255 } 1256 1257 // Only do this transformation if the int is intptrty in size, otherwise 1258 // there is a truncation or extension that we aren't modeling. 1259 if (CE0->getOpcode() == Instruction::PtrToInt) { 1260 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType()); 1261 if (CE0->getType() == IntPtrTy && 1262 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) { 1263 return ConstantFoldCompareInstOperands( 1264 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI); 1265 } 1266 } 1267 } 1268 } 1269 1270 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0) 1271 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0) 1272 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) && 1273 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) { 1274 Constant *LHS = ConstantFoldCompareInstOperands( 1275 Predicate, CE0->getOperand(0), Ops1, DL, TLI); 1276 Constant *RHS = ConstantFoldCompareInstOperands( 1277 Predicate, CE0->getOperand(1), Ops1, DL, TLI); 1278 unsigned OpC = 1279 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or; 1280 return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL); 1281 } 1282 } else if (isa<ConstantExpr>(Ops1)) { 1283 // If RHS is a constant expression, but the left side isn't, swap the 1284 // operands and try again. 1285 Predicate = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)Predicate); 1286 return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI); 1287 } 1288 1289 return ConstantExpr::getCompare(Predicate, Ops0, Ops1); 1290 } 1291 1292 Constant *llvm::ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, 1293 const DataLayout &DL) { 1294 assert(Instruction::isUnaryOp(Opcode)); 1295 1296 return ConstantExpr::get(Opcode, Op); 1297 } 1298 1299 Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, 1300 Constant *RHS, 1301 const DataLayout &DL) { 1302 assert(Instruction::isBinaryOp(Opcode)); 1303 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS)) 1304 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL)) 1305 return C; 1306 1307 return ConstantExpr::get(Opcode, LHS, RHS); 1308 } 1309 1310 Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C, 1311 Type *DestTy, const DataLayout &DL) { 1312 assert(Instruction::isCast(Opcode)); 1313 switch (Opcode) { 1314 default: 1315 llvm_unreachable("Missing case"); 1316 case Instruction::PtrToInt: 1317 // If the input is a inttoptr, eliminate the pair. This requires knowing 1318 // the width of a pointer, so it can't be done in ConstantExpr::getCast. 1319 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 1320 if (CE->getOpcode() == Instruction::IntToPtr) { 1321 Constant *Input = CE->getOperand(0); 1322 unsigned InWidth = Input->getType()->getScalarSizeInBits(); 1323 unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType()); 1324 if (PtrWidth < InWidth) { 1325 Constant *Mask = 1326 ConstantInt::get(CE->getContext(), 1327 APInt::getLowBitsSet(InWidth, PtrWidth)); 1328 Input = ConstantExpr::getAnd(Input, Mask); 1329 } 1330 // Do a zext or trunc to get to the dest size. 1331 return ConstantExpr::getIntegerCast(Input, DestTy, false); 1332 } 1333 } 1334 return ConstantExpr::getCast(Opcode, C, DestTy); 1335 case Instruction::IntToPtr: 1336 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if 1337 // the int size is >= the ptr size and the address spaces are the same. 1338 // This requires knowing the width of a pointer, so it can't be done in 1339 // ConstantExpr::getCast. 1340 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 1341 if (CE->getOpcode() == Instruction::PtrToInt) { 1342 Constant *SrcPtr = CE->getOperand(0); 1343 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType()); 1344 unsigned MidIntSize = CE->getType()->getScalarSizeInBits(); 1345 1346 if (MidIntSize >= SrcPtrSize) { 1347 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace(); 1348 if (SrcAS == DestTy->getPointerAddressSpace()) 1349 return FoldBitCast(CE->getOperand(0), DestTy, DL); 1350 } 1351 } 1352 } 1353 1354 return ConstantExpr::getCast(Opcode, C, DestTy); 1355 case Instruction::Trunc: 1356 case Instruction::ZExt: 1357 case Instruction::SExt: 1358 case Instruction::FPTrunc: 1359 case Instruction::FPExt: 1360 case Instruction::UIToFP: 1361 case Instruction::SIToFP: 1362 case Instruction::FPToUI: 1363 case Instruction::FPToSI: 1364 case Instruction::AddrSpaceCast: 1365 return ConstantExpr::getCast(Opcode, C, DestTy); 1366 case Instruction::BitCast: 1367 return FoldBitCast(C, DestTy, DL); 1368 } 1369 } 1370 1371 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, 1372 ConstantExpr *CE) { 1373 if (!CE->getOperand(1)->isNullValue()) 1374 return nullptr; // Do not allow stepping over the value! 1375 1376 // Loop over all of the operands, tracking down which value we are 1377 // addressing. 1378 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) { 1379 C = C->getAggregateElement(CE->getOperand(i)); 1380 if (!C) 1381 return nullptr; 1382 } 1383 return C; 1384 } 1385 1386 Constant * 1387 llvm::ConstantFoldLoadThroughGEPIndices(Constant *C, 1388 ArrayRef<Constant *> Indices) { 1389 // Loop over all of the operands, tracking down which value we are 1390 // addressing. 1391 for (Constant *Index : Indices) { 1392 C = C->getAggregateElement(Index); 1393 if (!C) 1394 return nullptr; 1395 } 1396 return C; 1397 } 1398 1399 //===----------------------------------------------------------------------===// 1400 // Constant Folding for Calls 1401 // 1402 1403 bool llvm::canConstantFoldCallTo(const CallBase *Call, const Function *F) { 1404 if (Call->isNoBuiltin() || Call->isStrictFP()) 1405 return false; 1406 switch (F->getIntrinsicID()) { 1407 case Intrinsic::fabs: 1408 case Intrinsic::minnum: 1409 case Intrinsic::maxnum: 1410 case Intrinsic::minimum: 1411 case Intrinsic::maximum: 1412 case Intrinsic::log: 1413 case Intrinsic::log2: 1414 case Intrinsic::log10: 1415 case Intrinsic::exp: 1416 case Intrinsic::exp2: 1417 case Intrinsic::floor: 1418 case Intrinsic::ceil: 1419 case Intrinsic::sqrt: 1420 case Intrinsic::sin: 1421 case Intrinsic::cos: 1422 case Intrinsic::trunc: 1423 case Intrinsic::rint: 1424 case Intrinsic::nearbyint: 1425 case Intrinsic::pow: 1426 case Intrinsic::powi: 1427 case Intrinsic::bswap: 1428 case Intrinsic::ctpop: 1429 case Intrinsic::ctlz: 1430 case Intrinsic::cttz: 1431 case Intrinsic::fshl: 1432 case Intrinsic::fshr: 1433 case Intrinsic::fma: 1434 case Intrinsic::fmuladd: 1435 case Intrinsic::copysign: 1436 case Intrinsic::launder_invariant_group: 1437 case Intrinsic::strip_invariant_group: 1438 case Intrinsic::round: 1439 case Intrinsic::masked_load: 1440 case Intrinsic::sadd_with_overflow: 1441 case Intrinsic::uadd_with_overflow: 1442 case Intrinsic::ssub_with_overflow: 1443 case Intrinsic::usub_with_overflow: 1444 case Intrinsic::smul_with_overflow: 1445 case Intrinsic::umul_with_overflow: 1446 case Intrinsic::sadd_sat: 1447 case Intrinsic::uadd_sat: 1448 case Intrinsic::ssub_sat: 1449 case Intrinsic::usub_sat: 1450 case Intrinsic::smul_fix: 1451 case Intrinsic::smul_fix_sat: 1452 case Intrinsic::convert_from_fp16: 1453 case Intrinsic::convert_to_fp16: 1454 case Intrinsic::bitreverse: 1455 case Intrinsic::x86_sse_cvtss2si: 1456 case Intrinsic::x86_sse_cvtss2si64: 1457 case Intrinsic::x86_sse_cvttss2si: 1458 case Intrinsic::x86_sse_cvttss2si64: 1459 case Intrinsic::x86_sse2_cvtsd2si: 1460 case Intrinsic::x86_sse2_cvtsd2si64: 1461 case Intrinsic::x86_sse2_cvttsd2si: 1462 case Intrinsic::x86_sse2_cvttsd2si64: 1463 case Intrinsic::x86_avx512_vcvtss2si32: 1464 case Intrinsic::x86_avx512_vcvtss2si64: 1465 case Intrinsic::x86_avx512_cvttss2si: 1466 case Intrinsic::x86_avx512_cvttss2si64: 1467 case Intrinsic::x86_avx512_vcvtsd2si32: 1468 case Intrinsic::x86_avx512_vcvtsd2si64: 1469 case Intrinsic::x86_avx512_cvttsd2si: 1470 case Intrinsic::x86_avx512_cvttsd2si64: 1471 case Intrinsic::x86_avx512_vcvtss2usi32: 1472 case Intrinsic::x86_avx512_vcvtss2usi64: 1473 case Intrinsic::x86_avx512_cvttss2usi: 1474 case Intrinsic::x86_avx512_cvttss2usi64: 1475 case Intrinsic::x86_avx512_vcvtsd2usi32: 1476 case Intrinsic::x86_avx512_vcvtsd2usi64: 1477 case Intrinsic::x86_avx512_cvttsd2usi: 1478 case Intrinsic::x86_avx512_cvttsd2usi64: 1479 case Intrinsic::is_constant: 1480 return true; 1481 default: 1482 return false; 1483 case Intrinsic::not_intrinsic: break; 1484 } 1485 1486 if (!F->hasName()) 1487 return false; 1488 1489 // In these cases, the check of the length is required. We don't want to 1490 // return true for a name like "cos\0blah" which strcmp would return equal to 1491 // "cos", but has length 8. 1492 StringRef Name = F->getName(); 1493 switch (Name[0]) { 1494 default: 1495 return false; 1496 case 'a': 1497 return Name == "acos" || Name == "acosf" || 1498 Name == "asin" || Name == "asinf" || 1499 Name == "atan" || Name == "atanf" || 1500 Name == "atan2" || Name == "atan2f"; 1501 case 'c': 1502 return Name == "ceil" || Name == "ceilf" || 1503 Name == "cos" || Name == "cosf" || 1504 Name == "cosh" || Name == "coshf"; 1505 case 'e': 1506 return Name == "exp" || Name == "expf" || 1507 Name == "exp2" || Name == "exp2f"; 1508 case 'f': 1509 return Name == "fabs" || Name == "fabsf" || 1510 Name == "floor" || Name == "floorf" || 1511 Name == "fmod" || Name == "fmodf"; 1512 case 'l': 1513 return Name == "log" || Name == "logf" || 1514 Name == "log2" || Name == "log2f" || 1515 Name == "log10" || Name == "log10f"; 1516 case 'n': 1517 return Name == "nearbyint" || Name == "nearbyintf"; 1518 case 'p': 1519 return Name == "pow" || Name == "powf"; 1520 case 'r': 1521 return Name == "rint" || Name == "rintf" || 1522 Name == "round" || Name == "roundf"; 1523 case 's': 1524 return Name == "sin" || Name == "sinf" || 1525 Name == "sinh" || Name == "sinhf" || 1526 Name == "sqrt" || Name == "sqrtf"; 1527 case 't': 1528 return Name == "tan" || Name == "tanf" || 1529 Name == "tanh" || Name == "tanhf" || 1530 Name == "trunc" || Name == "truncf"; 1531 case '_': 1532 // Check for various function names that get used for the math functions 1533 // when the header files are preprocessed with the macro 1534 // __FINITE_MATH_ONLY__ enabled. 1535 // The '12' here is the length of the shortest name that can match. 1536 // We need to check the size before looking at Name[1] and Name[2] 1537 // so we may as well check a limit that will eliminate mismatches. 1538 if (Name.size() < 12 || Name[1] != '_') 1539 return false; 1540 switch (Name[2]) { 1541 default: 1542 return false; 1543 case 'a': 1544 return Name == "__acos_finite" || Name == "__acosf_finite" || 1545 Name == "__asin_finite" || Name == "__asinf_finite" || 1546 Name == "__atan2_finite" || Name == "__atan2f_finite"; 1547 case 'c': 1548 return Name == "__cosh_finite" || Name == "__coshf_finite"; 1549 case 'e': 1550 return Name == "__exp_finite" || Name == "__expf_finite" || 1551 Name == "__exp2_finite" || Name == "__exp2f_finite"; 1552 case 'l': 1553 return Name == "__log_finite" || Name == "__logf_finite" || 1554 Name == "__log10_finite" || Name == "__log10f_finite"; 1555 case 'p': 1556 return Name == "__pow_finite" || Name == "__powf_finite"; 1557 case 's': 1558 return Name == "__sinh_finite" || Name == "__sinhf_finite"; 1559 } 1560 } 1561 } 1562 1563 namespace { 1564 1565 Constant *GetConstantFoldFPValue(double V, Type *Ty) { 1566 if (Ty->isHalfTy() || Ty->isFloatTy()) { 1567 APFloat APF(V); 1568 bool unused; 1569 APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused); 1570 return ConstantFP::get(Ty->getContext(), APF); 1571 } 1572 if (Ty->isDoubleTy()) 1573 return ConstantFP::get(Ty->getContext(), APFloat(V)); 1574 llvm_unreachable("Can only constant fold half/float/double"); 1575 } 1576 1577 /// Clear the floating-point exception state. 1578 inline void llvm_fenv_clearexcept() { 1579 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT 1580 feclearexcept(FE_ALL_EXCEPT); 1581 #endif 1582 errno = 0; 1583 } 1584 1585 /// Test if a floating-point exception was raised. 1586 inline bool llvm_fenv_testexcept() { 1587 int errno_val = errno; 1588 if (errno_val == ERANGE || errno_val == EDOM) 1589 return true; 1590 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT 1591 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT)) 1592 return true; 1593 #endif 1594 return false; 1595 } 1596 1597 Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) { 1598 llvm_fenv_clearexcept(); 1599 V = NativeFP(V); 1600 if (llvm_fenv_testexcept()) { 1601 llvm_fenv_clearexcept(); 1602 return nullptr; 1603 } 1604 1605 return GetConstantFoldFPValue(V, Ty); 1606 } 1607 1608 Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V, 1609 double W, Type *Ty) { 1610 llvm_fenv_clearexcept(); 1611 V = NativeFP(V, W); 1612 if (llvm_fenv_testexcept()) { 1613 llvm_fenv_clearexcept(); 1614 return nullptr; 1615 } 1616 1617 return GetConstantFoldFPValue(V, Ty); 1618 } 1619 1620 /// Attempt to fold an SSE floating point to integer conversion of a constant 1621 /// floating point. If roundTowardZero is false, the default IEEE rounding is 1622 /// used (toward nearest, ties to even). This matches the behavior of the 1623 /// non-truncating SSE instructions in the default rounding mode. The desired 1624 /// integer type Ty is used to select how many bits are available for the 1625 /// result. Returns null if the conversion cannot be performed, otherwise 1626 /// returns the Constant value resulting from the conversion. 1627 Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero, 1628 Type *Ty, bool IsSigned) { 1629 // All of these conversion intrinsics form an integer of at most 64bits. 1630 unsigned ResultWidth = Ty->getIntegerBitWidth(); 1631 assert(ResultWidth <= 64 && 1632 "Can only constant fold conversions to 64 and 32 bit ints"); 1633 1634 uint64_t UIntVal; 1635 bool isExact = false; 1636 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero 1637 : APFloat::rmNearestTiesToEven; 1638 APFloat::opStatus status = 1639 Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth, 1640 IsSigned, mode, &isExact); 1641 if (status != APFloat::opOK && 1642 (!roundTowardZero || status != APFloat::opInexact)) 1643 return nullptr; 1644 return ConstantInt::get(Ty, UIntVal, IsSigned); 1645 } 1646 1647 double getValueAsDouble(ConstantFP *Op) { 1648 Type *Ty = Op->getType(); 1649 1650 if (Ty->isFloatTy()) 1651 return Op->getValueAPF().convertToFloat(); 1652 1653 if (Ty->isDoubleTy()) 1654 return Op->getValueAPF().convertToDouble(); 1655 1656 bool unused; 1657 APFloat APF = Op->getValueAPF(); 1658 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused); 1659 return APF.convertToDouble(); 1660 } 1661 1662 static bool isManifestConstant(const Constant *c) { 1663 if (isa<ConstantData>(c)) { 1664 return true; 1665 } else if (isa<ConstantAggregate>(c) || isa<ConstantExpr>(c)) { 1666 for (const Value *subc : c->operand_values()) { 1667 if (!isManifestConstant(cast<Constant>(subc))) 1668 return false; 1669 } 1670 return true; 1671 } 1672 return false; 1673 } 1674 1675 static bool getConstIntOrUndef(Value *Op, const APInt *&C) { 1676 if (auto *CI = dyn_cast<ConstantInt>(Op)) { 1677 C = &CI->getValue(); 1678 return true; 1679 } 1680 if (isa<UndefValue>(Op)) { 1681 C = nullptr; 1682 return true; 1683 } 1684 return false; 1685 } 1686 1687 static Constant *ConstantFoldScalarCall1(StringRef Name, 1688 Intrinsic::ID IntrinsicID, 1689 Type *Ty, 1690 ArrayRef<Constant *> Operands, 1691 const TargetLibraryInfo *TLI, 1692 const CallBase *Call) { 1693 assert(Operands.size() == 1 && "Wrong number of operands."); 1694 1695 if (IntrinsicID == Intrinsic::is_constant) { 1696 // We know we have a "Constant" argument. But we want to only 1697 // return true for manifest constants, not those that depend on 1698 // constants with unknowable values, e.g. GlobalValue or BlockAddress. 1699 if (isManifestConstant(Operands[0])) 1700 return ConstantInt::getTrue(Ty->getContext()); 1701 return nullptr; 1702 } 1703 if (isa<UndefValue>(Operands[0])) { 1704 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN. 1705 // ctpop() is between 0 and bitwidth, pick 0 for undef. 1706 if (IntrinsicID == Intrinsic::cos || 1707 IntrinsicID == Intrinsic::ctpop) 1708 return Constant::getNullValue(Ty); 1709 if (IntrinsicID == Intrinsic::bswap || 1710 IntrinsicID == Intrinsic::bitreverse || 1711 IntrinsicID == Intrinsic::launder_invariant_group || 1712 IntrinsicID == Intrinsic::strip_invariant_group) 1713 return Operands[0]; 1714 } 1715 1716 if (isa<ConstantPointerNull>(Operands[0])) { 1717 // launder(null) == null == strip(null) iff in addrspace 0 1718 if (IntrinsicID == Intrinsic::launder_invariant_group || 1719 IntrinsicID == Intrinsic::strip_invariant_group) { 1720 // If instruction is not yet put in a basic block (e.g. when cloning 1721 // a function during inlining), Call's caller may not be available. 1722 // So check Call's BB first before querying Call->getCaller. 1723 const Function *Caller = 1724 Call->getParent() ? Call->getCaller() : nullptr; 1725 if (Caller && 1726 !NullPointerIsDefined( 1727 Caller, Operands[0]->getType()->getPointerAddressSpace())) { 1728 return Operands[0]; 1729 } 1730 return nullptr; 1731 } 1732 } 1733 1734 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) { 1735 if (IntrinsicID == Intrinsic::convert_to_fp16) { 1736 APFloat Val(Op->getValueAPF()); 1737 1738 bool lost = false; 1739 Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost); 1740 1741 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt()); 1742 } 1743 1744 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy()) 1745 return nullptr; 1746 1747 // Use internal versions of these intrinsics. 1748 APFloat U = Op->getValueAPF(); 1749 1750 if (IntrinsicID == Intrinsic::nearbyint || IntrinsicID == Intrinsic::rint) { 1751 U.roundToIntegral(APFloat::rmNearestTiesToEven); 1752 return ConstantFP::get(Ty->getContext(), U); 1753 } 1754 1755 if (IntrinsicID == Intrinsic::round) { 1756 U.roundToIntegral(APFloat::rmNearestTiesToAway); 1757 return ConstantFP::get(Ty->getContext(), U); 1758 } 1759 1760 if (IntrinsicID == Intrinsic::ceil) { 1761 U.roundToIntegral(APFloat::rmTowardPositive); 1762 return ConstantFP::get(Ty->getContext(), U); 1763 } 1764 1765 if (IntrinsicID == Intrinsic::floor) { 1766 U.roundToIntegral(APFloat::rmTowardNegative); 1767 return ConstantFP::get(Ty->getContext(), U); 1768 } 1769 1770 if (IntrinsicID == Intrinsic::trunc) { 1771 U.roundToIntegral(APFloat::rmTowardZero); 1772 return ConstantFP::get(Ty->getContext(), U); 1773 } 1774 1775 if (IntrinsicID == Intrinsic::fabs) { 1776 U.clearSign(); 1777 return ConstantFP::get(Ty->getContext(), U); 1778 } 1779 1780 /// We only fold functions with finite arguments. Folding NaN and inf is 1781 /// likely to be aborted with an exception anyway, and some host libms 1782 /// have known errors raising exceptions. 1783 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity()) 1784 return nullptr; 1785 1786 /// Currently APFloat versions of these functions do not exist, so we use 1787 /// the host native double versions. Float versions are not called 1788 /// directly but for all these it is true (float)(f((double)arg)) == 1789 /// f(arg). Long double not supported yet. 1790 double V = getValueAsDouble(Op); 1791 1792 switch (IntrinsicID) { 1793 default: break; 1794 case Intrinsic::log: 1795 return ConstantFoldFP(log, V, Ty); 1796 case Intrinsic::log2: 1797 // TODO: What about hosts that lack a C99 library? 1798 return ConstantFoldFP(Log2, V, Ty); 1799 case Intrinsic::log10: 1800 // TODO: What about hosts that lack a C99 library? 1801 return ConstantFoldFP(log10, V, Ty); 1802 case Intrinsic::exp: 1803 return ConstantFoldFP(exp, V, Ty); 1804 case Intrinsic::exp2: 1805 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library. 1806 return ConstantFoldBinaryFP(pow, 2.0, V, Ty); 1807 case Intrinsic::sin: 1808 return ConstantFoldFP(sin, V, Ty); 1809 case Intrinsic::cos: 1810 return ConstantFoldFP(cos, V, Ty); 1811 case Intrinsic::sqrt: 1812 return ConstantFoldFP(sqrt, V, Ty); 1813 } 1814 1815 if (!TLI) 1816 return nullptr; 1817 1818 LibFunc Func = NotLibFunc; 1819 TLI->getLibFunc(Name, Func); 1820 switch (Func) { 1821 default: 1822 break; 1823 case LibFunc_acos: 1824 case LibFunc_acosf: 1825 case LibFunc_acos_finite: 1826 case LibFunc_acosf_finite: 1827 if (TLI->has(Func)) 1828 return ConstantFoldFP(acos, V, Ty); 1829 break; 1830 case LibFunc_asin: 1831 case LibFunc_asinf: 1832 case LibFunc_asin_finite: 1833 case LibFunc_asinf_finite: 1834 if (TLI->has(Func)) 1835 return ConstantFoldFP(asin, V, Ty); 1836 break; 1837 case LibFunc_atan: 1838 case LibFunc_atanf: 1839 if (TLI->has(Func)) 1840 return ConstantFoldFP(atan, V, Ty); 1841 break; 1842 case LibFunc_ceil: 1843 case LibFunc_ceilf: 1844 if (TLI->has(Func)) { 1845 U.roundToIntegral(APFloat::rmTowardPositive); 1846 return ConstantFP::get(Ty->getContext(), U); 1847 } 1848 break; 1849 case LibFunc_cos: 1850 case LibFunc_cosf: 1851 if (TLI->has(Func)) 1852 return ConstantFoldFP(cos, V, Ty); 1853 break; 1854 case LibFunc_cosh: 1855 case LibFunc_coshf: 1856 case LibFunc_cosh_finite: 1857 case LibFunc_coshf_finite: 1858 if (TLI->has(Func)) 1859 return ConstantFoldFP(cosh, V, Ty); 1860 break; 1861 case LibFunc_exp: 1862 case LibFunc_expf: 1863 case LibFunc_exp_finite: 1864 case LibFunc_expf_finite: 1865 if (TLI->has(Func)) 1866 return ConstantFoldFP(exp, V, Ty); 1867 break; 1868 case LibFunc_exp2: 1869 case LibFunc_exp2f: 1870 case LibFunc_exp2_finite: 1871 case LibFunc_exp2f_finite: 1872 if (TLI->has(Func)) 1873 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library. 1874 return ConstantFoldBinaryFP(pow, 2.0, V, Ty); 1875 break; 1876 case LibFunc_fabs: 1877 case LibFunc_fabsf: 1878 if (TLI->has(Func)) { 1879 U.clearSign(); 1880 return ConstantFP::get(Ty->getContext(), U); 1881 } 1882 break; 1883 case LibFunc_floor: 1884 case LibFunc_floorf: 1885 if (TLI->has(Func)) { 1886 U.roundToIntegral(APFloat::rmTowardNegative); 1887 return ConstantFP::get(Ty->getContext(), U); 1888 } 1889 break; 1890 case LibFunc_log: 1891 case LibFunc_logf: 1892 case LibFunc_log_finite: 1893 case LibFunc_logf_finite: 1894 if (V > 0.0 && TLI->has(Func)) 1895 return ConstantFoldFP(log, V, Ty); 1896 break; 1897 case LibFunc_log2: 1898 case LibFunc_log2f: 1899 case LibFunc_log2_finite: 1900 case LibFunc_log2f_finite: 1901 if (V > 0.0 && TLI->has(Func)) 1902 // TODO: What about hosts that lack a C99 library? 1903 return ConstantFoldFP(Log2, V, Ty); 1904 break; 1905 case LibFunc_log10: 1906 case LibFunc_log10f: 1907 case LibFunc_log10_finite: 1908 case LibFunc_log10f_finite: 1909 if (V > 0.0 && TLI->has(Func)) 1910 // TODO: What about hosts that lack a C99 library? 1911 return ConstantFoldFP(log10, V, Ty); 1912 break; 1913 case LibFunc_nearbyint: 1914 case LibFunc_nearbyintf: 1915 case LibFunc_rint: 1916 case LibFunc_rintf: 1917 if (TLI->has(Func)) { 1918 U.roundToIntegral(APFloat::rmNearestTiesToEven); 1919 return ConstantFP::get(Ty->getContext(), U); 1920 } 1921 break; 1922 case LibFunc_round: 1923 case LibFunc_roundf: 1924 if (TLI->has(Func)) { 1925 U.roundToIntegral(APFloat::rmNearestTiesToAway); 1926 return ConstantFP::get(Ty->getContext(), U); 1927 } 1928 break; 1929 case LibFunc_sin: 1930 case LibFunc_sinf: 1931 if (TLI->has(Func)) 1932 return ConstantFoldFP(sin, V, Ty); 1933 break; 1934 case LibFunc_sinh: 1935 case LibFunc_sinhf: 1936 case LibFunc_sinh_finite: 1937 case LibFunc_sinhf_finite: 1938 if (TLI->has(Func)) 1939 return ConstantFoldFP(sinh, V, Ty); 1940 break; 1941 case LibFunc_sqrt: 1942 case LibFunc_sqrtf: 1943 if (V >= 0.0 && TLI->has(Func)) 1944 return ConstantFoldFP(sqrt, V, Ty); 1945 break; 1946 case LibFunc_tan: 1947 case LibFunc_tanf: 1948 if (TLI->has(Func)) 1949 return ConstantFoldFP(tan, V, Ty); 1950 break; 1951 case LibFunc_tanh: 1952 case LibFunc_tanhf: 1953 if (TLI->has(Func)) 1954 return ConstantFoldFP(tanh, V, Ty); 1955 break; 1956 case LibFunc_trunc: 1957 case LibFunc_truncf: 1958 if (TLI->has(Func)) { 1959 U.roundToIntegral(APFloat::rmTowardZero); 1960 return ConstantFP::get(Ty->getContext(), U); 1961 } 1962 break; 1963 } 1964 return nullptr; 1965 } 1966 1967 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) { 1968 switch (IntrinsicID) { 1969 case Intrinsic::bswap: 1970 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap()); 1971 case Intrinsic::ctpop: 1972 return ConstantInt::get(Ty, Op->getValue().countPopulation()); 1973 case Intrinsic::bitreverse: 1974 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits()); 1975 case Intrinsic::convert_from_fp16: { 1976 APFloat Val(APFloat::IEEEhalf(), Op->getValue()); 1977 1978 bool lost = false; 1979 APFloat::opStatus status = Val.convert( 1980 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost); 1981 1982 // Conversion is always precise. 1983 (void)status; 1984 assert(status == APFloat::opOK && !lost && 1985 "Precision lost during fp16 constfolding"); 1986 1987 return ConstantFP::get(Ty->getContext(), Val); 1988 } 1989 default: 1990 return nullptr; 1991 } 1992 } 1993 1994 // Support ConstantVector in case we have an Undef in the top. 1995 if (isa<ConstantVector>(Operands[0]) || 1996 isa<ConstantDataVector>(Operands[0])) { 1997 auto *Op = cast<Constant>(Operands[0]); 1998 switch (IntrinsicID) { 1999 default: break; 2000 case Intrinsic::x86_sse_cvtss2si: 2001 case Intrinsic::x86_sse_cvtss2si64: 2002 case Intrinsic::x86_sse2_cvtsd2si: 2003 case Intrinsic::x86_sse2_cvtsd2si64: 2004 if (ConstantFP *FPOp = 2005 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) 2006 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), 2007 /*roundTowardZero=*/false, Ty, 2008 /*IsSigned*/true); 2009 break; 2010 case Intrinsic::x86_sse_cvttss2si: 2011 case Intrinsic::x86_sse_cvttss2si64: 2012 case Intrinsic::x86_sse2_cvttsd2si: 2013 case Intrinsic::x86_sse2_cvttsd2si64: 2014 if (ConstantFP *FPOp = 2015 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) 2016 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), 2017 /*roundTowardZero=*/true, Ty, 2018 /*IsSigned*/true); 2019 break; 2020 } 2021 } 2022 2023 return nullptr; 2024 } 2025 2026 static Constant *ConstantFoldScalarCall2(StringRef Name, 2027 Intrinsic::ID IntrinsicID, 2028 Type *Ty, 2029 ArrayRef<Constant *> Operands, 2030 const TargetLibraryInfo *TLI, 2031 const CallBase *Call) { 2032 assert(Operands.size() == 2 && "Wrong number of operands."); 2033 2034 if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) { 2035 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy()) 2036 return nullptr; 2037 double Op1V = getValueAsDouble(Op1); 2038 2039 if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) { 2040 if (Op2->getType() != Op1->getType()) 2041 return nullptr; 2042 2043 double Op2V = getValueAsDouble(Op2); 2044 if (IntrinsicID == Intrinsic::pow) { 2045 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty); 2046 } 2047 if (IntrinsicID == Intrinsic::copysign) { 2048 APFloat V1 = Op1->getValueAPF(); 2049 const APFloat &V2 = Op2->getValueAPF(); 2050 V1.copySign(V2); 2051 return ConstantFP::get(Ty->getContext(), V1); 2052 } 2053 2054 if (IntrinsicID == Intrinsic::minnum) { 2055 const APFloat &C1 = Op1->getValueAPF(); 2056 const APFloat &C2 = Op2->getValueAPF(); 2057 return ConstantFP::get(Ty->getContext(), minnum(C1, C2)); 2058 } 2059 2060 if (IntrinsicID == Intrinsic::maxnum) { 2061 const APFloat &C1 = Op1->getValueAPF(); 2062 const APFloat &C2 = Op2->getValueAPF(); 2063 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2)); 2064 } 2065 2066 if (IntrinsicID == Intrinsic::minimum) { 2067 const APFloat &C1 = Op1->getValueAPF(); 2068 const APFloat &C2 = Op2->getValueAPF(); 2069 return ConstantFP::get(Ty->getContext(), minimum(C1, C2)); 2070 } 2071 2072 if (IntrinsicID == Intrinsic::maximum) { 2073 const APFloat &C1 = Op1->getValueAPF(); 2074 const APFloat &C2 = Op2->getValueAPF(); 2075 return ConstantFP::get(Ty->getContext(), maximum(C1, C2)); 2076 } 2077 2078 if (!TLI) 2079 return nullptr; 2080 2081 LibFunc Func = NotLibFunc; 2082 TLI->getLibFunc(Name, Func); 2083 switch (Func) { 2084 default: 2085 break; 2086 case LibFunc_pow: 2087 case LibFunc_powf: 2088 case LibFunc_pow_finite: 2089 case LibFunc_powf_finite: 2090 if (TLI->has(Func)) 2091 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty); 2092 break; 2093 case LibFunc_fmod: 2094 case LibFunc_fmodf: 2095 if (TLI->has(Func)) { 2096 APFloat V = Op1->getValueAPF(); 2097 if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF())) 2098 return ConstantFP::get(Ty->getContext(), V); 2099 } 2100 break; 2101 case LibFunc_atan2: 2102 case LibFunc_atan2f: 2103 case LibFunc_atan2_finite: 2104 case LibFunc_atan2f_finite: 2105 if (TLI->has(Func)) 2106 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty); 2107 break; 2108 } 2109 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) { 2110 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy()) 2111 return ConstantFP::get(Ty->getContext(), 2112 APFloat((float)std::pow((float)Op1V, 2113 (int)Op2C->getZExtValue()))); 2114 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy()) 2115 return ConstantFP::get(Ty->getContext(), 2116 APFloat((float)std::pow((float)Op1V, 2117 (int)Op2C->getZExtValue()))); 2118 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy()) 2119 return ConstantFP::get(Ty->getContext(), 2120 APFloat((double)std::pow((double)Op1V, 2121 (int)Op2C->getZExtValue()))); 2122 } 2123 return nullptr; 2124 } 2125 2126 if (Operands[0]->getType()->isIntegerTy() && 2127 Operands[1]->getType()->isIntegerTy()) { 2128 const APInt *C0, *C1; 2129 if (!getConstIntOrUndef(Operands[0], C0) || 2130 !getConstIntOrUndef(Operands[1], C1)) 2131 return nullptr; 2132 2133 switch (IntrinsicID) { 2134 default: break; 2135 case Intrinsic::usub_with_overflow: 2136 case Intrinsic::ssub_with_overflow: 2137 case Intrinsic::uadd_with_overflow: 2138 case Intrinsic::sadd_with_overflow: 2139 // X - undef -> { undef, false } 2140 // undef - X -> { undef, false } 2141 // X + undef -> { undef, false } 2142 // undef + x -> { undef, false } 2143 if (!C0 || !C1) { 2144 return ConstantStruct::get( 2145 cast<StructType>(Ty), 2146 {UndefValue::get(Ty->getStructElementType(0)), 2147 Constant::getNullValue(Ty->getStructElementType(1))}); 2148 } 2149 LLVM_FALLTHROUGH; 2150 case Intrinsic::smul_with_overflow: 2151 case Intrinsic::umul_with_overflow: { 2152 // undef * X -> { 0, false } 2153 // X * undef -> { 0, false } 2154 if (!C0 || !C1) 2155 return Constant::getNullValue(Ty); 2156 2157 APInt Res; 2158 bool Overflow; 2159 switch (IntrinsicID) { 2160 default: llvm_unreachable("Invalid case"); 2161 case Intrinsic::sadd_with_overflow: 2162 Res = C0->sadd_ov(*C1, Overflow); 2163 break; 2164 case Intrinsic::uadd_with_overflow: 2165 Res = C0->uadd_ov(*C1, Overflow); 2166 break; 2167 case Intrinsic::ssub_with_overflow: 2168 Res = C0->ssub_ov(*C1, Overflow); 2169 break; 2170 case Intrinsic::usub_with_overflow: 2171 Res = C0->usub_ov(*C1, Overflow); 2172 break; 2173 case Intrinsic::smul_with_overflow: 2174 Res = C0->smul_ov(*C1, Overflow); 2175 break; 2176 case Intrinsic::umul_with_overflow: 2177 Res = C0->umul_ov(*C1, Overflow); 2178 break; 2179 } 2180 Constant *Ops[] = { 2181 ConstantInt::get(Ty->getContext(), Res), 2182 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow) 2183 }; 2184 return ConstantStruct::get(cast<StructType>(Ty), Ops); 2185 } 2186 case Intrinsic::uadd_sat: 2187 case Intrinsic::sadd_sat: 2188 if (!C0 && !C1) 2189 return UndefValue::get(Ty); 2190 if (!C0 || !C1) 2191 return Constant::getAllOnesValue(Ty); 2192 if (IntrinsicID == Intrinsic::uadd_sat) 2193 return ConstantInt::get(Ty, C0->uadd_sat(*C1)); 2194 else 2195 return ConstantInt::get(Ty, C0->sadd_sat(*C1)); 2196 case Intrinsic::usub_sat: 2197 case Intrinsic::ssub_sat: 2198 if (!C0 && !C1) 2199 return UndefValue::get(Ty); 2200 if (!C0 || !C1) 2201 return Constant::getNullValue(Ty); 2202 if (IntrinsicID == Intrinsic::usub_sat) 2203 return ConstantInt::get(Ty, C0->usub_sat(*C1)); 2204 else 2205 return ConstantInt::get(Ty, C0->ssub_sat(*C1)); 2206 case Intrinsic::cttz: 2207 case Intrinsic::ctlz: 2208 assert(C1 && "Must be constant int"); 2209 2210 // cttz(0, 1) and ctlz(0, 1) are undef. 2211 if (C1->isOneValue() && (!C0 || C0->isNullValue())) 2212 return UndefValue::get(Ty); 2213 if (!C0) 2214 return Constant::getNullValue(Ty); 2215 if (IntrinsicID == Intrinsic::cttz) 2216 return ConstantInt::get(Ty, C0->countTrailingZeros()); 2217 else 2218 return ConstantInt::get(Ty, C0->countLeadingZeros()); 2219 } 2220 2221 return nullptr; 2222 } 2223 2224 // Support ConstantVector in case we have an Undef in the top. 2225 if ((isa<ConstantVector>(Operands[0]) || 2226 isa<ConstantDataVector>(Operands[0])) && 2227 // Check for default rounding mode. 2228 // FIXME: Support other rounding modes? 2229 isa<ConstantInt>(Operands[1]) && 2230 cast<ConstantInt>(Operands[1])->getValue() == 4) { 2231 auto *Op = cast<Constant>(Operands[0]); 2232 switch (IntrinsicID) { 2233 default: break; 2234 case Intrinsic::x86_avx512_vcvtss2si32: 2235 case Intrinsic::x86_avx512_vcvtss2si64: 2236 case Intrinsic::x86_avx512_vcvtsd2si32: 2237 case Intrinsic::x86_avx512_vcvtsd2si64: 2238 if (ConstantFP *FPOp = 2239 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) 2240 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), 2241 /*roundTowardZero=*/false, Ty, 2242 /*IsSigned*/true); 2243 break; 2244 case Intrinsic::x86_avx512_vcvtss2usi32: 2245 case Intrinsic::x86_avx512_vcvtss2usi64: 2246 case Intrinsic::x86_avx512_vcvtsd2usi32: 2247 case Intrinsic::x86_avx512_vcvtsd2usi64: 2248 if (ConstantFP *FPOp = 2249 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) 2250 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), 2251 /*roundTowardZero=*/false, Ty, 2252 /*IsSigned*/false); 2253 break; 2254 case Intrinsic::x86_avx512_cvttss2si: 2255 case Intrinsic::x86_avx512_cvttss2si64: 2256 case Intrinsic::x86_avx512_cvttsd2si: 2257 case Intrinsic::x86_avx512_cvttsd2si64: 2258 if (ConstantFP *FPOp = 2259 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) 2260 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), 2261 /*roundTowardZero=*/true, Ty, 2262 /*IsSigned*/true); 2263 break; 2264 case Intrinsic::x86_avx512_cvttss2usi: 2265 case Intrinsic::x86_avx512_cvttss2usi64: 2266 case Intrinsic::x86_avx512_cvttsd2usi: 2267 case Intrinsic::x86_avx512_cvttsd2usi64: 2268 if (ConstantFP *FPOp = 2269 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) 2270 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), 2271 /*roundTowardZero=*/true, Ty, 2272 /*IsSigned*/false); 2273 break; 2274 } 2275 } 2276 return nullptr; 2277 } 2278 2279 static Constant *ConstantFoldScalarCall3(StringRef Name, 2280 Intrinsic::ID IntrinsicID, 2281 Type *Ty, 2282 ArrayRef<Constant *> Operands, 2283 const TargetLibraryInfo *TLI, 2284 const CallBase *Call) { 2285 assert(Operands.size() == 3 && "Wrong number of operands."); 2286 2287 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) { 2288 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) { 2289 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) { 2290 switch (IntrinsicID) { 2291 default: break; 2292 case Intrinsic::fma: 2293 case Intrinsic::fmuladd: { 2294 APFloat V = Op1->getValueAPF(); 2295 V.fusedMultiplyAdd(Op2->getValueAPF(), Op3->getValueAPF(), 2296 APFloat::rmNearestTiesToEven); 2297 return ConstantFP::get(Ty->getContext(), V); 2298 } 2299 } 2300 } 2301 } 2302 } 2303 2304 if (const auto *Op1 = dyn_cast<ConstantInt>(Operands[0])) { 2305 if (const auto *Op2 = dyn_cast<ConstantInt>(Operands[1])) { 2306 if (const auto *Op3 = dyn_cast<ConstantInt>(Operands[2])) { 2307 switch (IntrinsicID) { 2308 default: break; 2309 case Intrinsic::smul_fix: 2310 case Intrinsic::smul_fix_sat: { 2311 // This code performs rounding towards negative infinity in case the 2312 // result cannot be represented exactly for the given scale. Targets 2313 // that do care about rounding should use a target hook for specifying 2314 // how rounding should be done, and provide their own folding to be 2315 // consistent with rounding. This is the same approach as used by 2316 // DAGTypeLegalizer::ExpandIntRes_MULFIX. 2317 APInt Lhs = Op1->getValue(); 2318 APInt Rhs = Op2->getValue(); 2319 unsigned Scale = Op3->getValue().getZExtValue(); 2320 unsigned Width = Lhs.getBitWidth(); 2321 assert(Scale < Width && "Illegal scale."); 2322 unsigned ExtendedWidth = Width * 2; 2323 APInt Product = (Lhs.sextOrSelf(ExtendedWidth) * 2324 Rhs.sextOrSelf(ExtendedWidth)).ashr(Scale); 2325 if (IntrinsicID == Intrinsic::smul_fix_sat) { 2326 APInt MaxValue = 2327 APInt::getSignedMaxValue(Width).sextOrSelf(ExtendedWidth); 2328 APInt MinValue = 2329 APInt::getSignedMinValue(Width).sextOrSelf(ExtendedWidth); 2330 Product = APIntOps::smin(Product, MaxValue); 2331 Product = APIntOps::smax(Product, MinValue); 2332 } 2333 return ConstantInt::get(Ty->getContext(), 2334 Product.sextOrTrunc(Width)); 2335 } 2336 } 2337 } 2338 } 2339 } 2340 2341 if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) { 2342 const APInt *C0, *C1, *C2; 2343 if (!getConstIntOrUndef(Operands[0], C0) || 2344 !getConstIntOrUndef(Operands[1], C1) || 2345 !getConstIntOrUndef(Operands[2], C2)) 2346 return nullptr; 2347 2348 bool IsRight = IntrinsicID == Intrinsic::fshr; 2349 if (!C2) 2350 return Operands[IsRight ? 1 : 0]; 2351 if (!C0 && !C1) 2352 return UndefValue::get(Ty); 2353 2354 // The shift amount is interpreted as modulo the bitwidth. If the shift 2355 // amount is effectively 0, avoid UB due to oversized inverse shift below. 2356 unsigned BitWidth = C2->getBitWidth(); 2357 unsigned ShAmt = C2->urem(BitWidth); 2358 if (!ShAmt) 2359 return Operands[IsRight ? 1 : 0]; 2360 2361 // (C0 << ShlAmt) | (C1 >> LshrAmt) 2362 unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt; 2363 unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt; 2364 if (!C0) 2365 return ConstantInt::get(Ty, C1->lshr(LshrAmt)); 2366 if (!C1) 2367 return ConstantInt::get(Ty, C0->shl(ShlAmt)); 2368 return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt)); 2369 } 2370 2371 return nullptr; 2372 } 2373 2374 static Constant *ConstantFoldScalarCall(StringRef Name, 2375 Intrinsic::ID IntrinsicID, 2376 Type *Ty, 2377 ArrayRef<Constant *> Operands, 2378 const TargetLibraryInfo *TLI, 2379 const CallBase *Call) { 2380 if (Operands.size() == 1) 2381 return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call); 2382 2383 if (Operands.size() == 2) 2384 return ConstantFoldScalarCall2(Name, IntrinsicID, Ty, Operands, TLI, Call); 2385 2386 if (Operands.size() == 3) 2387 return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call); 2388 2389 return nullptr; 2390 } 2391 2392 static Constant *ConstantFoldVectorCall(StringRef Name, 2393 Intrinsic::ID IntrinsicID, 2394 VectorType *VTy, 2395 ArrayRef<Constant *> Operands, 2396 const DataLayout &DL, 2397 const TargetLibraryInfo *TLI, 2398 const CallBase *Call) { 2399 SmallVector<Constant *, 4> Result(VTy->getNumElements()); 2400 SmallVector<Constant *, 4> Lane(Operands.size()); 2401 Type *Ty = VTy->getElementType(); 2402 2403 if (IntrinsicID == Intrinsic::masked_load) { 2404 auto *SrcPtr = Operands[0]; 2405 auto *Mask = Operands[2]; 2406 auto *Passthru = Operands[3]; 2407 2408 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, VTy, DL); 2409 2410 SmallVector<Constant *, 32> NewElements; 2411 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) { 2412 auto *MaskElt = Mask->getAggregateElement(I); 2413 if (!MaskElt) 2414 break; 2415 auto *PassthruElt = Passthru->getAggregateElement(I); 2416 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr; 2417 if (isa<UndefValue>(MaskElt)) { 2418 if (PassthruElt) 2419 NewElements.push_back(PassthruElt); 2420 else if (VecElt) 2421 NewElements.push_back(VecElt); 2422 else 2423 return nullptr; 2424 } 2425 if (MaskElt->isNullValue()) { 2426 if (!PassthruElt) 2427 return nullptr; 2428 NewElements.push_back(PassthruElt); 2429 } else if (MaskElt->isOneValue()) { 2430 if (!VecElt) 2431 return nullptr; 2432 NewElements.push_back(VecElt); 2433 } else { 2434 return nullptr; 2435 } 2436 } 2437 if (NewElements.size() != VTy->getNumElements()) 2438 return nullptr; 2439 return ConstantVector::get(NewElements); 2440 } 2441 2442 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) { 2443 // Gather a column of constants. 2444 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) { 2445 // Some intrinsics use a scalar type for certain arguments. 2446 if (hasVectorInstrinsicScalarOpd(IntrinsicID, J)) { 2447 Lane[J] = Operands[J]; 2448 continue; 2449 } 2450 2451 Constant *Agg = Operands[J]->getAggregateElement(I); 2452 if (!Agg) 2453 return nullptr; 2454 2455 Lane[J] = Agg; 2456 } 2457 2458 // Use the regular scalar folding to simplify this column. 2459 Constant *Folded = 2460 ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call); 2461 if (!Folded) 2462 return nullptr; 2463 Result[I] = Folded; 2464 } 2465 2466 return ConstantVector::get(Result); 2467 } 2468 2469 } // end anonymous namespace 2470 2471 Constant *llvm::ConstantFoldCall(const CallBase *Call, Function *F, 2472 ArrayRef<Constant *> Operands, 2473 const TargetLibraryInfo *TLI) { 2474 if (Call->isNoBuiltin() || Call->isStrictFP()) 2475 return nullptr; 2476 if (!F->hasName()) 2477 return nullptr; 2478 StringRef Name = F->getName(); 2479 2480 Type *Ty = F->getReturnType(); 2481 2482 if (auto *VTy = dyn_cast<VectorType>(Ty)) 2483 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, 2484 F->getParent()->getDataLayout(), TLI, Call); 2485 2486 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI, 2487 Call); 2488 } 2489 2490 bool llvm::isMathLibCallNoop(const CallBase *Call, 2491 const TargetLibraryInfo *TLI) { 2492 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap 2493 // (and to some extent ConstantFoldScalarCall). 2494 if (Call->isNoBuiltin() || Call->isStrictFP()) 2495 return false; 2496 Function *F = Call->getCalledFunction(); 2497 if (!F) 2498 return false; 2499 2500 LibFunc Func; 2501 if (!TLI || !TLI->getLibFunc(*F, Func)) 2502 return false; 2503 2504 if (Call->getNumArgOperands() == 1) { 2505 if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) { 2506 const APFloat &Op = OpC->getValueAPF(); 2507 switch (Func) { 2508 case LibFunc_logl: 2509 case LibFunc_log: 2510 case LibFunc_logf: 2511 case LibFunc_log2l: 2512 case LibFunc_log2: 2513 case LibFunc_log2f: 2514 case LibFunc_log10l: 2515 case LibFunc_log10: 2516 case LibFunc_log10f: 2517 return Op.isNaN() || (!Op.isZero() && !Op.isNegative()); 2518 2519 case LibFunc_expl: 2520 case LibFunc_exp: 2521 case LibFunc_expf: 2522 // FIXME: These boundaries are slightly conservative. 2523 if (OpC->getType()->isDoubleTy()) 2524 return Op.compare(APFloat(-745.0)) != APFloat::cmpLessThan && 2525 Op.compare(APFloat(709.0)) != APFloat::cmpGreaterThan; 2526 if (OpC->getType()->isFloatTy()) 2527 return Op.compare(APFloat(-103.0f)) != APFloat::cmpLessThan && 2528 Op.compare(APFloat(88.0f)) != APFloat::cmpGreaterThan; 2529 break; 2530 2531 case LibFunc_exp2l: 2532 case LibFunc_exp2: 2533 case LibFunc_exp2f: 2534 // FIXME: These boundaries are slightly conservative. 2535 if (OpC->getType()->isDoubleTy()) 2536 return Op.compare(APFloat(-1074.0)) != APFloat::cmpLessThan && 2537 Op.compare(APFloat(1023.0)) != APFloat::cmpGreaterThan; 2538 if (OpC->getType()->isFloatTy()) 2539 return Op.compare(APFloat(-149.0f)) != APFloat::cmpLessThan && 2540 Op.compare(APFloat(127.0f)) != APFloat::cmpGreaterThan; 2541 break; 2542 2543 case LibFunc_sinl: 2544 case LibFunc_sin: 2545 case LibFunc_sinf: 2546 case LibFunc_cosl: 2547 case LibFunc_cos: 2548 case LibFunc_cosf: 2549 return !Op.isInfinity(); 2550 2551 case LibFunc_tanl: 2552 case LibFunc_tan: 2553 case LibFunc_tanf: { 2554 // FIXME: Stop using the host math library. 2555 // FIXME: The computation isn't done in the right precision. 2556 Type *Ty = OpC->getType(); 2557 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) { 2558 double OpV = getValueAsDouble(OpC); 2559 return ConstantFoldFP(tan, OpV, Ty) != nullptr; 2560 } 2561 break; 2562 } 2563 2564 case LibFunc_asinl: 2565 case LibFunc_asin: 2566 case LibFunc_asinf: 2567 case LibFunc_acosl: 2568 case LibFunc_acos: 2569 case LibFunc_acosf: 2570 return Op.compare(APFloat(Op.getSemantics(), "-1")) != 2571 APFloat::cmpLessThan && 2572 Op.compare(APFloat(Op.getSemantics(), "1")) != 2573 APFloat::cmpGreaterThan; 2574 2575 case LibFunc_sinh: 2576 case LibFunc_cosh: 2577 case LibFunc_sinhf: 2578 case LibFunc_coshf: 2579 case LibFunc_sinhl: 2580 case LibFunc_coshl: 2581 // FIXME: These boundaries are slightly conservative. 2582 if (OpC->getType()->isDoubleTy()) 2583 return Op.compare(APFloat(-710.0)) != APFloat::cmpLessThan && 2584 Op.compare(APFloat(710.0)) != APFloat::cmpGreaterThan; 2585 if (OpC->getType()->isFloatTy()) 2586 return Op.compare(APFloat(-89.0f)) != APFloat::cmpLessThan && 2587 Op.compare(APFloat(89.0f)) != APFloat::cmpGreaterThan; 2588 break; 2589 2590 case LibFunc_sqrtl: 2591 case LibFunc_sqrt: 2592 case LibFunc_sqrtf: 2593 return Op.isNaN() || Op.isZero() || !Op.isNegative(); 2594 2595 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p, 2596 // maybe others? 2597 default: 2598 break; 2599 } 2600 } 2601 } 2602 2603 if (Call->getNumArgOperands() == 2) { 2604 ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0)); 2605 ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1)); 2606 if (Op0C && Op1C) { 2607 const APFloat &Op0 = Op0C->getValueAPF(); 2608 const APFloat &Op1 = Op1C->getValueAPF(); 2609 2610 switch (Func) { 2611 case LibFunc_powl: 2612 case LibFunc_pow: 2613 case LibFunc_powf: { 2614 // FIXME: Stop using the host math library. 2615 // FIXME: The computation isn't done in the right precision. 2616 Type *Ty = Op0C->getType(); 2617 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) { 2618 if (Ty == Op1C->getType()) { 2619 double Op0V = getValueAsDouble(Op0C); 2620 double Op1V = getValueAsDouble(Op1C); 2621 return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr; 2622 } 2623 } 2624 break; 2625 } 2626 2627 case LibFunc_fmodl: 2628 case LibFunc_fmod: 2629 case LibFunc_fmodf: 2630 return Op0.isNaN() || Op1.isNaN() || 2631 (!Op0.isInfinity() && !Op1.isZero()); 2632 2633 default: 2634 break; 2635 } 2636 } 2637 } 2638 2639 return false; 2640 } 2641