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