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"
45 // FIXME: Clang's #include handling apparently doesn't work for libstdc++'s
46 // fenv.h; see PR6907 for details.
47 #if defined(__clang__) && defined(_GLIBCXX_FENV_H)
53 //===----------------------------------------------------------------------===//
54 // Constant Folding internal helper functions
55 //===----------------------------------------------------------------------===//
57 /// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
58 /// DataLayout. This always returns a non-null constant, but it may be a
59 /// ConstantExpr if unfoldable.
60 static Constant *FoldBitCast(Constant *C, Type *DestTy,
61 const DataLayout &TD) {
62 // Catch the obvious splat cases.
63 if (C->isNullValue() && !DestTy->isX86_MMXTy())
64 return Constant::getNullValue(DestTy);
65 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy())
66 return Constant::getAllOnesValue(DestTy);
68 // Handle a vector->integer cast.
69 if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
70 VectorType *VTy = dyn_cast<VectorType>(C->getType());
72 return ConstantExpr::getBitCast(C, DestTy);
74 unsigned NumSrcElts = VTy->getNumElements();
75 Type *SrcEltTy = VTy->getElementType();
77 // If the vector is a vector of floating point, convert it to vector of int
78 // to simplify things.
79 if (SrcEltTy->isFloatingPointTy()) {
80 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
82 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
83 // Ask IR to do the conversion now that #elts line up.
84 C = ConstantExpr::getBitCast(C, SrcIVTy);
87 ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
89 return ConstantExpr::getBitCast(C, DestTy);
91 // Now that we know that the input value is a vector of integers, just shift
92 // and insert them into our result.
93 unsigned BitShift = TD.getTypeAllocSizeInBits(SrcEltTy);
94 APInt Result(IT->getBitWidth(), 0);
95 for (unsigned i = 0; i != NumSrcElts; ++i) {
97 if (TD.isLittleEndian())
98 Result |= CDV->getElementAsInteger(NumSrcElts-i-1);
100 Result |= CDV->getElementAsInteger(i);
103 return ConstantInt::get(IT, Result);
106 // The code below only handles casts to vectors currently.
107 VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
109 return ConstantExpr::getBitCast(C, DestTy);
111 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
112 // vector so the code below can handle it uniformly.
113 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
114 Constant *Ops = C; // don't take the address of C!
115 return FoldBitCast(ConstantVector::get(Ops), DestTy, TD);
118 // If this is a bitcast from constant vector -> vector, fold it.
119 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
120 return ConstantExpr::getBitCast(C, DestTy);
122 // If the element types match, IR can fold it.
123 unsigned NumDstElt = DestVTy->getNumElements();
124 unsigned NumSrcElt = C->getType()->getVectorNumElements();
125 if (NumDstElt == NumSrcElt)
126 return ConstantExpr::getBitCast(C, DestTy);
128 Type *SrcEltTy = C->getType()->getVectorElementType();
129 Type *DstEltTy = DestVTy->getElementType();
131 // Otherwise, we're changing the number of elements in a vector, which
132 // requires endianness information to do the right thing. For example,
133 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
134 // folds to (little endian):
135 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
136 // and to (big endian):
137 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
139 // First thing is first. We only want to think about integer here, so if
140 // we have something in FP form, recast it as integer.
141 if (DstEltTy->isFloatingPointTy()) {
142 // Fold to an vector of integers with same size as our FP type.
143 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
145 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
146 // Recursively handle this integer conversion, if possible.
147 C = FoldBitCast(C, DestIVTy, TD);
149 // Finally, IR can handle this now that #elts line up.
150 return ConstantExpr::getBitCast(C, DestTy);
153 // Okay, we know the destination is integer, if the input is FP, convert
154 // it to integer first.
155 if (SrcEltTy->isFloatingPointTy()) {
156 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
158 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
159 // Ask IR to do the conversion now that #elts line up.
160 C = ConstantExpr::getBitCast(C, SrcIVTy);
161 // If IR wasn't able to fold it, bail out.
162 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
163 !isa<ConstantDataVector>(C))
167 // Now we know that the input and output vectors are both integer vectors
168 // of the same size, and that their #elements is not the same. Do the
169 // conversion here, which depends on whether the input or output has
171 bool isLittleEndian = TD.isLittleEndian();
173 SmallVector<Constant*, 32> Result;
174 if (NumDstElt < NumSrcElt) {
175 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
176 Constant *Zero = Constant::getNullValue(DstEltTy);
177 unsigned Ratio = NumSrcElt/NumDstElt;
178 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
180 for (unsigned i = 0; i != NumDstElt; ++i) {
181 // Build each element of the result.
182 Constant *Elt = Zero;
183 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
184 for (unsigned j = 0; j != Ratio; ++j) {
185 Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
186 if (!Src) // Reject constantexpr elements.
187 return ConstantExpr::getBitCast(C, DestTy);
189 // Zero extend the element to the right size.
190 Src = ConstantExpr::getZExt(Src, Elt->getType());
192 // Shift it to the right place, depending on endianness.
193 Src = ConstantExpr::getShl(Src,
194 ConstantInt::get(Src->getType(), ShiftAmt));
195 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
198 Elt = ConstantExpr::getOr(Elt, Src);
200 Result.push_back(Elt);
202 return ConstantVector::get(Result);
205 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
206 unsigned Ratio = NumDstElt/NumSrcElt;
207 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
209 // Loop over each source value, expanding into multiple results.
210 for (unsigned i = 0; i != NumSrcElt; ++i) {
211 Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
212 if (!Src) // Reject constantexpr elements.
213 return ConstantExpr::getBitCast(C, DestTy);
215 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
216 for (unsigned j = 0; j != Ratio; ++j) {
217 // Shift the piece of the value into the right place, depending on
219 Constant *Elt = ConstantExpr::getLShr(Src,
220 ConstantInt::get(Src->getType(), ShiftAmt));
221 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
223 // Truncate and remember this piece.
224 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
228 return ConstantVector::get(Result);
232 /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
233 /// from a global, return the global and the constant. Because of
234 /// constantexprs, this function is recursive.
235 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
236 APInt &Offset, const DataLayout &TD) {
237 // Trivial case, constant is the global.
238 if ((GV = dyn_cast<GlobalValue>(C))) {
239 unsigned BitWidth = TD.getPointerTypeSizeInBits(GV->getType());
240 Offset = APInt(BitWidth, 0);
244 // Otherwise, if this isn't a constant expr, bail out.
245 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
246 if (!CE) return false;
248 // Look through ptr->int and ptr->ptr casts.
249 if (CE->getOpcode() == Instruction::PtrToInt ||
250 CE->getOpcode() == Instruction::BitCast)
251 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
253 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
254 GEPOperator *GEP = dyn_cast<GEPOperator>(CE);
258 unsigned BitWidth = TD.getPointerTypeSizeInBits(GEP->getType());
259 APInt TmpOffset(BitWidth, 0);
261 // If the base isn't a global+constant, we aren't either.
262 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, TD))
265 // Otherwise, add any offset that our operands provide.
266 if (!GEP->accumulateConstantOffset(TD, TmpOffset))
273 /// ReadDataFromGlobal - Recursive helper to read bits out of global. C is the
274 /// constant being copied out of. ByteOffset is an offset into C. CurPtr is the
275 /// pointer to copy results into and BytesLeft is the number of bytes left in
276 /// the CurPtr buffer. TD is the target data.
277 static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
278 unsigned char *CurPtr, unsigned BytesLeft,
279 const DataLayout &TD) {
280 assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
281 "Out of range access");
283 // If this element is zero or undefined, we can just return since *CurPtr is
285 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
288 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
289 if (CI->getBitWidth() > 64 ||
290 (CI->getBitWidth() & 7) != 0)
293 uint64_t Val = CI->getZExtValue();
294 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
296 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
298 if (!TD.isLittleEndian())
299 n = IntBytes - n - 1;
300 CurPtr[i] = (unsigned char)(Val >> (n * 8));
306 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
307 if (CFP->getType()->isDoubleTy()) {
308 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
309 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
311 if (CFP->getType()->isFloatTy()){
312 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
313 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
315 if (CFP->getType()->isHalfTy()){
316 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), TD);
317 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
322 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
323 const StructLayout *SL = TD.getStructLayout(CS->getType());
324 unsigned Index = SL->getElementContainingOffset(ByteOffset);
325 uint64_t CurEltOffset = SL->getElementOffset(Index);
326 ByteOffset -= CurEltOffset;
329 // If the element access is to the element itself and not to tail padding,
330 // read the bytes from the element.
331 uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
333 if (ByteOffset < EltSize &&
334 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
340 // Check to see if we read from the last struct element, if so we're done.
341 if (Index == CS->getType()->getNumElements())
344 // If we read all of the bytes we needed from this element we're done.
345 uint64_t NextEltOffset = SL->getElementOffset(Index);
347 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
350 // Move to the next element of the struct.
351 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
352 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
354 CurEltOffset = NextEltOffset;
359 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
360 isa<ConstantDataSequential>(C)) {
361 Type *EltTy = C->getType()->getSequentialElementType();
362 uint64_t EltSize = TD.getTypeAllocSize(EltTy);
363 uint64_t Index = ByteOffset / EltSize;
364 uint64_t Offset = ByteOffset - Index * EltSize;
366 if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
367 NumElts = AT->getNumElements();
369 NumElts = C->getType()->getVectorNumElements();
371 for (; Index != NumElts; ++Index) {
372 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
376 uint64_t BytesWritten = EltSize - Offset;
377 assert(BytesWritten <= EltSize && "Not indexing into this element?");
378 if (BytesWritten >= BytesLeft)
382 BytesLeft -= BytesWritten;
383 CurPtr += BytesWritten;
388 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
389 if (CE->getOpcode() == Instruction::IntToPtr &&
390 CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getType())) {
391 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
396 // Otherwise, unknown initializer type.
400 static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
401 const DataLayout &TD) {
402 PointerType *PTy = cast<PointerType>(C->getType());
403 Type *LoadTy = PTy->getElementType();
404 IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
406 // If this isn't an integer load we can't fold it directly.
408 unsigned AS = PTy->getAddressSpace();
410 // If this is a float/double load, we can try folding it as an int32/64 load
411 // and then bitcast the result. This can be useful for union cases. Note
412 // that address spaces don't matter here since we're not going to result in
413 // an actual new load.
415 if (LoadTy->isHalfTy())
416 MapTy = Type::getInt16PtrTy(C->getContext(), AS);
417 else if (LoadTy->isFloatTy())
418 MapTy = Type::getInt32PtrTy(C->getContext(), AS);
419 else if (LoadTy->isDoubleTy())
420 MapTy = Type::getInt64PtrTy(C->getContext(), AS);
421 else if (LoadTy->isVectorTy()) {
422 MapTy = PointerType::getIntNPtrTy(C->getContext(),
423 TD.getTypeAllocSizeInBits(LoadTy),
428 C = FoldBitCast(C, MapTy, TD);
429 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
430 return FoldBitCast(Res, LoadTy, TD);
434 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
435 if (BytesLoaded > 32 || BytesLoaded == 0)
440 if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
443 GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
444 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
445 !GV->getInitializer()->getType()->isSized())
448 // If we're loading off the beginning of the global, some bytes may be valid,
449 // but we don't try to handle this.
450 if (Offset.isNegative())
453 // If we're not accessing anything in this constant, the result is undefined.
454 if (Offset.getZExtValue() >=
455 TD.getTypeAllocSize(GV->getInitializer()->getType()))
456 return UndefValue::get(IntType);
458 unsigned char RawBytes[32] = {0};
459 if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
463 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
464 if (TD.isLittleEndian()) {
465 ResultVal = RawBytes[BytesLoaded - 1];
466 for (unsigned i = 1; i != BytesLoaded; ++i) {
468 ResultVal |= RawBytes[BytesLoaded - 1 - i];
471 ResultVal = RawBytes[0];
472 for (unsigned i = 1; i != BytesLoaded; ++i) {
474 ResultVal |= RawBytes[i];
478 return ConstantInt::get(IntType->getContext(), ResultVal);
481 static Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE,
482 const DataLayout *DL) {
485 auto *DestPtrTy = dyn_cast<PointerType>(CE->getType());
488 Type *DestTy = DestPtrTy->getElementType();
490 Constant *C = ConstantFoldLoadFromConstPtr(CE->getOperand(0), DL);
495 Type *SrcTy = C->getType();
497 // If the type sizes are the same and a cast is legal, just directly
498 // cast the constant.
499 if (DL->getTypeSizeInBits(DestTy) == DL->getTypeSizeInBits(SrcTy)) {
500 Instruction::CastOps Cast = Instruction::BitCast;
501 // If we are going from a pointer to int or vice versa, we spell the cast
503 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
504 Cast = Instruction::IntToPtr;
505 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
506 Cast = Instruction::PtrToInt;
508 if (CastInst::castIsValid(Cast, C, DestTy))
509 return ConstantExpr::getCast(Cast, C, DestTy);
512 // If this isn't an aggregate type, there is nothing we can do to drill down
513 // and find a bitcastable constant.
514 if (!SrcTy->isAggregateType())
517 // We're simulating a load through a pointer that was bitcast to point to
518 // a different type, so we can try to walk down through the initial
519 // elements of an aggregate to see if some part of th e aggregate is
520 // castable to implement the "load" semantic model.
521 C = C->getAggregateElement(0u);
527 /// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
528 /// produce if it is constant and determinable. If this is not determinable,
530 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
531 const DataLayout *TD) {
532 // First, try the easy cases:
533 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
534 if (GV->isConstant() && GV->hasDefinitiveInitializer())
535 return GV->getInitializer();
537 // If the loaded value isn't a constant expr, we can't handle it.
538 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
542 if (CE->getOpcode() == Instruction::GetElementPtr) {
543 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
544 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
546 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
552 if (CE->getOpcode() == Instruction::BitCast)
553 if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, TD))
556 // Instead of loading constant c string, use corresponding integer value
557 // directly if string length is small enough.
559 if (TD && getConstantStringInfo(CE, Str) && !Str.empty()) {
560 unsigned StrLen = Str.size();
561 Type *Ty = cast<PointerType>(CE->getType())->getElementType();
562 unsigned NumBits = Ty->getPrimitiveSizeInBits();
563 // Replace load with immediate integer if the result is an integer or fp
565 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
566 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
567 APInt StrVal(NumBits, 0);
568 APInt SingleChar(NumBits, 0);
569 if (TD->isLittleEndian()) {
570 for (signed i = StrLen-1; i >= 0; i--) {
571 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
572 StrVal = (StrVal << 8) | SingleChar;
575 for (unsigned i = 0; i < StrLen; i++) {
576 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
577 StrVal = (StrVal << 8) | SingleChar;
579 // Append NULL at the end.
581 StrVal = (StrVal << 8) | SingleChar;
584 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
585 if (Ty->isFloatingPointTy())
586 Res = ConstantExpr::getBitCast(Res, Ty);
591 // If this load comes from anywhere in a constant global, and if the global
592 // is all undef or zero, we know what it loads.
593 if (GlobalVariable *GV =
594 dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
595 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
596 Type *ResTy = cast<PointerType>(C->getType())->getElementType();
597 if (GV->getInitializer()->isNullValue())
598 return Constant::getNullValue(ResTy);
599 if (isa<UndefValue>(GV->getInitializer()))
600 return UndefValue::get(ResTy);
604 // Try hard to fold loads from bitcasted strange and non-type-safe things.
606 return FoldReinterpretLoadFromConstPtr(CE, *TD);
610 static Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout *TD){
611 if (LI->isVolatile()) return nullptr;
613 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
614 return ConstantFoldLoadFromConstPtr(C, TD);
619 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
620 /// Attempt to symbolically evaluate the result of a binary operator merging
621 /// these together. If target data info is available, it is provided as DL,
622 /// otherwise DL is null.
623 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
624 Constant *Op1, const DataLayout *DL){
627 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
628 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
632 if (Opc == Instruction::And && DL) {
633 unsigned BitWidth = DL->getTypeSizeInBits(Op0->getType()->getScalarType());
634 APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
635 APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
636 computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
637 computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
638 if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
639 // All the bits of Op0 that the 'and' could be masking are already zero.
642 if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
643 // All the bits of Op1 that the 'and' could be masking are already zero.
647 APInt KnownZero = KnownZero0 | KnownZero1;
648 APInt KnownOne = KnownOne0 & KnownOne1;
649 if ((KnownZero | KnownOne).isAllOnesValue()) {
650 return ConstantInt::get(Op0->getType(), KnownOne);
654 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
655 // constant. This happens frequently when iterating over a global array.
656 if (Opc == Instruction::Sub && DL) {
657 GlobalValue *GV1, *GV2;
660 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *DL))
661 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *DL) &&
663 unsigned OpSize = DL->getTypeSizeInBits(Op0->getType());
665 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
666 // PtrToInt may change the bitwidth so we have convert to the right size
668 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
669 Offs2.zextOrTrunc(OpSize));
676 /// CastGEPIndices - If array indices are not pointer-sized integers,
677 /// explicitly cast them so that they aren't implicitly casted by the
679 static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
680 Type *ResultTy, const DataLayout *TD,
681 const TargetLibraryInfo *TLI) {
685 Type *IntPtrTy = TD->getIntPtrType(ResultTy);
688 SmallVector<Constant*, 32> NewIdxs;
689 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
691 !isa<StructType>(GetElementPtrInst::getIndexedType(
693 Ops.slice(1, i - 1)))) &&
694 Ops[i]->getType() != IntPtrTy) {
696 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
702 NewIdxs.push_back(Ops[i]);
708 Constant *C = ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
709 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
710 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD, TLI))
717 /// Strip the pointer casts, but preserve the address space information.
718 static Constant* StripPtrCastKeepAS(Constant* Ptr) {
719 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
720 PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
721 Ptr = Ptr->stripPointerCasts();
722 PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
724 // Preserve the address space number of the pointer.
725 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
726 NewPtrTy = NewPtrTy->getElementType()->getPointerTo(
727 OldPtrTy->getAddressSpace());
728 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
733 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
734 /// 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 /// ConstantFoldInstruction - 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 SmallPtrSet<ConstantExpr *, 4> &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))
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 /// ConstantFoldConstantExpression - 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 /// ConstantFoldInstOperands - 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 /// ConstantFoldCompareInstOperands - 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.
1115 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
1116 Constant *Ops0, Constant *Ops1,
1117 const DataLayout *TD,
1118 const TargetLibraryInfo *TLI) {
1119 // fold: icmp (inttoptr x), null -> icmp x, 0
1120 // fold: icmp (ptrtoint x), 0 -> icmp x, null
1121 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1122 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1124 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
1125 // around to know if bit truncation is happening.
1126 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1127 if (TD && Ops1->isNullValue()) {
1128 if (CE0->getOpcode() == Instruction::IntToPtr) {
1129 Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
1130 // Convert the integer value to the right size to ensure we get the
1131 // proper extension or truncation.
1132 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1134 Constant *Null = Constant::getNullValue(C->getType());
1135 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
1138 // Only do this transformation if the int is intptrty in size, otherwise
1139 // there is a truncation or extension that we aren't modeling.
1140 if (CE0->getOpcode() == Instruction::PtrToInt) {
1141 Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
1142 if (CE0->getType() == IntPtrTy) {
1143 Constant *C = CE0->getOperand(0);
1144 Constant *Null = Constant::getNullValue(C->getType());
1145 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
1150 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1151 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
1152 if (CE0->getOpcode() == Instruction::IntToPtr) {
1153 Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
1155 // Convert the integer value to the right size to ensure we get the
1156 // proper extension or truncation.
1157 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1159 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1161 return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD, TLI);
1164 // Only do this transformation if the int is intptrty in size, otherwise
1165 // there is a truncation or extension that we aren't modeling.
1166 if (CE0->getOpcode() == Instruction::PtrToInt) {
1167 Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
1168 if (CE0->getType() == IntPtrTy &&
1169 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1170 return ConstantFoldCompareInstOperands(Predicate,
1180 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1181 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1182 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1183 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1185 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,
1188 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,
1191 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1192 Constant *Ops[] = { LHS, RHS };
1193 return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD, TLI);
1197 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1201 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
1202 /// getelementptr constantexpr, return the constant value being addressed by the
1203 /// constant expression, or null if something is funny and we can't decide.
1204 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
1206 if (!CE->getOperand(1)->isNullValue())
1207 return nullptr; // Do not allow stepping over the value!
1209 // Loop over all of the operands, tracking down which value we are
1211 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1212 C = C->getAggregateElement(CE->getOperand(i));
1219 /// ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr
1220 /// indices (with an *implied* zero pointer index that is not in the list),
1221 /// return the constant value being addressed by a virtual load, or null if
1222 /// something is funny and we can't decide.
1223 Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1224 ArrayRef<Constant*> Indices) {
1225 // Loop over all of the operands, tracking down which value we are
1227 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1228 C = C->getAggregateElement(Indices[i]);
1236 //===----------------------------------------------------------------------===//
1237 // Constant Folding for Calls
1240 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
1241 /// the specified function.
1242 bool llvm::canConstantFoldCallTo(const Function *F) {
1243 switch (F->getIntrinsicID()) {
1244 case Intrinsic::fabs:
1245 case Intrinsic::log:
1246 case Intrinsic::log2:
1247 case Intrinsic::log10:
1248 case Intrinsic::exp:
1249 case Intrinsic::exp2:
1250 case Intrinsic::floor:
1251 case Intrinsic::ceil:
1252 case Intrinsic::sqrt:
1253 case Intrinsic::pow:
1254 case Intrinsic::powi:
1255 case Intrinsic::bswap:
1256 case Intrinsic::ctpop:
1257 case Intrinsic::ctlz:
1258 case Intrinsic::cttz:
1259 case Intrinsic::fma:
1260 case Intrinsic::fmuladd:
1261 case Intrinsic::copysign:
1262 case Intrinsic::round:
1263 case Intrinsic::sadd_with_overflow:
1264 case Intrinsic::uadd_with_overflow:
1265 case Intrinsic::ssub_with_overflow:
1266 case Intrinsic::usub_with_overflow:
1267 case Intrinsic::smul_with_overflow:
1268 case Intrinsic::umul_with_overflow:
1269 case Intrinsic::convert_from_fp16:
1270 case Intrinsic::convert_to_fp16:
1271 case Intrinsic::x86_sse_cvtss2si:
1272 case Intrinsic::x86_sse_cvtss2si64:
1273 case Intrinsic::x86_sse_cvttss2si:
1274 case Intrinsic::x86_sse_cvttss2si64:
1275 case Intrinsic::x86_sse2_cvtsd2si:
1276 case Intrinsic::x86_sse2_cvtsd2si64:
1277 case Intrinsic::x86_sse2_cvttsd2si:
1278 case Intrinsic::x86_sse2_cvttsd2si64:
1287 StringRef Name = F->getName();
1289 // In these cases, the check of the length is required. We don't want to
1290 // return true for a name like "cos\0blah" which strcmp would return equal to
1291 // "cos", but has length 8.
1293 default: return false;
1295 return Name == "acos" || Name == "asin" || Name == "atan" || Name =="atan2";
1297 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
1299 return Name == "exp" || Name == "exp2";
1301 return Name == "fabs" || Name == "fmod" || Name == "floor";
1303 return Name == "log" || Name == "log10";
1305 return Name == "pow";
1307 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1308 Name == "sinf" || Name == "sqrtf";
1310 return Name == "tan" || Name == "tanh";
1314 static Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1315 if (Ty->isHalfTy()) {
1318 APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1319 return ConstantFP::get(Ty->getContext(), APF);
1321 if (Ty->isFloatTy())
1322 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1323 if (Ty->isDoubleTy())
1324 return ConstantFP::get(Ty->getContext(), APFloat(V));
1325 llvm_unreachable("Can only constant fold half/float/double");
1330 /// llvm_fenv_clearexcept - Clear the floating-point exception state.
1331 static inline void llvm_fenv_clearexcept() {
1332 #if defined(USE_FENV) && HAVE_DECL_FE_ALL_EXCEPT
1333 feclearexcept(FE_ALL_EXCEPT);
1338 /// llvm_fenv_testexcept - Test if a floating-point exception was raised.
1339 static inline bool llvm_fenv_testexcept() {
1340 int errno_val = errno;
1341 if (errno_val == ERANGE || errno_val == EDOM)
1343 #if defined(USE_FENV) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
1344 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1351 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
1353 llvm_fenv_clearexcept();
1355 if (llvm_fenv_testexcept()) {
1356 llvm_fenv_clearexcept();
1360 return GetConstantFoldFPValue(V, Ty);
1363 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1364 double V, double W, Type *Ty) {
1365 llvm_fenv_clearexcept();
1367 if (llvm_fenv_testexcept()) {
1368 llvm_fenv_clearexcept();
1372 return GetConstantFoldFPValue(V, Ty);
1375 /// ConstantFoldConvertToInt - Attempt to an SSE floating point to integer
1376 /// conversion of a constant floating point. If roundTowardZero is false, the
1377 /// default IEEE rounding is used (toward nearest, ties to even). This matches
1378 /// the behavior of the non-truncating SSE instructions in the default rounding
1379 /// mode. The desired integer type Ty is used to select how many bits are
1380 /// available for the result. Returns null if the conversion cannot be
1381 /// performed, otherwise returns the Constant value resulting from the
1383 static Constant *ConstantFoldConvertToInt(const APFloat &Val,
1384 bool roundTowardZero, Type *Ty) {
1385 // All of these conversion intrinsics form an integer of at most 64bits.
1386 unsigned ResultWidth = Ty->getIntegerBitWidth();
1387 assert(ResultWidth <= 64 &&
1388 "Can only constant fold conversions to 64 and 32 bit ints");
1391 bool isExact = false;
1392 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1393 : APFloat::rmNearestTiesToEven;
1394 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1395 /*isSigned=*/true, mode,
1397 if (status != APFloat::opOK && status != APFloat::opInexact)
1399 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1402 static double getValueAsDouble(ConstantFP *Op) {
1403 Type *Ty = Op->getType();
1405 if (Ty->isFloatTy())
1406 return Op->getValueAPF().convertToFloat();
1408 if (Ty->isDoubleTy())
1409 return Op->getValueAPF().convertToDouble();
1412 APFloat APF = Op->getValueAPF();
1413 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1414 return APF.convertToDouble();
1417 static Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID,
1418 Type *Ty, ArrayRef<Constant *> Operands,
1419 const TargetLibraryInfo *TLI) {
1420 if (Operands.size() == 1) {
1421 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
1422 if (IntrinsicID == Intrinsic::convert_to_fp16) {
1423 APFloat Val(Op->getValueAPF());
1426 Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1428 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1431 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1434 if (IntrinsicID == Intrinsic::round) {
1435 APFloat V = Op->getValueAPF();
1436 V.roundToIntegral(APFloat::rmNearestTiesToAway);
1437 return ConstantFP::get(Ty->getContext(), V);
1440 /// We only fold functions with finite arguments. Folding NaN and inf is
1441 /// likely to be aborted with an exception anyway, and some host libms
1442 /// have known errors raising exceptions.
1443 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1446 /// Currently APFloat versions of these functions do not exist, so we use
1447 /// the host native double versions. Float versions are not called
1448 /// directly but for all these it is true (float)(f((double)arg)) ==
1449 /// f(arg). Long double not supported yet.
1450 double V = getValueAsDouble(Op);
1452 switch (IntrinsicID) {
1454 case Intrinsic::fabs:
1455 return ConstantFoldFP(fabs, V, Ty);
1457 case Intrinsic::log2:
1458 return ConstantFoldFP(log2, V, Ty);
1461 case Intrinsic::log:
1462 return ConstantFoldFP(log, V, Ty);
1465 case Intrinsic::log10:
1466 return ConstantFoldFP(log10, V, Ty);
1469 case Intrinsic::exp:
1470 return ConstantFoldFP(exp, V, Ty);
1473 case Intrinsic::exp2:
1474 return ConstantFoldFP(exp2, V, Ty);
1476 case Intrinsic::floor:
1477 return ConstantFoldFP(floor, V, Ty);
1478 case Intrinsic::ceil:
1479 return ConstantFoldFP(ceil, V, Ty);
1487 if (Name == "acos" && TLI->has(LibFunc::acos))
1488 return ConstantFoldFP(acos, V, Ty);
1489 else if (Name == "asin" && TLI->has(LibFunc::asin))
1490 return ConstantFoldFP(asin, V, Ty);
1491 else if (Name == "atan" && TLI->has(LibFunc::atan))
1492 return ConstantFoldFP(atan, V, Ty);
1495 if (Name == "ceil" && TLI->has(LibFunc::ceil))
1496 return ConstantFoldFP(ceil, V, Ty);
1497 else if (Name == "cos" && TLI->has(LibFunc::cos))
1498 return ConstantFoldFP(cos, V, Ty);
1499 else if (Name == "cosh" && TLI->has(LibFunc::cosh))
1500 return ConstantFoldFP(cosh, V, Ty);
1501 else if (Name == "cosf" && TLI->has(LibFunc::cosf))
1502 return ConstantFoldFP(cos, V, Ty);
1505 if (Name == "exp" && TLI->has(LibFunc::exp))
1506 return ConstantFoldFP(exp, V, Ty);
1508 if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
1509 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1511 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1515 if (Name == "fabs" && TLI->has(LibFunc::fabs))
1516 return ConstantFoldFP(fabs, V, Ty);
1517 else if (Name == "floor" && TLI->has(LibFunc::floor))
1518 return ConstantFoldFP(floor, V, Ty);
1521 if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
1522 return ConstantFoldFP(log, V, Ty);
1523 else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
1524 return ConstantFoldFP(log10, V, Ty);
1525 else if (IntrinsicID == Intrinsic::sqrt &&
1526 (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
1528 return ConstantFoldFP(sqrt, V, Ty);
1530 return Constant::getNullValue(Ty);
1534 if (Name == "sin" && TLI->has(LibFunc::sin))
1535 return ConstantFoldFP(sin, V, Ty);
1536 else if (Name == "sinh" && TLI->has(LibFunc::sinh))
1537 return ConstantFoldFP(sinh, V, Ty);
1538 else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
1539 return ConstantFoldFP(sqrt, V, Ty);
1540 else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
1541 return ConstantFoldFP(sqrt, V, Ty);
1542 else if (Name == "sinf" && TLI->has(LibFunc::sinf))
1543 return ConstantFoldFP(sin, V, Ty);
1546 if (Name == "tan" && TLI->has(LibFunc::tan))
1547 return ConstantFoldFP(tan, V, Ty);
1548 else if (Name == "tanh" && TLI->has(LibFunc::tanh))
1549 return ConstantFoldFP(tanh, V, Ty);
1557 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
1558 switch (IntrinsicID) {
1559 case Intrinsic::bswap:
1560 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
1561 case Intrinsic::ctpop:
1562 return ConstantInt::get(Ty, Op->getValue().countPopulation());
1563 case Intrinsic::convert_from_fp16: {
1564 APFloat Val(APFloat::IEEEhalf, Op->getValue());
1567 APFloat::opStatus status =
1568 Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
1570 // Conversion is always precise.
1572 assert(status == APFloat::opOK && !lost &&
1573 "Precision lost during fp16 constfolding");
1575 return ConstantFP::get(Ty->getContext(), Val);
1582 // Support ConstantVector in case we have an Undef in the top.
1583 if (isa<ConstantVector>(Operands[0]) ||
1584 isa<ConstantDataVector>(Operands[0])) {
1585 Constant *Op = cast<Constant>(Operands[0]);
1586 switch (IntrinsicID) {
1588 case Intrinsic::x86_sse_cvtss2si:
1589 case Intrinsic::x86_sse_cvtss2si64:
1590 case Intrinsic::x86_sse2_cvtsd2si:
1591 case Intrinsic::x86_sse2_cvtsd2si64:
1592 if (ConstantFP *FPOp =
1593 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1594 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1595 /*roundTowardZero=*/false, Ty);
1596 case Intrinsic::x86_sse_cvttss2si:
1597 case Intrinsic::x86_sse_cvttss2si64:
1598 case Intrinsic::x86_sse2_cvttsd2si:
1599 case Intrinsic::x86_sse2_cvttsd2si64:
1600 if (ConstantFP *FPOp =
1601 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1602 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1603 /*roundTowardZero=*/true, Ty);
1607 if (isa<UndefValue>(Operands[0])) {
1608 if (IntrinsicID == Intrinsic::bswap)
1616 if (Operands.size() == 2) {
1617 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1618 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1620 double Op1V = getValueAsDouble(Op1);
1622 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1623 if (Op2->getType() != Op1->getType())
1626 double Op2V = getValueAsDouble(Op2);
1627 if (IntrinsicID == Intrinsic::pow) {
1628 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1630 if (IntrinsicID == Intrinsic::copysign) {
1631 APFloat V1 = Op1->getValueAPF();
1632 APFloat V2 = Op2->getValueAPF();
1634 return ConstantFP::get(Ty->getContext(), V1);
1638 if (Name == "pow" && TLI->has(LibFunc::pow))
1639 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1640 if (Name == "fmod" && TLI->has(LibFunc::fmod))
1641 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1642 if (Name == "atan2" && TLI->has(LibFunc::atan2))
1643 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1644 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1645 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1646 return ConstantFP::get(Ty->getContext(),
1647 APFloat((float)std::pow((float)Op1V,
1648 (int)Op2C->getZExtValue())));
1649 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1650 return ConstantFP::get(Ty->getContext(),
1651 APFloat((float)std::pow((float)Op1V,
1652 (int)Op2C->getZExtValue())));
1653 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1654 return ConstantFP::get(Ty->getContext(),
1655 APFloat((double)std::pow((double)Op1V,
1656 (int)Op2C->getZExtValue())));
1661 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1662 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1663 switch (IntrinsicID) {
1665 case Intrinsic::sadd_with_overflow:
1666 case Intrinsic::uadd_with_overflow:
1667 case Intrinsic::ssub_with_overflow:
1668 case Intrinsic::usub_with_overflow:
1669 case Intrinsic::smul_with_overflow:
1670 case Intrinsic::umul_with_overflow: {
1673 switch (IntrinsicID) {
1674 default: llvm_unreachable("Invalid case");
1675 case Intrinsic::sadd_with_overflow:
1676 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1678 case Intrinsic::uadd_with_overflow:
1679 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1681 case Intrinsic::ssub_with_overflow:
1682 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1684 case Intrinsic::usub_with_overflow:
1685 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1687 case Intrinsic::smul_with_overflow:
1688 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1690 case Intrinsic::umul_with_overflow:
1691 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1695 ConstantInt::get(Ty->getContext(), Res),
1696 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
1698 return ConstantStruct::get(cast<StructType>(Ty), Ops);
1700 case Intrinsic::cttz:
1701 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1702 return UndefValue::get(Ty);
1703 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1704 case Intrinsic::ctlz:
1705 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1706 return UndefValue::get(Ty);
1707 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
1716 if (Operands.size() != 3)
1719 if (const ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1720 if (const ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1721 if (const ConstantFP *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
1722 switch (IntrinsicID) {
1724 case Intrinsic::fma:
1725 case Intrinsic::fmuladd: {
1726 APFloat V = Op1->getValueAPF();
1727 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1729 APFloat::rmNearestTiesToEven);
1730 if (s != APFloat::opInvalidOp)
1731 return ConstantFP::get(Ty->getContext(), V);
1743 static Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1745 ArrayRef<Constant *> Operands,
1746 const TargetLibraryInfo *TLI) {
1747 SmallVector<Constant *, 4> Result(VTy->getNumElements());
1748 SmallVector<Constant *, 4> Lane(Operands.size());
1749 Type *Ty = VTy->getElementType();
1751 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1752 // Gather a column of constants.
1753 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1754 Constant *Agg = Operands[J]->getAggregateElement(I);
1761 // Use the regular scalar folding to simplify this column.
1762 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1768 return ConstantVector::get(Result);
1771 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
1772 /// with the specified arguments, returning null if unsuccessful.
1774 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1775 const TargetLibraryInfo *TLI) {
1778 StringRef Name = F->getName();
1780 Type *Ty = F->getReturnType();
1782 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1783 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, TLI);
1785 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);