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