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