1 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines routines for folding instructions into constants.
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
17 //===----------------------------------------------------------------------===//
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/ValueTracking.h"
24 #include "llvm/Config/config.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/GetElementPtrTypeIterator.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/Operator.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Target/TargetLibraryInfo.h"
46 //===----------------------------------------------------------------------===//
47 // Constant Folding internal helper functions
48 //===----------------------------------------------------------------------===//
50 /// Constant fold bitcast, symbolically evaluating it with DataLayout.
51 /// This always returns a non-null constant, but it may be a
52 /// ConstantExpr if unfoldable.
53 static Constant *FoldBitCast(Constant *C, Type *DestTy,
54 const DataLayout &TD) {
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);
62 // Handle a vector->integer cast.
63 if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
64 VectorType *VTy = dyn_cast<VectorType>(C->getType());
66 return ConstantExpr::getBitCast(C, DestTy);
68 unsigned NumSrcElts = VTy->getNumElements();
69 Type *SrcEltTy = VTy->getElementType();
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();
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);
81 ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
83 return ConstantExpr::getBitCast(C, DestTy);
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 = TD.getTypeAllocSizeInBits(SrcEltTy);
88 APInt Result(IT->getBitWidth(), 0);
89 for (unsigned i = 0; i != NumSrcElts; ++i) {
91 if (TD.isLittleEndian())
92 Result |= CDV->getElementAsInteger(NumSrcElts-i-1);
94 Result |= CDV->getElementAsInteger(i);
97 return ConstantInt::get(IT, Result);
100 // The code below only handles casts to vectors currently.
101 VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
103 return ConstantExpr::getBitCast(C, DestTy);
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, TD);
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);
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);
122 Type *SrcEltTy = C->getType()->getVectorElementType();
123 Type *DstEltTy = DestVTy->getElementType();
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>
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();
139 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
140 // Recursively handle this integer conversion, if possible.
141 C = FoldBitCast(C, DestIVTy, TD);
143 // Finally, IR can handle this now that #elts line up.
144 return ConstantExpr::getBitCast(C, DestTy);
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();
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))
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
165 bool isLittleEndian = TD.isLittleEndian();
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();
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);
183 // Zero extend the element to the right size.
184 Src = ConstantExpr::getZExt(Src, Elt->getType());
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;
192 Elt = ConstantExpr::getOr(Elt, Src);
194 Result.push_back(Elt);
196 return ConstantVector::get(Result);
199 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
200 unsigned Ratio = NumDstElt/NumSrcElt;
201 unsigned DstBitSize = TD.getTypeSizeInBits(DstEltTy);
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);
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
213 Constant *Elt = ConstantExpr::getLShr(Src,
214 ConstantInt::get(Src->getType(), ShiftAmt));
215 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
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));
226 // Truncate and remember this piece.
227 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
231 return ConstantVector::get(Result);
235 /// If this constant is a constant offset from a global, return the global and
236 /// the constant. Because of constantexprs, this function is recursive.
237 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
238 APInt &Offset, const DataLayout &TD) {
239 // Trivial case, constant is the global.
240 if ((GV = dyn_cast<GlobalValue>(C))) {
241 unsigned BitWidth = TD.getPointerTypeSizeInBits(GV->getType());
242 Offset = APInt(BitWidth, 0);
246 // Otherwise, if this isn't a constant expr, bail out.
247 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
248 if (!CE) return false;
250 // Look through ptr->int and ptr->ptr casts.
251 if (CE->getOpcode() == Instruction::PtrToInt ||
252 CE->getOpcode() == Instruction::BitCast ||
253 CE->getOpcode() == Instruction::AddrSpaceCast)
254 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
256 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
257 GEPOperator *GEP = dyn_cast<GEPOperator>(CE);
261 unsigned BitWidth = TD.getPointerTypeSizeInBits(GEP->getType());
262 APInt TmpOffset(BitWidth, 0);
264 // If the base isn't a global+constant, we aren't either.
265 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, TD))
268 // Otherwise, add any offset that our operands provide.
269 if (!GEP->accumulateConstantOffset(TD, TmpOffset))
276 /// Recursive helper to read bits out of global. C is the constant being copied
277 /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
278 /// results into and BytesLeft is the number of bytes left in
279 /// the CurPtr buffer. TD is the target data.
280 static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
281 unsigned char *CurPtr, unsigned BytesLeft,
282 const DataLayout &TD) {
283 assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
284 "Out of range access");
286 // If this element is zero or undefined, we can just return since *CurPtr is
288 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
291 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
292 if (CI->getBitWidth() > 64 ||
293 (CI->getBitWidth() & 7) != 0)
296 uint64_t Val = CI->getZExtValue();
297 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
299 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
301 if (!TD.isLittleEndian())
302 n = IntBytes - n - 1;
303 CurPtr[i] = (unsigned char)(Val >> (n * 8));
309 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
310 if (CFP->getType()->isDoubleTy()) {
311 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
312 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
314 if (CFP->getType()->isFloatTy()){
315 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
316 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
318 if (CFP->getType()->isHalfTy()){
319 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), TD);
320 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
325 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
326 const StructLayout *SL = TD.getStructLayout(CS->getType());
327 unsigned Index = SL->getElementContainingOffset(ByteOffset);
328 uint64_t CurEltOffset = SL->getElementOffset(Index);
329 ByteOffset -= CurEltOffset;
332 // If the element access is to the element itself and not to tail padding,
333 // read the bytes from the element.
334 uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
336 if (ByteOffset < EltSize &&
337 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
343 // Check to see if we read from the last struct element, if so we're done.
344 if (Index == CS->getType()->getNumElements())
347 // If we read all of the bytes we needed from this element we're done.
348 uint64_t NextEltOffset = SL->getElementOffset(Index);
350 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
353 // Move to the next element of the struct.
354 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
355 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
357 CurEltOffset = NextEltOffset;
362 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
363 isa<ConstantDataSequential>(C)) {
364 Type *EltTy = C->getType()->getSequentialElementType();
365 uint64_t EltSize = TD.getTypeAllocSize(EltTy);
366 uint64_t Index = ByteOffset / EltSize;
367 uint64_t Offset = ByteOffset - Index * EltSize;
369 if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
370 NumElts = AT->getNumElements();
372 NumElts = C->getType()->getVectorNumElements();
374 for (; Index != NumElts; ++Index) {
375 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
379 uint64_t BytesWritten = EltSize - Offset;
380 assert(BytesWritten <= EltSize && "Not indexing into this element?");
381 if (BytesWritten >= BytesLeft)
385 BytesLeft -= BytesWritten;
386 CurPtr += BytesWritten;
391 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
392 if (CE->getOpcode() == Instruction::IntToPtr &&
393 CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getType())) {
394 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
399 // Otherwise, unknown initializer type.
403 static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
404 const DataLayout &TD) {
405 PointerType *PTy = cast<PointerType>(C->getType());
406 Type *LoadTy = PTy->getElementType();
407 IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
409 // If this isn't an integer load we can't fold it directly.
411 unsigned AS = PTy->getAddressSpace();
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.
418 if (LoadTy->isHalfTy())
419 MapTy = Type::getInt16PtrTy(C->getContext(), AS);
420 else if (LoadTy->isFloatTy())
421 MapTy = Type::getInt32PtrTy(C->getContext(), AS);
422 else if (LoadTy->isDoubleTy())
423 MapTy = Type::getInt64PtrTy(C->getContext(), AS);
424 else if (LoadTy->isVectorTy()) {
425 MapTy = PointerType::getIntNPtrTy(C->getContext(),
426 TD.getTypeAllocSizeInBits(LoadTy),
431 C = FoldBitCast(C, MapTy, TD);
432 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
433 return FoldBitCast(Res, LoadTy, TD);
437 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
438 if (BytesLoaded > 32 || BytesLoaded == 0)
443 if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
446 GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
447 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
448 !GV->getInitializer()->getType()->isSized())
451 // If we're loading off the beginning of the global, some bytes may be valid,
452 // but we don't try to handle this.
453 if (Offset.isNegative())
456 // If we're not accessing anything in this constant, the result is undefined.
457 if (Offset.getZExtValue() >=
458 TD.getTypeAllocSize(GV->getInitializer()->getType()))
459 return UndefValue::get(IntType);
461 unsigned char RawBytes[32] = {0};
462 if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
466 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
467 if (TD.isLittleEndian()) {
468 ResultVal = RawBytes[BytesLoaded - 1];
469 for (unsigned i = 1; i != BytesLoaded; ++i) {
471 ResultVal |= RawBytes[BytesLoaded - 1 - i];
474 ResultVal = RawBytes[0];
475 for (unsigned i = 1; i != BytesLoaded; ++i) {
477 ResultVal |= RawBytes[i];
481 return ConstantInt::get(IntType->getContext(), ResultVal);
484 static Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE,
485 const DataLayout *DL) {
488 auto *DestPtrTy = dyn_cast<PointerType>(CE->getType());
491 Type *DestTy = DestPtrTy->getElementType();
493 Constant *C = ConstantFoldLoadFromConstPtr(CE->getOperand(0), DL);
498 Type *SrcTy = C->getType();
500 // If the type sizes are the same and a cast is legal, just directly
501 // cast the constant.
502 if (DL->getTypeSizeInBits(DestTy) == DL->getTypeSizeInBits(SrcTy)) {
503 Instruction::CastOps Cast = Instruction::BitCast;
504 // If we are going from a pointer to int or vice versa, we spell the cast
506 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
507 Cast = Instruction::IntToPtr;
508 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
509 Cast = Instruction::PtrToInt;
511 if (CastInst::castIsValid(Cast, C, DestTy))
512 return ConstantExpr::getCast(Cast, C, DestTy);
515 // If this isn't an aggregate type, there is nothing we can do to drill down
516 // and find a bitcastable constant.
517 if (!SrcTy->isAggregateType())
520 // We're simulating a load through a pointer that was bitcast to point to
521 // a different type, so we can try to walk down through the initial
522 // elements of an aggregate to see if some part of th e aggregate is
523 // castable to implement the "load" semantic model.
524 C = C->getAggregateElement(0u);
530 /// Return the value that a load from C would produce if it is constant and
531 /// determinable. If this is not determinable, return null.
532 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
533 const DataLayout *TD) {
534 // First, try the easy cases:
535 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
536 if (GV->isConstant() && GV->hasDefinitiveInitializer())
537 return GV->getInitializer();
539 // If the loaded value isn't a constant expr, we can't handle it.
540 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
544 if (CE->getOpcode() == Instruction::GetElementPtr) {
545 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
546 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
548 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
554 if (CE->getOpcode() == Instruction::BitCast)
555 if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, TD))
558 // Instead of loading constant c string, use corresponding integer value
559 // directly if string length is small enough.
561 if (TD && getConstantStringInfo(CE, Str) && !Str.empty()) {
562 unsigned StrLen = Str.size();
563 Type *Ty = cast<PointerType>(CE->getType())->getElementType();
564 unsigned NumBits = Ty->getPrimitiveSizeInBits();
565 // Replace load with immediate integer if the result is an integer or fp
567 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
568 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
569 APInt StrVal(NumBits, 0);
570 APInt SingleChar(NumBits, 0);
571 if (TD->isLittleEndian()) {
572 for (signed i = StrLen-1; i >= 0; i--) {
573 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
574 StrVal = (StrVal << 8) | SingleChar;
577 for (unsigned i = 0; i < StrLen; i++) {
578 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
579 StrVal = (StrVal << 8) | SingleChar;
581 // Append NULL at the end.
583 StrVal = (StrVal << 8) | SingleChar;
586 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
587 if (Ty->isFloatingPointTy())
588 Res = ConstantExpr::getBitCast(Res, Ty);
593 // If this load comes from anywhere in a constant global, and if the global
594 // is all undef or zero, we know what it loads.
595 if (GlobalVariable *GV =
596 dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
597 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
598 Type *ResTy = cast<PointerType>(C->getType())->getElementType();
599 if (GV->getInitializer()->isNullValue())
600 return Constant::getNullValue(ResTy);
601 if (isa<UndefValue>(GV->getInitializer()))
602 return UndefValue::get(ResTy);
606 // Try hard to fold loads from bitcasted strange and non-type-safe things.
608 return FoldReinterpretLoadFromConstPtr(CE, *TD);
612 static Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout *TD){
613 if (LI->isVolatile()) return nullptr;
615 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
616 return ConstantFoldLoadFromConstPtr(C, TD);
621 /// One of Op0/Op1 is a constant expression.
622 /// Attempt to symbolically evaluate the result of a binary operator merging
623 /// these together. If target data info is available, it is provided as DL,
624 /// otherwise DL is null.
625 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
626 Constant *Op1, const DataLayout *DL){
629 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
630 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
634 if (Opc == Instruction::And && DL) {
635 unsigned BitWidth = DL->getTypeSizeInBits(Op0->getType()->getScalarType());
636 APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
637 APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
638 computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
639 computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
640 if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
641 // All the bits of Op0 that the 'and' could be masking are already zero.
644 if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
645 // All the bits of Op1 that the 'and' could be masking are already zero.
649 APInt KnownZero = KnownZero0 | KnownZero1;
650 APInt KnownOne = KnownOne0 & KnownOne1;
651 if ((KnownZero | KnownOne).isAllOnesValue()) {
652 return ConstantInt::get(Op0->getType(), KnownOne);
656 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
657 // constant. This happens frequently when iterating over a global array.
658 if (Opc == Instruction::Sub && DL) {
659 GlobalValue *GV1, *GV2;
662 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *DL))
663 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *DL) &&
665 unsigned OpSize = DL->getTypeSizeInBits(Op0->getType());
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
670 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
671 Offs2.zextOrTrunc(OpSize));
678 /// If array indices are not pointer-sized integers, explicitly cast them so
679 /// that they aren't implicitly casted by the getelementptr.
680 static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
681 Type *ResultTy, const DataLayout *TD,
682 const TargetLibraryInfo *TLI) {
686 Type *IntPtrTy = TD->getIntPtrType(ResultTy);
689 SmallVector<Constant*, 32> NewIdxs;
690 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
692 !isa<StructType>(GetElementPtrInst::getIndexedType(
694 Ops.slice(1, i - 1)))) &&
695 Ops[i]->getType() != IntPtrTy) {
697 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
703 NewIdxs.push_back(Ops[i]);
709 Constant *C = ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
710 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
711 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD, TLI))
718 /// Strip the pointer casts, but preserve the address space information.
719 static Constant* StripPtrCastKeepAS(Constant* Ptr) {
720 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
721 PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
722 Ptr = Ptr->stripPointerCasts();
723 PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
725 // Preserve the address space number of the pointer.
726 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
727 NewPtrTy = NewPtrTy->getElementType()->getPointerTo(
728 OldPtrTy->getAddressSpace());
729 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
734 /// If we can symbolically evaluate the GEP constant expression, do so.
735 static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
736 Type *ResultTy, const DataLayout *TD,
737 const TargetLibraryInfo *TLI) {
738 Constant *Ptr = Ops[0];
739 if (!TD || !Ptr->getType()->getPointerElementType()->isSized() ||
740 !Ptr->getType()->isPointerTy())
743 Type *IntPtrTy = TD->getIntPtrType(Ptr->getType());
744 Type *ResultElementTy = ResultTy->getPointerElementType();
746 // If this is a constant expr gep that is effectively computing an
747 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
748 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
749 if (!isa<ConstantInt>(Ops[i])) {
751 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
752 // "inttoptr (sub (ptrtoint Ptr), V)"
753 if (Ops.size() == 2 && ResultElementTy->isIntegerTy(8)) {
754 ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
755 assert((!CE || CE->getType() == IntPtrTy) &&
756 "CastGEPIndices didn't canonicalize index types!");
757 if (CE && CE->getOpcode() == Instruction::Sub &&
758 CE->getOperand(0)->isNullValue()) {
759 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
760 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
761 Res = ConstantExpr::getIntToPtr(Res, ResultTy);
762 if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
763 Res = ConstantFoldConstantExpression(ResCE, TD, TLI);
770 unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
772 APInt(BitWidth, TD->getIndexedOffset(Ptr->getType(),
773 makeArrayRef((Value *const*)
776 Ptr = StripPtrCastKeepAS(Ptr);
778 // If this is a GEP of a GEP, fold it all into a single GEP.
779 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
780 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
782 // Do not try the incorporate the sub-GEP if some index is not a number.
783 bool AllConstantInt = true;
784 for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
785 if (!isa<ConstantInt>(NestedOps[i])) {
786 AllConstantInt = false;
792 Ptr = cast<Constant>(GEP->getOperand(0));
793 Offset += APInt(BitWidth,
794 TD->getIndexedOffset(Ptr->getType(), NestedOps));
795 Ptr = StripPtrCastKeepAS(Ptr);
798 // If the base value for this address is a literal integer value, fold the
799 // getelementptr to the resulting integer value casted to the pointer type.
800 APInt BasePtr(BitWidth, 0);
801 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
802 if (CE->getOpcode() == Instruction::IntToPtr) {
803 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
804 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
808 if (Ptr->isNullValue() || BasePtr != 0) {
809 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
810 return ConstantExpr::getIntToPtr(C, ResultTy);
813 // Otherwise form a regular getelementptr. Recompute the indices so that
814 // we eliminate over-indexing of the notional static type array bounds.
815 // This makes it easy to determine if the getelementptr is "inbounds".
816 // Also, this helps GlobalOpt do SROA on GlobalVariables.
817 Type *Ty = Ptr->getType();
818 assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
819 SmallVector<Constant *, 32> NewIdxs;
822 if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
823 if (ATy->isPointerTy()) {
824 // The only pointer indexing we'll do is on the first index of the GEP.
825 if (!NewIdxs.empty())
828 // Only handle pointers to sized types, not pointers to functions.
829 if (!ATy->getElementType()->isSized())
833 // Determine which element of the array the offset points into.
834 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
836 // The element size is 0. This may be [0 x Ty]*, so just use a zero
837 // index for this level and proceed to the next level to see if it can
838 // accommodate the offset.
839 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
841 // The element size is non-zero divide the offset by the element
842 // size (rounding down), to compute the index at this level.
843 APInt NewIdx = Offset.udiv(ElemSize);
844 Offset -= NewIdx * ElemSize;
845 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
847 Ty = ATy->getElementType();
848 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
849 // If we end up with an offset that isn't valid for this struct type, we
850 // can't re-form this GEP in a regular form, so bail out. The pointer
851 // operand likely went through casts that are necessary to make the GEP
853 const StructLayout &SL = *TD->getStructLayout(STy);
854 if (Offset.uge(SL.getSizeInBytes()))
857 // Determine which field of the struct the offset points into. The
858 // getZExtValue is fine as we've already ensured that the offset is
859 // within the range representable by the StructLayout API.
860 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
861 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
863 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
864 Ty = STy->getTypeAtIndex(ElIdx);
866 // We've reached some non-indexable type.
869 } while (Ty != ResultElementTy);
871 // If we haven't used up the entire offset by descending the static
872 // type, then the offset is pointing into the middle of an indivisible
873 // member, so we can't simplify it.
878 Constant *C = ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
879 assert(C->getType()->getPointerElementType() == Ty &&
880 "Computed GetElementPtr has unexpected type!");
882 // If we ended up indexing a member with a type that doesn't match
883 // the type of what the original indices indexed, add a cast.
884 if (Ty != ResultElementTy)
885 C = FoldBitCast(C, ResultTy, *TD);
892 //===----------------------------------------------------------------------===//
893 // Constant Folding public APIs
894 //===----------------------------------------------------------------------===//
896 /// Try to constant fold the specified instruction.
897 /// If successful, the constant result is returned, if not, null is returned.
898 /// Note that this fails if not all of the operands are constant. Otherwise,
899 /// this function can only fail when attempting to fold instructions like loads
900 /// and stores, which have no constant expression form.
901 Constant *llvm::ConstantFoldInstruction(Instruction *I,
902 const DataLayout *TD,
903 const TargetLibraryInfo *TLI) {
904 // Handle PHI nodes quickly here...
905 if (PHINode *PN = dyn_cast<PHINode>(I)) {
906 Constant *CommonValue = nullptr;
908 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
909 Value *Incoming = PN->getIncomingValue(i);
910 // If the incoming value is undef then skip it. Note that while we could
911 // skip the value if it is equal to the phi node itself we choose not to
912 // because that would break the rule that constant folding only applies if
913 // all operands are constants.
914 if (isa<UndefValue>(Incoming))
916 // If the incoming value is not a constant, then give up.
917 Constant *C = dyn_cast<Constant>(Incoming);
920 // Fold the PHI's operands.
921 if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
922 C = ConstantFoldConstantExpression(NewC, TD, TLI);
923 // If the incoming value is a different constant to
924 // the one we saw previously, then give up.
925 if (CommonValue && C != CommonValue)
931 // If we reach here, all incoming values are the same constant or undef.
932 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
935 // Scan the operand list, checking to see if they are all constants, if so,
936 // hand off to ConstantFoldInstOperands.
937 SmallVector<Constant*, 8> Ops;
938 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
939 Constant *Op = dyn_cast<Constant>(*i);
941 return nullptr; // All operands not constant!
943 // Fold the Instruction's operands.
944 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
945 Op = ConstantFoldConstantExpression(NewCE, TD, TLI);
950 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
951 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
954 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
955 return ConstantFoldLoadInst(LI, TD);
957 if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I)) {
958 return ConstantExpr::getInsertValue(
959 cast<Constant>(IVI->getAggregateOperand()),
960 cast<Constant>(IVI->getInsertedValueOperand()),
964 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I)) {
965 return ConstantExpr::getExtractValue(
966 cast<Constant>(EVI->getAggregateOperand()),
970 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD, TLI);
974 ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout *TD,
975 const TargetLibraryInfo *TLI,
976 SmallPtrSetImpl<ConstantExpr *> &FoldedOps) {
977 SmallVector<Constant *, 8> Ops;
978 for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end(); i != e;
980 Constant *NewC = cast<Constant>(*i);
981 // Recursively fold the ConstantExpr's operands. If we have already folded
982 // a ConstantExpr, we don't have to process it again.
983 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC)) {
984 if (FoldedOps.insert(NewCE).second)
985 NewC = ConstantFoldConstantExpressionImpl(NewCE, TD, TLI, FoldedOps);
991 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
993 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD, TLI);
996 /// Attempt to fold the constant expression
997 /// using the specified DataLayout. If successful, the constant result is
998 /// result is returned, if not, null is returned.
999 Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
1000 const DataLayout *TD,
1001 const TargetLibraryInfo *TLI) {
1002 SmallPtrSet<ConstantExpr *, 4> FoldedOps;
1003 return ConstantFoldConstantExpressionImpl(CE, TD, TLI, FoldedOps);
1006 /// Attempt to constant fold an instruction with the
1007 /// specified opcode and operands. If successful, the constant result is
1008 /// returned, if not, null is returned. Note that this function can fail when
1009 /// attempting to fold instructions like loads and stores, which have no
1010 /// constant expression form.
1012 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
1013 /// information, due to only being passed an opcode and operands. Constant
1014 /// folding using this function strips this information.
1016 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
1017 ArrayRef<Constant *> Ops,
1018 const DataLayout *TD,
1019 const TargetLibraryInfo *TLI) {
1020 // Handle easy binops first.
1021 if (Instruction::isBinaryOp(Opcode)) {
1022 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1])) {
1023 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
1027 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
1031 default: return nullptr;
1032 case Instruction::ICmp:
1033 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
1034 case Instruction::Call:
1035 if (Function *F = dyn_cast<Function>(Ops.back()))
1036 if (canConstantFoldCallTo(F))
1037 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
1039 case Instruction::PtrToInt:
1040 // If the input is a inttoptr, eliminate the pair. This requires knowing
1041 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1042 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
1043 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
1044 Constant *Input = CE->getOperand(0);
1045 unsigned InWidth = Input->getType()->getScalarSizeInBits();
1046 unsigned PtrWidth = TD->getPointerTypeSizeInBits(CE->getType());
1047 if (PtrWidth < InWidth) {
1049 ConstantInt::get(CE->getContext(),
1050 APInt::getLowBitsSet(InWidth, PtrWidth));
1051 Input = ConstantExpr::getAnd(Input, Mask);
1053 // Do a zext or trunc to get to the dest size.
1054 return ConstantExpr::getIntegerCast(Input, DestTy, false);
1057 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
1058 case Instruction::IntToPtr:
1059 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1060 // the int size is >= the ptr size and the address spaces are the same.
1061 // This requires knowing the width of a pointer, so it can't be done in
1062 // ConstantExpr::getCast.
1063 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
1064 if (TD && CE->getOpcode() == Instruction::PtrToInt) {
1065 Constant *SrcPtr = CE->getOperand(0);
1066 unsigned SrcPtrSize = TD->getPointerTypeSizeInBits(SrcPtr->getType());
1067 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1069 if (MidIntSize >= SrcPtrSize) {
1070 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1071 if (SrcAS == DestTy->getPointerAddressSpace())
1072 return FoldBitCast(CE->getOperand(0), DestTy, *TD);
1077 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
1078 case Instruction::Trunc:
1079 case Instruction::ZExt:
1080 case Instruction::SExt:
1081 case Instruction::FPTrunc:
1082 case Instruction::FPExt:
1083 case Instruction::UIToFP:
1084 case Instruction::SIToFP:
1085 case Instruction::FPToUI:
1086 case Instruction::FPToSI:
1087 case Instruction::AddrSpaceCast:
1088 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
1089 case Instruction::BitCast:
1091 return FoldBitCast(Ops[0], DestTy, *TD);
1092 return ConstantExpr::getBitCast(Ops[0], DestTy);
1093 case Instruction::Select:
1094 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1095 case Instruction::ExtractElement:
1096 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1097 case Instruction::InsertElement:
1098 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1099 case Instruction::ShuffleVector:
1100 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1101 case Instruction::GetElementPtr:
1102 if (Constant *C = CastGEPIndices(Ops, DestTy, TD, TLI))
1104 if (Constant *C = SymbolicallyEvaluateGEP(Ops, DestTy, TD, TLI))
1107 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
1111 /// Attempt to constant fold a compare
1112 /// instruction (icmp/fcmp) with the specified operands. If it fails, it
1113 /// returns a constant expression of the specified operands.
1114 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
1115 Constant *Ops0, Constant *Ops1,
1116 const DataLayout *TD,
1117 const TargetLibraryInfo *TLI) {
1118 // fold: icmp (inttoptr x), null -> icmp x, 0
1119 // fold: icmp (ptrtoint x), 0 -> icmp x, null
1120 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1121 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1123 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
1124 // around to know if bit truncation is happening.
1125 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1126 if (TD && Ops1->isNullValue()) {
1127 if (CE0->getOpcode() == Instruction::IntToPtr) {
1128 Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
1129 // Convert the integer value to the right size to ensure we get the
1130 // proper extension or truncation.
1131 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1133 Constant *Null = Constant::getNullValue(C->getType());
1134 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
1137 // Only do this transformation if the int is intptrty in size, otherwise
1138 // there is a truncation or extension that we aren't modeling.
1139 if (CE0->getOpcode() == Instruction::PtrToInt) {
1140 Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
1141 if (CE0->getType() == IntPtrTy) {
1142 Constant *C = CE0->getOperand(0);
1143 Constant *Null = Constant::getNullValue(C->getType());
1144 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
1149 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1150 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
1151 if (CE0->getOpcode() == Instruction::IntToPtr) {
1152 Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
1154 // Convert the integer value to the right size to ensure we get the
1155 // proper extension or truncation.
1156 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1158 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1160 return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD, TLI);
1163 // Only do this transformation if the int is intptrty in size, otherwise
1164 // there is a truncation or extension that we aren't modeling.
1165 if (CE0->getOpcode() == Instruction::PtrToInt) {
1166 Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
1167 if (CE0->getType() == IntPtrTy &&
1168 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1169 return ConstantFoldCompareInstOperands(Predicate,
1179 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1180 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1181 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1182 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1184 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,
1187 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,
1190 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1191 Constant *Ops[] = { LHS, RHS };
1192 return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD, TLI);
1196 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1200 /// Given a constant and a getelementptr constantexpr, return the constant value
1201 /// being addressed by the constant expression, or null if something is funny
1202 /// and we can't decide.
1203 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
1205 if (!CE->getOperand(1)->isNullValue())
1206 return nullptr; // Do not allow stepping over the value!
1208 // Loop over all of the operands, tracking down which value we are
1210 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1211 C = C->getAggregateElement(CE->getOperand(i));
1218 /// Given a constant and getelementptr indices (with an *implied* zero pointer
1219 /// index that is not in the list), return the constant value being addressed by
1220 /// a virtual load, or null if something is funny and we can't decide.
1221 Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1222 ArrayRef<Constant*> Indices) {
1223 // Loop over all of the operands, tracking down which value we are
1225 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1226 C = C->getAggregateElement(Indices[i]);
1234 //===----------------------------------------------------------------------===//
1235 // Constant Folding for Calls
1238 /// Return true if it's even possible to fold a call to the specified function.
1239 bool llvm::canConstantFoldCallTo(const Function *F) {
1240 switch (F->getIntrinsicID()) {
1241 case Intrinsic::fabs:
1242 case Intrinsic::minnum:
1243 case Intrinsic::maxnum:
1244 case Intrinsic::log:
1245 case Intrinsic::log2:
1246 case Intrinsic::log10:
1247 case Intrinsic::exp:
1248 case Intrinsic::exp2:
1249 case Intrinsic::floor:
1250 case Intrinsic::ceil:
1251 case Intrinsic::sqrt:
1252 case Intrinsic::pow:
1253 case Intrinsic::powi:
1254 case Intrinsic::bswap:
1255 case Intrinsic::ctpop:
1256 case Intrinsic::ctlz:
1257 case Intrinsic::cttz:
1258 case Intrinsic::fma:
1259 case Intrinsic::fmuladd:
1260 case Intrinsic::copysign:
1261 case Intrinsic::round:
1262 case Intrinsic::sadd_with_overflow:
1263 case Intrinsic::uadd_with_overflow:
1264 case Intrinsic::ssub_with_overflow:
1265 case Intrinsic::usub_with_overflow:
1266 case Intrinsic::smul_with_overflow:
1267 case Intrinsic::umul_with_overflow:
1268 case Intrinsic::convert_from_fp16:
1269 case Intrinsic::convert_to_fp16:
1270 case Intrinsic::x86_sse_cvtss2si:
1271 case Intrinsic::x86_sse_cvtss2si64:
1272 case Intrinsic::x86_sse_cvttss2si:
1273 case Intrinsic::x86_sse_cvttss2si64:
1274 case Intrinsic::x86_sse2_cvtsd2si:
1275 case Intrinsic::x86_sse2_cvtsd2si64:
1276 case Intrinsic::x86_sse2_cvttsd2si:
1277 case Intrinsic::x86_sse2_cvttsd2si64:
1286 StringRef Name = F->getName();
1288 // In these cases, the check of the length is required. We don't want to
1289 // return true for a name like "cos\0blah" which strcmp would return equal to
1290 // "cos", but has length 8.
1292 default: return false;
1294 return Name == "acos" || Name == "asin" || Name == "atan" || Name =="atan2";
1296 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
1298 return Name == "exp" || Name == "exp2";
1300 return Name == "fabs" || Name == "fmod" || Name == "floor";
1302 return Name == "log" || Name == "log10";
1304 return Name == "pow";
1306 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1307 Name == "sinf" || Name == "sqrtf";
1309 return Name == "tan" || Name == "tanh";
1313 static Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1314 if (Ty->isHalfTy()) {
1317 APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1318 return ConstantFP::get(Ty->getContext(), APF);
1320 if (Ty->isFloatTy())
1321 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1322 if (Ty->isDoubleTy())
1323 return ConstantFP::get(Ty->getContext(), APFloat(V));
1324 llvm_unreachable("Can only constant fold half/float/double");
1329 /// Clear the floating-point exception state.
1330 static inline void llvm_fenv_clearexcept() {
1331 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
1332 feclearexcept(FE_ALL_EXCEPT);
1337 /// Test if a floating-point exception was raised.
1338 static inline bool llvm_fenv_testexcept() {
1339 int errno_val = errno;
1340 if (errno_val == ERANGE || errno_val == EDOM)
1342 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
1343 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1350 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
1352 llvm_fenv_clearexcept();
1354 if (llvm_fenv_testexcept()) {
1355 llvm_fenv_clearexcept();
1359 return GetConstantFoldFPValue(V, Ty);
1362 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1363 double V, double W, Type *Ty) {
1364 llvm_fenv_clearexcept();
1366 if (llvm_fenv_testexcept()) {
1367 llvm_fenv_clearexcept();
1371 return GetConstantFoldFPValue(V, Ty);
1374 /// Attempt to fold an SSE floating point to integer conversion of a constant
1375 /// floating point. If roundTowardZero is false, the default IEEE rounding is
1376 /// used (toward nearest, ties to even). This matches the behavior of the
1377 /// non-truncating SSE instructions in the default rounding mode. The desired
1378 /// integer type Ty is used to select how many bits are available for the
1379 /// result. Returns null if the conversion cannot be performed, otherwise
1380 /// returns the Constant value resulting from the conversion.
1381 static Constant *ConstantFoldConvertToInt(const APFloat &Val,
1382 bool roundTowardZero, Type *Ty) {
1383 // All of these conversion intrinsics form an integer of at most 64bits.
1384 unsigned ResultWidth = Ty->getIntegerBitWidth();
1385 assert(ResultWidth <= 64 &&
1386 "Can only constant fold conversions to 64 and 32 bit ints");
1389 bool isExact = false;
1390 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1391 : APFloat::rmNearestTiesToEven;
1392 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1393 /*isSigned=*/true, mode,
1395 if (status != APFloat::opOK && status != APFloat::opInexact)
1397 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1400 static double getValueAsDouble(ConstantFP *Op) {
1401 Type *Ty = Op->getType();
1403 if (Ty->isFloatTy())
1404 return Op->getValueAPF().convertToFloat();
1406 if (Ty->isDoubleTy())
1407 return Op->getValueAPF().convertToDouble();
1410 APFloat APF = Op->getValueAPF();
1411 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1412 return APF.convertToDouble();
1415 static Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID,
1416 Type *Ty, ArrayRef<Constant *> Operands,
1417 const TargetLibraryInfo *TLI) {
1418 if (Operands.size() == 1) {
1419 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
1420 if (IntrinsicID == Intrinsic::convert_to_fp16) {
1421 APFloat Val(Op->getValueAPF());
1424 Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1426 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1429 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1432 if (IntrinsicID == Intrinsic::round) {
1433 APFloat V = Op->getValueAPF();
1434 V.roundToIntegral(APFloat::rmNearestTiesToAway);
1435 return ConstantFP::get(Ty->getContext(), V);
1438 /// We only fold functions with finite arguments. Folding NaN and inf is
1439 /// likely to be aborted with an exception anyway, and some host libms
1440 /// have known errors raising exceptions.
1441 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1444 /// Currently APFloat versions of these functions do not exist, so we use
1445 /// the host native double versions. Float versions are not called
1446 /// directly but for all these it is true (float)(f((double)arg)) ==
1447 /// f(arg). Long double not supported yet.
1448 double V = getValueAsDouble(Op);
1450 switch (IntrinsicID) {
1452 case Intrinsic::fabs:
1453 return ConstantFoldFP(fabs, V, Ty);
1455 case Intrinsic::log2:
1456 return ConstantFoldFP(log2, V, Ty);
1459 case Intrinsic::log:
1460 return ConstantFoldFP(log, V, Ty);
1463 case Intrinsic::log10:
1464 return ConstantFoldFP(log10, V, Ty);
1467 case Intrinsic::exp:
1468 return ConstantFoldFP(exp, V, Ty);
1471 case Intrinsic::exp2:
1472 return ConstantFoldFP(exp2, V, Ty);
1474 case Intrinsic::floor:
1475 return ConstantFoldFP(floor, V, Ty);
1476 case Intrinsic::ceil:
1477 return ConstantFoldFP(ceil, V, Ty);
1485 if (Name == "acos" && TLI->has(LibFunc::acos))
1486 return ConstantFoldFP(acos, V, Ty);
1487 else if (Name == "asin" && TLI->has(LibFunc::asin))
1488 return ConstantFoldFP(asin, V, Ty);
1489 else if (Name == "atan" && TLI->has(LibFunc::atan))
1490 return ConstantFoldFP(atan, V, Ty);
1493 if (Name == "ceil" && TLI->has(LibFunc::ceil))
1494 return ConstantFoldFP(ceil, V, Ty);
1495 else if (Name == "cos" && TLI->has(LibFunc::cos))
1496 return ConstantFoldFP(cos, V, Ty);
1497 else if (Name == "cosh" && TLI->has(LibFunc::cosh))
1498 return ConstantFoldFP(cosh, V, Ty);
1499 else if (Name == "cosf" && TLI->has(LibFunc::cosf))
1500 return ConstantFoldFP(cos, V, Ty);
1503 if (Name == "exp" && TLI->has(LibFunc::exp))
1504 return ConstantFoldFP(exp, V, Ty);
1506 if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
1507 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1509 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1513 if (Name == "fabs" && TLI->has(LibFunc::fabs))
1514 return ConstantFoldFP(fabs, V, Ty);
1515 else if (Name == "floor" && TLI->has(LibFunc::floor))
1516 return ConstantFoldFP(floor, V, Ty);
1519 if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
1520 return ConstantFoldFP(log, V, Ty);
1521 else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
1522 return ConstantFoldFP(log10, V, Ty);
1523 else if (IntrinsicID == Intrinsic::sqrt &&
1524 (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
1526 return ConstantFoldFP(sqrt, V, Ty);
1528 // Unlike the sqrt definitions in C/C++, POSIX, and IEEE-754 - which
1529 // all guarantee or favor returning NaN - the square root of a
1530 // negative number is not defined for the LLVM sqrt intrinsic.
1531 // This is because the intrinsic should only be emitted in place of
1532 // libm's sqrt function when using "no-nans-fp-math".
1533 return UndefValue::get(Ty);
1538 if (Name == "sin" && TLI->has(LibFunc::sin))
1539 return ConstantFoldFP(sin, V, Ty);
1540 else if (Name == "sinh" && TLI->has(LibFunc::sinh))
1541 return ConstantFoldFP(sinh, V, Ty);
1542 else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
1543 return ConstantFoldFP(sqrt, V, Ty);
1544 else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
1545 return ConstantFoldFP(sqrt, V, Ty);
1546 else if (Name == "sinf" && TLI->has(LibFunc::sinf))
1547 return ConstantFoldFP(sin, V, Ty);
1550 if (Name == "tan" && TLI->has(LibFunc::tan))
1551 return ConstantFoldFP(tan, V, Ty);
1552 else if (Name == "tanh" && TLI->has(LibFunc::tanh))
1553 return ConstantFoldFP(tanh, V, Ty);
1561 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
1562 switch (IntrinsicID) {
1563 case Intrinsic::bswap:
1564 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
1565 case Intrinsic::ctpop:
1566 return ConstantInt::get(Ty, Op->getValue().countPopulation());
1567 case Intrinsic::convert_from_fp16: {
1568 APFloat Val(APFloat::IEEEhalf, Op->getValue());
1571 APFloat::opStatus status =
1572 Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
1574 // Conversion is always precise.
1576 assert(status == APFloat::opOK && !lost &&
1577 "Precision lost during fp16 constfolding");
1579 return ConstantFP::get(Ty->getContext(), Val);
1586 // Support ConstantVector in case we have an Undef in the top.
1587 if (isa<ConstantVector>(Operands[0]) ||
1588 isa<ConstantDataVector>(Operands[0])) {
1589 Constant *Op = cast<Constant>(Operands[0]);
1590 switch (IntrinsicID) {
1592 case Intrinsic::x86_sse_cvtss2si:
1593 case Intrinsic::x86_sse_cvtss2si64:
1594 case Intrinsic::x86_sse2_cvtsd2si:
1595 case Intrinsic::x86_sse2_cvtsd2si64:
1596 if (ConstantFP *FPOp =
1597 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1598 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1599 /*roundTowardZero=*/false, Ty);
1600 case Intrinsic::x86_sse_cvttss2si:
1601 case Intrinsic::x86_sse_cvttss2si64:
1602 case Intrinsic::x86_sse2_cvttsd2si:
1603 case Intrinsic::x86_sse2_cvttsd2si64:
1604 if (ConstantFP *FPOp =
1605 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1606 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1607 /*roundTowardZero=*/true, Ty);
1611 if (isa<UndefValue>(Operands[0])) {
1612 if (IntrinsicID == Intrinsic::bswap)
1620 if (Operands.size() == 2) {
1621 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1622 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1624 double Op1V = getValueAsDouble(Op1);
1626 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1627 if (Op2->getType() != Op1->getType())
1630 double Op2V = getValueAsDouble(Op2);
1631 if (IntrinsicID == Intrinsic::pow) {
1632 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1634 if (IntrinsicID == Intrinsic::copysign) {
1635 APFloat V1 = Op1->getValueAPF();
1636 APFloat V2 = Op2->getValueAPF();
1638 return ConstantFP::get(Ty->getContext(), V1);
1641 if (IntrinsicID == Intrinsic::minnum) {
1642 const APFloat &C1 = Op1->getValueAPF();
1643 const APFloat &C2 = Op2->getValueAPF();
1644 return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1647 if (IntrinsicID == Intrinsic::maxnum) {
1648 const APFloat &C1 = Op1->getValueAPF();
1649 const APFloat &C2 = Op2->getValueAPF();
1650 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1655 if (Name == "pow" && TLI->has(LibFunc::pow))
1656 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1657 if (Name == "fmod" && TLI->has(LibFunc::fmod))
1658 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1659 if (Name == "atan2" && TLI->has(LibFunc::atan2))
1660 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1661 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1662 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1663 return ConstantFP::get(Ty->getContext(),
1664 APFloat((float)std::pow((float)Op1V,
1665 (int)Op2C->getZExtValue())));
1666 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1667 return ConstantFP::get(Ty->getContext(),
1668 APFloat((float)std::pow((float)Op1V,
1669 (int)Op2C->getZExtValue())));
1670 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1671 return ConstantFP::get(Ty->getContext(),
1672 APFloat((double)std::pow((double)Op1V,
1673 (int)Op2C->getZExtValue())));
1678 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1679 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1680 switch (IntrinsicID) {
1682 case Intrinsic::sadd_with_overflow:
1683 case Intrinsic::uadd_with_overflow:
1684 case Intrinsic::ssub_with_overflow:
1685 case Intrinsic::usub_with_overflow:
1686 case Intrinsic::smul_with_overflow:
1687 case Intrinsic::umul_with_overflow: {
1690 switch (IntrinsicID) {
1691 default: llvm_unreachable("Invalid case");
1692 case Intrinsic::sadd_with_overflow:
1693 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1695 case Intrinsic::uadd_with_overflow:
1696 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1698 case Intrinsic::ssub_with_overflow:
1699 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1701 case Intrinsic::usub_with_overflow:
1702 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1704 case Intrinsic::smul_with_overflow:
1705 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1707 case Intrinsic::umul_with_overflow:
1708 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1712 ConstantInt::get(Ty->getContext(), Res),
1713 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
1715 return ConstantStruct::get(cast<StructType>(Ty), Ops);
1717 case Intrinsic::cttz:
1718 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1719 return UndefValue::get(Ty);
1720 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1721 case Intrinsic::ctlz:
1722 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1723 return UndefValue::get(Ty);
1724 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
1733 if (Operands.size() != 3)
1736 if (const ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1737 if (const ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1738 if (const ConstantFP *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
1739 switch (IntrinsicID) {
1741 case Intrinsic::fma:
1742 case Intrinsic::fmuladd: {
1743 APFloat V = Op1->getValueAPF();
1744 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1746 APFloat::rmNearestTiesToEven);
1747 if (s != APFloat::opInvalidOp)
1748 return ConstantFP::get(Ty->getContext(), V);
1760 static Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1762 ArrayRef<Constant *> Operands,
1763 const TargetLibraryInfo *TLI) {
1764 SmallVector<Constant *, 4> Result(VTy->getNumElements());
1765 SmallVector<Constant *, 4> Lane(Operands.size());
1766 Type *Ty = VTy->getElementType();
1768 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1769 // Gather a column of constants.
1770 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1771 Constant *Agg = Operands[J]->getAggregateElement(I);
1778 // Use the regular scalar folding to simplify this column.
1779 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1785 return ConstantVector::get(Result);
1788 /// Attempt to constant fold a call to the specified function
1789 /// with the specified arguments, returning null if unsuccessful.
1791 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1792 const TargetLibraryInfo *TLI) {
1795 StringRef Name = F->getName();
1797 Type *Ty = F->getReturnType();
1799 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1800 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, TLI);
1802 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);