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