1 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines routines for folding instructions into constants. 11 // 12 // Also, to supplement the basic IR ConstantExpr simplifications, 13 // this file defines some additional folding routines that can make use of 14 // DataLayout information. These functions cannot go in IR due to library 15 // dependency issues. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/Analysis/ConstantFolding.h" 20 #include "llvm/ADT/APFloat.h" 21 #include "llvm/ADT/APInt.h" 22 #include "llvm/ADT/ArrayRef.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/StringRef.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/Analysis/TargetLibraryInfo.h" 28 #include "llvm/Analysis/ValueTracking.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/Operator.h" 41 #include "llvm/IR/Type.h" 42 #include "llvm/IR/Value.h" 43 #include "llvm/Support/Casting.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include "llvm/Support/MathExtras.h" 46 #include <cassert> 47 #include <cerrno> 48 #include <cfenv> 49 #include <cmath> 50 #include <cstddef> 51 #include <cstdint> 52 53 using namespace llvm; 54 55 namespace { 56 57 //===----------------------------------------------------------------------===// 58 // Constant Folding internal helper functions 59 //===----------------------------------------------------------------------===// 60 61 /// Constant fold bitcast, symbolically evaluating it with DataLayout. 62 /// This always returns a non-null constant, but it may be a 63 /// ConstantExpr if unfoldable. 64 Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) { 65 // Catch the obvious splat cases. 66 if (C->isNullValue() && !DestTy->isX86_MMXTy()) 67 return Constant::getNullValue(DestTy); 68 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() && 69 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types! 70 return Constant::getAllOnesValue(DestTy); 71 72 // Handle a vector->integer cast. 73 if (auto *IT = dyn_cast<IntegerType>(DestTy)) { 74 auto *VTy = dyn_cast<VectorType>(C->getType()); 75 if (!VTy) 76 return ConstantExpr::getBitCast(C, DestTy); 77 78 unsigned NumSrcElts = VTy->getNumElements(); 79 Type *SrcEltTy = VTy->getElementType(); 80 81 // If the vector is a vector of floating point, convert it to vector of int 82 // to simplify things. 83 if (SrcEltTy->isFloatingPointTy()) { 84 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits(); 85 Type *SrcIVTy = 86 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts); 87 // Ask IR to do the conversion now that #elts line up. 88 C = ConstantExpr::getBitCast(C, SrcIVTy); 89 } 90 91 // Now that we know that the input value is a vector of integers, just shift 92 // and insert them into our result. 93 unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy); 94 APInt Result(IT->getBitWidth(), 0); 95 for (unsigned i = 0; i != NumSrcElts; ++i) { 96 Constant *Element; 97 if (DL.isLittleEndian()) 98 Element = C->getAggregateElement(NumSrcElts-i-1); 99 else 100 Element = C->getAggregateElement(i); 101 102 if (Element && isa<UndefValue>(Element)) { 103 Result <<= BitShift; 104 continue; 105 } 106 107 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element); 108 if (!ElementCI) 109 return ConstantExpr::getBitCast(C, DestTy); 110 111 Result <<= BitShift; 112 Result |= ElementCI->getValue().zextOrSelf(IT->getBitWidth()); 113 } 114 115 return ConstantInt::get(IT, Result); 116 } 117 118 // The code below only handles casts to vectors currently. 119 auto *DestVTy = dyn_cast<VectorType>(DestTy); 120 if (!DestVTy) 121 return ConstantExpr::getBitCast(C, DestTy); 122 123 // If this is a scalar -> vector cast, convert the input into a <1 x scalar> 124 // vector so the code below can handle it uniformly. 125 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) { 126 Constant *Ops = C; // don't take the address of C! 127 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL); 128 } 129 130 // If this is a bitcast from constant vector -> vector, fold it. 131 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C)) 132 return ConstantExpr::getBitCast(C, DestTy); 133 134 // If the element types match, IR can fold it. 135 unsigned NumDstElt = DestVTy->getNumElements(); 136 unsigned NumSrcElt = C->getType()->getVectorNumElements(); 137 if (NumDstElt == NumSrcElt) 138 return ConstantExpr::getBitCast(C, DestTy); 139 140 Type *SrcEltTy = C->getType()->getVectorElementType(); 141 Type *DstEltTy = DestVTy->getElementType(); 142 143 // Otherwise, we're changing the number of elements in a vector, which 144 // requires endianness information to do the right thing. For example, 145 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>) 146 // folds to (little endian): 147 // <4 x i32> <i32 0, i32 0, i32 1, i32 0> 148 // and to (big endian): 149 // <4 x i32> <i32 0, i32 0, i32 0, i32 1> 150 151 // First thing is first. We only want to think about integer here, so if 152 // we have something in FP form, recast it as integer. 153 if (DstEltTy->isFloatingPointTy()) { 154 // Fold to an vector of integers with same size as our FP type. 155 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits(); 156 Type *DestIVTy = 157 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt); 158 // Recursively handle this integer conversion, if possible. 159 C = FoldBitCast(C, DestIVTy, DL); 160 161 // Finally, IR can handle this now that #elts line up. 162 return ConstantExpr::getBitCast(C, DestTy); 163 } 164 165 // Okay, we know the destination is integer, if the input is FP, convert 166 // it to integer first. 167 if (SrcEltTy->isFloatingPointTy()) { 168 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits(); 169 Type *SrcIVTy = 170 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt); 171 // Ask IR to do the conversion now that #elts line up. 172 C = ConstantExpr::getBitCast(C, SrcIVTy); 173 // If IR wasn't able to fold it, bail out. 174 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector. 175 !isa<ConstantDataVector>(C)) 176 return C; 177 } 178 179 // Now we know that the input and output vectors are both integer vectors 180 // of the same size, and that their #elements is not the same. Do the 181 // conversion here, which depends on whether the input or output has 182 // more elements. 183 bool isLittleEndian = DL.isLittleEndian(); 184 185 SmallVector<Constant*, 32> Result; 186 if (NumDstElt < NumSrcElt) { 187 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>) 188 Constant *Zero = Constant::getNullValue(DstEltTy); 189 unsigned Ratio = NumSrcElt/NumDstElt; 190 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits(); 191 unsigned SrcElt = 0; 192 for (unsigned i = 0; i != NumDstElt; ++i) { 193 // Build each element of the result. 194 Constant *Elt = Zero; 195 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1); 196 for (unsigned j = 0; j != Ratio; ++j) { 197 Constant *Src = C->getAggregateElement(SrcElt++); 198 if (Src && isa<UndefValue>(Src)) 199 Src = Constant::getNullValue(C->getType()->getVectorElementType()); 200 else 201 Src = dyn_cast_or_null<ConstantInt>(Src); 202 if (!Src) // Reject constantexpr elements. 203 return ConstantExpr::getBitCast(C, DestTy); 204 205 // Zero extend the element to the right size. 206 Src = ConstantExpr::getZExt(Src, Elt->getType()); 207 208 // Shift it to the right place, depending on endianness. 209 Src = ConstantExpr::getShl(Src, 210 ConstantInt::get(Src->getType(), ShiftAmt)); 211 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize; 212 213 // Mix it in. 214 Elt = ConstantExpr::getOr(Elt, Src); 215 } 216 Result.push_back(Elt); 217 } 218 return ConstantVector::get(Result); 219 } 220 221 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>) 222 unsigned Ratio = NumDstElt/NumSrcElt; 223 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy); 224 225 // Loop over each source value, expanding into multiple results. 226 for (unsigned i = 0; i != NumSrcElt; ++i) { 227 auto *Element = C->getAggregateElement(i); 228 229 if (!Element) // Reject constantexpr elements. 230 return ConstantExpr::getBitCast(C, DestTy); 231 232 if (isa<UndefValue>(Element)) { 233 // Correctly Propagate undef values. 234 Result.append(Ratio, UndefValue::get(DstEltTy)); 235 continue; 236 } 237 238 auto *Src = dyn_cast<ConstantInt>(Element); 239 if (!Src) 240 return ConstantExpr::getBitCast(C, DestTy); 241 242 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1); 243 for (unsigned j = 0; j != Ratio; ++j) { 244 // Shift the piece of the value into the right place, depending on 245 // endianness. 246 Constant *Elt = ConstantExpr::getLShr(Src, 247 ConstantInt::get(Src->getType(), ShiftAmt)); 248 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize; 249 250 // Truncate the element to an integer with the same pointer size and 251 // convert the element back to a pointer using a inttoptr. 252 if (DstEltTy->isPointerTy()) { 253 IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize); 254 Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy); 255 Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy)); 256 continue; 257 } 258 259 // Truncate and remember this piece. 260 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy)); 261 } 262 } 263 264 return ConstantVector::get(Result); 265 } 266 267 } // end anonymous namespace 268 269 /// If this constant is a constant offset from a global, return the global and 270 /// the constant. Because of constantexprs, this function is recursive. 271 bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, 272 APInt &Offset, const DataLayout &DL) { 273 // Trivial case, constant is the global. 274 if ((GV = dyn_cast<GlobalValue>(C))) { 275 unsigned BitWidth = DL.getPointerTypeSizeInBits(GV->getType()); 276 Offset = APInt(BitWidth, 0); 277 return true; 278 } 279 280 // Otherwise, if this isn't a constant expr, bail out. 281 auto *CE = dyn_cast<ConstantExpr>(C); 282 if (!CE) return false; 283 284 // Look through ptr->int and ptr->ptr casts. 285 if (CE->getOpcode() == Instruction::PtrToInt || 286 CE->getOpcode() == Instruction::BitCast) 287 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL); 288 289 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5) 290 auto *GEP = dyn_cast<GEPOperator>(CE); 291 if (!GEP) 292 return false; 293 294 unsigned BitWidth = DL.getPointerTypeSizeInBits(GEP->getType()); 295 APInt TmpOffset(BitWidth, 0); 296 297 // If the base isn't a global+constant, we aren't either. 298 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL)) 299 return false; 300 301 // Otherwise, add any offset that our operands provide. 302 if (!GEP->accumulateConstantOffset(DL, TmpOffset)) 303 return false; 304 305 Offset = TmpOffset; 306 return true; 307 } 308 309 namespace { 310 311 /// Recursive helper to read bits out of global. C is the constant being copied 312 /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy 313 /// results into and BytesLeft is the number of bytes left in 314 /// the CurPtr buffer. DL is the DataLayout. 315 bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr, 316 unsigned BytesLeft, const DataLayout &DL) { 317 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) && 318 "Out of range access"); 319 320 // If this element is zero or undefined, we can just return since *CurPtr is 321 // zero initialized. 322 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) 323 return true; 324 325 if (auto *CI = dyn_cast<ConstantInt>(C)) { 326 if (CI->getBitWidth() > 64 || 327 (CI->getBitWidth() & 7) != 0) 328 return false; 329 330 uint64_t Val = CI->getZExtValue(); 331 unsigned IntBytes = unsigned(CI->getBitWidth()/8); 332 333 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) { 334 int n = ByteOffset; 335 if (!DL.isLittleEndian()) 336 n = IntBytes - n - 1; 337 CurPtr[i] = (unsigned char)(Val >> (n * 8)); 338 ++ByteOffset; 339 } 340 return true; 341 } 342 343 if (auto *CFP = dyn_cast<ConstantFP>(C)) { 344 if (CFP->getType()->isDoubleTy()) { 345 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL); 346 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL); 347 } 348 if (CFP->getType()->isFloatTy()){ 349 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL); 350 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL); 351 } 352 if (CFP->getType()->isHalfTy()){ 353 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL); 354 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL); 355 } 356 return false; 357 } 358 359 if (auto *CS = dyn_cast<ConstantStruct>(C)) { 360 const StructLayout *SL = DL.getStructLayout(CS->getType()); 361 unsigned Index = SL->getElementContainingOffset(ByteOffset); 362 uint64_t CurEltOffset = SL->getElementOffset(Index); 363 ByteOffset -= CurEltOffset; 364 365 while (true) { 366 // If the element access is to the element itself and not to tail padding, 367 // read the bytes from the element. 368 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType()); 369 370 if (ByteOffset < EltSize && 371 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr, 372 BytesLeft, DL)) 373 return false; 374 375 ++Index; 376 377 // Check to see if we read from the last struct element, if so we're done. 378 if (Index == CS->getType()->getNumElements()) 379 return true; 380 381 // If we read all of the bytes we needed from this element we're done. 382 uint64_t NextEltOffset = SL->getElementOffset(Index); 383 384 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset) 385 return true; 386 387 // Move to the next element of the struct. 388 CurPtr += NextEltOffset - CurEltOffset - ByteOffset; 389 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset; 390 ByteOffset = 0; 391 CurEltOffset = NextEltOffset; 392 } 393 // not reached. 394 } 395 396 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) || 397 isa<ConstantDataSequential>(C)) { 398 Type *EltTy = C->getType()->getSequentialElementType(); 399 uint64_t EltSize = DL.getTypeAllocSize(EltTy); 400 uint64_t Index = ByteOffset / EltSize; 401 uint64_t Offset = ByteOffset - Index * EltSize; 402 uint64_t NumElts; 403 if (auto *AT = dyn_cast<ArrayType>(C->getType())) 404 NumElts = AT->getNumElements(); 405 else 406 NumElts = C->getType()->getVectorNumElements(); 407 408 for (; Index != NumElts; ++Index) { 409 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr, 410 BytesLeft, DL)) 411 return false; 412 413 uint64_t BytesWritten = EltSize - Offset; 414 assert(BytesWritten <= EltSize && "Not indexing into this element?"); 415 if (BytesWritten >= BytesLeft) 416 return true; 417 418 Offset = 0; 419 BytesLeft -= BytesWritten; 420 CurPtr += BytesWritten; 421 } 422 return true; 423 } 424 425 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 426 if (CE->getOpcode() == Instruction::IntToPtr && 427 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) { 428 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr, 429 BytesLeft, DL); 430 } 431 } 432 433 // Otherwise, unknown initializer type. 434 return false; 435 } 436 437 Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy, 438 const DataLayout &DL) { 439 auto *PTy = cast<PointerType>(C->getType()); 440 auto *IntType = dyn_cast<IntegerType>(LoadTy); 441 442 // If this isn't an integer load we can't fold it directly. 443 if (!IntType) { 444 unsigned AS = PTy->getAddressSpace(); 445 446 // If this is a float/double load, we can try folding it as an int32/64 load 447 // and then bitcast the result. This can be useful for union cases. Note 448 // that address spaces don't matter here since we're not going to result in 449 // an actual new load. 450 Type *MapTy; 451 if (LoadTy->isHalfTy()) 452 MapTy = Type::getInt16Ty(C->getContext()); 453 else if (LoadTy->isFloatTy()) 454 MapTy = Type::getInt32Ty(C->getContext()); 455 else if (LoadTy->isDoubleTy()) 456 MapTy = Type::getInt64Ty(C->getContext()); 457 else if (LoadTy->isVectorTy()) { 458 MapTy = PointerType::getIntNTy(C->getContext(), 459 DL.getTypeAllocSizeInBits(LoadTy)); 460 } else 461 return nullptr; 462 463 C = FoldBitCast(C, MapTy->getPointerTo(AS), DL); 464 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL)) 465 return FoldBitCast(Res, LoadTy, DL); 466 return nullptr; 467 } 468 469 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8; 470 if (BytesLoaded > 32 || BytesLoaded == 0) 471 return nullptr; 472 473 GlobalValue *GVal; 474 APInt OffsetAI; 475 if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL)) 476 return nullptr; 477 478 auto *GV = dyn_cast<GlobalVariable>(GVal); 479 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 480 !GV->getInitializer()->getType()->isSized()) 481 return nullptr; 482 483 int64_t Offset = OffsetAI.getSExtValue(); 484 int64_t InitializerSize = DL.getTypeAllocSize(GV->getInitializer()->getType()); 485 486 // If we're not accessing anything in this constant, the result is undefined. 487 if (Offset + BytesLoaded <= 0) 488 return UndefValue::get(IntType); 489 490 // If we're not accessing anything in this constant, the result is undefined. 491 if (Offset >= InitializerSize) 492 return UndefValue::get(IntType); 493 494 unsigned char RawBytes[32] = {0}; 495 unsigned char *CurPtr = RawBytes; 496 unsigned BytesLeft = BytesLoaded; 497 498 // If we're loading off the beginning of the global, some bytes may be valid. 499 if (Offset < 0) { 500 CurPtr += -Offset; 501 BytesLeft += Offset; 502 Offset = 0; 503 } 504 505 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL)) 506 return nullptr; 507 508 APInt ResultVal = APInt(IntType->getBitWidth(), 0); 509 if (DL.isLittleEndian()) { 510 ResultVal = RawBytes[BytesLoaded - 1]; 511 for (unsigned i = 1; i != BytesLoaded; ++i) { 512 ResultVal <<= 8; 513 ResultVal |= RawBytes[BytesLoaded - 1 - i]; 514 } 515 } else { 516 ResultVal = RawBytes[0]; 517 for (unsigned i = 1; i != BytesLoaded; ++i) { 518 ResultVal <<= 8; 519 ResultVal |= RawBytes[i]; 520 } 521 } 522 523 return ConstantInt::get(IntType->getContext(), ResultVal); 524 } 525 526 Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE, Type *DestTy, 527 const DataLayout &DL) { 528 auto *SrcPtr = CE->getOperand(0); 529 auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType()); 530 if (!SrcPtrTy) 531 return nullptr; 532 Type *SrcTy = SrcPtrTy->getPointerElementType(); 533 534 Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL); 535 if (!C) 536 return nullptr; 537 538 do { 539 Type *SrcTy = C->getType(); 540 541 // If the type sizes are the same and a cast is legal, just directly 542 // cast the constant. 543 if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) { 544 Instruction::CastOps Cast = Instruction::BitCast; 545 // If we are going from a pointer to int or vice versa, we spell the cast 546 // differently. 547 if (SrcTy->isIntegerTy() && DestTy->isPointerTy()) 548 Cast = Instruction::IntToPtr; 549 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy()) 550 Cast = Instruction::PtrToInt; 551 552 if (CastInst::castIsValid(Cast, C, DestTy)) 553 return ConstantExpr::getCast(Cast, C, DestTy); 554 } 555 556 // If this isn't an aggregate type, there is nothing we can do to drill down 557 // and find a bitcastable constant. 558 if (!SrcTy->isAggregateType()) 559 return nullptr; 560 561 // We're simulating a load through a pointer that was bitcast to point to 562 // a different type, so we can try to walk down through the initial 563 // elements of an aggregate to see if some part of th e aggregate is 564 // castable to implement the "load" semantic model. 565 C = C->getAggregateElement(0u); 566 } while (C); 567 568 return nullptr; 569 } 570 571 } // end anonymous namespace 572 573 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, 574 const DataLayout &DL) { 575 // First, try the easy cases: 576 if (auto *GV = dyn_cast<GlobalVariable>(C)) 577 if (GV->isConstant() && GV->hasDefinitiveInitializer()) 578 return GV->getInitializer(); 579 580 if (auto *GA = dyn_cast<GlobalAlias>(C)) 581 if (GA->getAliasee() && !GA->isInterposable()) 582 return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL); 583 584 // If the loaded value isn't a constant expr, we can't handle it. 585 auto *CE = dyn_cast<ConstantExpr>(C); 586 if (!CE) 587 return nullptr; 588 589 if (CE->getOpcode() == Instruction::GetElementPtr) { 590 if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) { 591 if (GV->isConstant() && GV->hasDefinitiveInitializer()) { 592 if (Constant *V = 593 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) 594 return V; 595 } 596 } 597 } 598 599 if (CE->getOpcode() == Instruction::BitCast) 600 if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, Ty, DL)) 601 return LoadedC; 602 603 // Instead of loading constant c string, use corresponding integer value 604 // directly if string length is small enough. 605 StringRef Str; 606 if (getConstantStringInfo(CE, Str) && !Str.empty()) { 607 size_t StrLen = Str.size(); 608 unsigned NumBits = Ty->getPrimitiveSizeInBits(); 609 // Replace load with immediate integer if the result is an integer or fp 610 // value. 611 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 && 612 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) { 613 APInt StrVal(NumBits, 0); 614 APInt SingleChar(NumBits, 0); 615 if (DL.isLittleEndian()) { 616 for (unsigned char C : reverse(Str.bytes())) { 617 SingleChar = static_cast<uint64_t>(C); 618 StrVal = (StrVal << 8) | SingleChar; 619 } 620 } else { 621 for (unsigned char C : Str.bytes()) { 622 SingleChar = static_cast<uint64_t>(C); 623 StrVal = (StrVal << 8) | SingleChar; 624 } 625 // Append NULL at the end. 626 SingleChar = 0; 627 StrVal = (StrVal << 8) | SingleChar; 628 } 629 630 Constant *Res = ConstantInt::get(CE->getContext(), StrVal); 631 if (Ty->isFloatingPointTy()) 632 Res = ConstantExpr::getBitCast(Res, Ty); 633 return Res; 634 } 635 } 636 637 // If this load comes from anywhere in a constant global, and if the global 638 // is all undef or zero, we know what it loads. 639 if (auto *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) { 640 if (GV->isConstant() && GV->hasDefinitiveInitializer()) { 641 if (GV->getInitializer()->isNullValue()) 642 return Constant::getNullValue(Ty); 643 if (isa<UndefValue>(GV->getInitializer())) 644 return UndefValue::get(Ty); 645 } 646 } 647 648 // Try hard to fold loads from bitcasted strange and non-type-safe things. 649 return FoldReinterpretLoadFromConstPtr(CE, Ty, DL); 650 } 651 652 namespace { 653 654 Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) { 655 if (LI->isVolatile()) return nullptr; 656 657 if (auto *C = dyn_cast<Constant>(LI->getOperand(0))) 658 return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL); 659 660 return nullptr; 661 } 662 663 /// One of Op0/Op1 is a constant expression. 664 /// Attempt to symbolically evaluate the result of a binary operator merging 665 /// these together. If target data info is available, it is provided as DL, 666 /// otherwise DL is null. 667 Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1, 668 const DataLayout &DL) { 669 // SROA 670 671 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl. 672 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute 673 // bits. 674 675 if (Opc == Instruction::And) { 676 unsigned BitWidth = DL.getTypeSizeInBits(Op0->getType()->getScalarType()); 677 APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0); 678 APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0); 679 computeKnownBits(Op0, KnownZero0, KnownOne0, DL); 680 computeKnownBits(Op1, KnownZero1, KnownOne1, DL); 681 if ((KnownOne1 | KnownZero0).isAllOnesValue()) { 682 // All the bits of Op0 that the 'and' could be masking are already zero. 683 return Op0; 684 } 685 if ((KnownOne0 | KnownZero1).isAllOnesValue()) { 686 // All the bits of Op1 that the 'and' could be masking are already zero. 687 return Op1; 688 } 689 690 APInt KnownZero = KnownZero0 | KnownZero1; 691 APInt KnownOne = KnownOne0 & KnownOne1; 692 if ((KnownZero | KnownOne).isAllOnesValue()) { 693 return ConstantInt::get(Op0->getType(), KnownOne); 694 } 695 } 696 697 // If the constant expr is something like &A[123] - &A[4].f, fold this into a 698 // constant. This happens frequently when iterating over a global array. 699 if (Opc == Instruction::Sub) { 700 GlobalValue *GV1, *GV2; 701 APInt Offs1, Offs2; 702 703 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL)) 704 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) { 705 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType()); 706 707 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow. 708 // PtrToInt may change the bitwidth so we have convert to the right size 709 // first. 710 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) - 711 Offs2.zextOrTrunc(OpSize)); 712 } 713 } 714 715 return nullptr; 716 } 717 718 /// If array indices are not pointer-sized integers, explicitly cast them so 719 /// that they aren't implicitly casted by the getelementptr. 720 Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops, 721 Type *ResultTy, Optional<unsigned> InRangeIndex, 722 const DataLayout &DL, const TargetLibraryInfo *TLI) { 723 Type *IntPtrTy = DL.getIntPtrType(ResultTy); 724 725 bool Any = false; 726 SmallVector<Constant*, 32> NewIdxs; 727 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 728 if ((i == 1 || 729 !isa<StructType>(GetElementPtrInst::getIndexedType(SrcElemTy, 730 Ops.slice(1, i - 1)))) && 731 Ops[i]->getType() != IntPtrTy) { 732 Any = true; 733 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i], 734 true, 735 IntPtrTy, 736 true), 737 Ops[i], IntPtrTy)); 738 } else 739 NewIdxs.push_back(Ops[i]); 740 } 741 742 if (!Any) 743 return nullptr; 744 745 Constant *C = ConstantExpr::getGetElementPtr( 746 SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex); 747 if (Constant *Folded = ConstantFoldConstant(C, DL, TLI)) 748 C = Folded; 749 750 return C; 751 } 752 753 /// Strip the pointer casts, but preserve the address space information. 754 Constant* StripPtrCastKeepAS(Constant* Ptr, Type *&ElemTy) { 755 assert(Ptr->getType()->isPointerTy() && "Not a pointer type"); 756 auto *OldPtrTy = cast<PointerType>(Ptr->getType()); 757 Ptr = Ptr->stripPointerCasts(); 758 auto *NewPtrTy = cast<PointerType>(Ptr->getType()); 759 760 ElemTy = NewPtrTy->getPointerElementType(); 761 762 // Preserve the address space number of the pointer. 763 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) { 764 NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace()); 765 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy); 766 } 767 return Ptr; 768 } 769 770 /// If we can symbolically evaluate the GEP constant expression, do so. 771 Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP, 772 ArrayRef<Constant *> Ops, 773 const DataLayout &DL, 774 const TargetLibraryInfo *TLI) { 775 const GEPOperator *InnermostGEP = GEP; 776 777 Type *SrcElemTy = GEP->getSourceElementType(); 778 Type *ResElemTy = GEP->getResultElementType(); 779 Type *ResTy = GEP->getType(); 780 if (!SrcElemTy->isSized()) 781 return nullptr; 782 783 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy, 784 GEP->getInRangeIndex(), DL, TLI)) 785 return C; 786 787 Constant *Ptr = Ops[0]; 788 if (!Ptr->getType()->isPointerTy()) 789 return nullptr; 790 791 Type *IntPtrTy = DL.getIntPtrType(Ptr->getType()); 792 793 // If this is a constant expr gep that is effectively computing an 794 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12' 795 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 796 if (!isa<ConstantInt>(Ops[i])) { 797 798 // If this is "gep i8* Ptr, (sub 0, V)", fold this as: 799 // "inttoptr (sub (ptrtoint Ptr), V)" 800 if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) { 801 auto *CE = dyn_cast<ConstantExpr>(Ops[1]); 802 assert((!CE || CE->getType() == IntPtrTy) && 803 "CastGEPIndices didn't canonicalize index types!"); 804 if (CE && CE->getOpcode() == Instruction::Sub && 805 CE->getOperand(0)->isNullValue()) { 806 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType()); 807 Res = ConstantExpr::getSub(Res, CE->getOperand(1)); 808 Res = ConstantExpr::getIntToPtr(Res, ResTy); 809 if (auto *FoldedRes = ConstantFoldConstant(Res, DL, TLI)) 810 Res = FoldedRes; 811 return Res; 812 } 813 } 814 return nullptr; 815 } 816 817 unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy); 818 APInt Offset = 819 APInt(BitWidth, 820 DL.getIndexedOffsetInType( 821 SrcElemTy, 822 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1))); 823 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy); 824 825 // If this is a GEP of a GEP, fold it all into a single GEP. 826 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) { 827 InnermostGEP = GEP; 828 829 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end()); 830 831 // Do not try the incorporate the sub-GEP if some index is not a number. 832 bool AllConstantInt = true; 833 for (Value *NestedOp : NestedOps) 834 if (!isa<ConstantInt>(NestedOp)) { 835 AllConstantInt = false; 836 break; 837 } 838 if (!AllConstantInt) 839 break; 840 841 Ptr = cast<Constant>(GEP->getOperand(0)); 842 SrcElemTy = GEP->getSourceElementType(); 843 Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps)); 844 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy); 845 } 846 847 // If the base value for this address is a literal integer value, fold the 848 // getelementptr to the resulting integer value casted to the pointer type. 849 APInt BasePtr(BitWidth, 0); 850 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) { 851 if (CE->getOpcode() == Instruction::IntToPtr) { 852 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) 853 BasePtr = Base->getValue().zextOrTrunc(BitWidth); 854 } 855 } 856 857 auto *PTy = cast<PointerType>(Ptr->getType()); 858 if ((Ptr->isNullValue() || BasePtr != 0) && 859 !DL.isNonIntegralPointerType(PTy)) { 860 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr); 861 return ConstantExpr::getIntToPtr(C, ResTy); 862 } 863 864 // Otherwise form a regular getelementptr. Recompute the indices so that 865 // we eliminate over-indexing of the notional static type array bounds. 866 // This makes it easy to determine if the getelementptr is "inbounds". 867 // Also, this helps GlobalOpt do SROA on GlobalVariables. 868 Type *Ty = PTy; 869 SmallVector<Constant *, 32> NewIdxs; 870 871 do { 872 if (!Ty->isStructTy()) { 873 if (Ty->isPointerTy()) { 874 // The only pointer indexing we'll do is on the first index of the GEP. 875 if (!NewIdxs.empty()) 876 break; 877 878 Ty = SrcElemTy; 879 880 // Only handle pointers to sized types, not pointers to functions. 881 if (!Ty->isSized()) 882 return nullptr; 883 } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) { 884 Ty = ATy->getElementType(); 885 } else { 886 // We've reached some non-indexable type. 887 break; 888 } 889 890 // Determine which element of the array the offset points into. 891 APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty)); 892 if (ElemSize == 0) { 893 // The element size is 0. This may be [0 x Ty]*, so just use a zero 894 // index for this level and proceed to the next level to see if it can 895 // accommodate the offset. 896 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0)); 897 } else { 898 // The element size is non-zero divide the offset by the element 899 // size (rounding down), to compute the index at this level. 900 bool Overflow; 901 APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow); 902 if (Overflow) 903 break; 904 Offset -= NewIdx * ElemSize; 905 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx)); 906 } 907 } else { 908 auto *STy = cast<StructType>(Ty); 909 // If we end up with an offset that isn't valid for this struct type, we 910 // can't re-form this GEP in a regular form, so bail out. The pointer 911 // operand likely went through casts that are necessary to make the GEP 912 // sensible. 913 const StructLayout &SL = *DL.getStructLayout(STy); 914 if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes())) 915 break; 916 917 // Determine which field of the struct the offset points into. The 918 // getZExtValue is fine as we've already ensured that the offset is 919 // within the range representable by the StructLayout API. 920 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue()); 921 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 922 ElIdx)); 923 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx)); 924 Ty = STy->getTypeAtIndex(ElIdx); 925 } 926 } while (Ty != ResElemTy); 927 928 // If we haven't used up the entire offset by descending the static 929 // type, then the offset is pointing into the middle of an indivisible 930 // member, so we can't simplify it. 931 if (Offset != 0) 932 return nullptr; 933 934 // Preserve the inrange index from the innermost GEP if possible. We must 935 // have calculated the same indices up to and including the inrange index. 936 Optional<unsigned> InRangeIndex; 937 if (Optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex()) 938 if (SrcElemTy == InnermostGEP->getSourceElementType() && 939 NewIdxs.size() > *LastIRIndex) { 940 InRangeIndex = LastIRIndex; 941 for (unsigned I = 0; I <= *LastIRIndex; ++I) 942 if (NewIdxs[I] != InnermostGEP->getOperand(I + 1)) { 943 InRangeIndex = None; 944 break; 945 } 946 } 947 948 // Create a GEP. 949 Constant *C = ConstantExpr::getGetElementPtr( 950 SrcElemTy, Ptr, NewIdxs, /*InBounds=*/false, InRangeIndex); 951 assert(C->getType()->getPointerElementType() == Ty && 952 "Computed GetElementPtr has unexpected type!"); 953 954 // If we ended up indexing a member with a type that doesn't match 955 // the type of what the original indices indexed, add a cast. 956 if (Ty != ResElemTy) 957 C = FoldBitCast(C, ResTy, DL); 958 959 return C; 960 } 961 962 /// Attempt to constant fold an instruction with the 963 /// specified opcode and operands. If successful, the constant result is 964 /// returned, if not, null is returned. Note that this function can fail when 965 /// attempting to fold instructions like loads and stores, which have no 966 /// constant expression form. 967 /// 968 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/inrange 969 /// etc information, due to only being passed an opcode and operands. Constant 970 /// folding using this function strips this information. 971 /// 972 Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode, 973 ArrayRef<Constant *> Ops, 974 const DataLayout &DL, 975 const TargetLibraryInfo *TLI) { 976 Type *DestTy = InstOrCE->getType(); 977 978 // Handle easy binops first. 979 if (Instruction::isBinaryOp(Opcode)) 980 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL); 981 982 if (Instruction::isCast(Opcode)) 983 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL); 984 985 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) { 986 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI)) 987 return C; 988 989 return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), Ops[0], 990 Ops.slice(1), GEP->isInBounds(), 991 GEP->getInRangeIndex()); 992 } 993 994 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE)) 995 return CE->getWithOperands(Ops); 996 997 switch (Opcode) { 998 default: return nullptr; 999 case Instruction::ICmp: 1000 case Instruction::FCmp: llvm_unreachable("Invalid for compares"); 1001 case Instruction::Call: 1002 if (auto *F = dyn_cast<Function>(Ops.back())) 1003 if (canConstantFoldCallTo(F)) 1004 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI); 1005 return nullptr; 1006 case Instruction::Select: 1007 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]); 1008 case Instruction::ExtractElement: 1009 return ConstantExpr::getExtractElement(Ops[0], Ops[1]); 1010 case Instruction::InsertElement: 1011 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]); 1012 case Instruction::ShuffleVector: 1013 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]); 1014 } 1015 } 1016 1017 } // end anonymous namespace 1018 1019 //===----------------------------------------------------------------------===// 1020 // Constant Folding public APIs 1021 //===----------------------------------------------------------------------===// 1022 1023 namespace { 1024 1025 Constant * 1026 ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL, 1027 const TargetLibraryInfo *TLI, 1028 SmallDenseMap<Constant *, Constant *> &FoldedOps) { 1029 if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C)) 1030 return nullptr; 1031 1032 SmallVector<Constant *, 8> Ops; 1033 for (const Use &NewU : C->operands()) { 1034 auto *NewC = cast<Constant>(&NewU); 1035 // Recursively fold the ConstantExpr's operands. If we have already folded 1036 // a ConstantExpr, we don't have to process it again. 1037 if (isa<ConstantVector>(NewC) || isa<ConstantExpr>(NewC)) { 1038 auto It = FoldedOps.find(NewC); 1039 if (It == FoldedOps.end()) { 1040 if (auto *FoldedC = 1041 ConstantFoldConstantImpl(NewC, DL, TLI, FoldedOps)) { 1042 NewC = FoldedC; 1043 FoldedOps.insert({NewC, FoldedC}); 1044 } else { 1045 FoldedOps.insert({NewC, NewC}); 1046 } 1047 } else { 1048 NewC = It->second; 1049 } 1050 } 1051 Ops.push_back(NewC); 1052 } 1053 1054 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 1055 if (CE->isCompare()) 1056 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1], 1057 DL, TLI); 1058 1059 return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI); 1060 } 1061 1062 assert(isa<ConstantVector>(C)); 1063 return ConstantVector::get(Ops); 1064 } 1065 1066 } // end anonymous namespace 1067 1068 Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL, 1069 const TargetLibraryInfo *TLI) { 1070 // Handle PHI nodes quickly here... 1071 if (auto *PN = dyn_cast<PHINode>(I)) { 1072 Constant *CommonValue = nullptr; 1073 1074 SmallDenseMap<Constant *, Constant *> FoldedOps; 1075 for (Value *Incoming : PN->incoming_values()) { 1076 // If the incoming value is undef then skip it. Note that while we could 1077 // skip the value if it is equal to the phi node itself we choose not to 1078 // because that would break the rule that constant folding only applies if 1079 // all operands are constants. 1080 if (isa<UndefValue>(Incoming)) 1081 continue; 1082 // If the incoming value is not a constant, then give up. 1083 auto *C = dyn_cast<Constant>(Incoming); 1084 if (!C) 1085 return nullptr; 1086 // Fold the PHI's operands. 1087 if (auto *FoldedC = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps)) 1088 C = FoldedC; 1089 // If the incoming value is a different constant to 1090 // the one we saw previously, then give up. 1091 if (CommonValue && C != CommonValue) 1092 return nullptr; 1093 CommonValue = C; 1094 } 1095 1096 // If we reach here, all incoming values are the same constant or undef. 1097 return CommonValue ? CommonValue : UndefValue::get(PN->getType()); 1098 } 1099 1100 // Scan the operand list, checking to see if they are all constants, if so, 1101 // hand off to ConstantFoldInstOperandsImpl. 1102 if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); })) 1103 return nullptr; 1104 1105 SmallDenseMap<Constant *, Constant *> FoldedOps; 1106 SmallVector<Constant *, 8> Ops; 1107 for (const Use &OpU : I->operands()) { 1108 auto *Op = cast<Constant>(&OpU); 1109 // Fold the Instruction's operands. 1110 if (auto *FoldedOp = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps)) 1111 Op = FoldedOp; 1112 1113 Ops.push_back(Op); 1114 } 1115 1116 if (const auto *CI = dyn_cast<CmpInst>(I)) 1117 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1], 1118 DL, TLI); 1119 1120 if (const auto *LI = dyn_cast<LoadInst>(I)) 1121 return ConstantFoldLoadInst(LI, DL); 1122 1123 if (auto *IVI = dyn_cast<InsertValueInst>(I)) { 1124 return ConstantExpr::getInsertValue( 1125 cast<Constant>(IVI->getAggregateOperand()), 1126 cast<Constant>(IVI->getInsertedValueOperand()), 1127 IVI->getIndices()); 1128 } 1129 1130 if (auto *EVI = dyn_cast<ExtractValueInst>(I)) { 1131 return ConstantExpr::getExtractValue( 1132 cast<Constant>(EVI->getAggregateOperand()), 1133 EVI->getIndices()); 1134 } 1135 1136 return ConstantFoldInstOperands(I, Ops, DL, TLI); 1137 } 1138 1139 Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL, 1140 const TargetLibraryInfo *TLI) { 1141 SmallDenseMap<Constant *, Constant *> FoldedOps; 1142 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps); 1143 } 1144 1145 Constant *llvm::ConstantFoldInstOperands(Instruction *I, 1146 ArrayRef<Constant *> Ops, 1147 const DataLayout &DL, 1148 const TargetLibraryInfo *TLI) { 1149 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI); 1150 } 1151 1152 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate, 1153 Constant *Ops0, Constant *Ops1, 1154 const DataLayout &DL, 1155 const TargetLibraryInfo *TLI) { 1156 // fold: icmp (inttoptr x), null -> icmp x, 0 1157 // fold: icmp (ptrtoint x), 0 -> icmp x, null 1158 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y 1159 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y 1160 // 1161 // FIXME: The following comment is out of data and the DataLayout is here now. 1162 // ConstantExpr::getCompare cannot do this, because it doesn't have DL 1163 // around to know if bit truncation is happening. 1164 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) { 1165 if (Ops1->isNullValue()) { 1166 if (CE0->getOpcode() == Instruction::IntToPtr) { 1167 Type *IntPtrTy = DL.getIntPtrType(CE0->getType()); 1168 // Convert the integer value to the right size to ensure we get the 1169 // proper extension or truncation. 1170 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0), 1171 IntPtrTy, false); 1172 Constant *Null = Constant::getNullValue(C->getType()); 1173 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI); 1174 } 1175 1176 // Only do this transformation if the int is intptrty in size, otherwise 1177 // there is a truncation or extension that we aren't modeling. 1178 if (CE0->getOpcode() == Instruction::PtrToInt) { 1179 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType()); 1180 if (CE0->getType() == IntPtrTy) { 1181 Constant *C = CE0->getOperand(0); 1182 Constant *Null = Constant::getNullValue(C->getType()); 1183 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI); 1184 } 1185 } 1186 } 1187 1188 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) { 1189 if (CE0->getOpcode() == CE1->getOpcode()) { 1190 if (CE0->getOpcode() == Instruction::IntToPtr) { 1191 Type *IntPtrTy = DL.getIntPtrType(CE0->getType()); 1192 1193 // Convert the integer value to the right size to ensure we get the 1194 // proper extension or truncation. 1195 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0), 1196 IntPtrTy, false); 1197 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0), 1198 IntPtrTy, false); 1199 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI); 1200 } 1201 1202 // Only do this transformation if the int is intptrty in size, otherwise 1203 // there is a truncation or extension that we aren't modeling. 1204 if (CE0->getOpcode() == Instruction::PtrToInt) { 1205 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType()); 1206 if (CE0->getType() == IntPtrTy && 1207 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) { 1208 return ConstantFoldCompareInstOperands( 1209 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI); 1210 } 1211 } 1212 } 1213 } 1214 1215 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0) 1216 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0) 1217 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) && 1218 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) { 1219 Constant *LHS = ConstantFoldCompareInstOperands( 1220 Predicate, CE0->getOperand(0), Ops1, DL, TLI); 1221 Constant *RHS = ConstantFoldCompareInstOperands( 1222 Predicate, CE0->getOperand(1), Ops1, DL, TLI); 1223 unsigned OpC = 1224 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or; 1225 return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL); 1226 } 1227 } 1228 1229 return ConstantExpr::getCompare(Predicate, Ops0, Ops1); 1230 } 1231 1232 Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, 1233 Constant *RHS, 1234 const DataLayout &DL) { 1235 assert(Instruction::isBinaryOp(Opcode)); 1236 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS)) 1237 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL)) 1238 return C; 1239 1240 return ConstantExpr::get(Opcode, LHS, RHS); 1241 } 1242 1243 Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C, 1244 Type *DestTy, const DataLayout &DL) { 1245 assert(Instruction::isCast(Opcode)); 1246 switch (Opcode) { 1247 default: 1248 llvm_unreachable("Missing case"); 1249 case Instruction::PtrToInt: 1250 // If the input is a inttoptr, eliminate the pair. This requires knowing 1251 // the width of a pointer, so it can't be done in ConstantExpr::getCast. 1252 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 1253 if (CE->getOpcode() == Instruction::IntToPtr) { 1254 Constant *Input = CE->getOperand(0); 1255 unsigned InWidth = Input->getType()->getScalarSizeInBits(); 1256 unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType()); 1257 if (PtrWidth < InWidth) { 1258 Constant *Mask = 1259 ConstantInt::get(CE->getContext(), 1260 APInt::getLowBitsSet(InWidth, PtrWidth)); 1261 Input = ConstantExpr::getAnd(Input, Mask); 1262 } 1263 // Do a zext or trunc to get to the dest size. 1264 return ConstantExpr::getIntegerCast(Input, DestTy, false); 1265 } 1266 } 1267 return ConstantExpr::getCast(Opcode, C, DestTy); 1268 case Instruction::IntToPtr: 1269 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if 1270 // the int size is >= the ptr size and the address spaces are the same. 1271 // This requires knowing the width of a pointer, so it can't be done in 1272 // ConstantExpr::getCast. 1273 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 1274 if (CE->getOpcode() == Instruction::PtrToInt) { 1275 Constant *SrcPtr = CE->getOperand(0); 1276 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType()); 1277 unsigned MidIntSize = CE->getType()->getScalarSizeInBits(); 1278 1279 if (MidIntSize >= SrcPtrSize) { 1280 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace(); 1281 if (SrcAS == DestTy->getPointerAddressSpace()) 1282 return FoldBitCast(CE->getOperand(0), DestTy, DL); 1283 } 1284 } 1285 } 1286 1287 return ConstantExpr::getCast(Opcode, C, DestTy); 1288 case Instruction::Trunc: 1289 case Instruction::ZExt: 1290 case Instruction::SExt: 1291 case Instruction::FPTrunc: 1292 case Instruction::FPExt: 1293 case Instruction::UIToFP: 1294 case Instruction::SIToFP: 1295 case Instruction::FPToUI: 1296 case Instruction::FPToSI: 1297 case Instruction::AddrSpaceCast: 1298 return ConstantExpr::getCast(Opcode, C, DestTy); 1299 case Instruction::BitCast: 1300 return FoldBitCast(C, DestTy, DL); 1301 } 1302 } 1303 1304 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, 1305 ConstantExpr *CE) { 1306 if (!CE->getOperand(1)->isNullValue()) 1307 return nullptr; // Do not allow stepping over the value! 1308 1309 // Loop over all of the operands, tracking down which value we are 1310 // addressing. 1311 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) { 1312 C = C->getAggregateElement(CE->getOperand(i)); 1313 if (!C) 1314 return nullptr; 1315 } 1316 return C; 1317 } 1318 1319 Constant * 1320 llvm::ConstantFoldLoadThroughGEPIndices(Constant *C, 1321 ArrayRef<Constant *> Indices) { 1322 // Loop over all of the operands, tracking down which value we are 1323 // addressing. 1324 for (Constant *Index : Indices) { 1325 C = C->getAggregateElement(Index); 1326 if (!C) 1327 return nullptr; 1328 } 1329 return C; 1330 } 1331 1332 //===----------------------------------------------------------------------===// 1333 // Constant Folding for Calls 1334 // 1335 1336 bool llvm::canConstantFoldCallTo(const Function *F) { 1337 switch (F->getIntrinsicID()) { 1338 case Intrinsic::fabs: 1339 case Intrinsic::minnum: 1340 case Intrinsic::maxnum: 1341 case Intrinsic::log: 1342 case Intrinsic::log2: 1343 case Intrinsic::log10: 1344 case Intrinsic::exp: 1345 case Intrinsic::exp2: 1346 case Intrinsic::floor: 1347 case Intrinsic::ceil: 1348 case Intrinsic::sqrt: 1349 case Intrinsic::sin: 1350 case Intrinsic::cos: 1351 case Intrinsic::trunc: 1352 case Intrinsic::rint: 1353 case Intrinsic::nearbyint: 1354 case Intrinsic::pow: 1355 case Intrinsic::powi: 1356 case Intrinsic::bswap: 1357 case Intrinsic::ctpop: 1358 case Intrinsic::ctlz: 1359 case Intrinsic::cttz: 1360 case Intrinsic::fma: 1361 case Intrinsic::fmuladd: 1362 case Intrinsic::copysign: 1363 case Intrinsic::round: 1364 case Intrinsic::masked_load: 1365 case Intrinsic::sadd_with_overflow: 1366 case Intrinsic::uadd_with_overflow: 1367 case Intrinsic::ssub_with_overflow: 1368 case Intrinsic::usub_with_overflow: 1369 case Intrinsic::smul_with_overflow: 1370 case Intrinsic::umul_with_overflow: 1371 case Intrinsic::convert_from_fp16: 1372 case Intrinsic::convert_to_fp16: 1373 case Intrinsic::bitreverse: 1374 case Intrinsic::x86_sse_cvtss2si: 1375 case Intrinsic::x86_sse_cvtss2si64: 1376 case Intrinsic::x86_sse_cvttss2si: 1377 case Intrinsic::x86_sse_cvttss2si64: 1378 case Intrinsic::x86_sse2_cvtsd2si: 1379 case Intrinsic::x86_sse2_cvtsd2si64: 1380 case Intrinsic::x86_sse2_cvttsd2si: 1381 case Intrinsic::x86_sse2_cvttsd2si64: 1382 return true; 1383 default: 1384 return false; 1385 case 0: break; 1386 } 1387 1388 if (!F->hasName()) 1389 return false; 1390 StringRef Name = F->getName(); 1391 1392 // In these cases, the check of the length is required. We don't want to 1393 // return true for a name like "cos\0blah" which strcmp would return equal to 1394 // "cos", but has length 8. 1395 switch (Name[0]) { 1396 default: 1397 return false; 1398 case 'a': 1399 return Name == "acos" || Name == "asin" || Name == "atan" || 1400 Name == "atan2" || Name == "acosf" || Name == "asinf" || 1401 Name == "atanf" || Name == "atan2f"; 1402 case 'c': 1403 return Name == "ceil" || Name == "cos" || Name == "cosh" || 1404 Name == "ceilf" || Name == "cosf" || Name == "coshf"; 1405 case 'e': 1406 return Name == "exp" || Name == "exp2" || Name == "expf" || Name == "exp2f"; 1407 case 'f': 1408 return Name == "fabs" || Name == "floor" || Name == "fmod" || 1409 Name == "fabsf" || Name == "floorf" || Name == "fmodf"; 1410 case 'l': 1411 return Name == "log" || Name == "log10" || Name == "logf" || 1412 Name == "log10f"; 1413 case 'p': 1414 return Name == "pow" || Name == "powf"; 1415 case 's': 1416 return Name == "sin" || Name == "sinh" || Name == "sqrt" || 1417 Name == "sinf" || Name == "sinhf" || Name == "sqrtf"; 1418 case 't': 1419 return Name == "tan" || Name == "tanh" || Name == "tanf" || Name == "tanhf"; 1420 } 1421 } 1422 1423 namespace { 1424 1425 Constant *GetConstantFoldFPValue(double V, Type *Ty) { 1426 if (Ty->isHalfTy()) { 1427 APFloat APF(V); 1428 bool unused; 1429 APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused); 1430 return ConstantFP::get(Ty->getContext(), APF); 1431 } 1432 if (Ty->isFloatTy()) 1433 return ConstantFP::get(Ty->getContext(), APFloat((float)V)); 1434 if (Ty->isDoubleTy()) 1435 return ConstantFP::get(Ty->getContext(), APFloat(V)); 1436 llvm_unreachable("Can only constant fold half/float/double"); 1437 } 1438 1439 /// Clear the floating-point exception state. 1440 inline void llvm_fenv_clearexcept() { 1441 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT 1442 feclearexcept(FE_ALL_EXCEPT); 1443 #endif 1444 errno = 0; 1445 } 1446 1447 /// Test if a floating-point exception was raised. 1448 inline bool llvm_fenv_testexcept() { 1449 int errno_val = errno; 1450 if (errno_val == ERANGE || errno_val == EDOM) 1451 return true; 1452 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT 1453 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT)) 1454 return true; 1455 #endif 1456 return false; 1457 } 1458 1459 Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) { 1460 llvm_fenv_clearexcept(); 1461 V = NativeFP(V); 1462 if (llvm_fenv_testexcept()) { 1463 llvm_fenv_clearexcept(); 1464 return nullptr; 1465 } 1466 1467 return GetConstantFoldFPValue(V, Ty); 1468 } 1469 1470 Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V, 1471 double W, Type *Ty) { 1472 llvm_fenv_clearexcept(); 1473 V = NativeFP(V, W); 1474 if (llvm_fenv_testexcept()) { 1475 llvm_fenv_clearexcept(); 1476 return nullptr; 1477 } 1478 1479 return GetConstantFoldFPValue(V, Ty); 1480 } 1481 1482 /// Attempt to fold an SSE floating point to integer conversion of a constant 1483 /// floating point. If roundTowardZero is false, the default IEEE rounding is 1484 /// used (toward nearest, ties to even). This matches the behavior of the 1485 /// non-truncating SSE instructions in the default rounding mode. The desired 1486 /// integer type Ty is used to select how many bits are available for the 1487 /// result. Returns null if the conversion cannot be performed, otherwise 1488 /// returns the Constant value resulting from the conversion. 1489 Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero, 1490 Type *Ty) { 1491 // All of these conversion intrinsics form an integer of at most 64bits. 1492 unsigned ResultWidth = Ty->getIntegerBitWidth(); 1493 assert(ResultWidth <= 64 && 1494 "Can only constant fold conversions to 64 and 32 bit ints"); 1495 1496 uint64_t UIntVal; 1497 bool isExact = false; 1498 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero 1499 : APFloat::rmNearestTiesToEven; 1500 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth, 1501 /*isSigned=*/true, mode, 1502 &isExact); 1503 if (status != APFloat::opOK && 1504 (!roundTowardZero || status != APFloat::opInexact)) 1505 return nullptr; 1506 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true); 1507 } 1508 1509 double getValueAsDouble(ConstantFP *Op) { 1510 Type *Ty = Op->getType(); 1511 1512 if (Ty->isFloatTy()) 1513 return Op->getValueAPF().convertToFloat(); 1514 1515 if (Ty->isDoubleTy()) 1516 return Op->getValueAPF().convertToDouble(); 1517 1518 bool unused; 1519 APFloat APF = Op->getValueAPF(); 1520 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused); 1521 return APF.convertToDouble(); 1522 } 1523 1524 Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty, 1525 ArrayRef<Constant *> Operands, 1526 const TargetLibraryInfo *TLI) { 1527 if (Operands.size() == 1) { 1528 if (isa<UndefValue>(Operands[0])) { 1529 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN 1530 if (IntrinsicID == Intrinsic::cos) 1531 return Constant::getNullValue(Ty); 1532 } 1533 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) { 1534 if (IntrinsicID == Intrinsic::convert_to_fp16) { 1535 APFloat Val(Op->getValueAPF()); 1536 1537 bool lost = false; 1538 Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost); 1539 1540 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt()); 1541 } 1542 1543 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy()) 1544 return nullptr; 1545 1546 if (IntrinsicID == Intrinsic::round) { 1547 APFloat V = Op->getValueAPF(); 1548 V.roundToIntegral(APFloat::rmNearestTiesToAway); 1549 return ConstantFP::get(Ty->getContext(), V); 1550 } 1551 1552 if (IntrinsicID == Intrinsic::floor) { 1553 APFloat V = Op->getValueAPF(); 1554 V.roundToIntegral(APFloat::rmTowardNegative); 1555 return ConstantFP::get(Ty->getContext(), V); 1556 } 1557 1558 if (IntrinsicID == Intrinsic::ceil) { 1559 APFloat V = Op->getValueAPF(); 1560 V.roundToIntegral(APFloat::rmTowardPositive); 1561 return ConstantFP::get(Ty->getContext(), V); 1562 } 1563 1564 if (IntrinsicID == Intrinsic::trunc) { 1565 APFloat V = Op->getValueAPF(); 1566 V.roundToIntegral(APFloat::rmTowardZero); 1567 return ConstantFP::get(Ty->getContext(), V); 1568 } 1569 1570 if (IntrinsicID == Intrinsic::rint) { 1571 APFloat V = Op->getValueAPF(); 1572 V.roundToIntegral(APFloat::rmNearestTiesToEven); 1573 return ConstantFP::get(Ty->getContext(), V); 1574 } 1575 1576 if (IntrinsicID == Intrinsic::nearbyint) { 1577 APFloat V = Op->getValueAPF(); 1578 V.roundToIntegral(APFloat::rmNearestTiesToEven); 1579 return ConstantFP::get(Ty->getContext(), V); 1580 } 1581 1582 /// We only fold functions with finite arguments. Folding NaN and inf is 1583 /// likely to be aborted with an exception anyway, and some host libms 1584 /// have known errors raising exceptions. 1585 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity()) 1586 return nullptr; 1587 1588 /// Currently APFloat versions of these functions do not exist, so we use 1589 /// the host native double versions. Float versions are not called 1590 /// directly but for all these it is true (float)(f((double)arg)) == 1591 /// f(arg). Long double not supported yet. 1592 double V = getValueAsDouble(Op); 1593 1594 switch (IntrinsicID) { 1595 default: break; 1596 case Intrinsic::fabs: 1597 return ConstantFoldFP(fabs, V, Ty); 1598 case Intrinsic::log2: 1599 return ConstantFoldFP(Log2, V, Ty); 1600 case Intrinsic::log: 1601 return ConstantFoldFP(log, V, Ty); 1602 case Intrinsic::log10: 1603 return ConstantFoldFP(log10, V, Ty); 1604 case Intrinsic::exp: 1605 return ConstantFoldFP(exp, V, Ty); 1606 case Intrinsic::exp2: 1607 return ConstantFoldFP(exp2, V, Ty); 1608 case Intrinsic::sin: 1609 return ConstantFoldFP(sin, V, Ty); 1610 case Intrinsic::cos: 1611 return ConstantFoldFP(cos, V, Ty); 1612 } 1613 1614 if (!TLI) 1615 return nullptr; 1616 1617 switch (Name[0]) { 1618 case 'a': 1619 if ((Name == "acos" && TLI->has(LibFunc::acos)) || 1620 (Name == "acosf" && TLI->has(LibFunc::acosf))) 1621 return ConstantFoldFP(acos, V, Ty); 1622 else if ((Name == "asin" && TLI->has(LibFunc::asin)) || 1623 (Name == "asinf" && TLI->has(LibFunc::asinf))) 1624 return ConstantFoldFP(asin, V, Ty); 1625 else if ((Name == "atan" && TLI->has(LibFunc::atan)) || 1626 (Name == "atanf" && TLI->has(LibFunc::atanf))) 1627 return ConstantFoldFP(atan, V, Ty); 1628 break; 1629 case 'c': 1630 if ((Name == "ceil" && TLI->has(LibFunc::ceil)) || 1631 (Name == "ceilf" && TLI->has(LibFunc::ceilf))) 1632 return ConstantFoldFP(ceil, V, Ty); 1633 else if ((Name == "cos" && TLI->has(LibFunc::cos)) || 1634 (Name == "cosf" && TLI->has(LibFunc::cosf))) 1635 return ConstantFoldFP(cos, V, Ty); 1636 else if ((Name == "cosh" && TLI->has(LibFunc::cosh)) || 1637 (Name == "coshf" && TLI->has(LibFunc::coshf))) 1638 return ConstantFoldFP(cosh, V, Ty); 1639 break; 1640 case 'e': 1641 if ((Name == "exp" && TLI->has(LibFunc::exp)) || 1642 (Name == "expf" && TLI->has(LibFunc::expf))) 1643 return ConstantFoldFP(exp, V, Ty); 1644 if ((Name == "exp2" && TLI->has(LibFunc::exp2)) || 1645 (Name == "exp2f" && TLI->has(LibFunc::exp2f))) 1646 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a 1647 // C99 library. 1648 return ConstantFoldBinaryFP(pow, 2.0, V, Ty); 1649 break; 1650 case 'f': 1651 if ((Name == "fabs" && TLI->has(LibFunc::fabs)) || 1652 (Name == "fabsf" && TLI->has(LibFunc::fabsf))) 1653 return ConstantFoldFP(fabs, V, Ty); 1654 else if ((Name == "floor" && TLI->has(LibFunc::floor)) || 1655 (Name == "floorf" && TLI->has(LibFunc::floorf))) 1656 return ConstantFoldFP(floor, V, Ty); 1657 break; 1658 case 'l': 1659 if ((Name == "log" && V > 0 && TLI->has(LibFunc::log)) || 1660 (Name == "logf" && V > 0 && TLI->has(LibFunc::logf))) 1661 return ConstantFoldFP(log, V, Ty); 1662 else if ((Name == "log10" && V > 0 && TLI->has(LibFunc::log10)) || 1663 (Name == "log10f" && V > 0 && TLI->has(LibFunc::log10f))) 1664 return ConstantFoldFP(log10, V, Ty); 1665 else if (IntrinsicID == Intrinsic::sqrt && 1666 (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) { 1667 if (V >= -0.0) 1668 return ConstantFoldFP(sqrt, V, Ty); 1669 else { 1670 // Unlike the sqrt definitions in C/C++, POSIX, and IEEE-754 - which 1671 // all guarantee or favor returning NaN - the square root of a 1672 // negative number is not defined for the LLVM sqrt intrinsic. 1673 // This is because the intrinsic should only be emitted in place of 1674 // libm's sqrt function when using "no-nans-fp-math". 1675 return UndefValue::get(Ty); 1676 } 1677 } 1678 break; 1679 case 's': 1680 if ((Name == "sin" && TLI->has(LibFunc::sin)) || 1681 (Name == "sinf" && TLI->has(LibFunc::sinf))) 1682 return ConstantFoldFP(sin, V, Ty); 1683 else if ((Name == "sinh" && TLI->has(LibFunc::sinh)) || 1684 (Name == "sinhf" && TLI->has(LibFunc::sinhf))) 1685 return ConstantFoldFP(sinh, V, Ty); 1686 else if ((Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt)) || 1687 (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))) 1688 return ConstantFoldFP(sqrt, V, Ty); 1689 break; 1690 case 't': 1691 if ((Name == "tan" && TLI->has(LibFunc::tan)) || 1692 (Name == "tanf" && TLI->has(LibFunc::tanf))) 1693 return ConstantFoldFP(tan, V, Ty); 1694 else if ((Name == "tanh" && TLI->has(LibFunc::tanh)) || 1695 (Name == "tanhf" && TLI->has(LibFunc::tanhf))) 1696 return ConstantFoldFP(tanh, V, Ty); 1697 break; 1698 default: 1699 break; 1700 } 1701 return nullptr; 1702 } 1703 1704 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) { 1705 switch (IntrinsicID) { 1706 case Intrinsic::bswap: 1707 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap()); 1708 case Intrinsic::ctpop: 1709 return ConstantInt::get(Ty, Op->getValue().countPopulation()); 1710 case Intrinsic::bitreverse: 1711 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits()); 1712 case Intrinsic::convert_from_fp16: { 1713 APFloat Val(APFloat::IEEEhalf, Op->getValue()); 1714 1715 bool lost = false; 1716 APFloat::opStatus status = Val.convert( 1717 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost); 1718 1719 // Conversion is always precise. 1720 (void)status; 1721 assert(status == APFloat::opOK && !lost && 1722 "Precision lost during fp16 constfolding"); 1723 1724 return ConstantFP::get(Ty->getContext(), Val); 1725 } 1726 default: 1727 return nullptr; 1728 } 1729 } 1730 1731 // Support ConstantVector in case we have an Undef in the top. 1732 if (isa<ConstantVector>(Operands[0]) || 1733 isa<ConstantDataVector>(Operands[0])) { 1734 auto *Op = cast<Constant>(Operands[0]); 1735 switch (IntrinsicID) { 1736 default: break; 1737 case Intrinsic::x86_sse_cvtss2si: 1738 case Intrinsic::x86_sse_cvtss2si64: 1739 case Intrinsic::x86_sse2_cvtsd2si: 1740 case Intrinsic::x86_sse2_cvtsd2si64: 1741 if (ConstantFP *FPOp = 1742 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) 1743 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), 1744 /*roundTowardZero=*/false, Ty); 1745 case Intrinsic::x86_sse_cvttss2si: 1746 case Intrinsic::x86_sse_cvttss2si64: 1747 case Intrinsic::x86_sse2_cvttsd2si: 1748 case Intrinsic::x86_sse2_cvttsd2si64: 1749 if (ConstantFP *FPOp = 1750 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) 1751 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), 1752 /*roundTowardZero=*/true, Ty); 1753 } 1754 } 1755 1756 if (isa<UndefValue>(Operands[0])) { 1757 if (IntrinsicID == Intrinsic::bswap) 1758 return Operands[0]; 1759 return nullptr; 1760 } 1761 1762 return nullptr; 1763 } 1764 1765 if (Operands.size() == 2) { 1766 if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) { 1767 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy()) 1768 return nullptr; 1769 double Op1V = getValueAsDouble(Op1); 1770 1771 if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) { 1772 if (Op2->getType() != Op1->getType()) 1773 return nullptr; 1774 1775 double Op2V = getValueAsDouble(Op2); 1776 if (IntrinsicID == Intrinsic::pow) { 1777 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty); 1778 } 1779 if (IntrinsicID == Intrinsic::copysign) { 1780 APFloat V1 = Op1->getValueAPF(); 1781 const APFloat &V2 = Op2->getValueAPF(); 1782 V1.copySign(V2); 1783 return ConstantFP::get(Ty->getContext(), V1); 1784 } 1785 1786 if (IntrinsicID == Intrinsic::minnum) { 1787 const APFloat &C1 = Op1->getValueAPF(); 1788 const APFloat &C2 = Op2->getValueAPF(); 1789 return ConstantFP::get(Ty->getContext(), minnum(C1, C2)); 1790 } 1791 1792 if (IntrinsicID == Intrinsic::maxnum) { 1793 const APFloat &C1 = Op1->getValueAPF(); 1794 const APFloat &C2 = Op2->getValueAPF(); 1795 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2)); 1796 } 1797 1798 if (!TLI) 1799 return nullptr; 1800 if ((Name == "pow" && TLI->has(LibFunc::pow)) || 1801 (Name == "powf" && TLI->has(LibFunc::powf))) 1802 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty); 1803 if ((Name == "fmod" && TLI->has(LibFunc::fmod)) || 1804 (Name == "fmodf" && TLI->has(LibFunc::fmodf))) 1805 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty); 1806 if ((Name == "atan2" && TLI->has(LibFunc::atan2)) || 1807 (Name == "atan2f" && TLI->has(LibFunc::atan2f))) 1808 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty); 1809 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) { 1810 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy()) 1811 return ConstantFP::get(Ty->getContext(), 1812 APFloat((float)std::pow((float)Op1V, 1813 (int)Op2C->getZExtValue()))); 1814 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy()) 1815 return ConstantFP::get(Ty->getContext(), 1816 APFloat((float)std::pow((float)Op1V, 1817 (int)Op2C->getZExtValue()))); 1818 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy()) 1819 return ConstantFP::get(Ty->getContext(), 1820 APFloat((double)std::pow((double)Op1V, 1821 (int)Op2C->getZExtValue()))); 1822 } 1823 return nullptr; 1824 } 1825 1826 if (auto *Op1 = dyn_cast<ConstantInt>(Operands[0])) { 1827 if (auto *Op2 = dyn_cast<ConstantInt>(Operands[1])) { 1828 switch (IntrinsicID) { 1829 default: break; 1830 case Intrinsic::sadd_with_overflow: 1831 case Intrinsic::uadd_with_overflow: 1832 case Intrinsic::ssub_with_overflow: 1833 case Intrinsic::usub_with_overflow: 1834 case Intrinsic::smul_with_overflow: 1835 case Intrinsic::umul_with_overflow: { 1836 APInt Res; 1837 bool Overflow; 1838 switch (IntrinsicID) { 1839 default: llvm_unreachable("Invalid case"); 1840 case Intrinsic::sadd_with_overflow: 1841 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow); 1842 break; 1843 case Intrinsic::uadd_with_overflow: 1844 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow); 1845 break; 1846 case Intrinsic::ssub_with_overflow: 1847 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow); 1848 break; 1849 case Intrinsic::usub_with_overflow: 1850 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow); 1851 break; 1852 case Intrinsic::smul_with_overflow: 1853 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow); 1854 break; 1855 case Intrinsic::umul_with_overflow: 1856 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow); 1857 break; 1858 } 1859 Constant *Ops[] = { 1860 ConstantInt::get(Ty->getContext(), Res), 1861 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow) 1862 }; 1863 return ConstantStruct::get(cast<StructType>(Ty), Ops); 1864 } 1865 case Intrinsic::cttz: 1866 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef. 1867 return UndefValue::get(Ty); 1868 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros()); 1869 case Intrinsic::ctlz: 1870 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef. 1871 return UndefValue::get(Ty); 1872 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros()); 1873 } 1874 } 1875 1876 return nullptr; 1877 } 1878 return nullptr; 1879 } 1880 1881 if (Operands.size() != 3) 1882 return nullptr; 1883 1884 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) { 1885 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) { 1886 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) { 1887 switch (IntrinsicID) { 1888 default: break; 1889 case Intrinsic::fma: 1890 case Intrinsic::fmuladd: { 1891 APFloat V = Op1->getValueAPF(); 1892 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(), 1893 Op3->getValueAPF(), 1894 APFloat::rmNearestTiesToEven); 1895 if (s != APFloat::opInvalidOp) 1896 return ConstantFP::get(Ty->getContext(), V); 1897 1898 return nullptr; 1899 } 1900 } 1901 } 1902 } 1903 } 1904 1905 return nullptr; 1906 } 1907 1908 Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID, 1909 VectorType *VTy, ArrayRef<Constant *> Operands, 1910 const DataLayout &DL, 1911 const TargetLibraryInfo *TLI) { 1912 SmallVector<Constant *, 4> Result(VTy->getNumElements()); 1913 SmallVector<Constant *, 4> Lane(Operands.size()); 1914 Type *Ty = VTy->getElementType(); 1915 1916 if (IntrinsicID == Intrinsic::masked_load) { 1917 auto *SrcPtr = Operands[0]; 1918 auto *Mask = Operands[2]; 1919 auto *Passthru = Operands[3]; 1920 1921 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, VTy, DL); 1922 1923 SmallVector<Constant *, 32> NewElements; 1924 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) { 1925 auto *MaskElt = Mask->getAggregateElement(I); 1926 if (!MaskElt) 1927 break; 1928 auto *PassthruElt = Passthru->getAggregateElement(I); 1929 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr; 1930 if (isa<UndefValue>(MaskElt)) { 1931 if (PassthruElt) 1932 NewElements.push_back(PassthruElt); 1933 else if (VecElt) 1934 NewElements.push_back(VecElt); 1935 else 1936 return nullptr; 1937 } 1938 if (MaskElt->isNullValue()) { 1939 if (!PassthruElt) 1940 return nullptr; 1941 NewElements.push_back(PassthruElt); 1942 } else if (MaskElt->isOneValue()) { 1943 if (!VecElt) 1944 return nullptr; 1945 NewElements.push_back(VecElt); 1946 } else { 1947 return nullptr; 1948 } 1949 } 1950 if (NewElements.size() != VTy->getNumElements()) 1951 return nullptr; 1952 return ConstantVector::get(NewElements); 1953 } 1954 1955 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) { 1956 // Gather a column of constants. 1957 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) { 1958 Constant *Agg = Operands[J]->getAggregateElement(I); 1959 if (!Agg) 1960 return nullptr; 1961 1962 Lane[J] = Agg; 1963 } 1964 1965 // Use the regular scalar folding to simplify this column. 1966 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI); 1967 if (!Folded) 1968 return nullptr; 1969 Result[I] = Folded; 1970 } 1971 1972 return ConstantVector::get(Result); 1973 } 1974 1975 } // end anonymous namespace 1976 1977 Constant * 1978 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands, 1979 const TargetLibraryInfo *TLI) { 1980 if (!F->hasName()) 1981 return nullptr; 1982 StringRef Name = F->getName(); 1983 1984 Type *Ty = F->getReturnType(); 1985 1986 if (auto *VTy = dyn_cast<VectorType>(Ty)) 1987 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, 1988 F->getParent()->getDataLayout(), TLI); 1989 1990 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI); 1991 } 1992 1993 bool llvm::isMathLibCallNoop(CallSite CS, const TargetLibraryInfo *TLI) { 1994 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap 1995 // (and to some extent ConstantFoldScalarCall). 1996 Function *F = CS.getCalledFunction(); 1997 if (!F) 1998 return false; 1999 2000 LibFunc::Func Func; 2001 if (!TLI || !TLI->getLibFunc(*F, Func)) 2002 return false; 2003 2004 if (CS.getNumArgOperands() == 1) { 2005 if (ConstantFP *OpC = dyn_cast<ConstantFP>(CS.getArgOperand(0))) { 2006 const APFloat &Op = OpC->getValueAPF(); 2007 switch (Func) { 2008 case LibFunc::logl: 2009 case LibFunc::log: 2010 case LibFunc::logf: 2011 case LibFunc::log2l: 2012 case LibFunc::log2: 2013 case LibFunc::log2f: 2014 case LibFunc::log10l: 2015 case LibFunc::log10: 2016 case LibFunc::log10f: 2017 return Op.isNaN() || (!Op.isZero() && !Op.isNegative()); 2018 2019 case LibFunc::expl: 2020 case LibFunc::exp: 2021 case LibFunc::expf: 2022 // FIXME: These boundaries are slightly conservative. 2023 if (OpC->getType()->isDoubleTy()) 2024 return Op.compare(APFloat(-745.0)) != APFloat::cmpLessThan && 2025 Op.compare(APFloat(709.0)) != APFloat::cmpGreaterThan; 2026 if (OpC->getType()->isFloatTy()) 2027 return Op.compare(APFloat(-103.0f)) != APFloat::cmpLessThan && 2028 Op.compare(APFloat(88.0f)) != APFloat::cmpGreaterThan; 2029 break; 2030 2031 case LibFunc::exp2l: 2032 case LibFunc::exp2: 2033 case LibFunc::exp2f: 2034 // FIXME: These boundaries are slightly conservative. 2035 if (OpC->getType()->isDoubleTy()) 2036 return Op.compare(APFloat(-1074.0)) != APFloat::cmpLessThan && 2037 Op.compare(APFloat(1023.0)) != APFloat::cmpGreaterThan; 2038 if (OpC->getType()->isFloatTy()) 2039 return Op.compare(APFloat(-149.0f)) != APFloat::cmpLessThan && 2040 Op.compare(APFloat(127.0f)) != APFloat::cmpGreaterThan; 2041 break; 2042 2043 case LibFunc::sinl: 2044 case LibFunc::sin: 2045 case LibFunc::sinf: 2046 case LibFunc::cosl: 2047 case LibFunc::cos: 2048 case LibFunc::cosf: 2049 return !Op.isInfinity(); 2050 2051 case LibFunc::tanl: 2052 case LibFunc::tan: 2053 case LibFunc::tanf: { 2054 // FIXME: Stop using the host math library. 2055 // FIXME: The computation isn't done in the right precision. 2056 Type *Ty = OpC->getType(); 2057 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) { 2058 double OpV = getValueAsDouble(OpC); 2059 return ConstantFoldFP(tan, OpV, Ty) != nullptr; 2060 } 2061 break; 2062 } 2063 2064 case LibFunc::asinl: 2065 case LibFunc::asin: 2066 case LibFunc::asinf: 2067 case LibFunc::acosl: 2068 case LibFunc::acos: 2069 case LibFunc::acosf: 2070 return Op.compare(APFloat(Op.getSemantics(), "-1")) != 2071 APFloat::cmpLessThan && 2072 Op.compare(APFloat(Op.getSemantics(), "1")) != 2073 APFloat::cmpGreaterThan; 2074 2075 case LibFunc::sinh: 2076 case LibFunc::cosh: 2077 case LibFunc::sinhf: 2078 case LibFunc::coshf: 2079 case LibFunc::sinhl: 2080 case LibFunc::coshl: 2081 // FIXME: These boundaries are slightly conservative. 2082 if (OpC->getType()->isDoubleTy()) 2083 return Op.compare(APFloat(-710.0)) != APFloat::cmpLessThan && 2084 Op.compare(APFloat(710.0)) != APFloat::cmpGreaterThan; 2085 if (OpC->getType()->isFloatTy()) 2086 return Op.compare(APFloat(-89.0f)) != APFloat::cmpLessThan && 2087 Op.compare(APFloat(89.0f)) != APFloat::cmpGreaterThan; 2088 break; 2089 2090 case LibFunc::sqrtl: 2091 case LibFunc::sqrt: 2092 case LibFunc::sqrtf: 2093 return Op.isNaN() || Op.isZero() || !Op.isNegative(); 2094 2095 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p, 2096 // maybe others? 2097 default: 2098 break; 2099 } 2100 } 2101 } 2102 2103 if (CS.getNumArgOperands() == 2) { 2104 ConstantFP *Op0C = dyn_cast<ConstantFP>(CS.getArgOperand(0)); 2105 ConstantFP *Op1C = dyn_cast<ConstantFP>(CS.getArgOperand(1)); 2106 if (Op0C && Op1C) { 2107 const APFloat &Op0 = Op0C->getValueAPF(); 2108 const APFloat &Op1 = Op1C->getValueAPF(); 2109 2110 switch (Func) { 2111 case LibFunc::powl: 2112 case LibFunc::pow: 2113 case LibFunc::powf: { 2114 // FIXME: Stop using the host math library. 2115 // FIXME: The computation isn't done in the right precision. 2116 Type *Ty = Op0C->getType(); 2117 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) { 2118 if (Ty == Op1C->getType()) { 2119 double Op0V = getValueAsDouble(Op0C); 2120 double Op1V = getValueAsDouble(Op1C); 2121 return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr; 2122 } 2123 } 2124 break; 2125 } 2126 2127 case LibFunc::fmodl: 2128 case LibFunc::fmod: 2129 case LibFunc::fmodf: 2130 return Op0.isNaN() || Op1.isNaN() || 2131 (!Op0.isInfinity() && !Op1.isZero()); 2132 2133 default: 2134 break; 2135 } 2136 } 2137 } 2138 2139 return false; 2140 } 2141