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/APFloat.h"
21 #include "llvm/ADT/APInt.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/Analysis/TargetLibraryInfo.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/Config/config.h"
30 #include "llvm/IR/Constant.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalValue.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/InstrTypes.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/IR/Value.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/KnownBits.h"
46 #include "llvm/Support/MathExtras.h"
58 //===----------------------------------------------------------------------===//
59 // Constant Folding internal helper functions
60 //===----------------------------------------------------------------------===//
62 static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
63 Constant *C, Type *SrcEltTy,
65 const DataLayout &DL) {
66 // Now that we know that the input value is a vector of integers, just shift
67 // and insert them into our result.
68 unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
69 for (unsigned i = 0; i != NumSrcElts; ++i) {
71 if (DL.isLittleEndian())
72 Element = C->getAggregateElement(NumSrcElts - i - 1);
74 Element = C->getAggregateElement(i);
76 if (Element && isa<UndefValue>(Element)) {
81 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
83 return ConstantExpr::getBitCast(C, DestTy);
86 Result |= ElementCI->getValue().zextOrSelf(Result.getBitWidth());
92 /// Constant fold bitcast, symbolically evaluating it with DataLayout.
93 /// This always returns a non-null constant, but it may be a
94 /// ConstantExpr if unfoldable.
95 Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
96 // Catch the obvious splat cases.
97 if (C->isNullValue() && !DestTy->isX86_MMXTy())
98 return Constant::getNullValue(DestTy);
99 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
100 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
101 return Constant::getAllOnesValue(DestTy);
103 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
104 // Handle a vector->scalar integer/fp cast.
105 if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) {
106 unsigned NumSrcElts = VTy->getNumElements();
107 Type *SrcEltTy = VTy->getElementType();
109 // If the vector is a vector of floating point, convert it to vector of int
110 // to simplify things.
111 if (SrcEltTy->isFloatingPointTy()) {
112 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
114 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
115 // Ask IR to do the conversion now that #elts line up.
116 C = ConstantExpr::getBitCast(C, SrcIVTy);
119 APInt Result(DL.getTypeSizeInBits(DestTy), 0);
120 if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C,
121 SrcEltTy, NumSrcElts, DL))
124 if (isa<IntegerType>(DestTy))
125 return ConstantInt::get(DestTy, Result);
127 APFloat FP(DestTy->getFltSemantics(), Result);
128 return ConstantFP::get(DestTy->getContext(), FP);
132 // The code below only handles casts to vectors currently.
133 auto *DestVTy = dyn_cast<VectorType>(DestTy);
135 return ConstantExpr::getBitCast(C, DestTy);
137 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
138 // vector so the code below can handle it uniformly.
139 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
140 Constant *Ops = C; // don't take the address of C!
141 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
144 // If this is a bitcast from constant vector -> vector, fold it.
145 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
146 return ConstantExpr::getBitCast(C, DestTy);
148 // If the element types match, IR can fold it.
149 unsigned NumDstElt = DestVTy->getNumElements();
150 unsigned NumSrcElt = C->getType()->getVectorNumElements();
151 if (NumDstElt == NumSrcElt)
152 return ConstantExpr::getBitCast(C, DestTy);
154 Type *SrcEltTy = C->getType()->getVectorElementType();
155 Type *DstEltTy = DestVTy->getElementType();
157 // Otherwise, we're changing the number of elements in a vector, which
158 // requires endianness information to do the right thing. For example,
159 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
160 // folds to (little endian):
161 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
162 // and to (big endian):
163 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
165 // First thing is first. We only want to think about integer here, so if
166 // we have something in FP form, recast it as integer.
167 if (DstEltTy->isFloatingPointTy()) {
168 // Fold to an vector of integers with same size as our FP type.
169 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
171 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
172 // Recursively handle this integer conversion, if possible.
173 C = FoldBitCast(C, DestIVTy, DL);
175 // Finally, IR can handle this now that #elts line up.
176 return ConstantExpr::getBitCast(C, DestTy);
179 // Okay, we know the destination is integer, if the input is FP, convert
180 // it to integer first.
181 if (SrcEltTy->isFloatingPointTy()) {
182 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
184 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
185 // Ask IR to do the conversion now that #elts line up.
186 C = ConstantExpr::getBitCast(C, SrcIVTy);
187 // If IR wasn't able to fold it, bail out.
188 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
189 !isa<ConstantDataVector>(C))
193 // Now we know that the input and output vectors are both integer vectors
194 // of the same size, and that their #elements is not the same. Do the
195 // conversion here, which depends on whether the input or output has
197 bool isLittleEndian = DL.isLittleEndian();
199 SmallVector<Constant*, 32> Result;
200 if (NumDstElt < NumSrcElt) {
201 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
202 Constant *Zero = Constant::getNullValue(DstEltTy);
203 unsigned Ratio = NumSrcElt/NumDstElt;
204 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
206 for (unsigned i = 0; i != NumDstElt; ++i) {
207 // Build each element of the result.
208 Constant *Elt = Zero;
209 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
210 for (unsigned j = 0; j != Ratio; ++j) {
211 Constant *Src = C->getAggregateElement(SrcElt++);
212 if (Src && isa<UndefValue>(Src))
213 Src = Constant::getNullValue(C->getType()->getVectorElementType());
215 Src = dyn_cast_or_null<ConstantInt>(Src);
216 if (!Src) // Reject constantexpr elements.
217 return ConstantExpr::getBitCast(C, DestTy);
219 // Zero extend the element to the right size.
220 Src = ConstantExpr::getZExt(Src, Elt->getType());
222 // Shift it to the right place, depending on endianness.
223 Src = ConstantExpr::getShl(Src,
224 ConstantInt::get(Src->getType(), ShiftAmt));
225 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
228 Elt = ConstantExpr::getOr(Elt, Src);
230 Result.push_back(Elt);
232 return ConstantVector::get(Result);
235 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
236 unsigned Ratio = NumDstElt/NumSrcElt;
237 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
239 // Loop over each source value, expanding into multiple results.
240 for (unsigned i = 0; i != NumSrcElt; ++i) {
241 auto *Element = C->getAggregateElement(i);
243 if (!Element) // Reject constantexpr elements.
244 return ConstantExpr::getBitCast(C, DestTy);
246 if (isa<UndefValue>(Element)) {
247 // Correctly Propagate undef values.
248 Result.append(Ratio, UndefValue::get(DstEltTy));
252 auto *Src = dyn_cast<ConstantInt>(Element);
254 return ConstantExpr::getBitCast(C, DestTy);
256 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
257 for (unsigned j = 0; j != Ratio; ++j) {
258 // Shift the piece of the value into the right place, depending on
260 Constant *Elt = ConstantExpr::getLShr(Src,
261 ConstantInt::get(Src->getType(), ShiftAmt));
262 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
264 // Truncate the element to an integer with the same pointer size and
265 // convert the element back to a pointer using a inttoptr.
266 if (DstEltTy->isPointerTy()) {
267 IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
268 Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
269 Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
273 // Truncate and remember this piece.
274 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
278 return ConstantVector::get(Result);
281 } // end anonymous namespace
283 /// If this constant is a constant offset from a global, return the global and
284 /// the constant. Because of constantexprs, this function is recursive.
285 bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
286 APInt &Offset, const DataLayout &DL) {
287 // Trivial case, constant is the global.
288 if ((GV = dyn_cast<GlobalValue>(C))) {
289 unsigned BitWidth = DL.getPointerTypeSizeInBits(GV->getType());
290 Offset = APInt(BitWidth, 0);
294 // Otherwise, if this isn't a constant expr, bail out.
295 auto *CE = dyn_cast<ConstantExpr>(C);
296 if (!CE) return false;
298 // Look through ptr->int and ptr->ptr casts.
299 if (CE->getOpcode() == Instruction::PtrToInt ||
300 CE->getOpcode() == Instruction::BitCast)
301 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
303 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
304 auto *GEP = dyn_cast<GEPOperator>(CE);
308 unsigned BitWidth = DL.getPointerTypeSizeInBits(GEP->getType());
309 APInt TmpOffset(BitWidth, 0);
311 // If the base isn't a global+constant, we aren't either.
312 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
315 // Otherwise, add any offset that our operands provide.
316 if (!GEP->accumulateConstantOffset(DL, TmpOffset))
325 /// Recursive helper to read bits out of global. C is the constant being copied
326 /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
327 /// results into and BytesLeft is the number of bytes left in
328 /// the CurPtr buffer. DL is the DataLayout.
329 bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
330 unsigned BytesLeft, const DataLayout &DL) {
331 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
332 "Out of range access");
334 // If this element is zero or undefined, we can just return since *CurPtr is
336 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
339 if (auto *CI = dyn_cast<ConstantInt>(C)) {
340 if (CI->getBitWidth() > 64 ||
341 (CI->getBitWidth() & 7) != 0)
344 uint64_t Val = CI->getZExtValue();
345 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
347 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
349 if (!DL.isLittleEndian())
350 n = IntBytes - n - 1;
351 CurPtr[i] = (unsigned char)(Val >> (n * 8));
357 if (auto *CFP = dyn_cast<ConstantFP>(C)) {
358 if (CFP->getType()->isDoubleTy()) {
359 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
360 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
362 if (CFP->getType()->isFloatTy()){
363 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
364 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
366 if (CFP->getType()->isHalfTy()){
367 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
368 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
373 if (auto *CS = dyn_cast<ConstantStruct>(C)) {
374 const StructLayout *SL = DL.getStructLayout(CS->getType());
375 unsigned Index = SL->getElementContainingOffset(ByteOffset);
376 uint64_t CurEltOffset = SL->getElementOffset(Index);
377 ByteOffset -= CurEltOffset;
380 // If the element access is to the element itself and not to tail padding,
381 // read the bytes from the element.
382 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
384 if (ByteOffset < EltSize &&
385 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
391 // Check to see if we read from the last struct element, if so we're done.
392 if (Index == CS->getType()->getNumElements())
395 // If we read all of the bytes we needed from this element we're done.
396 uint64_t NextEltOffset = SL->getElementOffset(Index);
398 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
401 // Move to the next element of the struct.
402 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
403 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
405 CurEltOffset = NextEltOffset;
410 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
411 isa<ConstantDataSequential>(C)) {
412 Type *EltTy = C->getType()->getSequentialElementType();
413 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
414 uint64_t Index = ByteOffset / EltSize;
415 uint64_t Offset = ByteOffset - Index * EltSize;
417 if (auto *AT = dyn_cast<ArrayType>(C->getType()))
418 NumElts = AT->getNumElements();
420 NumElts = C->getType()->getVectorNumElements();
422 for (; Index != NumElts; ++Index) {
423 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
427 uint64_t BytesWritten = EltSize - Offset;
428 assert(BytesWritten <= EltSize && "Not indexing into this element?");
429 if (BytesWritten >= BytesLeft)
433 BytesLeft -= BytesWritten;
434 CurPtr += BytesWritten;
439 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
440 if (CE->getOpcode() == Instruction::IntToPtr &&
441 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
442 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
447 // Otherwise, unknown initializer type.
451 Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
452 const DataLayout &DL) {
453 auto *PTy = cast<PointerType>(C->getType());
454 auto *IntType = dyn_cast<IntegerType>(LoadTy);
456 // If this isn't an integer load we can't fold it directly.
458 unsigned AS = PTy->getAddressSpace();
460 // If this is a float/double load, we can try folding it as an int32/64 load
461 // and then bitcast the result. This can be useful for union cases. Note
462 // that address spaces don't matter here since we're not going to result in
463 // an actual new load.
465 if (LoadTy->isHalfTy())
466 MapTy = Type::getInt16Ty(C->getContext());
467 else if (LoadTy->isFloatTy())
468 MapTy = Type::getInt32Ty(C->getContext());
469 else if (LoadTy->isDoubleTy())
470 MapTy = Type::getInt64Ty(C->getContext());
471 else if (LoadTy->isVectorTy()) {
472 MapTy = PointerType::getIntNTy(C->getContext(),
473 DL.getTypeAllocSizeInBits(LoadTy));
477 C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
478 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL))
479 return FoldBitCast(Res, LoadTy, DL);
483 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
484 if (BytesLoaded > 32 || BytesLoaded == 0)
489 if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL))
492 auto *GV = dyn_cast<GlobalVariable>(GVal);
493 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
494 !GV->getInitializer()->getType()->isSized())
497 int64_t Offset = OffsetAI.getSExtValue();
498 int64_t InitializerSize = DL.getTypeAllocSize(GV->getInitializer()->getType());
500 // If we're not accessing anything in this constant, the result is undefined.
501 if (Offset + BytesLoaded <= 0)
502 return UndefValue::get(IntType);
504 // If we're not accessing anything in this constant, the result is undefined.
505 if (Offset >= InitializerSize)
506 return UndefValue::get(IntType);
508 unsigned char RawBytes[32] = {0};
509 unsigned char *CurPtr = RawBytes;
510 unsigned BytesLeft = BytesLoaded;
512 // If we're loading off the beginning of the global, some bytes may be valid.
519 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL))
522 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
523 if (DL.isLittleEndian()) {
524 ResultVal = RawBytes[BytesLoaded - 1];
525 for (unsigned i = 1; i != BytesLoaded; ++i) {
527 ResultVal |= RawBytes[BytesLoaded - 1 - i];
530 ResultVal = RawBytes[0];
531 for (unsigned i = 1; i != BytesLoaded; ++i) {
533 ResultVal |= RawBytes[i];
537 return ConstantInt::get(IntType->getContext(), ResultVal);
540 Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE, Type *DestTy,
541 const DataLayout &DL) {
542 auto *SrcPtr = CE->getOperand(0);
543 auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
546 Type *SrcTy = SrcPtrTy->getPointerElementType();
548 Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
553 Type *SrcTy = C->getType();
555 // If the type sizes are the same and a cast is legal, just directly
556 // cast the constant.
557 if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
558 Instruction::CastOps Cast = Instruction::BitCast;
559 // If we are going from a pointer to int or vice versa, we spell the cast
561 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
562 Cast = Instruction::IntToPtr;
563 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
564 Cast = Instruction::PtrToInt;
566 if (CastInst::castIsValid(Cast, C, DestTy))
567 return ConstantExpr::getCast(Cast, C, DestTy);
570 // If this isn't an aggregate type, there is nothing we can do to drill down
571 // and find a bitcastable constant.
572 if (!SrcTy->isAggregateType())
575 // We're simulating a load through a pointer that was bitcast to point to
576 // a different type, so we can try to walk down through the initial
577 // elements of an aggregate to see if some part of th e aggregate is
578 // castable to implement the "load" semantic model.
579 C = C->getAggregateElement(0u);
585 } // end anonymous namespace
587 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
588 const DataLayout &DL) {
589 // First, try the easy cases:
590 if (auto *GV = dyn_cast<GlobalVariable>(C))
591 if (GV->isConstant() && GV->hasDefinitiveInitializer())
592 return GV->getInitializer();
594 if (auto *GA = dyn_cast<GlobalAlias>(C))
595 if (GA->getAliasee() && !GA->isInterposable())
596 return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
598 // If the loaded value isn't a constant expr, we can't handle it.
599 auto *CE = dyn_cast<ConstantExpr>(C);
603 if (CE->getOpcode() == Instruction::GetElementPtr) {
604 if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
605 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
607 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
613 if (CE->getOpcode() == Instruction::BitCast)
614 if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, Ty, DL))
617 // Instead of loading constant c string, use corresponding integer value
618 // directly if string length is small enough.
620 if (getConstantStringInfo(CE, Str) && !Str.empty()) {
621 size_t StrLen = Str.size();
622 unsigned NumBits = Ty->getPrimitiveSizeInBits();
623 // Replace load with immediate integer if the result is an integer or fp
625 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
626 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
627 APInt StrVal(NumBits, 0);
628 APInt SingleChar(NumBits, 0);
629 if (DL.isLittleEndian()) {
630 for (unsigned char C : reverse(Str.bytes())) {
631 SingleChar = static_cast<uint64_t>(C);
632 StrVal = (StrVal << 8) | SingleChar;
635 for (unsigned char C : Str.bytes()) {
636 SingleChar = static_cast<uint64_t>(C);
637 StrVal = (StrVal << 8) | SingleChar;
639 // Append NULL at the end.
641 StrVal = (StrVal << 8) | SingleChar;
644 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
645 if (Ty->isFloatingPointTy())
646 Res = ConstantExpr::getBitCast(Res, Ty);
651 // If this load comes from anywhere in a constant global, and if the global
652 // is all undef or zero, we know what it loads.
653 if (auto *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
654 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
655 if (GV->getInitializer()->isNullValue())
656 return Constant::getNullValue(Ty);
657 if (isa<UndefValue>(GV->getInitializer()))
658 return UndefValue::get(Ty);
662 // Try hard to fold loads from bitcasted strange and non-type-safe things.
663 return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
668 Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) {
669 if (LI->isVolatile()) return nullptr;
671 if (auto *C = dyn_cast<Constant>(LI->getOperand(0)))
672 return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
677 /// One of Op0/Op1 is a constant expression.
678 /// Attempt to symbolically evaluate the result of a binary operator merging
679 /// these together. If target data info is available, it is provided as DL,
680 /// otherwise DL is null.
681 Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
682 const DataLayout &DL) {
685 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
686 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
689 if (Opc == Instruction::And) {
690 KnownBits Known0 = computeKnownBits(Op0, DL);
691 KnownBits Known1 = computeKnownBits(Op1, DL);
692 if ((Known1.One | Known0.Zero).isAllOnesValue()) {
693 // All the bits of Op0 that the 'and' could be masking are already zero.
696 if ((Known0.One | Known1.Zero).isAllOnesValue()) {
697 // All the bits of Op1 that the 'and' could be masking are already zero.
701 Known0.Zero |= Known1.Zero;
702 Known0.One &= Known1.One;
703 if (Known0.isConstant())
704 return ConstantInt::get(Op0->getType(), Known0.getConstant());
707 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
708 // constant. This happens frequently when iterating over a global array.
709 if (Opc == Instruction::Sub) {
710 GlobalValue *GV1, *GV2;
713 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
714 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
715 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
717 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
718 // PtrToInt may change the bitwidth so we have convert to the right size
720 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
721 Offs2.zextOrTrunc(OpSize));
728 /// If array indices are not pointer-sized integers, explicitly cast them so
729 /// that they aren't implicitly casted by the getelementptr.
730 Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
731 Type *ResultTy, Optional<unsigned> InRangeIndex,
732 const DataLayout &DL, const TargetLibraryInfo *TLI) {
733 Type *IntPtrTy = DL.getIntPtrType(ResultTy);
734 Type *IntPtrScalarTy = IntPtrTy->getScalarType();
737 SmallVector<Constant*, 32> NewIdxs;
738 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
740 !isa<StructType>(GetElementPtrInst::getIndexedType(
741 SrcElemTy, Ops.slice(1, i - 1)))) &&
742 Ops[i]->getType()->getScalarType() != IntPtrScalarTy) {
744 Type *NewType = Ops[i]->getType()->isVectorTy()
746 : IntPtrTy->getScalarType();
747 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
753 NewIdxs.push_back(Ops[i]);
759 Constant *C = ConstantExpr::getGetElementPtr(
760 SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex);
761 if (Constant *Folded = ConstantFoldConstant(C, DL, TLI))
767 /// Strip the pointer casts, but preserve the address space information.
768 Constant* StripPtrCastKeepAS(Constant* Ptr, Type *&ElemTy) {
769 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
770 auto *OldPtrTy = cast<PointerType>(Ptr->getType());
771 Ptr = Ptr->stripPointerCasts();
772 auto *NewPtrTy = cast<PointerType>(Ptr->getType());
774 ElemTy = NewPtrTy->getPointerElementType();
776 // Preserve the address space number of the pointer.
777 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
778 NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
779 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
784 /// If we can symbolically evaluate the GEP constant expression, do so.
785 Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
786 ArrayRef<Constant *> Ops,
787 const DataLayout &DL,
788 const TargetLibraryInfo *TLI) {
789 const GEPOperator *InnermostGEP = GEP;
790 bool InBounds = GEP->isInBounds();
792 Type *SrcElemTy = GEP->getSourceElementType();
793 Type *ResElemTy = GEP->getResultElementType();
794 Type *ResTy = GEP->getType();
795 if (!SrcElemTy->isSized())
798 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy,
799 GEP->getInRangeIndex(), DL, TLI))
802 Constant *Ptr = Ops[0];
803 if (!Ptr->getType()->isPointerTy())
806 Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
808 // If this is a constant expr gep that is effectively computing an
809 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
810 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
811 if (!isa<ConstantInt>(Ops[i])) {
813 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
814 // "inttoptr (sub (ptrtoint Ptr), V)"
815 if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
816 auto *CE = dyn_cast<ConstantExpr>(Ops[1]);
817 assert((!CE || CE->getType() == IntPtrTy) &&
818 "CastGEPIndices didn't canonicalize index types!");
819 if (CE && CE->getOpcode() == Instruction::Sub &&
820 CE->getOperand(0)->isNullValue()) {
821 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
822 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
823 Res = ConstantExpr::getIntToPtr(Res, ResTy);
824 if (auto *FoldedRes = ConstantFoldConstant(Res, DL, TLI))
832 unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
835 DL.getIndexedOffsetInType(
837 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
838 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
840 // If this is a GEP of a GEP, fold it all into a single GEP.
841 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
843 InBounds &= GEP->isInBounds();
845 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
847 // Do not try the incorporate the sub-GEP if some index is not a number.
848 bool AllConstantInt = true;
849 for (Value *NestedOp : NestedOps)
850 if (!isa<ConstantInt>(NestedOp)) {
851 AllConstantInt = false;
857 Ptr = cast<Constant>(GEP->getOperand(0));
858 SrcElemTy = GEP->getSourceElementType();
859 Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
860 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
863 // If the base value for this address is a literal integer value, fold the
864 // getelementptr to the resulting integer value casted to the pointer type.
865 APInt BasePtr(BitWidth, 0);
866 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
867 if (CE->getOpcode() == Instruction::IntToPtr) {
868 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
869 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
873 auto *PTy = cast<PointerType>(Ptr->getType());
874 if ((Ptr->isNullValue() || BasePtr != 0) &&
875 !DL.isNonIntegralPointerType(PTy)) {
876 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
877 return ConstantExpr::getIntToPtr(C, ResTy);
880 // Otherwise form a regular getelementptr. Recompute the indices so that
881 // we eliminate over-indexing of the notional static type array bounds.
882 // This makes it easy to determine if the getelementptr is "inbounds".
883 // Also, this helps GlobalOpt do SROA on GlobalVariables.
885 SmallVector<Constant *, 32> NewIdxs;
888 if (!Ty->isStructTy()) {
889 if (Ty->isPointerTy()) {
890 // The only pointer indexing we'll do is on the first index of the GEP.
891 if (!NewIdxs.empty())
896 // Only handle pointers to sized types, not pointers to functions.
899 } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) {
900 Ty = ATy->getElementType();
902 // We've reached some non-indexable type.
906 // Determine which element of the array the offset points into.
907 APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
909 // The element size is 0. This may be [0 x Ty]*, so just use a zero
910 // index for this level and proceed to the next level to see if it can
911 // accommodate the offset.
912 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
914 // The element size is non-zero divide the offset by the element
915 // size (rounding down), to compute the index at this level.
917 APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow);
920 Offset -= NewIdx * ElemSize;
921 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
924 auto *STy = cast<StructType>(Ty);
925 // If we end up with an offset that isn't valid for this struct type, we
926 // can't re-form this GEP in a regular form, so bail out. The pointer
927 // operand likely went through casts that are necessary to make the GEP
929 const StructLayout &SL = *DL.getStructLayout(STy);
930 if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes()))
933 // Determine which field of the struct the offset points into. The
934 // getZExtValue is fine as we've already ensured that the offset is
935 // within the range representable by the StructLayout API.
936 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
937 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
939 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
940 Ty = STy->getTypeAtIndex(ElIdx);
942 } while (Ty != ResElemTy);
944 // If we haven't used up the entire offset by descending the static
945 // type, then the offset is pointing into the middle of an indivisible
946 // member, so we can't simplify it.
950 // Preserve the inrange index from the innermost GEP if possible. We must
951 // have calculated the same indices up to and including the inrange index.
952 Optional<unsigned> InRangeIndex;
953 if (Optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex())
954 if (SrcElemTy == InnermostGEP->getSourceElementType() &&
955 NewIdxs.size() > *LastIRIndex) {
956 InRangeIndex = LastIRIndex;
957 for (unsigned I = 0; I <= *LastIRIndex; ++I)
958 if (NewIdxs[I] != InnermostGEP->getOperand(I + 1)) {
965 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs,
966 InBounds, InRangeIndex);
967 assert(C->getType()->getPointerElementType() == Ty &&
968 "Computed GetElementPtr has unexpected type!");
970 // If we ended up indexing a member with a type that doesn't match
971 // the type of what the original indices indexed, add a cast.
973 C = FoldBitCast(C, ResTy, DL);
978 /// Attempt to constant fold an instruction with the
979 /// specified opcode and operands. If successful, the constant result is
980 /// returned, if not, null is returned. Note that this function can fail when
981 /// attempting to fold instructions like loads and stores, which have no
982 /// constant expression form.
984 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/inrange
985 /// etc information, due to only being passed an opcode and operands. Constant
986 /// folding using this function strips this information.
988 Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
989 ArrayRef<Constant *> Ops,
990 const DataLayout &DL,
991 const TargetLibraryInfo *TLI) {
992 Type *DestTy = InstOrCE->getType();
994 // Handle easy binops first.
995 if (Instruction::isBinaryOp(Opcode))
996 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
998 if (Instruction::isCast(Opcode))
999 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1001 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
1002 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
1005 return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), Ops[0],
1006 Ops.slice(1), GEP->isInBounds(),
1007 GEP->getInRangeIndex());
1010 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
1011 return CE->getWithOperands(Ops);
1014 default: return nullptr;
1015 case Instruction::ICmp:
1016 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
1017 case Instruction::Call:
1018 if (auto *F = dyn_cast<Function>(Ops.back()))
1019 if (canConstantFoldCallTo(F))
1020 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
1022 case Instruction::Select:
1023 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1024 case Instruction::ExtractElement:
1025 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1026 case Instruction::InsertElement:
1027 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1028 case Instruction::ShuffleVector:
1029 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1033 } // end anonymous namespace
1035 //===----------------------------------------------------------------------===//
1036 // Constant Folding public APIs
1037 //===----------------------------------------------------------------------===//
1042 ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1043 const TargetLibraryInfo *TLI,
1044 SmallDenseMap<Constant *, Constant *> &FoldedOps) {
1045 if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1048 SmallVector<Constant *, 8> Ops;
1049 for (const Use &NewU : C->operands()) {
1050 auto *NewC = cast<Constant>(&NewU);
1051 // Recursively fold the ConstantExpr's operands. If we have already folded
1052 // a ConstantExpr, we don't have to process it again.
1053 if (isa<ConstantVector>(NewC) || isa<ConstantExpr>(NewC)) {
1054 auto It = FoldedOps.find(NewC);
1055 if (It == FoldedOps.end()) {
1057 ConstantFoldConstantImpl(NewC, DL, TLI, FoldedOps)) {
1058 FoldedOps.insert({NewC, FoldedC});
1061 FoldedOps.insert({NewC, NewC});
1067 Ops.push_back(NewC);
1070 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1071 if (CE->isCompare())
1072 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1075 return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI);
1078 assert(isa<ConstantVector>(C));
1079 return ConstantVector::get(Ops);
1082 } // end anonymous namespace
1084 Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
1085 const TargetLibraryInfo *TLI) {
1086 // Handle PHI nodes quickly here...
1087 if (auto *PN = dyn_cast<PHINode>(I)) {
1088 Constant *CommonValue = nullptr;
1090 SmallDenseMap<Constant *, Constant *> FoldedOps;
1091 for (Value *Incoming : PN->incoming_values()) {
1092 // If the incoming value is undef then skip it. Note that while we could
1093 // skip the value if it is equal to the phi node itself we choose not to
1094 // because that would break the rule that constant folding only applies if
1095 // all operands are constants.
1096 if (isa<UndefValue>(Incoming))
1098 // If the incoming value is not a constant, then give up.
1099 auto *C = dyn_cast<Constant>(Incoming);
1102 // Fold the PHI's operands.
1103 if (auto *FoldedC = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps))
1105 // If the incoming value is a different constant to
1106 // the one we saw previously, then give up.
1107 if (CommonValue && C != CommonValue)
1112 // If we reach here, all incoming values are the same constant or undef.
1113 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
1116 // Scan the operand list, checking to see if they are all constants, if so,
1117 // hand off to ConstantFoldInstOperandsImpl.
1118 if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1121 SmallDenseMap<Constant *, Constant *> FoldedOps;
1122 SmallVector<Constant *, 8> Ops;
1123 for (const Use &OpU : I->operands()) {
1124 auto *Op = cast<Constant>(&OpU);
1125 // Fold the Instruction's operands.
1126 if (auto *FoldedOp = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps))
1132 if (const auto *CI = dyn_cast<CmpInst>(I))
1133 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
1136 if (const auto *LI = dyn_cast<LoadInst>(I))
1137 return ConstantFoldLoadInst(LI, DL);
1139 if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
1140 return ConstantExpr::getInsertValue(
1141 cast<Constant>(IVI->getAggregateOperand()),
1142 cast<Constant>(IVI->getInsertedValueOperand()),
1146 if (auto *EVI = dyn_cast<ExtractValueInst>(I)) {
1147 return ConstantExpr::getExtractValue(
1148 cast<Constant>(EVI->getAggregateOperand()),
1152 return ConstantFoldInstOperands(I, Ops, DL, TLI);
1155 Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL,
1156 const TargetLibraryInfo *TLI) {
1157 SmallDenseMap<Constant *, Constant *> FoldedOps;
1158 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1161 Constant *llvm::ConstantFoldInstOperands(Instruction *I,
1162 ArrayRef<Constant *> Ops,
1163 const DataLayout &DL,
1164 const TargetLibraryInfo *TLI) {
1165 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
1168 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
1169 Constant *Ops0, Constant *Ops1,
1170 const DataLayout &DL,
1171 const TargetLibraryInfo *TLI) {
1172 // fold: icmp (inttoptr x), null -> icmp x, 0
1173 // fold: icmp (ptrtoint x), 0 -> icmp x, null
1174 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1175 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1177 // FIXME: The following comment is out of data and the DataLayout is here now.
1178 // ConstantExpr::getCompare cannot do this, because it doesn't have DL
1179 // around to know if bit truncation is happening.
1180 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1181 if (Ops1->isNullValue()) {
1182 if (CE0->getOpcode() == Instruction::IntToPtr) {
1183 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1184 // Convert the integer value to the right size to ensure we get the
1185 // proper extension or truncation.
1186 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1188 Constant *Null = Constant::getNullValue(C->getType());
1189 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1192 // Only do this transformation if the int is intptrty in size, otherwise
1193 // there is a truncation or extension that we aren't modeling.
1194 if (CE0->getOpcode() == Instruction::PtrToInt) {
1195 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1196 if (CE0->getType() == IntPtrTy) {
1197 Constant *C = CE0->getOperand(0);
1198 Constant *Null = Constant::getNullValue(C->getType());
1199 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1204 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1205 if (CE0->getOpcode() == CE1->getOpcode()) {
1206 if (CE0->getOpcode() == Instruction::IntToPtr) {
1207 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1209 // Convert the integer value to the right size to ensure we get the
1210 // proper extension or truncation.
1211 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1213 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1215 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
1218 // Only do this transformation if the int is intptrty in size, otherwise
1219 // there is a truncation or extension that we aren't modeling.
1220 if (CE0->getOpcode() == Instruction::PtrToInt) {
1221 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1222 if (CE0->getType() == IntPtrTy &&
1223 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1224 return ConstantFoldCompareInstOperands(
1225 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
1231 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1232 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1233 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1234 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1235 Constant *LHS = ConstantFoldCompareInstOperands(
1236 Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1237 Constant *RHS = ConstantFoldCompareInstOperands(
1238 Predicate, CE0->getOperand(1), Ops1, DL, TLI);
1240 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1241 return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
1245 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1248 Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1250 const DataLayout &DL) {
1251 assert(Instruction::isBinaryOp(Opcode));
1252 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1253 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1256 return ConstantExpr::get(Opcode, LHS, RHS);
1259 Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1260 Type *DestTy, const DataLayout &DL) {
1261 assert(Instruction::isCast(Opcode));
1264 llvm_unreachable("Missing case");
1265 case Instruction::PtrToInt:
1266 // If the input is a inttoptr, eliminate the pair. This requires knowing
1267 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1268 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1269 if (CE->getOpcode() == Instruction::IntToPtr) {
1270 Constant *Input = CE->getOperand(0);
1271 unsigned InWidth = Input->getType()->getScalarSizeInBits();
1272 unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1273 if (PtrWidth < InWidth) {
1275 ConstantInt::get(CE->getContext(),
1276 APInt::getLowBitsSet(InWidth, PtrWidth));
1277 Input = ConstantExpr::getAnd(Input, Mask);
1279 // Do a zext or trunc to get to the dest size.
1280 return ConstantExpr::getIntegerCast(Input, DestTy, false);
1283 return ConstantExpr::getCast(Opcode, C, DestTy);
1284 case Instruction::IntToPtr:
1285 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1286 // the int size is >= the ptr size and the address spaces are the same.
1287 // This requires knowing the width of a pointer, so it can't be done in
1288 // ConstantExpr::getCast.
1289 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1290 if (CE->getOpcode() == Instruction::PtrToInt) {
1291 Constant *SrcPtr = CE->getOperand(0);
1292 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1293 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1295 if (MidIntSize >= SrcPtrSize) {
1296 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1297 if (SrcAS == DestTy->getPointerAddressSpace())
1298 return FoldBitCast(CE->getOperand(0), DestTy, DL);
1303 return ConstantExpr::getCast(Opcode, C, DestTy);
1304 case Instruction::Trunc:
1305 case Instruction::ZExt:
1306 case Instruction::SExt:
1307 case Instruction::FPTrunc:
1308 case Instruction::FPExt:
1309 case Instruction::UIToFP:
1310 case Instruction::SIToFP:
1311 case Instruction::FPToUI:
1312 case Instruction::FPToSI:
1313 case Instruction::AddrSpaceCast:
1314 return ConstantExpr::getCast(Opcode, C, DestTy);
1315 case Instruction::BitCast:
1316 return FoldBitCast(C, DestTy, DL);
1320 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
1322 if (!CE->getOperand(1)->isNullValue())
1323 return nullptr; // Do not allow stepping over the value!
1325 // Loop over all of the operands, tracking down which value we are
1327 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1328 C = C->getAggregateElement(CE->getOperand(i));
1336 llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1337 ArrayRef<Constant *> Indices) {
1338 // Loop over all of the operands, tracking down which value we are
1340 for (Constant *Index : Indices) {
1341 C = C->getAggregateElement(Index);
1348 //===----------------------------------------------------------------------===//
1349 // Constant Folding for Calls
1352 bool llvm::canConstantFoldCallTo(const Function *F) {
1353 switch (F->getIntrinsicID()) {
1354 case Intrinsic::fabs:
1355 case Intrinsic::minnum:
1356 case Intrinsic::maxnum:
1357 case Intrinsic::log:
1358 case Intrinsic::log2:
1359 case Intrinsic::log10:
1360 case Intrinsic::exp:
1361 case Intrinsic::exp2:
1362 case Intrinsic::floor:
1363 case Intrinsic::ceil:
1364 case Intrinsic::sqrt:
1365 case Intrinsic::sin:
1366 case Intrinsic::cos:
1367 case Intrinsic::trunc:
1368 case Intrinsic::rint:
1369 case Intrinsic::nearbyint:
1370 case Intrinsic::pow:
1371 case Intrinsic::powi:
1372 case Intrinsic::bswap:
1373 case Intrinsic::ctpop:
1374 case Intrinsic::ctlz:
1375 case Intrinsic::cttz:
1376 case Intrinsic::fma:
1377 case Intrinsic::fmuladd:
1378 case Intrinsic::copysign:
1379 case Intrinsic::round:
1380 case Intrinsic::masked_load:
1381 case Intrinsic::sadd_with_overflow:
1382 case Intrinsic::uadd_with_overflow:
1383 case Intrinsic::ssub_with_overflow:
1384 case Intrinsic::usub_with_overflow:
1385 case Intrinsic::smul_with_overflow:
1386 case Intrinsic::umul_with_overflow:
1387 case Intrinsic::convert_from_fp16:
1388 case Intrinsic::convert_to_fp16:
1389 case Intrinsic::bitreverse:
1390 case Intrinsic::x86_sse_cvtss2si:
1391 case Intrinsic::x86_sse_cvtss2si64:
1392 case Intrinsic::x86_sse_cvttss2si:
1393 case Intrinsic::x86_sse_cvttss2si64:
1394 case Intrinsic::x86_sse2_cvtsd2si:
1395 case Intrinsic::x86_sse2_cvtsd2si64:
1396 case Intrinsic::x86_sse2_cvttsd2si:
1397 case Intrinsic::x86_sse2_cvttsd2si64:
1401 case Intrinsic::not_intrinsic: break;
1406 StringRef Name = F->getName();
1408 // In these cases, the check of the length is required. We don't want to
1409 // return true for a name like "cos\0blah" which strcmp would return equal to
1410 // "cos", but has length 8.
1415 return Name == "acos" || Name == "asin" || Name == "atan" ||
1416 Name == "atan2" || Name == "acosf" || Name == "asinf" ||
1417 Name == "atanf" || Name == "atan2f";
1419 return Name == "ceil" || Name == "cos" || Name == "cosh" ||
1420 Name == "ceilf" || Name == "cosf" || Name == "coshf";
1422 return Name == "exp" || Name == "exp2" || Name == "expf" || Name == "exp2f";
1424 return Name == "fabs" || Name == "floor" || Name == "fmod" ||
1425 Name == "fabsf" || Name == "floorf" || Name == "fmodf";
1427 return Name == "log" || Name == "log10" || Name == "logf" ||
1430 return Name == "pow" || Name == "powf";
1432 return Name == "round" || Name == "roundf";
1434 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1435 Name == "sinf" || Name == "sinhf" || Name == "sqrtf";
1437 return Name == "tan" || Name == "tanh" || Name == "tanf" || Name == "tanhf";
1440 // Check for various function names that get used for the math functions
1441 // when the header files are preprocessed with the macro
1442 // __FINITE_MATH_ONLY__ enabled.
1443 // The '12' here is the length of the shortest name that can match.
1444 // We need to check the size before looking at Name[1] and Name[2]
1445 // so we may as well check a limit that will eliminate mismatches.
1446 if (Name.size() < 12 || Name[1] != '_')
1452 return Name == "__acos_finite" || Name == "__acosf_finite" ||
1453 Name == "__asin_finite" || Name == "__asinf_finite" ||
1454 Name == "__atan2_finite" || Name == "__atan2f_finite";
1456 return Name == "__cosh_finite" || Name == "__coshf_finite";
1458 return Name == "__exp_finite" || Name == "__expf_finite" ||
1459 Name == "__exp2_finite" || Name == "__exp2f_finite";
1461 return Name == "__log_finite" || Name == "__logf_finite" ||
1462 Name == "__log10_finite" || Name == "__log10f_finite";
1464 return Name == "__pow_finite" || Name == "__powf_finite";
1466 return Name == "__sinh_finite" || Name == "__sinhf_finite";
1473 Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1474 if (Ty->isHalfTy()) {
1477 APF.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &unused);
1478 return ConstantFP::get(Ty->getContext(), APF);
1480 if (Ty->isFloatTy())
1481 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1482 if (Ty->isDoubleTy())
1483 return ConstantFP::get(Ty->getContext(), APFloat(V));
1484 llvm_unreachable("Can only constant fold half/float/double");
1487 /// Clear the floating-point exception state.
1488 inline void llvm_fenv_clearexcept() {
1489 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
1490 feclearexcept(FE_ALL_EXCEPT);
1495 /// Test if a floating-point exception was raised.
1496 inline bool llvm_fenv_testexcept() {
1497 int errno_val = errno;
1498 if (errno_val == ERANGE || errno_val == EDOM)
1500 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
1501 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1507 Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
1508 llvm_fenv_clearexcept();
1510 if (llvm_fenv_testexcept()) {
1511 llvm_fenv_clearexcept();
1515 return GetConstantFoldFPValue(V, Ty);
1518 Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1519 double W, Type *Ty) {
1520 llvm_fenv_clearexcept();
1522 if (llvm_fenv_testexcept()) {
1523 llvm_fenv_clearexcept();
1527 return GetConstantFoldFPValue(V, Ty);
1530 /// Attempt to fold an SSE floating point to integer conversion of a constant
1531 /// floating point. If roundTowardZero is false, the default IEEE rounding is
1532 /// used (toward nearest, ties to even). This matches the behavior of the
1533 /// non-truncating SSE instructions in the default rounding mode. The desired
1534 /// integer type Ty is used to select how many bits are available for the
1535 /// result. Returns null if the conversion cannot be performed, otherwise
1536 /// returns the Constant value resulting from the conversion.
1537 Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
1539 // All of these conversion intrinsics form an integer of at most 64bits.
1540 unsigned ResultWidth = Ty->getIntegerBitWidth();
1541 assert(ResultWidth <= 64 &&
1542 "Can only constant fold conversions to 64 and 32 bit ints");
1545 bool isExact = false;
1546 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1547 : APFloat::rmNearestTiesToEven;
1548 APFloat::opStatus status =
1549 Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth,
1550 /*isSigned=*/true, mode, &isExact);
1551 if (status != APFloat::opOK &&
1552 (!roundTowardZero || status != APFloat::opInexact))
1554 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1557 double getValueAsDouble(ConstantFP *Op) {
1558 Type *Ty = Op->getType();
1560 if (Ty->isFloatTy())
1561 return Op->getValueAPF().convertToFloat();
1563 if (Ty->isDoubleTy())
1564 return Op->getValueAPF().convertToDouble();
1567 APFloat APF = Op->getValueAPF();
1568 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
1569 return APF.convertToDouble();
1572 Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty,
1573 ArrayRef<Constant *> Operands,
1574 const TargetLibraryInfo *TLI) {
1575 if (Operands.size() == 1) {
1576 if (isa<UndefValue>(Operands[0])) {
1577 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN
1578 if (IntrinsicID == Intrinsic::cos)
1579 return Constant::getNullValue(Ty);
1581 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
1582 if (IntrinsicID == Intrinsic::convert_to_fp16) {
1583 APFloat Val(Op->getValueAPF());
1586 Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
1588 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1591 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1594 if (IntrinsicID == Intrinsic::round) {
1595 APFloat V = Op->getValueAPF();
1596 V.roundToIntegral(APFloat::rmNearestTiesToAway);
1597 return ConstantFP::get(Ty->getContext(), V);
1600 if (IntrinsicID == Intrinsic::floor) {
1601 APFloat V = Op->getValueAPF();
1602 V.roundToIntegral(APFloat::rmTowardNegative);
1603 return ConstantFP::get(Ty->getContext(), V);
1606 if (IntrinsicID == Intrinsic::ceil) {
1607 APFloat V = Op->getValueAPF();
1608 V.roundToIntegral(APFloat::rmTowardPositive);
1609 return ConstantFP::get(Ty->getContext(), V);
1612 if (IntrinsicID == Intrinsic::trunc) {
1613 APFloat V = Op->getValueAPF();
1614 V.roundToIntegral(APFloat::rmTowardZero);
1615 return ConstantFP::get(Ty->getContext(), V);
1618 if (IntrinsicID == Intrinsic::rint) {
1619 APFloat V = Op->getValueAPF();
1620 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1621 return ConstantFP::get(Ty->getContext(), V);
1624 if (IntrinsicID == Intrinsic::nearbyint) {
1625 APFloat V = Op->getValueAPF();
1626 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1627 return ConstantFP::get(Ty->getContext(), V);
1630 /// We only fold functions with finite arguments. Folding NaN and inf is
1631 /// likely to be aborted with an exception anyway, and some host libms
1632 /// have known errors raising exceptions.
1633 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1636 /// Currently APFloat versions of these functions do not exist, so we use
1637 /// the host native double versions. Float versions are not called
1638 /// directly but for all these it is true (float)(f((double)arg)) ==
1639 /// f(arg). Long double not supported yet.
1640 double V = getValueAsDouble(Op);
1642 switch (IntrinsicID) {
1644 case Intrinsic::fabs:
1645 return ConstantFoldFP(fabs, V, Ty);
1646 case Intrinsic::log2:
1647 return ConstantFoldFP(Log2, V, Ty);
1648 case Intrinsic::log:
1649 return ConstantFoldFP(log, V, Ty);
1650 case Intrinsic::log10:
1651 return ConstantFoldFP(log10, V, Ty);
1652 case Intrinsic::exp:
1653 return ConstantFoldFP(exp, V, Ty);
1654 case Intrinsic::exp2:
1655 return ConstantFoldFP(exp2, V, Ty);
1656 case Intrinsic::sin:
1657 return ConstantFoldFP(sin, V, Ty);
1658 case Intrinsic::cos:
1659 return ConstantFoldFP(cos, V, Ty);
1660 case Intrinsic::sqrt:
1661 return ConstantFoldFP(sqrt, V, Ty);
1667 char NameKeyChar = Name[0];
1668 if (Name[0] == '_' && Name.size() > 2 && Name[1] == '_')
1669 NameKeyChar = Name[2];
1671 switch (NameKeyChar) {
1673 if ((Name == "acos" && TLI->has(LibFunc_acos)) ||
1674 (Name == "acosf" && TLI->has(LibFunc_acosf)) ||
1675 (Name == "__acos_finite" && TLI->has(LibFunc_acos_finite)) ||
1676 (Name == "__acosf_finite" && TLI->has(LibFunc_acosf_finite)))
1677 return ConstantFoldFP(acos, V, Ty);
1678 else if ((Name == "asin" && TLI->has(LibFunc_asin)) ||
1679 (Name == "asinf" && TLI->has(LibFunc_asinf)) ||
1680 (Name == "__asin_finite" && TLI->has(LibFunc_asin_finite)) ||
1681 (Name == "__asinf_finite" && TLI->has(LibFunc_asinf_finite)))
1682 return ConstantFoldFP(asin, V, Ty);
1683 else if ((Name == "atan" && TLI->has(LibFunc_atan)) ||
1684 (Name == "atanf" && TLI->has(LibFunc_atanf)))
1685 return ConstantFoldFP(atan, V, Ty);
1688 if ((Name == "ceil" && TLI->has(LibFunc_ceil)) ||
1689 (Name == "ceilf" && TLI->has(LibFunc_ceilf)))
1690 return ConstantFoldFP(ceil, V, Ty);
1691 else if ((Name == "cos" && TLI->has(LibFunc_cos)) ||
1692 (Name == "cosf" && TLI->has(LibFunc_cosf)))
1693 return ConstantFoldFP(cos, V, Ty);
1694 else if ((Name == "cosh" && TLI->has(LibFunc_cosh)) ||
1695 (Name == "coshf" && TLI->has(LibFunc_coshf)) ||
1696 (Name == "__cosh_finite" && TLI->has(LibFunc_cosh_finite)) ||
1697 (Name == "__coshf_finite" && TLI->has(LibFunc_coshf_finite)))
1698 return ConstantFoldFP(cosh, V, Ty);
1701 if ((Name == "exp" && TLI->has(LibFunc_exp)) ||
1702 (Name == "expf" && TLI->has(LibFunc_expf)) ||
1703 (Name == "__exp_finite" && TLI->has(LibFunc_exp_finite)) ||
1704 (Name == "__expf_finite" && TLI->has(LibFunc_expf_finite)))
1705 return ConstantFoldFP(exp, V, Ty);
1706 if ((Name == "exp2" && TLI->has(LibFunc_exp2)) ||
1707 (Name == "exp2f" && TLI->has(LibFunc_exp2f)) ||
1708 (Name == "__exp2_finite" && TLI->has(LibFunc_exp2_finite)) ||
1709 (Name == "__exp2f_finite" && TLI->has(LibFunc_exp2f_finite)))
1710 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1712 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1715 if ((Name == "fabs" && TLI->has(LibFunc_fabs)) ||
1716 (Name == "fabsf" && TLI->has(LibFunc_fabsf)))
1717 return ConstantFoldFP(fabs, V, Ty);
1718 else if ((Name == "floor" && TLI->has(LibFunc_floor)) ||
1719 (Name == "floorf" && TLI->has(LibFunc_floorf)))
1720 return ConstantFoldFP(floor, V, Ty);
1723 if ((Name == "log" && V > 0 && TLI->has(LibFunc_log)) ||
1724 (Name == "logf" && V > 0 && TLI->has(LibFunc_logf)) ||
1725 (Name == "__log_finite" && V > 0 &&
1726 TLI->has(LibFunc_log_finite)) ||
1727 (Name == "__logf_finite" && V > 0 &&
1728 TLI->has(LibFunc_logf_finite)))
1729 return ConstantFoldFP(log, V, Ty);
1730 else if ((Name == "log10" && V > 0 && TLI->has(LibFunc_log10)) ||
1731 (Name == "log10f" && V > 0 && TLI->has(LibFunc_log10f)) ||
1732 (Name == "__log10_finite" && V > 0 &&
1733 TLI->has(LibFunc_log10_finite)) ||
1734 (Name == "__log10f_finite" && V > 0 &&
1735 TLI->has(LibFunc_log10f_finite)))
1736 return ConstantFoldFP(log10, V, Ty);
1739 if ((Name == "round" && TLI->has(LibFunc_round)) ||
1740 (Name == "roundf" && TLI->has(LibFunc_roundf)))
1741 return ConstantFoldFP(round, V, Ty);
1744 if ((Name == "sin" && TLI->has(LibFunc_sin)) ||
1745 (Name == "sinf" && TLI->has(LibFunc_sinf)))
1746 return ConstantFoldFP(sin, V, Ty);
1747 else if ((Name == "sinh" && TLI->has(LibFunc_sinh)) ||
1748 (Name == "sinhf" && TLI->has(LibFunc_sinhf)) ||
1749 (Name == "__sinh_finite" && TLI->has(LibFunc_sinh_finite)) ||
1750 (Name == "__sinhf_finite" && TLI->has(LibFunc_sinhf_finite)))
1751 return ConstantFoldFP(sinh, V, Ty);
1752 else if ((Name == "sqrt" && V >= 0 && TLI->has(LibFunc_sqrt)) ||
1753 (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc_sqrtf)))
1754 return ConstantFoldFP(sqrt, V, Ty);
1757 if ((Name == "tan" && TLI->has(LibFunc_tan)) ||
1758 (Name == "tanf" && TLI->has(LibFunc_tanf)))
1759 return ConstantFoldFP(tan, V, Ty);
1760 else if ((Name == "tanh" && TLI->has(LibFunc_tanh)) ||
1761 (Name == "tanhf" && TLI->has(LibFunc_tanhf)))
1762 return ConstantFoldFP(tanh, V, Ty);
1770 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
1771 switch (IntrinsicID) {
1772 case Intrinsic::bswap:
1773 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
1774 case Intrinsic::ctpop:
1775 return ConstantInt::get(Ty, Op->getValue().countPopulation());
1776 case Intrinsic::bitreverse:
1777 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
1778 case Intrinsic::convert_from_fp16: {
1779 APFloat Val(APFloat::IEEEhalf(), Op->getValue());
1782 APFloat::opStatus status = Val.convert(
1783 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
1785 // Conversion is always precise.
1787 assert(status == APFloat::opOK && !lost &&
1788 "Precision lost during fp16 constfolding");
1790 return ConstantFP::get(Ty->getContext(), Val);
1797 // Support ConstantVector in case we have an Undef in the top.
1798 if (isa<ConstantVector>(Operands[0]) ||
1799 isa<ConstantDataVector>(Operands[0])) {
1800 auto *Op = cast<Constant>(Operands[0]);
1801 switch (IntrinsicID) {
1803 case Intrinsic::x86_sse_cvtss2si:
1804 case Intrinsic::x86_sse_cvtss2si64:
1805 case Intrinsic::x86_sse2_cvtsd2si:
1806 case Intrinsic::x86_sse2_cvtsd2si64:
1807 if (ConstantFP *FPOp =
1808 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1809 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1810 /*roundTowardZero=*/false, Ty);
1812 case Intrinsic::x86_sse_cvttss2si:
1813 case Intrinsic::x86_sse_cvttss2si64:
1814 case Intrinsic::x86_sse2_cvttsd2si:
1815 case Intrinsic::x86_sse2_cvttsd2si64:
1816 if (ConstantFP *FPOp =
1817 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1818 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1819 /*roundTowardZero=*/true, Ty);
1823 if (isa<UndefValue>(Operands[0])) {
1824 if (IntrinsicID == Intrinsic::bswap ||
1825 IntrinsicID == Intrinsic::bitreverse)
1833 if (Operands.size() == 2) {
1834 if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1835 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1837 double Op1V = getValueAsDouble(Op1);
1839 if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1840 if (Op2->getType() != Op1->getType())
1843 double Op2V = getValueAsDouble(Op2);
1844 if (IntrinsicID == Intrinsic::pow) {
1845 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1847 if (IntrinsicID == Intrinsic::copysign) {
1848 APFloat V1 = Op1->getValueAPF();
1849 const APFloat &V2 = Op2->getValueAPF();
1851 return ConstantFP::get(Ty->getContext(), V1);
1854 if (IntrinsicID == Intrinsic::minnum) {
1855 const APFloat &C1 = Op1->getValueAPF();
1856 const APFloat &C2 = Op2->getValueAPF();
1857 return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1860 if (IntrinsicID == Intrinsic::maxnum) {
1861 const APFloat &C1 = Op1->getValueAPF();
1862 const APFloat &C2 = Op2->getValueAPF();
1863 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1868 if ((Name == "pow" && TLI->has(LibFunc_pow)) ||
1869 (Name == "powf" && TLI->has(LibFunc_powf)) ||
1870 (Name == "__pow_finite" && TLI->has(LibFunc_pow_finite)) ||
1871 (Name == "__powf_finite" && TLI->has(LibFunc_powf_finite)))
1872 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1873 if ((Name == "fmod" && TLI->has(LibFunc_fmod)) ||
1874 (Name == "fmodf" && TLI->has(LibFunc_fmodf)))
1875 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1876 if ((Name == "atan2" && TLI->has(LibFunc_atan2)) ||
1877 (Name == "atan2f" && TLI->has(LibFunc_atan2f)) ||
1878 (Name == "__atan2_finite" && TLI->has(LibFunc_atan2_finite)) ||
1879 (Name == "__atan2f_finite" && TLI->has(LibFunc_atan2f_finite)))
1880 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1881 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1882 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1883 return ConstantFP::get(Ty->getContext(),
1884 APFloat((float)std::pow((float)Op1V,
1885 (int)Op2C->getZExtValue())));
1886 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1887 return ConstantFP::get(Ty->getContext(),
1888 APFloat((float)std::pow((float)Op1V,
1889 (int)Op2C->getZExtValue())));
1890 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1891 return ConstantFP::get(Ty->getContext(),
1892 APFloat((double)std::pow((double)Op1V,
1893 (int)Op2C->getZExtValue())));
1898 if (auto *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1899 if (auto *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1900 switch (IntrinsicID) {
1902 case Intrinsic::sadd_with_overflow:
1903 case Intrinsic::uadd_with_overflow:
1904 case Intrinsic::ssub_with_overflow:
1905 case Intrinsic::usub_with_overflow:
1906 case Intrinsic::smul_with_overflow:
1907 case Intrinsic::umul_with_overflow: {
1910 switch (IntrinsicID) {
1911 default: llvm_unreachable("Invalid case");
1912 case Intrinsic::sadd_with_overflow:
1913 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1915 case Intrinsic::uadd_with_overflow:
1916 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1918 case Intrinsic::ssub_with_overflow:
1919 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1921 case Intrinsic::usub_with_overflow:
1922 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1924 case Intrinsic::smul_with_overflow:
1925 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1927 case Intrinsic::umul_with_overflow:
1928 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1932 ConstantInt::get(Ty->getContext(), Res),
1933 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
1935 return ConstantStruct::get(cast<StructType>(Ty), Ops);
1937 case Intrinsic::cttz:
1938 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1939 return UndefValue::get(Ty);
1940 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1941 case Intrinsic::ctlz:
1942 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1943 return UndefValue::get(Ty);
1944 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
1953 if (Operands.size() != 3)
1956 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1957 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1958 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
1959 switch (IntrinsicID) {
1961 case Intrinsic::fma:
1962 case Intrinsic::fmuladd: {
1963 APFloat V = Op1->getValueAPF();
1964 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1966 APFloat::rmNearestTiesToEven);
1967 if (s != APFloat::opInvalidOp)
1968 return ConstantFP::get(Ty->getContext(), V);
1980 Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1981 VectorType *VTy, ArrayRef<Constant *> Operands,
1982 const DataLayout &DL,
1983 const TargetLibraryInfo *TLI) {
1984 SmallVector<Constant *, 4> Result(VTy->getNumElements());
1985 SmallVector<Constant *, 4> Lane(Operands.size());
1986 Type *Ty = VTy->getElementType();
1988 if (IntrinsicID == Intrinsic::masked_load) {
1989 auto *SrcPtr = Operands[0];
1990 auto *Mask = Operands[2];
1991 auto *Passthru = Operands[3];
1993 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, VTy, DL);
1995 SmallVector<Constant *, 32> NewElements;
1996 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1997 auto *MaskElt = Mask->getAggregateElement(I);
2000 auto *PassthruElt = Passthru->getAggregateElement(I);
2001 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
2002 if (isa<UndefValue>(MaskElt)) {
2004 NewElements.push_back(PassthruElt);
2006 NewElements.push_back(VecElt);
2010 if (MaskElt->isNullValue()) {
2013 NewElements.push_back(PassthruElt);
2014 } else if (MaskElt->isOneValue()) {
2017 NewElements.push_back(VecElt);
2022 if (NewElements.size() != VTy->getNumElements())
2024 return ConstantVector::get(NewElements);
2027 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
2028 // Gather a column of constants.
2029 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
2030 Constant *Agg = Operands[J]->getAggregateElement(I);
2037 // Use the regular scalar folding to simplify this column.
2038 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
2044 return ConstantVector::get(Result);
2047 } // end anonymous namespace
2050 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
2051 const TargetLibraryInfo *TLI) {
2054 StringRef Name = F->getName();
2056 Type *Ty = F->getReturnType();
2058 if (auto *VTy = dyn_cast<VectorType>(Ty))
2059 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands,
2060 F->getParent()->getDataLayout(), TLI);
2062 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
2065 bool llvm::isMathLibCallNoop(CallSite CS, const TargetLibraryInfo *TLI) {
2066 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
2067 // (and to some extent ConstantFoldScalarCall).
2068 Function *F = CS.getCalledFunction();
2073 if (!TLI || !TLI->getLibFunc(*F, Func))
2076 if (CS.getNumArgOperands() == 1) {
2077 if (ConstantFP *OpC = dyn_cast<ConstantFP>(CS.getArgOperand(0))) {
2078 const APFloat &Op = OpC->getValueAPF();
2086 case LibFunc_log10l:
2088 case LibFunc_log10f:
2089 return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
2094 // FIXME: These boundaries are slightly conservative.
2095 if (OpC->getType()->isDoubleTy())
2096 return Op.compare(APFloat(-745.0)) != APFloat::cmpLessThan &&
2097 Op.compare(APFloat(709.0)) != APFloat::cmpGreaterThan;
2098 if (OpC->getType()->isFloatTy())
2099 return Op.compare(APFloat(-103.0f)) != APFloat::cmpLessThan &&
2100 Op.compare(APFloat(88.0f)) != APFloat::cmpGreaterThan;
2106 // FIXME: These boundaries are slightly conservative.
2107 if (OpC->getType()->isDoubleTy())
2108 return Op.compare(APFloat(-1074.0)) != APFloat::cmpLessThan &&
2109 Op.compare(APFloat(1023.0)) != APFloat::cmpGreaterThan;
2110 if (OpC->getType()->isFloatTy())
2111 return Op.compare(APFloat(-149.0f)) != APFloat::cmpLessThan &&
2112 Op.compare(APFloat(127.0f)) != APFloat::cmpGreaterThan;
2121 return !Op.isInfinity();
2125 case LibFunc_tanf: {
2126 // FIXME: Stop using the host math library.
2127 // FIXME: The computation isn't done in the right precision.
2128 Type *Ty = OpC->getType();
2129 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2130 double OpV = getValueAsDouble(OpC);
2131 return ConstantFoldFP(tan, OpV, Ty) != nullptr;
2142 return Op.compare(APFloat(Op.getSemantics(), "-1")) !=
2143 APFloat::cmpLessThan &&
2144 Op.compare(APFloat(Op.getSemantics(), "1")) !=
2145 APFloat::cmpGreaterThan;
2153 // FIXME: These boundaries are slightly conservative.
2154 if (OpC->getType()->isDoubleTy())
2155 return Op.compare(APFloat(-710.0)) != APFloat::cmpLessThan &&
2156 Op.compare(APFloat(710.0)) != APFloat::cmpGreaterThan;
2157 if (OpC->getType()->isFloatTy())
2158 return Op.compare(APFloat(-89.0f)) != APFloat::cmpLessThan &&
2159 Op.compare(APFloat(89.0f)) != APFloat::cmpGreaterThan;
2165 return Op.isNaN() || Op.isZero() || !Op.isNegative();
2167 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
2175 if (CS.getNumArgOperands() == 2) {
2176 ConstantFP *Op0C = dyn_cast<ConstantFP>(CS.getArgOperand(0));
2177 ConstantFP *Op1C = dyn_cast<ConstantFP>(CS.getArgOperand(1));
2179 const APFloat &Op0 = Op0C->getValueAPF();
2180 const APFloat &Op1 = Op1C->getValueAPF();
2185 case LibFunc_powf: {
2186 // FIXME: Stop using the host math library.
2187 // FIXME: The computation isn't done in the right precision.
2188 Type *Ty = Op0C->getType();
2189 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2190 if (Ty == Op1C->getType()) {
2191 double Op0V = getValueAsDouble(Op0C);
2192 double Op1V = getValueAsDouble(Op1C);
2193 return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr;
2202 return Op0.isNaN() || Op1.isNaN() ||
2203 (!Op0.isInfinity() && !Op1.isZero());