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