blob: 0ce1c24bed67b4d4badddad01b0bcc1a94adc090 [file] [log] [blame]
Dan Gohmance128852009-09-10 23:07:18 +00001//===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
Dan Gohmance128852009-09-10 23:07:18 +000010// This file defines routines for folding instructions into constants.
11//
12// Also, to supplement the basic VMCore ConstantExpr simplifications,
13// this file defines some additional folding routines that can make use of
14// TargetData information. These functions cannot go in VMCore due to library
15// dependency issues.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000016//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Analysis/ConstantFolding.h"
20#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Dan Gohmand46dc022009-05-07 19:46:24 +000023#include "llvm/GlobalVariable.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Owen Andersond4d90a02009-07-06 18:42:36 +000026#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/ADT/SmallVector.h"
Chris Lattnereb8fdd32007-08-08 06:55:43 +000028#include "llvm/ADT/StringMap.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#include "llvm/Target/TargetData.h"
Edwin Török675d5622009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
32#include "llvm/Support/MathExtras.h"
33#include <cerrno>
34#include <cmath>
35using namespace llvm;
36
37//===----------------------------------------------------------------------===//
38// Constant Folding internal helper functions
39//===----------------------------------------------------------------------===//
40
41/// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
42/// from a global, return the global and the constant. Because of
43/// constantexprs, this function is recursive.
44static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
45 int64_t &Offset, const TargetData &TD) {
46 // Trivial case, constant is the global.
47 if ((GV = dyn_cast<GlobalValue>(C))) {
48 Offset = 0;
49 return true;
50 }
51
52 // Otherwise, if this isn't a constant expr, bail out.
53 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
54 if (!CE) return false;
55
56 // Look through ptr->int and ptr->ptr casts.
57 if (CE->getOpcode() == Instruction::PtrToInt ||
58 CE->getOpcode() == Instruction::BitCast)
59 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
60
61 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
62 if (CE->getOpcode() == Instruction::GetElementPtr) {
63 // Cannot compute this if the element type of the pointer is missing size
64 // info.
Chris Lattnerd6e56912007-12-10 22:53:04 +000065 if (!cast<PointerType>(CE->getOperand(0)->getType())
66 ->getElementType()->isSized())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067 return false;
68
69 // If the base isn't a global+constant, we aren't either.
70 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
71 return false;
72
73 // Otherwise, add any offset that our operands provide.
74 gep_type_iterator GTI = gep_type_begin(CE);
Gabor Greifece177d2008-05-22 06:43:33 +000075 for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
Gabor Greiff3a502a2008-05-22 19:24:54 +000076 i != e; ++i, ++GTI) {
Gabor Greifece177d2008-05-22 06:43:33 +000077 ConstantInt *CI = dyn_cast<ConstantInt>(*i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078 if (!CI) return false; // Index isn't a simple constant?
79 if (CI->getZExtValue() == 0) continue; // Not adding anything.
80
81 if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
82 // N = N + Offset
83 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
84 } else {
85 const SequentialType *SQT = cast<SequentialType>(*GTI);
Duncan Sandsec4f97d2009-05-09 07:06:46 +000086 Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087 }
88 }
89 return true;
90 }
91
92 return false;
93}
94
95
96/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
Nick Lewycky238c5b22008-12-15 01:35:36 +000097/// Attempt to symbolically evaluate the result of a binary operator merging
Dan Gohmanf17a25c2007-07-18 16:29:46 +000098/// these together. If target data info is available, it is provided as TD,
99/// otherwise TD is null.
100static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
Owen Andersond4d90a02009-07-06 18:42:36 +0000101 Constant *Op1, const TargetData *TD,
Owen Anderson175b6542009-07-22 00:24:57 +0000102 LLVMContext &Context){
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103 // SROA
104
105 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
106 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
107 // bits.
108
109
110 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
111 // constant. This happens frequently when iterating over a global array.
112 if (Opc == Instruction::Sub && TD) {
113 GlobalValue *GV1, *GV2;
114 int64_t Offs1, Offs2;
115
116 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
117 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
118 GV1 == GV2) {
119 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Owen Andersoneacb44d2009-07-24 23:12:02 +0000120 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000121 }
122 }
123
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000124 return 0;
125}
126
127/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
128/// constant expression, do so.
Chris Lattnerd6e56912007-12-10 22:53:04 +0000129static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000130 const Type *ResultTy,
Owen Anderson175b6542009-07-22 00:24:57 +0000131 LLVMContext &Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 const TargetData *TD) {
133 Constant *Ptr = Ops[0];
Chris Lattner3c894522008-05-08 04:54:43 +0000134 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135 return 0;
Dan Gohman7c193842009-08-21 16:52:54 +0000136
137 unsigned BitWidth = TD->getTypeSizeInBits(TD->getIntPtrType(Context));
138 APInt BasePtr(BitWidth, 0);
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000139 bool BaseIsInt = true;
Chris Lattner3c894522008-05-08 04:54:43 +0000140 if (!Ptr->isNullValue()) {
141 // If this is a inttoptr from a constant int, we can fold this as the base,
142 // otherwise we can't.
143 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
144 if (CE->getOpcode() == Instruction::IntToPtr)
Dan Gohmanbfae8f32009-08-21 18:27:26 +0000145 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) {
Dan Gohman7c193842009-08-21 16:52:54 +0000146 BasePtr = Base->getValue();
Dan Gohmanbfae8f32009-08-21 18:27:26 +0000147 BasePtr.zextOrTrunc(BitWidth);
148 }
Chris Lattner3c894522008-05-08 04:54:43 +0000149
150 if (BasePtr == 0)
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000151 BaseIsInt = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152 }
Chris Lattner3c894522008-05-08 04:54:43 +0000153
154 // If this is a constant expr gep that is effectively computing an
155 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
156 for (unsigned i = 1; i != NumOps; ++i)
157 if (!isa<ConstantInt>(Ops[i]))
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000158 return 0;
Chris Lattner3c894522008-05-08 04:54:43 +0000159
Dan Gohman7c193842009-08-21 16:52:54 +0000160 APInt Offset = APInt(BitWidth,
161 TD->getIndexedOffset(Ptr->getType(),
162 (Value**)Ops+1, NumOps-1));
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000163 // If the base value for this address is a literal integer value, fold the
164 // getelementptr to the resulting integer value casted to the pointer type.
165 if (BaseIsInt) {
Dan Gohman7c193842009-08-21 16:52:54 +0000166 Constant *C = ConstantInt::get(Context, Offset+BasePtr);
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000167 return ConstantExpr::getIntToPtr(C, ResultTy);
168 }
169
170 // Otherwise form a regular getelementptr. Recompute the indices so that
171 // we eliminate over-indexing of the notional static type array bounds.
172 // This makes it easy to determine if the getelementptr is "inbounds".
173 // Also, this helps GlobalOpt do SROA on GlobalVariables.
174 const Type *Ty = Ptr->getType();
175 SmallVector<Constant*, 32> NewIdxs;
Dan Gohmane4575382009-08-19 22:46:59 +0000176 do {
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000177 if (const SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
Dan Gohmane4575382009-08-19 22:46:59 +0000178 // The only pointer indexing we'll do is on the first index of the GEP.
Chris Lattner12aaa012009-09-02 05:35:45 +0000179 if (isa<PointerType>(ATy) && !NewIdxs.empty())
Dan Gohmane4575382009-08-19 22:46:59 +0000180 break;
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000181 // Determine which element of the array the offset points into.
Dan Gohman7c193842009-08-21 16:52:54 +0000182 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000183 if (ElemSize == 0)
184 return 0;
Dan Gohman7c193842009-08-21 16:52:54 +0000185 APInt NewIdx = Offset.udiv(ElemSize);
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000186 Offset -= NewIdx * ElemSize;
187 NewIdxs.push_back(ConstantInt::get(TD->getIntPtrType(Context), NewIdx));
188 Ty = ATy->getElementType();
189 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Dan Gohman7c193842009-08-21 16:52:54 +0000190 // Determine which field of the struct the offset points into. The
191 // getZExtValue is at least as safe as the StructLayout API because we
192 // know the offset is within the struct at this point.
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000193 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman7c193842009-08-21 16:52:54 +0000194 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000195 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Context), ElIdx));
Dan Gohman7c193842009-08-21 16:52:54 +0000196 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000197 Ty = STy->getTypeAtIndex(ElIdx);
198 } else {
Dan Gohmane4575382009-08-19 22:46:59 +0000199 // We've reached some non-indexable type.
200 break;
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000201 }
Dan Gohmane4575382009-08-19 22:46:59 +0000202 } while (Ty != cast<PointerType>(ResultTy)->getElementType());
203
204 // If we haven't used up the entire offset by descending the static
205 // type, then the offset is pointing into the middle of an indivisible
206 // member, so we can't simplify it.
207 if (Offset != 0)
208 return 0;
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000209
Dan Gohman6200a6e2009-09-11 00:04:14 +0000210 // Create a GEP.
211 Constant *C =
Dan Gohman1046e412009-09-03 23:34:49 +0000212 ConstantExpr::getGetElementPtr(Ptr, &NewIdxs[0], NewIdxs.size());
213 assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
214 "Computed GetElementPtr has unexpected type!");
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000215
Dan Gohmane4575382009-08-19 22:46:59 +0000216 // If we ended up indexing a member with a type that doesn't match
Dan Gohman576c91e2009-08-20 16:42:55 +0000217 // the type of what the original indices indexed, add a cast.
Dan Gohmane4575382009-08-19 22:46:59 +0000218 if (Ty != cast<PointerType>(ResultTy)->getElementType())
219 C = ConstantExpr::getBitCast(C, ResultTy);
220
221 return C;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222}
223
Chris Lattner09d481b2007-12-11 07:29:44 +0000224/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
225/// targetdata. Return 0 if unfoldable.
226static Constant *FoldBitCast(Constant *C, const Type *DestTy,
Owen Anderson175b6542009-07-22 00:24:57 +0000227 const TargetData &TD, LLVMContext &Context) {
Chris Lattner09d481b2007-12-11 07:29:44 +0000228 // If this is a bitcast from constant vector -> vector, fold it.
229 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
230 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
231 // If the element types match, VMCore can fold it.
232 unsigned NumDstElt = DestVTy->getNumElements();
233 unsigned NumSrcElt = CV->getNumOperands();
234 if (NumDstElt == NumSrcElt)
235 return 0;
236
237 const Type *SrcEltTy = CV->getType()->getElementType();
238 const Type *DstEltTy = DestVTy->getElementType();
239
240 // Otherwise, we're changing the number of elements in a vector, which
241 // requires endianness information to do the right thing. For example,
242 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
243 // folds to (little endian):
244 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
245 // and to (big endian):
246 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
247
248 // First thing is first. We only want to think about integer here, so if
249 // we have something in FP form, recast it as integer.
250 if (DstEltTy->isFloatingPoint()) {
251 // Fold to an vector of integers with same size as our FP type.
252 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Owen Anderson6b6e2d92009-07-29 22:17:13 +0000253 const Type *DestIVTy = VectorType::get(
Owen Anderson35b47072009-08-13 21:58:54 +0000254 IntegerType::get(Context, FPWidth), NumDstElt);
Chris Lattner09d481b2007-12-11 07:29:44 +0000255 // Recursively handle this integer conversion, if possible.
Owen Andersond4d90a02009-07-06 18:42:36 +0000256 C = FoldBitCast(C, DestIVTy, TD, Context);
Chris Lattner09d481b2007-12-11 07:29:44 +0000257 if (!C) return 0;
258
259 // Finally, VMCore can handle this now that #elts line up.
Owen Anderson02b48c32009-07-29 18:55:55 +0000260 return ConstantExpr::getBitCast(C, DestTy);
Chris Lattner09d481b2007-12-11 07:29:44 +0000261 }
262
263 // Okay, we know the destination is integer, if the input is FP, convert
264 // it to integer first.
265 if (SrcEltTy->isFloatingPoint()) {
266 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Owen Anderson6b6e2d92009-07-29 22:17:13 +0000267 const Type *SrcIVTy = VectorType::get(
Owen Anderson35b47072009-08-13 21:58:54 +0000268 IntegerType::get(Context, FPWidth), NumSrcElt);
Chris Lattner09d481b2007-12-11 07:29:44 +0000269 // Ask VMCore to do the conversion now that #elts line up.
Owen Anderson02b48c32009-07-29 18:55:55 +0000270 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chris Lattner09d481b2007-12-11 07:29:44 +0000271 CV = dyn_cast<ConstantVector>(C);
272 if (!CV) return 0; // If VMCore wasn't able to fold it, bail out.
273 }
274
275 // Now we know that the input and output vectors are both integer vectors
276 // of the same size, and that their #elements is not the same. Do the
277 // conversion here, which depends on whether the input or output has
278 // more elements.
279 bool isLittleEndian = TD.isLittleEndian();
280
281 SmallVector<Constant*, 32> Result;
282 if (NumDstElt < NumSrcElt) {
283 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
Owen Andersonaac28372009-07-31 20:28:14 +0000284 Constant *Zero = Constant::getNullValue(DstEltTy);
Chris Lattner09d481b2007-12-11 07:29:44 +0000285 unsigned Ratio = NumSrcElt/NumDstElt;
286 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
287 unsigned SrcElt = 0;
288 for (unsigned i = 0; i != NumDstElt; ++i) {
289 // Build each element of the result.
290 Constant *Elt = Zero;
291 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
292 for (unsigned j = 0; j != Ratio; ++j) {
293 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
294 if (!Src) return 0; // Reject constantexpr elements.
295
296 // Zero extend the element to the right size.
Owen Anderson02b48c32009-07-29 18:55:55 +0000297 Src = ConstantExpr::getZExt(Src, Elt->getType());
Chris Lattner09d481b2007-12-11 07:29:44 +0000298
299 // Shift it to the right place, depending on endianness.
Owen Anderson02b48c32009-07-29 18:55:55 +0000300 Src = ConstantExpr::getShl(Src,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000301 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner09d481b2007-12-11 07:29:44 +0000302 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
303
304 // Mix it in.
Owen Anderson02b48c32009-07-29 18:55:55 +0000305 Elt = ConstantExpr::getOr(Elt, Src);
Chris Lattner09d481b2007-12-11 07:29:44 +0000306 }
307 Result.push_back(Elt);
308 }
309 } else {
310 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
311 unsigned Ratio = NumDstElt/NumSrcElt;
312 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
313
314 // Loop over each source value, expanding into multiple results.
315 for (unsigned i = 0; i != NumSrcElt; ++i) {
316 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
317 if (!Src) return 0; // Reject constantexpr elements.
318
319 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
320 for (unsigned j = 0; j != Ratio; ++j) {
321 // Shift the piece of the value into the right place, depending on
322 // endianness.
Owen Anderson02b48c32009-07-29 18:55:55 +0000323 Constant *Elt = ConstantExpr::getLShr(Src,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000324 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner09d481b2007-12-11 07:29:44 +0000325 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
326
327 // Truncate and remember this piece.
Owen Anderson02b48c32009-07-29 18:55:55 +0000328 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner09d481b2007-12-11 07:29:44 +0000329 }
330 }
331 }
332
Owen Anderson2f422e02009-07-28 21:19:26 +0000333 return ConstantVector::get(Result.data(), Result.size());
Chris Lattner09d481b2007-12-11 07:29:44 +0000334 }
335 }
336
337 return 0;
338}
339
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340
341//===----------------------------------------------------------------------===//
342// Constant Folding public APIs
343//===----------------------------------------------------------------------===//
344
345
346/// ConstantFoldInstruction - Attempt to constant fold the specified
347/// instruction. If successful, the constant result is returned, if not, null
348/// is returned. Note that this function can only fail when attempting to fold
349/// instructions like loads and stores, which have no constant expression form.
350///
Owen Anderson175b6542009-07-22 00:24:57 +0000351Constant *llvm::ConstantFoldInstruction(Instruction *I, LLVMContext &Context,
Owen Andersond4d90a02009-07-06 18:42:36 +0000352 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000353 if (PHINode *PN = dyn_cast<PHINode>(I)) {
354 if (PN->getNumIncomingValues() == 0)
Owen Andersonb99ecca2009-07-30 23:03:37 +0000355 return UndefValue::get(PN->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000356
357 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
358 if (Result == 0) return 0;
359
360 // Handle PHI nodes specially here...
361 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
362 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
363 return 0; // Not all the same incoming constants...
364
365 // If we reach here, all incoming values are the same constant.
366 return Result;
367 }
368
369 // Scan the operand list, checking to see if they are all constants, if so,
370 // hand off to ConstantFoldInstOperands.
371 SmallVector<Constant*, 8> Ops;
Gabor Greifece177d2008-05-22 06:43:33 +0000372 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
373 if (Constant *Op = dyn_cast<Constant>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000374 Ops.push_back(Op);
375 else
376 return 0; // All operands not constant!
377
Chris Lattnerd6e56912007-12-10 22:53:04 +0000378 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
379 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +0000380 Ops.data(), Ops.size(),
381 Context, TD);
Chris Lattnerfe0e2532009-09-16 00:08:07 +0000382
383 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
384 Ops.data(), Ops.size(), Context, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385}
386
Nick Lewyckyadb67922008-05-25 20:56:15 +0000387/// ConstantFoldConstantExpression - Attempt to fold the constant expression
388/// using the specified TargetData. If successful, the constant result is
389/// result is returned, if not, null is returned.
390Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
Owen Anderson175b6542009-07-22 00:24:57 +0000391 LLVMContext &Context,
Nick Lewyckyadb67922008-05-25 20:56:15 +0000392 const TargetData *TD) {
Nick Lewyckyadb67922008-05-25 20:56:15 +0000393 SmallVector<Constant*, 8> Ops;
394 for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
395 Ops.push_back(cast<Constant>(*i));
396
397 if (CE->isCompare())
398 return ConstantFoldCompareInstOperands(CE->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +0000399 Ops.data(), Ops.size(),
400 Context, TD);
Chris Lattnerfe0e2532009-09-16 00:08:07 +0000401 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
402 Ops.data(), Ops.size(), Context, TD);
Nick Lewyckyadb67922008-05-25 20:56:15 +0000403}
404
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
406/// specified opcode and operands. If successful, the constant result is
407/// returned, if not, null is returned. Note that this function can fail when
408/// attempting to fold instructions like loads and stores, which have no
409/// constant expression form.
410///
Chris Lattnerd6e56912007-12-10 22:53:04 +0000411Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
412 Constant* const* Ops, unsigned NumOps,
Owen Anderson175b6542009-07-22 00:24:57 +0000413 LLVMContext &Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000415 // Handle easy binops first.
Chris Lattnerd6e56912007-12-10 22:53:04 +0000416 if (Instruction::isBinaryOp(Opcode)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000417 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
Owen Andersond4d90a02009-07-06 18:42:36 +0000418 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD,
419 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420 return C;
421
Owen Anderson02b48c32009-07-29 18:55:55 +0000422 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423 }
424
Chris Lattnerd6e56912007-12-10 22:53:04 +0000425 switch (Opcode) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426 default: return 0;
427 case Instruction::Call:
428 if (Function *F = dyn_cast<Function>(Ops[0]))
429 if (canConstantFoldCallTo(F))
430 return ConstantFoldCall(F, Ops+1, NumOps-1);
431 return 0;
432 case Instruction::ICmp:
433 case Instruction::FCmp:
Edwin Törökbd448e32009-07-14 16:55:14 +0000434 llvm_unreachable("This function is invalid for compares: no predicate specified");
Chris Lattner21a98652007-08-11 23:49:01 +0000435 case Instruction::PtrToInt:
436 // If the input is a inttoptr, eliminate the pair. This requires knowing
437 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
438 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
439 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
440 Constant *Input = CE->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +0000441 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Nick Lewycky2a890b42008-10-24 06:14:27 +0000442 if (TD->getPointerSizeInBits() < InWidth) {
443 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +0000444 ConstantInt::get(Context, APInt::getLowBitsSet(InWidth,
Nick Lewycky2a890b42008-10-24 06:14:27 +0000445 TD->getPointerSizeInBits()));
Owen Anderson02b48c32009-07-29 18:55:55 +0000446 Input = ConstantExpr::getAnd(Input, Mask);
Nick Lewycky2a890b42008-10-24 06:14:27 +0000447 }
Chris Lattner21a98652007-08-11 23:49:01 +0000448 // Do a zext or trunc to get to the dest size.
Owen Anderson02b48c32009-07-29 18:55:55 +0000449 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner21a98652007-08-11 23:49:01 +0000450 }
451 }
Owen Anderson02b48c32009-07-29 18:55:55 +0000452 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner21a98652007-08-11 23:49:01 +0000453 case Instruction::IntToPtr:
Duncan Sandsabe39132008-08-13 20:20:35 +0000454 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
455 // the int size is >= the ptr size. This requires knowing the width of a
456 // pointer, so it can't be done in ConstantExpr::getCast.
457 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
Dan Gohmand46dc022009-05-07 19:46:24 +0000458 if (TD &&
Duncan Sandsabe39132008-08-13 20:20:35 +0000459 TD->getPointerSizeInBits() <=
Dan Gohman8fd520a2009-06-15 22:12:54 +0000460 CE->getType()->getScalarSizeInBits()) {
Dan Gohmand46dc022009-05-07 19:46:24 +0000461 if (CE->getOpcode() == Instruction::PtrToInt) {
462 Constant *Input = CE->getOperand(0);
Owen Andersond4d90a02009-07-06 18:42:36 +0000463 Constant *C = FoldBitCast(Input, DestTy, *TD, Context);
Owen Anderson02b48c32009-07-29 18:55:55 +0000464 return C ? C : ConstantExpr::getBitCast(Input, DestTy);
Dan Gohmand46dc022009-05-07 19:46:24 +0000465 }
466 // If there's a constant offset added to the integer value before
467 // it is casted back to a pointer, see if the expression can be
468 // converted into a GEP.
469 if (CE->getOpcode() == Instruction::Add)
470 if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
471 if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
472 if (R->getOpcode() == Instruction::PtrToInt)
473 if (GlobalVariable *GV =
474 dyn_cast<GlobalVariable>(R->getOperand(0))) {
475 const PointerType *GVTy = cast<PointerType>(GV->getType());
476 if (const ArrayType *AT =
477 dyn_cast<ArrayType>(GVTy->getElementType())) {
478 const Type *ElTy = AT->getElementType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000479 uint64_t AllocSize = TD->getTypeAllocSize(ElTy);
480 APInt PSA(L->getValue().getBitWidth(), AllocSize);
Dan Gohmand46dc022009-05-07 19:46:24 +0000481 if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
482 L->getValue().urem(PSA) == 0) {
483 APInt ElemIdx = L->getValue().udiv(PSA);
484 if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
485 AT->getNumElements()))) {
486 Constant *Index[] = {
Owen Andersonaac28372009-07-31 20:28:14 +0000487 Constant::getNullValue(CE->getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +0000488 ConstantInt::get(Context, ElemIdx)
Dan Gohmand46dc022009-05-07 19:46:24 +0000489 };
Owen Andersond4d90a02009-07-06 18:42:36 +0000490 return
Owen Anderson02b48c32009-07-29 18:55:55 +0000491 ConstantExpr::getGetElementPtr(GV, &Index[0], 2);
Dan Gohmand46dc022009-05-07 19:46:24 +0000492 }
493 }
494 }
495 }
Duncan Sandsabe39132008-08-13 20:20:35 +0000496 }
497 }
Owen Anderson02b48c32009-07-29 18:55:55 +0000498 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000499 case Instruction::Trunc:
500 case Instruction::ZExt:
501 case Instruction::SExt:
502 case Instruction::FPTrunc:
503 case Instruction::FPExt:
504 case Instruction::UIToFP:
505 case Instruction::SIToFP:
506 case Instruction::FPToUI:
507 case Instruction::FPToSI:
Owen Anderson02b48c32009-07-29 18:55:55 +0000508 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000509 case Instruction::BitCast:
Chris Lattner09d481b2007-12-11 07:29:44 +0000510 if (TD)
Owen Andersond4d90a02009-07-06 18:42:36 +0000511 if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD, Context))
Chris Lattner09d481b2007-12-11 07:29:44 +0000512 return C;
Owen Anderson02b48c32009-07-29 18:55:55 +0000513 return ConstantExpr::getBitCast(Ops[0], DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514 case Instruction::Select:
Owen Anderson02b48c32009-07-29 18:55:55 +0000515 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000516 case Instruction::ExtractElement:
Owen Anderson02b48c32009-07-29 18:55:55 +0000517 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000518 case Instruction::InsertElement:
Owen Anderson02b48c32009-07-29 18:55:55 +0000519 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520 case Instruction::ShuffleVector:
Owen Anderson02b48c32009-07-29 18:55:55 +0000521 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000522 case Instruction::GetElementPtr:
Owen Andersond4d90a02009-07-06 18:42:36 +0000523 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, Context, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000524 return C;
525
Owen Anderson02b48c32009-07-29 18:55:55 +0000526 return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527 }
528}
529
Chris Lattnerd6e56912007-12-10 22:53:04 +0000530/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
531/// instruction (icmp/fcmp) with the specified operands. If it fails, it
532/// returns a constant expression of the specified operands.
533///
534Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
535 Constant*const * Ops,
536 unsigned NumOps,
Owen Anderson175b6542009-07-22 00:24:57 +0000537 LLVMContext &Context,
Chris Lattnerd6e56912007-12-10 22:53:04 +0000538 const TargetData *TD) {
539 // fold: icmp (inttoptr x), null -> icmp x, 0
540 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewyckyadb67922008-05-25 20:56:15 +0000541 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd6e56912007-12-10 22:53:04 +0000542 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
543 //
544 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
545 // around to know if bit truncation is happening.
546 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
547 if (TD && Ops[1]->isNullValue()) {
Owen Anderson35b47072009-08-13 21:58:54 +0000548 const Type *IntPtrTy = TD->getIntPtrType(Context);
Chris Lattnerd6e56912007-12-10 22:53:04 +0000549 if (CE0->getOpcode() == Instruction::IntToPtr) {
550 // Convert the integer value to the right size to ensure we get the
551 // proper extension or truncation.
Owen Anderson02b48c32009-07-29 18:55:55 +0000552 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd6e56912007-12-10 22:53:04 +0000553 IntPtrTy, false);
Owen Andersonaac28372009-07-31 20:28:14 +0000554 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Owen Andersond4d90a02009-07-06 18:42:36 +0000555 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
556 Context, TD);
Chris Lattnerd6e56912007-12-10 22:53:04 +0000557 }
558
559 // Only do this transformation if the int is intptrty in size, otherwise
560 // there is a truncation or extension that we aren't modeling.
561 if (CE0->getOpcode() == Instruction::PtrToInt &&
562 CE0->getType() == IntPtrTy) {
563 Constant *C = CE0->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +0000564 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Chris Lattnerd6e56912007-12-10 22:53:04 +0000565 // FIXME!
Owen Andersond4d90a02009-07-06 18:42:36 +0000566 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
567 Context, TD);
Chris Lattnerd6e56912007-12-10 22:53:04 +0000568 }
569 }
570
Nick Lewyckyadb67922008-05-25 20:56:15 +0000571 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
572 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
Owen Anderson35b47072009-08-13 21:58:54 +0000573 const Type *IntPtrTy = TD->getIntPtrType(Context);
Nick Lewyckyadb67922008-05-25 20:56:15 +0000574
575 if (CE0->getOpcode() == Instruction::IntToPtr) {
576 // Convert the integer value to the right size to ensure we get the
577 // proper extension or truncation.
Owen Anderson02b48c32009-07-29 18:55:55 +0000578 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyadb67922008-05-25 20:56:15 +0000579 IntPtrTy, false);
Owen Anderson02b48c32009-07-29 18:55:55 +0000580 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyadb67922008-05-25 20:56:15 +0000581 IntPtrTy, false);
582 Constant *NewOps[] = { C0, C1 };
Owen Andersond4d90a02009-07-06 18:42:36 +0000583 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
584 Context, TD);
Nick Lewyckyadb67922008-05-25 20:56:15 +0000585 }
586
587 // Only do this transformation if the int is intptrty in size, otherwise
588 // there is a truncation or extension that we aren't modeling.
589 if ((CE0->getOpcode() == Instruction::PtrToInt &&
590 CE0->getType() == IntPtrTy &&
591 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
592 Constant *NewOps[] = {
593 CE0->getOperand(0), CE1->getOperand(0)
594 };
Owen Andersond4d90a02009-07-06 18:42:36 +0000595 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
596 Context, TD);
Nick Lewyckyadb67922008-05-25 20:56:15 +0000597 }
Chris Lattnerd6e56912007-12-10 22:53:04 +0000598 }
599 }
600 }
Owen Anderson02b48c32009-07-29 18:55:55 +0000601 return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
Chris Lattnerd6e56912007-12-10 22:53:04 +0000602}
603
604
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000605/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
606/// getelementptr constantexpr, return the constant value being addressed by the
607/// constant expression, or null if something is funny and we can't decide.
608Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmanf49f7b02009-10-05 16:36:26 +0000609 ConstantExpr *CE) {
Owen Andersonaac28372009-07-31 20:28:14 +0000610 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 return 0; // Do not allow stepping over the value!
612
613 // Loop over all of the operands, tracking down which value we are
614 // addressing...
615 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
616 for (++I; I != E; ++I)
617 if (const StructType *STy = dyn_cast<StructType>(*I)) {
618 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
619 assert(CU->getZExtValue() < STy->getNumElements() &&
620 "Struct index out of range!");
621 unsigned El = (unsigned)CU->getZExtValue();
622 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
623 C = CS->getOperand(El);
624 } else if (isa<ConstantAggregateZero>(C)) {
Owen Andersonaac28372009-07-31 20:28:14 +0000625 C = Constant::getNullValue(STy->getElementType(El));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 } else if (isa<UndefValue>(C)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +0000627 C = UndefValue::get(STy->getElementType(El));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628 } else {
629 return 0;
630 }
631 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
632 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
633 if (CI->getZExtValue() >= ATy->getNumElements())
634 return 0;
635 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
636 C = CA->getOperand(CI->getZExtValue());
637 else if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +0000638 C = Constant::getNullValue(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639 else if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +0000640 C = UndefValue::get(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 else
642 return 0;
643 } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
644 if (CI->getZExtValue() >= PTy->getNumElements())
645 return 0;
646 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
647 C = CP->getOperand(CI->getZExtValue());
648 else if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +0000649 C = Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000650 else if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +0000651 C = UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 else
653 return 0;
654 } else {
655 return 0;
656 }
657 } else {
658 return 0;
659 }
660 return C;
661}
662
663
664//===----------------------------------------------------------------------===//
665// Constant Folding for Calls
666//
667
668/// canConstantFoldCallTo - Return true if its even possible to fold a call to
669/// the specified function.
670bool
Dan Gohmane6e001f2008-01-31 01:05:10 +0000671llvm::canConstantFoldCallTo(const Function *F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000672 switch (F->getIntrinsicID()) {
Dale Johannesenc339d8e2007-10-02 17:43:59 +0000673 case Intrinsic::sqrt:
674 case Intrinsic::powi:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000675 case Intrinsic::bswap:
676 case Intrinsic::ctpop:
677 case Intrinsic::ctlz:
678 case Intrinsic::cttz:
Chris Lattner28250982009-10-05 05:26:04 +0000679 case Intrinsic::uadd_with_overflow:
680 case Intrinsic::usub_with_overflow:
Evan Phoenix2bffa8f2009-10-05 22:53:52 +0000681 case Intrinsic::sadd_with_overflow:
682 case Intrinsic::ssub_with_overflow:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000683 return true;
Chris Lattner5fd5ce62009-10-05 05:00:35 +0000684 default:
685 return false;
686 case 0: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687 }
688
Chris Lattnerae15af62009-04-03 00:02:39 +0000689 if (!F->hasName()) return false;
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000690 StringRef Name = F->getName();
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000691
692 // In these cases, the check of the length is required. We don't want to
693 // return true for a name like "cos\0blah" which strcmp would return equal to
694 // "cos", but has length 8.
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000695 switch (Name[0]) {
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000696 default: return false;
697 case 'a':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000698 return Name == "acos" || Name == "asin" ||
699 Name == "atan" || Name == "atan2";
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000700 case 'c':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000701 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000702 case 'e':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000703 return Name == "exp";
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000704 case 'f':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000705 return Name == "fabs" || Name == "fmod" || Name == "floor";
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000706 case 'l':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000707 return Name == "log" || Name == "log10";
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000708 case 'p':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000709 return Name == "pow";
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000710 case 's':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000711 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
712 Name == "sinf" || Name == "sqrtf";
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000713 case 't':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000714 return Name == "tan" || Name == "tanh";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 }
716}
717
718static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
Owen Anderson175b6542009-07-22 00:24:57 +0000719 const Type *Ty, LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720 errno = 0;
721 V = NativeFP(V);
Chris Lattner6192ce02008-03-30 18:02:00 +0000722 if (errno != 0) {
723 errno = 0;
724 return 0;
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000725 }
Chris Lattner6192ce02008-03-30 18:02:00 +0000726
Chris Lattnercc5e4672009-10-05 05:06:24 +0000727 if (Ty->isFloatTy())
Owen Andersond363a0e2009-07-27 20:59:43 +0000728 return ConstantFP::get(Context, APFloat((float)V));
Chris Lattnercc5e4672009-10-05 05:06:24 +0000729 if (Ty->isDoubleTy())
Owen Andersond363a0e2009-07-27 20:59:43 +0000730 return ConstantFP::get(Context, APFloat(V));
Edwin Törökbd448e32009-07-14 16:55:14 +0000731 llvm_unreachable("Can only constant fold float/double");
Gabor Greif04a115e2008-05-21 14:07:30 +0000732 return 0; // dummy return to suppress warning
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733}
734
735static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
736 double V, double W,
Owen Andersond4d90a02009-07-06 18:42:36 +0000737 const Type *Ty,
Owen Anderson175b6542009-07-22 00:24:57 +0000738 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 errno = 0;
740 V = NativeFP(V, W);
Chris Lattner6192ce02008-03-30 18:02:00 +0000741 if (errno != 0) {
742 errno = 0;
743 return 0;
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000744 }
Chris Lattner6192ce02008-03-30 18:02:00 +0000745
Chris Lattnercc5e4672009-10-05 05:06:24 +0000746 if (Ty->isFloatTy())
Owen Andersond363a0e2009-07-27 20:59:43 +0000747 return ConstantFP::get(Context, APFloat((float)V));
Chris Lattnercc5e4672009-10-05 05:06:24 +0000748 if (Ty->isDoubleTy())
Owen Andersond363a0e2009-07-27 20:59:43 +0000749 return ConstantFP::get(Context, APFloat(V));
Edwin Törökbd448e32009-07-14 16:55:14 +0000750 llvm_unreachable("Can only constant fold float/double");
Gabor Greif04a115e2008-05-21 14:07:30 +0000751 return 0; // dummy return to suppress warning
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752}
753
754/// ConstantFoldCall - Attempt to constant fold a call to the specified function
755/// with the specified arguments, returning null if unsuccessful.
756Constant *
Chris Lattnerd6e56912007-12-10 22:53:04 +0000757llvm::ConstantFoldCall(Function *F,
Chris Lattner5fd5ce62009-10-05 05:00:35 +0000758 Constant *const *Operands, unsigned NumOperands) {
Chris Lattnerae15af62009-04-03 00:02:39 +0000759 if (!F->hasName()) return 0;
Owen Anderson175b6542009-07-22 00:24:57 +0000760 LLVMContext &Context = F->getContext();
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000761 StringRef Name = F->getName();
Chris Lattner28250982009-10-05 05:26:04 +0000762
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763 const Type *Ty = F->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000764 if (NumOperands == 1) {
765 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Chris Lattnercc5e4672009-10-05 05:06:24 +0000766 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000767 return 0;
768 /// Currently APFloat versions of these functions do not exist, so we use
769 /// the host native double versions. Float versions are not called
770 /// directly but for all these it is true (float)(f((double)arg)) ==
771 /// f(arg). Long double not supported yet.
Chris Lattnercc5e4672009-10-05 05:06:24 +0000772 double V = Ty->isFloatTy() ? (double)Op->getValueAPF().convertToFloat() :
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000773 Op->getValueAPF().convertToDouble();
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000774 switch (Name[0]) {
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000775 case 'a':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000776 if (Name == "acos")
Owen Andersond4d90a02009-07-06 18:42:36 +0000777 return ConstantFoldFP(acos, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000778 else if (Name == "asin")
Owen Andersond4d90a02009-07-06 18:42:36 +0000779 return ConstantFoldFP(asin, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000780 else if (Name == "atan")
Owen Andersond4d90a02009-07-06 18:42:36 +0000781 return ConstantFoldFP(atan, V, Ty, Context);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000782 break;
783 case 'c':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000784 if (Name == "ceil")
Owen Andersond4d90a02009-07-06 18:42:36 +0000785 return ConstantFoldFP(ceil, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000786 else if (Name == "cos")
Owen Andersond4d90a02009-07-06 18:42:36 +0000787 return ConstantFoldFP(cos, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000788 else if (Name == "cosh")
Owen Andersond4d90a02009-07-06 18:42:36 +0000789 return ConstantFoldFP(cosh, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000790 else if (Name == "cosf")
Owen Andersond4d90a02009-07-06 18:42:36 +0000791 return ConstantFoldFP(cos, V, Ty, Context);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000792 break;
793 case 'e':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000794 if (Name == "exp")
Owen Andersond4d90a02009-07-06 18:42:36 +0000795 return ConstantFoldFP(exp, V, Ty, Context);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000796 break;
797 case 'f':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000798 if (Name == "fabs")
Owen Andersond4d90a02009-07-06 18:42:36 +0000799 return ConstantFoldFP(fabs, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000800 else if (Name == "floor")
Owen Andersond4d90a02009-07-06 18:42:36 +0000801 return ConstantFoldFP(floor, V, Ty, Context);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000802 break;
803 case 'l':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000804 if (Name == "log" && V > 0)
Owen Andersond4d90a02009-07-06 18:42:36 +0000805 return ConstantFoldFP(log, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000806 else if (Name == "log10" && V > 0)
Owen Andersond4d90a02009-07-06 18:42:36 +0000807 return ConstantFoldFP(log10, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000808 else if (Name == "llvm.sqrt.f32" ||
809 Name == "llvm.sqrt.f64") {
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000810 if (V >= -0.0)
Owen Andersond4d90a02009-07-06 18:42:36 +0000811 return ConstantFoldFP(sqrt, V, Ty, Context);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000812 else // Undefined
Owen Andersonaac28372009-07-31 20:28:14 +0000813 return Constant::getNullValue(Ty);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000814 }
815 break;
816 case 's':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000817 if (Name == "sin")
Owen Andersond4d90a02009-07-06 18:42:36 +0000818 return ConstantFoldFP(sin, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000819 else if (Name == "sinh")
Owen Andersond4d90a02009-07-06 18:42:36 +0000820 return ConstantFoldFP(sinh, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000821 else if (Name == "sqrt" && V >= 0)
Owen Andersond4d90a02009-07-06 18:42:36 +0000822 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000823 else if (Name == "sqrtf" && V >= 0)
Owen Andersond4d90a02009-07-06 18:42:36 +0000824 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000825 else if (Name == "sinf")
Owen Andersond4d90a02009-07-06 18:42:36 +0000826 return ConstantFoldFP(sin, V, Ty, Context);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000827 break;
828 case 't':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000829 if (Name == "tan")
Owen Andersond4d90a02009-07-06 18:42:36 +0000830 return ConstantFoldFP(tan, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000831 else if (Name == "tanh")
Owen Andersond4d90a02009-07-06 18:42:36 +0000832 return ConstantFoldFP(tanh, V, Ty, Context);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000833 break;
834 default:
835 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836 }
Chris Lattner5fd5ce62009-10-05 05:00:35 +0000837 return 0;
838 }
839
840
841 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000842 if (Name.startswith("llvm.bswap"))
Owen Andersoneacb44d2009-07-24 23:12:02 +0000843 return ConstantInt::get(Context, Op->getValue().byteSwap());
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000844 else if (Name.startswith("llvm.ctpop"))
Owen Andersoneacb44d2009-07-24 23:12:02 +0000845 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000846 else if (Name.startswith("llvm.cttz"))
Owen Andersoneacb44d2009-07-24 23:12:02 +0000847 return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000848 else if (Name.startswith("llvm.ctlz"))
Owen Andersoneacb44d2009-07-24 23:12:02 +0000849 return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
Chris Lattner5fd5ce62009-10-05 05:00:35 +0000850 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851 }
Chris Lattner5fd5ce62009-10-05 05:00:35 +0000852
853 return 0;
854 }
855
856 if (NumOperands == 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000857 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Chris Lattnercc5e4672009-10-05 05:06:24 +0000858 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesenc339d8e2007-10-02 17:43:59 +0000859 return 0;
Chris Lattnercc5e4672009-10-05 05:06:24 +0000860 double Op1V = Ty->isFloatTy() ?
861 (double)Op1->getValueAPF().convertToFloat() :
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000862 Op1->getValueAPF().convertToDouble();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000863 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattnercc5e4672009-10-05 05:06:24 +0000864 if (Op2->getType() != Op1->getType())
865 return 0;
866
867 double Op2V = Ty->isFloatTy() ?
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000868 (double)Op2->getValueAPF().convertToFloat():
869 Op2->getValueAPF().convertToDouble();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000870
Chris Lattner5fd5ce62009-10-05 05:00:35 +0000871 if (Name == "pow")
Owen Andersond4d90a02009-07-06 18:42:36 +0000872 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty, Context);
Chris Lattner5fd5ce62009-10-05 05:00:35 +0000873 if (Name == "fmod")
Owen Andersond4d90a02009-07-06 18:42:36 +0000874 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty, Context);
Chris Lattner5fd5ce62009-10-05 05:00:35 +0000875 if (Name == "atan2")
Owen Andersond4d90a02009-07-06 18:42:36 +0000876 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000877 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Chris Lattner5fd5ce62009-10-05 05:00:35 +0000878 if (Name == "llvm.powi.f32")
Owen Andersond363a0e2009-07-27 20:59:43 +0000879 return ConstantFP::get(Context, APFloat((float)std::pow((float)Op1V,
Chris Lattner5e0610f2008-04-20 00:41:09 +0000880 (int)Op2C->getZExtValue())));
Chris Lattner5fd5ce62009-10-05 05:00:35 +0000881 if (Name == "llvm.powi.f64")
Owen Andersond363a0e2009-07-27 20:59:43 +0000882 return ConstantFP::get(Context, APFloat((double)std::pow((double)Op1V,
Chris Lattner5e0610f2008-04-20 00:41:09 +0000883 (int)Op2C->getZExtValue())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 }
Chris Lattner5fd5ce62009-10-05 05:00:35 +0000885 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000886 }
Chris Lattner28250982009-10-05 05:26:04 +0000887
888
889 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
890 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
891 switch (F->getIntrinsicID()) {
892 default: break;
893 case Intrinsic::uadd_with_overflow: {
894 Constant *Res = ConstantExpr::getAdd(Op1, Op2); // result.
895 Constant *Ops[] = {
896 Res, ConstantExpr::getICmp(CmpInst::ICMP_ULT, Res, Op1) // overflow.
897 };
898 return ConstantStruct::get(F->getContext(), Ops, 2, false);
899 }
900 case Intrinsic::usub_with_overflow: {
901 Constant *Res = ConstantExpr::getSub(Op1, Op2); // result.
902 Constant *Ops[] = {
903 Res, ConstantExpr::getICmp(CmpInst::ICMP_UGT, Res, Op1) // overflow.
904 };
905 return ConstantStruct::get(F->getContext(), Ops, 2, false);
906 }
Evan Phoenix2bffa8f2009-10-05 22:53:52 +0000907 case Intrinsic::sadd_with_overflow: {
908 Constant *Res = ConstantExpr::getAdd(Op1, Op2); // result.
909 Constant *Overflow = ConstantExpr::getSelect(
910 ConstantExpr::getICmp(CmpInst::ICMP_SGT,
911 ConstantInt::get(Op1->getType(), 0), Op1),
912 ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op2),
913 ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op2)); // overflow.
914
915 Constant *Ops[] = { Res, Overflow };
916 return ConstantStruct::get(F->getContext(), Ops, 2, false);
917 }
918 case Intrinsic::ssub_with_overflow: {
919 Constant *Res = ConstantExpr::getSub(Op1, Op2); // result.
920 Constant *Overflow = ConstantExpr::getSelect(
921 ConstantExpr::getICmp(CmpInst::ICMP_SGT,
922 ConstantInt::get(Op2->getType(), 0), Op2),
923 ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op1),
924 ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op1)); // overflow.
925
926 Constant *Ops[] = { Res, Overflow };
927 return ConstantStruct::get(F->getContext(), Ops, 2, false);
928 }
Chris Lattner28250982009-10-05 05:26:04 +0000929 }
930 }
931
932 return 0;
933 }
934 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000935 }
936 return 0;
937}
938