blob: 9bc009388167b098fa9eac57ae70994d35ac19a2 [file] [log] [blame]
John Criswellbd9d3702005-10-27 16:00:10 +00001//===-- ConstantFolding.cpp - Analyze constant folding possibilities ------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
John Criswellbd9d3702005-10-27 16:00:10 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This family of functions determines the possibility of performing constant
11// folding.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/ConstantFolding.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
Chris Lattner55207322007-01-30 23:45:45 +000018#include "llvm/Function.h"
Dan Gohman9a38e3e2009-05-07 19:46:24 +000019#include "llvm/GlobalVariable.h"
John Criswellbd9d3702005-10-27 16:00:10 +000020#include "llvm/Instructions.h"
21#include "llvm/Intrinsics.h"
Owen Anderson50895512009-07-06 18:42:36 +000022#include "llvm/LLVMContext.h"
Chris Lattner55207322007-01-30 23:45:45 +000023#include "llvm/ADT/SmallVector.h"
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +000024#include "llvm/ADT/StringMap.h"
Chris Lattner03dd25c2007-01-31 00:51:48 +000025#include "llvm/Target/TargetData.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
John Criswellbd9d3702005-10-27 16:00:10 +000027#include "llvm/Support/GetElementPtrTypeIterator.h"
28#include "llvm/Support/MathExtras.h"
29#include <cerrno>
Jeff Cohen97af7512006-12-02 02:22:01 +000030#include <cmath>
John Criswellbd9d3702005-10-27 16:00:10 +000031using namespace llvm;
32
Chris Lattner03dd25c2007-01-31 00:51:48 +000033//===----------------------------------------------------------------------===//
34// Constant Folding internal helper functions
35//===----------------------------------------------------------------------===//
36
37/// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
38/// from a global, return the global and the constant. Because of
39/// constantexprs, this function is recursive.
40static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
41 int64_t &Offset, const TargetData &TD) {
42 // Trivial case, constant is the global.
43 if ((GV = dyn_cast<GlobalValue>(C))) {
44 Offset = 0;
45 return true;
46 }
47
48 // Otherwise, if this isn't a constant expr, bail out.
49 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
50 if (!CE) return false;
51
52 // Look through ptr->int and ptr->ptr casts.
53 if (CE->getOpcode() == Instruction::PtrToInt ||
54 CE->getOpcode() == Instruction::BitCast)
55 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
56
57 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
58 if (CE->getOpcode() == Instruction::GetElementPtr) {
59 // Cannot compute this if the element type of the pointer is missing size
60 // info.
Chris Lattnerf286f6f2007-12-10 22:53:04 +000061 if (!cast<PointerType>(CE->getOperand(0)->getType())
62 ->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +000063 return false;
64
65 // If the base isn't a global+constant, we aren't either.
66 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
67 return false;
68
69 // Otherwise, add any offset that our operands provide.
70 gep_type_iterator GTI = gep_type_begin(CE);
Gabor Greifde2d74b2008-05-22 06:43:33 +000071 for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
Gabor Greif785c6af2008-05-22 19:24:54 +000072 i != e; ++i, ++GTI) {
Gabor Greifde2d74b2008-05-22 06:43:33 +000073 ConstantInt *CI = dyn_cast<ConstantInt>(*i);
Chris Lattner03dd25c2007-01-31 00:51:48 +000074 if (!CI) return false; // Index isn't a simple constant?
75 if (CI->getZExtValue() == 0) continue; // Not adding anything.
76
77 if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
78 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +000079 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
Chris Lattner03dd25c2007-01-31 00:51:48 +000080 } else {
Jeff Cohenca5183d2007-03-05 00:00:42 +000081 const SequentialType *SQT = cast<SequentialType>(*GTI);
Duncan Sands777d2302009-05-09 07:06:46 +000082 Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
Chris Lattner03dd25c2007-01-31 00:51:48 +000083 }
84 }
85 return true;
86 }
87
88 return false;
89}
90
91
92/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
Nick Lewycky67e35662008-12-15 01:35:36 +000093/// Attempt to symbolically evaluate the result of a binary operator merging
Chris Lattner03dd25c2007-01-31 00:51:48 +000094/// these together. If target data info is available, it is provided as TD,
95/// otherwise TD is null.
96static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
Owen Anderson50895512009-07-06 18:42:36 +000097 Constant *Op1, const TargetData *TD,
Owen Andersone922c022009-07-22 00:24:57 +000098 LLVMContext &Context){
Chris Lattner03dd25c2007-01-31 00:51:48 +000099 // SROA
100
101 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
102 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
103 // bits.
104
105
106 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
107 // constant. This happens frequently when iterating over a global array.
108 if (Opc == Instruction::Sub && TD) {
109 GlobalValue *GV1, *GV2;
110 int64_t Offs1, Offs2;
111
112 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
113 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
114 GV1 == GV2) {
115 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Owen Andersoneed707b2009-07-24 23:12:02 +0000116 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000117 }
118 }
119
Chris Lattner03dd25c2007-01-31 00:51:48 +0000120 return 0;
121}
122
123/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
124/// constant expression, do so.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000125static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000126 const Type *ResultTy,
Owen Andersone922c022009-07-22 00:24:57 +0000127 LLVMContext &Context,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000128 const TargetData *TD) {
129 Constant *Ptr = Ops[0];
Chris Lattner268e7d72008-05-08 04:54:43 +0000130 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +0000131 return 0;
Dan Gohmancda97062009-08-21 16:52:54 +0000132
133 unsigned BitWidth = TD->getTypeSizeInBits(TD->getIntPtrType(Context));
134 APInt BasePtr(BitWidth, 0);
Dan Gohmande0e5872009-08-19 18:18:36 +0000135 bool BaseIsInt = true;
Chris Lattner268e7d72008-05-08 04:54:43 +0000136 if (!Ptr->isNullValue()) {
137 // If this is a inttoptr from a constant int, we can fold this as the base,
138 // otherwise we can't.
139 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
140 if (CE->getOpcode() == Instruction::IntToPtr)
Dan Gohman71780102009-08-21 18:27:26 +0000141 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) {
Dan Gohmancda97062009-08-21 16:52:54 +0000142 BasePtr = Base->getValue();
Dan Gohman71780102009-08-21 18:27:26 +0000143 BasePtr.zextOrTrunc(BitWidth);
144 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000145
146 if (BasePtr == 0)
Dan Gohmande0e5872009-08-19 18:18:36 +0000147 BaseIsInt = false;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000148 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000149
150 // If this is a constant expr gep that is effectively computing an
151 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
152 for (unsigned i = 1; i != NumOps; ++i)
153 if (!isa<ConstantInt>(Ops[i]))
Dan Gohmande0e5872009-08-19 18:18:36 +0000154 return 0;
Chris Lattner268e7d72008-05-08 04:54:43 +0000155
Dan Gohmancda97062009-08-21 16:52:54 +0000156 APInt Offset = APInt(BitWidth,
157 TD->getIndexedOffset(Ptr->getType(),
158 (Value**)Ops+1, NumOps-1));
Dan Gohmande0e5872009-08-19 18:18:36 +0000159 // If the base value for this address is a literal integer value, fold the
160 // getelementptr to the resulting integer value casted to the pointer type.
161 if (BaseIsInt) {
Dan Gohmancda97062009-08-21 16:52:54 +0000162 Constant *C = ConstantInt::get(Context, Offset+BasePtr);
Dan Gohmande0e5872009-08-19 18:18:36 +0000163 return ConstantExpr::getIntToPtr(C, ResultTy);
164 }
165
166 // Otherwise form a regular getelementptr. Recompute the indices so that
167 // we eliminate over-indexing of the notional static type array bounds.
168 // This makes it easy to determine if the getelementptr is "inbounds".
169 // Also, this helps GlobalOpt do SROA on GlobalVariables.
170 const Type *Ty = Ptr->getType();
171 SmallVector<Constant*, 32> NewIdxs;
Dan Gohman3d013342009-08-19 22:46:59 +0000172 do {
Dan Gohmande0e5872009-08-19 18:18:36 +0000173 if (const SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
Dan Gohman3d013342009-08-19 22:46:59 +0000174 // The only pointer indexing we'll do is on the first index of the GEP.
Chris Lattnerf19f9342009-09-02 05:35:45 +0000175 if (isa<PointerType>(ATy) && !NewIdxs.empty())
Dan Gohman3d013342009-08-19 22:46:59 +0000176 break;
Dan Gohmande0e5872009-08-19 18:18:36 +0000177 // Determine which element of the array the offset points into.
Dan Gohmancda97062009-08-21 16:52:54 +0000178 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
Dan Gohmande0e5872009-08-19 18:18:36 +0000179 if (ElemSize == 0)
180 return 0;
Dan Gohmancda97062009-08-21 16:52:54 +0000181 APInt NewIdx = Offset.udiv(ElemSize);
Dan Gohmande0e5872009-08-19 18:18:36 +0000182 Offset -= NewIdx * ElemSize;
183 NewIdxs.push_back(ConstantInt::get(TD->getIntPtrType(Context), NewIdx));
184 Ty = ATy->getElementType();
185 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Dan Gohmancda97062009-08-21 16:52:54 +0000186 // Determine which field of the struct the offset points into. The
187 // getZExtValue is at least as safe as the StructLayout API because we
188 // know the offset is within the struct at this point.
Dan Gohmande0e5872009-08-19 18:18:36 +0000189 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohmancda97062009-08-21 16:52:54 +0000190 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Dan Gohmande0e5872009-08-19 18:18:36 +0000191 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Context), ElIdx));
Dan Gohmancda97062009-08-21 16:52:54 +0000192 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohmande0e5872009-08-19 18:18:36 +0000193 Ty = STy->getTypeAtIndex(ElIdx);
194 } else {
Dan Gohman3d013342009-08-19 22:46:59 +0000195 // We've reached some non-indexable type.
196 break;
Dan Gohmande0e5872009-08-19 18:18:36 +0000197 }
Dan Gohman3d013342009-08-19 22:46:59 +0000198 } while (Ty != cast<PointerType>(ResultTy)->getElementType());
199
200 // If we haven't used up the entire offset by descending the static
201 // type, then the offset is pointing into the middle of an indivisible
202 // member, so we can't simplify it.
203 if (Offset != 0)
204 return 0;
Dan Gohmande0e5872009-08-19 18:18:36 +0000205
Dan Gohmane56a94e2009-09-03 22:17:40 +0000206 // Create the GEP constant expr.
207 Constant *C = ConstantExpr::getGetElementPtr(Ptr,
208 &NewIdxs[0], NewIdxs.size());
209 assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
210 "Computed GetElementPtr has unexpected type!");
211
Dan Gohmande0e5872009-08-19 18:18:36 +0000212 // If the base is the start of a GlobalVariable and all the array indices
213 // remain in their static bounds, the GEP is inbounds. We can check that
214 // all indices are in bounds by just checking the first index only
Dan Gohmane56a94e2009-09-03 22:17:40 +0000215 // because we've just normalized all the indices. We can mutate the
216 // Constant in place because we've proven that the indices are in bounds,
217 // so they'll always be in bounds.
218 if (isa<GlobalVariable>(Ptr) && NewIdxs[0]->isNullValue())
219 if (GEPOperator *GEP = dyn_cast<GEPOperator>(C))
220 GEP->setIsInBounds(true);
Dan Gohmande0e5872009-08-19 18:18:36 +0000221
Dan Gohman3d013342009-08-19 22:46:59 +0000222 // If we ended up indexing a member with a type that doesn't match
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000223 // the type of what the original indices indexed, add a cast.
Dan Gohman3d013342009-08-19 22:46:59 +0000224 if (Ty != cast<PointerType>(ResultTy)->getElementType())
225 C = ConstantExpr::getBitCast(C, ResultTy);
226
227 return C;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000228}
229
Chris Lattner1afab9c2007-12-11 07:29:44 +0000230/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
231/// targetdata. Return 0 if unfoldable.
232static Constant *FoldBitCast(Constant *C, const Type *DestTy,
Owen Andersone922c022009-07-22 00:24:57 +0000233 const TargetData &TD, LLVMContext &Context) {
Chris Lattner1afab9c2007-12-11 07:29:44 +0000234 // If this is a bitcast from constant vector -> vector, fold it.
235 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
236 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
237 // If the element types match, VMCore can fold it.
238 unsigned NumDstElt = DestVTy->getNumElements();
239 unsigned NumSrcElt = CV->getNumOperands();
240 if (NumDstElt == NumSrcElt)
241 return 0;
242
243 const Type *SrcEltTy = CV->getType()->getElementType();
244 const Type *DstEltTy = DestVTy->getElementType();
245
246 // Otherwise, we're changing the number of elements in a vector, which
247 // requires endianness information to do the right thing. For example,
248 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
249 // folds to (little endian):
250 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
251 // and to (big endian):
252 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
253
254 // First thing is first. We only want to think about integer here, so if
255 // we have something in FP form, recast it as integer.
256 if (DstEltTy->isFloatingPoint()) {
257 // Fold to an vector of integers with same size as our FP type.
258 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Owen Andersondebcb012009-07-29 22:17:13 +0000259 const Type *DestIVTy = VectorType::get(
Owen Anderson1d0be152009-08-13 21:58:54 +0000260 IntegerType::get(Context, FPWidth), NumDstElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000261 // Recursively handle this integer conversion, if possible.
Owen Anderson50895512009-07-06 18:42:36 +0000262 C = FoldBitCast(C, DestIVTy, TD, Context);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000263 if (!C) return 0;
264
265 // Finally, VMCore can handle this now that #elts line up.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000266 return ConstantExpr::getBitCast(C, DestTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000267 }
268
269 // Okay, we know the destination is integer, if the input is FP, convert
270 // it to integer first.
271 if (SrcEltTy->isFloatingPoint()) {
272 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Owen Andersondebcb012009-07-29 22:17:13 +0000273 const Type *SrcIVTy = VectorType::get(
Owen Anderson1d0be152009-08-13 21:58:54 +0000274 IntegerType::get(Context, FPWidth), NumSrcElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000275 // Ask VMCore to do the conversion now that #elts line up.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000276 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000277 CV = dyn_cast<ConstantVector>(C);
278 if (!CV) return 0; // If VMCore wasn't able to fold it, bail out.
279 }
280
281 // Now we know that the input and output vectors are both integer vectors
282 // of the same size, and that their #elements is not the same. Do the
283 // conversion here, which depends on whether the input or output has
284 // more elements.
285 bool isLittleEndian = TD.isLittleEndian();
286
287 SmallVector<Constant*, 32> Result;
288 if (NumDstElt < NumSrcElt) {
289 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
Owen Andersona7235ea2009-07-31 20:28:14 +0000290 Constant *Zero = Constant::getNullValue(DstEltTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000291 unsigned Ratio = NumSrcElt/NumDstElt;
292 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
293 unsigned SrcElt = 0;
294 for (unsigned i = 0; i != NumDstElt; ++i) {
295 // Build each element of the result.
296 Constant *Elt = Zero;
297 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
298 for (unsigned j = 0; j != Ratio; ++j) {
299 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
300 if (!Src) return 0; // Reject constantexpr elements.
301
302 // Zero extend the element to the right size.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000303 Src = ConstantExpr::getZExt(Src, Elt->getType());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000304
305 // Shift it to the right place, depending on endianness.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000306 Src = ConstantExpr::getShl(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000307 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000308 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
309
310 // Mix it in.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000311 Elt = ConstantExpr::getOr(Elt, Src);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000312 }
313 Result.push_back(Elt);
314 }
315 } else {
316 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
317 unsigned Ratio = NumDstElt/NumSrcElt;
318 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
319
320 // Loop over each source value, expanding into multiple results.
321 for (unsigned i = 0; i != NumSrcElt; ++i) {
322 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
323 if (!Src) return 0; // Reject constantexpr elements.
324
325 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
326 for (unsigned j = 0; j != Ratio; ++j) {
327 // Shift the piece of the value into the right place, depending on
328 // endianness.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000329 Constant *Elt = ConstantExpr::getLShr(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000330 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000331 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
332
333 // Truncate and remember this piece.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000334 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000335 }
336 }
337 }
338
Owen Andersonaf7ec972009-07-28 21:19:26 +0000339 return ConstantVector::get(Result.data(), Result.size());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000340 }
341 }
342
343 return 0;
344}
345
Chris Lattner03dd25c2007-01-31 00:51:48 +0000346
347//===----------------------------------------------------------------------===//
348// Constant Folding public APIs
349//===----------------------------------------------------------------------===//
350
351
Chris Lattner55207322007-01-30 23:45:45 +0000352/// ConstantFoldInstruction - Attempt to constant fold the specified
353/// instruction. If successful, the constant result is returned, if not, null
354/// is returned. Note that this function can only fail when attempting to fold
355/// instructions like loads and stores, which have no constant expression form.
356///
Owen Andersone922c022009-07-22 00:24:57 +0000357Constant *llvm::ConstantFoldInstruction(Instruction *I, LLVMContext &Context,
Owen Anderson50895512009-07-06 18:42:36 +0000358 const TargetData *TD) {
Chris Lattner55207322007-01-30 23:45:45 +0000359 if (PHINode *PN = dyn_cast<PHINode>(I)) {
360 if (PN->getNumIncomingValues() == 0)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000361 return UndefValue::get(PN->getType());
John Criswellbd9d3702005-10-27 16:00:10 +0000362
Chris Lattner55207322007-01-30 23:45:45 +0000363 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
364 if (Result == 0) return 0;
365
366 // Handle PHI nodes specially here...
367 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
368 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
369 return 0; // Not all the same incoming constants...
370
371 // If we reach here, all incoming values are the same constant.
372 return Result;
373 }
374
375 // Scan the operand list, checking to see if they are all constants, if so,
376 // hand off to ConstantFoldInstOperands.
377 SmallVector<Constant*, 8> Ops;
Gabor Greifde2d74b2008-05-22 06:43:33 +0000378 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
379 if (Constant *Op = dyn_cast<Constant>(*i))
Chris Lattner55207322007-01-30 23:45:45 +0000380 Ops.push_back(Op);
381 else
382 return 0; // All operands not constant!
383
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000384 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
385 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000386 Ops.data(), Ops.size(),
387 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000388 else
389 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +0000390 Ops.data(), Ops.size(), Context, TD);
Chris Lattner55207322007-01-30 23:45:45 +0000391}
392
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000393/// ConstantFoldConstantExpression - Attempt to fold the constant expression
394/// using the specified TargetData. If successful, the constant result is
395/// result is returned, if not, null is returned.
396Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
Owen Andersone922c022009-07-22 00:24:57 +0000397 LLVMContext &Context,
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000398 const TargetData *TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000399 SmallVector<Constant*, 8> Ops;
400 for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
401 Ops.push_back(cast<Constant>(*i));
402
403 if (CE->isCompare())
404 return ConstantFoldCompareInstOperands(CE->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000405 Ops.data(), Ops.size(),
406 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000407 else
408 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
Owen Anderson50895512009-07-06 18:42:36 +0000409 Ops.data(), Ops.size(), Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000410}
411
Chris Lattner55207322007-01-30 23:45:45 +0000412/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
413/// specified opcode and operands. If successful, the constant result is
414/// returned, if not, null is returned. Note that this function can fail when
415/// attempting to fold instructions like loads and stores, which have no
416/// constant expression form.
417///
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000418Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
419 Constant* const* Ops, unsigned NumOps,
Owen Andersone922c022009-07-22 00:24:57 +0000420 LLVMContext &Context,
Chris Lattner55207322007-01-30 23:45:45 +0000421 const TargetData *TD) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000422 // Handle easy binops first.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000423 if (Instruction::isBinaryOp(Opcode)) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000424 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
Owen Anderson50895512009-07-06 18:42:36 +0000425 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD,
426 Context))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000427 return C;
428
Owen Andersonbaf3c402009-07-29 18:55:55 +0000429 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000430 }
Chris Lattner55207322007-01-30 23:45:45 +0000431
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000432 switch (Opcode) {
Chris Lattner55207322007-01-30 23:45:45 +0000433 default: return 0;
434 case Instruction::Call:
435 if (Function *F = dyn_cast<Function>(Ops[0]))
436 if (canConstantFoldCallTo(F))
Chris Lattnerad58eb32007-01-31 18:04:55 +0000437 return ConstantFoldCall(F, Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000438 return 0;
439 case Instruction::ICmp:
440 case Instruction::FCmp:
Torok Edwinc23197a2009-07-14 16:55:14 +0000441 llvm_unreachable("This function is invalid for compares: no predicate specified");
Chris Lattner001f7532007-08-11 23:49:01 +0000442 case Instruction::PtrToInt:
443 // If the input is a inttoptr, eliminate the pair. This requires knowing
444 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
445 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
446 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
447 Constant *Input = CE->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +0000448 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000449 if (TD->getPointerSizeInBits() < InWidth) {
450 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +0000451 ConstantInt::get(Context, APInt::getLowBitsSet(InWidth,
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000452 TD->getPointerSizeInBits()));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000453 Input = ConstantExpr::getAnd(Input, Mask);
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000454 }
Chris Lattner001f7532007-08-11 23:49:01 +0000455 // Do a zext or trunc to get to the dest size.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000456 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner001f7532007-08-11 23:49:01 +0000457 }
458 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000459 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner001f7532007-08-11 23:49:01 +0000460 case Instruction::IntToPtr:
Duncan Sands81b06be2008-08-13 20:20:35 +0000461 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
462 // the int size is >= the ptr size. This requires knowing the width of a
463 // pointer, so it can't be done in ConstantExpr::getCast.
464 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000465 if (TD &&
Duncan Sands81b06be2008-08-13 20:20:35 +0000466 TD->getPointerSizeInBits() <=
Dan Gohman6de29f82009-06-15 22:12:54 +0000467 CE->getType()->getScalarSizeInBits()) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000468 if (CE->getOpcode() == Instruction::PtrToInt) {
469 Constant *Input = CE->getOperand(0);
Owen Anderson50895512009-07-06 18:42:36 +0000470 Constant *C = FoldBitCast(Input, DestTy, *TD, Context);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000471 return C ? C : ConstantExpr::getBitCast(Input, DestTy);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000472 }
473 // If there's a constant offset added to the integer value before
474 // it is casted back to a pointer, see if the expression can be
475 // converted into a GEP.
476 if (CE->getOpcode() == Instruction::Add)
477 if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
478 if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
479 if (R->getOpcode() == Instruction::PtrToInt)
480 if (GlobalVariable *GV =
481 dyn_cast<GlobalVariable>(R->getOperand(0))) {
482 const PointerType *GVTy = cast<PointerType>(GV->getType());
483 if (const ArrayType *AT =
484 dyn_cast<ArrayType>(GVTy->getElementType())) {
485 const Type *ElTy = AT->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000486 uint64_t AllocSize = TD->getTypeAllocSize(ElTy);
487 APInt PSA(L->getValue().getBitWidth(), AllocSize);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000488 if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
489 L->getValue().urem(PSA) == 0) {
490 APInt ElemIdx = L->getValue().udiv(PSA);
491 if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
492 AT->getNumElements()))) {
493 Constant *Index[] = {
Owen Andersona7235ea2009-07-31 20:28:14 +0000494 Constant::getNullValue(CE->getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +0000495 ConstantInt::get(Context, ElemIdx)
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000496 };
Owen Anderson50895512009-07-06 18:42:36 +0000497 return
Owen Andersonbaf3c402009-07-29 18:55:55 +0000498 ConstantExpr::getGetElementPtr(GV, &Index[0], 2);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000499 }
500 }
501 }
502 }
Duncan Sands81b06be2008-08-13 20:20:35 +0000503 }
504 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000505 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000506 case Instruction::Trunc:
507 case Instruction::ZExt:
508 case Instruction::SExt:
509 case Instruction::FPTrunc:
510 case Instruction::FPExt:
511 case Instruction::UIToFP:
512 case Instruction::SIToFP:
513 case Instruction::FPToUI:
514 case Instruction::FPToSI:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000515 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000516 case Instruction::BitCast:
Chris Lattner1afab9c2007-12-11 07:29:44 +0000517 if (TD)
Owen Anderson50895512009-07-06 18:42:36 +0000518 if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD, Context))
Chris Lattner1afab9c2007-12-11 07:29:44 +0000519 return C;
Owen Andersonbaf3c402009-07-29 18:55:55 +0000520 return ConstantExpr::getBitCast(Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000521 case Instruction::Select:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000522 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000523 case Instruction::ExtractElement:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000524 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner55207322007-01-30 23:45:45 +0000525 case Instruction::InsertElement:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000526 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000527 case Instruction::ShuffleVector:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000528 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000529 case Instruction::GetElementPtr:
Owen Anderson50895512009-07-06 18:42:36 +0000530 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, Context, TD))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000531 return C;
532
Owen Andersonbaf3c402009-07-29 18:55:55 +0000533 return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000534 }
535}
536
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000537/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
538/// instruction (icmp/fcmp) with the specified operands. If it fails, it
539/// returns a constant expression of the specified operands.
540///
541Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
542 Constant*const * Ops,
543 unsigned NumOps,
Owen Andersone922c022009-07-22 00:24:57 +0000544 LLVMContext &Context,
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000545 const TargetData *TD) {
546 // fold: icmp (inttoptr x), null -> icmp x, 0
547 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000548 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000549 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
550 //
551 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
552 // around to know if bit truncation is happening.
553 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
554 if (TD && Ops[1]->isNullValue()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000555 const Type *IntPtrTy = TD->getIntPtrType(Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000556 if (CE0->getOpcode() == Instruction::IntToPtr) {
557 // Convert the integer value to the right size to ensure we get the
558 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000559 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000560 IntPtrTy, false);
Owen Andersona7235ea2009-07-31 20:28:14 +0000561 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Owen Anderson50895512009-07-06 18:42:36 +0000562 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
563 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000564 }
565
566 // Only do this transformation if the int is intptrty in size, otherwise
567 // there is a truncation or extension that we aren't modeling.
568 if (CE0->getOpcode() == Instruction::PtrToInt &&
569 CE0->getType() == IntPtrTy) {
570 Constant *C = CE0->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +0000571 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000572 // FIXME!
Owen Anderson50895512009-07-06 18:42:36 +0000573 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
574 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000575 }
576 }
577
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000578 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
579 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000580 const Type *IntPtrTy = TD->getIntPtrType(Context);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000581
582 if (CE0->getOpcode() == Instruction::IntToPtr) {
583 // Convert the integer value to the right size to ensure we get the
584 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000585 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000586 IntPtrTy, false);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000587 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000588 IntPtrTy, false);
589 Constant *NewOps[] = { C0, C1 };
Owen Anderson50895512009-07-06 18:42:36 +0000590 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
591 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000592 }
593
594 // Only do this transformation if the int is intptrty in size, otherwise
595 // there is a truncation or extension that we aren't modeling.
596 if ((CE0->getOpcode() == Instruction::PtrToInt &&
597 CE0->getType() == IntPtrTy &&
598 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
599 Constant *NewOps[] = {
600 CE0->getOperand(0), CE1->getOperand(0)
601 };
Owen Anderson50895512009-07-06 18:42:36 +0000602 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
603 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000604 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000605 }
606 }
607 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000608 return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000609}
610
611
Chris Lattner55207322007-01-30 23:45:45 +0000612/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
613/// getelementptr constantexpr, return the constant value being addressed by the
614/// constant expression, or null if something is funny and we can't decide.
615Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Owen Anderson50895512009-07-06 18:42:36 +0000616 ConstantExpr *CE,
Owen Andersone922c022009-07-22 00:24:57 +0000617 LLVMContext &Context) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000618 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner55207322007-01-30 23:45:45 +0000619 return 0; // Do not allow stepping over the value!
620
621 // Loop over all of the operands, tracking down which value we are
622 // addressing...
623 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
624 for (++I; I != E; ++I)
625 if (const StructType *STy = dyn_cast<StructType>(*I)) {
626 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
627 assert(CU->getZExtValue() < STy->getNumElements() &&
628 "Struct index out of range!");
629 unsigned El = (unsigned)CU->getZExtValue();
630 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
631 C = CS->getOperand(El);
632 } else if (isa<ConstantAggregateZero>(C)) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000633 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000634 } else if (isa<UndefValue>(C)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000635 C = UndefValue::get(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000636 } else {
637 return 0;
638 }
639 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
640 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
641 if (CI->getZExtValue() >= ATy->getNumElements())
642 return 0;
643 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
644 C = CA->getOperand(CI->getZExtValue());
645 else if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +0000646 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000647 else if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000648 C = UndefValue::get(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000649 else
650 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000651 } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
Chris Lattner55207322007-01-30 23:45:45 +0000652 if (CI->getZExtValue() >= PTy->getNumElements())
653 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000654 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
Chris Lattner55207322007-01-30 23:45:45 +0000655 C = CP->getOperand(CI->getZExtValue());
656 else if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +0000657 C = Constant::getNullValue(PTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000658 else if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000659 C = UndefValue::get(PTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000660 else
661 return 0;
662 } else {
663 return 0;
664 }
665 } else {
666 return 0;
667 }
668 return C;
669}
670
671
672//===----------------------------------------------------------------------===//
673// Constant Folding for Calls
674//
John Criswellbd9d3702005-10-27 16:00:10 +0000675
676/// canConstantFoldCallTo - Return true if its even possible to fold a call to
677/// the specified function.
678bool
Dan Gohmanfa9b80e2008-01-31 01:05:10 +0000679llvm::canConstantFoldCallTo(const Function *F) {
John Criswellbd9d3702005-10-27 16:00:10 +0000680 switch (F->getIntrinsicID()) {
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000681 case Intrinsic::sqrt:
682 case Intrinsic::powi:
Reid Spencere9391fd2007-04-01 07:35:23 +0000683 case Intrinsic::bswap:
684 case Intrinsic::ctpop:
685 case Intrinsic::ctlz:
686 case Intrinsic::cttz:
John Criswellbd9d3702005-10-27 16:00:10 +0000687 return true;
688 default: break;
689 }
690
Chris Lattner6f532a92009-04-03 00:02:39 +0000691 if (!F->hasName()) return false;
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000692 StringRef Name = F->getName();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000693
694 // In these cases, the check of the length is required. We don't want to
695 // return true for a name like "cos\0blah" which strcmp would return equal to
696 // "cos", but has length 8.
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000697 switch (Name[0]) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000698 default: return false;
699 case 'a':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000700 return Name == "acos" || Name == "asin" ||
701 Name == "atan" || Name == "atan2";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000702 case 'c':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000703 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000704 case 'e':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000705 return Name == "exp";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000706 case 'f':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000707 return Name == "fabs" || Name == "fmod" || Name == "floor";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000708 case 'l':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000709 return Name == "log" || Name == "log10";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000710 case 'p':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000711 return Name == "pow";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000712 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000713 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
714 Name == "sinf" || Name == "sqrtf";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000715 case 't':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000716 return Name == "tan" || Name == "tanh";
John Criswellbd9d3702005-10-27 16:00:10 +0000717 }
718}
719
Chris Lattner72d88ae2007-01-30 23:15:43 +0000720static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
Owen Andersone922c022009-07-22 00:24:57 +0000721 const Type *Ty, LLVMContext &Context) {
John Criswellbd9d3702005-10-27 16:00:10 +0000722 errno = 0;
723 V = NativeFP(V);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000724 if (errno != 0) {
725 errno = 0;
726 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000727 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000728
Owen Anderson1d0be152009-08-13 21:58:54 +0000729 if (Ty == Type::getFloatTy(Context))
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000730 return ConstantFP::get(Context, APFloat((float)V));
Owen Anderson1d0be152009-08-13 21:58:54 +0000731 if (Ty == Type::getDoubleTy(Context))
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000732 return ConstantFP::get(Context, APFloat(V));
Torok Edwinc23197a2009-07-14 16:55:14 +0000733 llvm_unreachable("Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000734 return 0; // dummy return to suppress warning
John Criswellbd9d3702005-10-27 16:00:10 +0000735}
736
Dan Gohman38415242007-07-16 15:26:22 +0000737static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
738 double V, double W,
Owen Anderson50895512009-07-06 18:42:36 +0000739 const Type *Ty,
Owen Andersone922c022009-07-22 00:24:57 +0000740 LLVMContext &Context) {
Dan Gohman38415242007-07-16 15:26:22 +0000741 errno = 0;
742 V = NativeFP(V, W);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000743 if (errno != 0) {
744 errno = 0;
745 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000746 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000747
Owen Anderson1d0be152009-08-13 21:58:54 +0000748 if (Ty == Type::getFloatTy(Context))
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000749 return ConstantFP::get(Context, APFloat((float)V));
Owen Anderson1d0be152009-08-13 21:58:54 +0000750 if (Ty == Type::getDoubleTy(Context))
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000751 return ConstantFP::get(Context, APFloat(V));
Torok Edwinc23197a2009-07-14 16:55:14 +0000752 llvm_unreachable("Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000753 return 0; // dummy return to suppress warning
Dan Gohman38415242007-07-16 15:26:22 +0000754}
755
John Criswellbd9d3702005-10-27 16:00:10 +0000756/// ConstantFoldCall - Attempt to constant fold a call to the specified function
757/// with the specified arguments, returning null if unsuccessful.
Dale Johannesen43421b32007-09-06 18:13:44 +0000758
John Criswellbd9d3702005-10-27 16:00:10 +0000759Constant *
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000760llvm::ConstantFoldCall(Function *F,
761 Constant* const* Operands, unsigned NumOperands) {
Chris Lattner6f532a92009-04-03 00:02:39 +0000762 if (!F->hasName()) return 0;
Owen Andersone922c022009-07-22 00:24:57 +0000763 LLVMContext &Context = F->getContext();
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000764 StringRef Name = F->getName();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000765
John Criswellbd9d3702005-10-27 16:00:10 +0000766 const Type *Ty = F->getReturnType();
Chris Lattner72d88ae2007-01-30 23:15:43 +0000767 if (NumOperands == 1) {
John Criswellbd9d3702005-10-27 16:00:10 +0000768 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000769 if (Ty!=Type::getFloatTy(F->getContext()) &&
770 Ty!=Type::getDoubleTy(Context))
Dale Johannesen43421b32007-09-06 18:13:44 +0000771 return 0;
772 /// Currently APFloat versions of these functions do not exist, so we use
773 /// the host native double versions. Float versions are not called
774 /// directly but for all these it is true (float)(f((double)arg)) ==
775 /// f(arg). Long double not supported yet.
Owen Anderson1d0be152009-08-13 21:58:54 +0000776 double V = Ty==Type::getFloatTy(F->getContext()) ?
777 (double)Op->getValueAPF().convertToFloat():
Dale Johannesen43421b32007-09-06 18:13:44 +0000778 Op->getValueAPF().convertToDouble();
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000779 switch (Name[0]) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000780 case 'a':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000781 if (Name == "acos")
Owen Anderson50895512009-07-06 18:42:36 +0000782 return ConstantFoldFP(acos, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000783 else if (Name == "asin")
Owen Anderson50895512009-07-06 18:42:36 +0000784 return ConstantFoldFP(asin, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000785 else if (Name == "atan")
Owen Anderson50895512009-07-06 18:42:36 +0000786 return ConstantFoldFP(atan, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000787 break;
788 case 'c':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000789 if (Name == "ceil")
Owen Anderson50895512009-07-06 18:42:36 +0000790 return ConstantFoldFP(ceil, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000791 else if (Name == "cos")
Owen Anderson50895512009-07-06 18:42:36 +0000792 return ConstantFoldFP(cos, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000793 else if (Name == "cosh")
Owen Anderson50895512009-07-06 18:42:36 +0000794 return ConstantFoldFP(cosh, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000795 else if (Name == "cosf")
Owen Anderson50895512009-07-06 18:42:36 +0000796 return ConstantFoldFP(cos, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000797 break;
798 case 'e':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000799 if (Name == "exp")
Owen Anderson50895512009-07-06 18:42:36 +0000800 return ConstantFoldFP(exp, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000801 break;
802 case 'f':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000803 if (Name == "fabs")
Owen Anderson50895512009-07-06 18:42:36 +0000804 return ConstantFoldFP(fabs, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000805 else if (Name == "floor")
Owen Anderson50895512009-07-06 18:42:36 +0000806 return ConstantFoldFP(floor, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000807 break;
808 case 'l':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000809 if (Name == "log" && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +0000810 return ConstantFoldFP(log, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000811 else if (Name == "log10" && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +0000812 return ConstantFoldFP(log10, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000813 else if (Name == "llvm.sqrt.f32" ||
814 Name == "llvm.sqrt.f64") {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000815 if (V >= -0.0)
Owen Anderson50895512009-07-06 18:42:36 +0000816 return ConstantFoldFP(sqrt, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000817 else // Undefined
Owen Andersona7235ea2009-07-31 20:28:14 +0000818 return Constant::getNullValue(Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000819 }
820 break;
821 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000822 if (Name == "sin")
Owen Anderson50895512009-07-06 18:42:36 +0000823 return ConstantFoldFP(sin, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000824 else if (Name == "sinh")
Owen Anderson50895512009-07-06 18:42:36 +0000825 return ConstantFoldFP(sinh, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000826 else if (Name == "sqrt" && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +0000827 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000828 else if (Name == "sqrtf" && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +0000829 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000830 else if (Name == "sinf")
Owen Anderson50895512009-07-06 18:42:36 +0000831 return ConstantFoldFP(sin, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000832 break;
833 case 't':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000834 if (Name == "tan")
Owen Anderson50895512009-07-06 18:42:36 +0000835 return ConstantFoldFP(tan, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000836 else if (Name == "tanh")
Owen Anderson50895512009-07-06 18:42:36 +0000837 return ConstantFoldFP(tanh, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000838 break;
839 default:
840 break;
John Criswellbd9d3702005-10-27 16:00:10 +0000841 }
Reid Spencerb83eb642006-10-20 07:07:24 +0000842 } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000843 if (Name.startswith("llvm.bswap"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000844 return ConstantInt::get(Context, Op->getValue().byteSwap());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000845 else if (Name.startswith("llvm.ctpop"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000846 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000847 else if (Name.startswith("llvm.cttz"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000848 return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000849 else if (Name.startswith("llvm.ctlz"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000850 return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
John Criswellbd9d3702005-10-27 16:00:10 +0000851 }
Chris Lattner72d88ae2007-01-30 23:15:43 +0000852 } else if (NumOperands == 2) {
John Criswellbd9d3702005-10-27 16:00:10 +0000853 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000854 if (Ty!=Type::getFloatTy(F->getContext()) &&
855 Ty!=Type::getDoubleTy(Context))
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000856 return 0;
Owen Anderson1d0be152009-08-13 21:58:54 +0000857 double Op1V = Ty==Type::getFloatTy(F->getContext()) ?
Dale Johannesen43421b32007-09-06 18:13:44 +0000858 (double)Op1->getValueAPF().convertToFloat():
859 Op1->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000860 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000861 double Op2V = Ty==Type::getFloatTy(F->getContext()) ?
Dale Johannesen43421b32007-09-06 18:13:44 +0000862 (double)Op2->getValueAPF().convertToFloat():
863 Op2->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000864
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000865 if (Name == "pow") {
Owen Anderson50895512009-07-06 18:42:36 +0000866 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000867 } else if (Name == "fmod") {
Owen Anderson50895512009-07-06 18:42:36 +0000868 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000869 } else if (Name == "atan2") {
Owen Anderson50895512009-07-06 18:42:36 +0000870 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty, Context);
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000871 }
872 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000873 if (Name == "llvm.powi.f32") {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000874 return ConstantFP::get(Context, APFloat((float)std::pow((float)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +0000875 (int)Op2C->getZExtValue())));
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000876 } else if (Name == "llvm.powi.f64") {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000877 return ConstantFP::get(Context, APFloat((double)std::pow((double)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +0000878 (int)Op2C->getZExtValue())));
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000879 }
John Criswellbd9d3702005-10-27 16:00:10 +0000880 }
881 }
882 }
883 return 0;
884}
885