blob: 5fae1ea0a75e50951b8669ee97eaca1aaa12d610 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- ConstantFolding.cpp - Analyze constant folding possibilities ------===//
2//
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//
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"
18#include "llvm/Function.h"
Dan Gohmand46dc022009-05-07 19:46:24 +000019#include "llvm/GlobalVariable.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000020#include "llvm/Instructions.h"
21#include "llvm/Intrinsics.h"
Owen Andersond4d90a02009-07-06 18:42:36 +000022#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023#include "llvm/ADT/SmallVector.h"
Chris Lattnereb8fdd32007-08-08 06:55:43 +000024#include "llvm/ADT/StringMap.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000025#include "llvm/Target/TargetData.h"
Edwin Török675d5622009-07-11 20:10:48 +000026#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/Support/GetElementPtrTypeIterator.h"
28#include "llvm/Support/MathExtras.h"
29#include <cerrno>
30#include <cmath>
31using namespace llvm;
32
33//===----------------------------------------------------------------------===//
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 Lattnerd6e56912007-12-10 22:53:04 +000061 if (!cast<PointerType>(CE->getOperand(0)->getType())
62 ->getElementType()->isSized())
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Greifece177d2008-05-22 06:43:33 +000071 for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
Gabor Greiff3a502a2008-05-22 19:24:54 +000072 i != e; ++i, ++GTI) {
Gabor Greifece177d2008-05-22 06:43:33 +000073 ConstantInt *CI = dyn_cast<ConstantInt>(*i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
79 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
80 } else {
81 const SequentialType *SQT = cast<SequentialType>(*GTI);
Duncan Sandsec4f97d2009-05-09 07:06:46 +000082 Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083 }
84 }
85 return true;
86 }
87
88 return false;
89}
90
91
92/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
Nick Lewycky238c5b22008-12-15 01:35:36 +000093/// Attempt to symbolically evaluate the result of a binary operator merging
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Andersond4d90a02009-07-06 18:42:36 +000097 Constant *Op1, const TargetData *TD,
Owen Anderson175b6542009-07-22 00:24:57 +000098 LLVMContext &Context){
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Andersoneacb44d2009-07-24 23:12:02 +0000116 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 }
118 }
119
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120 return 0;
121}
122
123/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
124/// constant expression, do so.
Chris Lattnerd6e56912007-12-10 22:53:04 +0000125static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000126 const Type *ResultTy,
Owen Anderson175b6542009-07-22 00:24:57 +0000127 LLVMContext &Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 const TargetData *TD) {
129 Constant *Ptr = Ops[0];
Chris Lattner3c894522008-05-08 04:54:43 +0000130 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000131 return 0;
132
Chris Lattner3c894522008-05-08 04:54:43 +0000133 uint64_t BasePtr = 0;
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000134 bool BaseIsInt = true;
Chris Lattner3c894522008-05-08 04:54:43 +0000135 if (!Ptr->isNullValue()) {
136 // If this is a inttoptr from a constant int, we can fold this as the base,
137 // otherwise we can't.
138 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
139 if (CE->getOpcode() == Instruction::IntToPtr)
140 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
141 BasePtr = Base->getZExtValue();
142
143 if (BasePtr == 0)
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000144 BaseIsInt = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 }
Chris Lattner3c894522008-05-08 04:54:43 +0000146
147 // If this is a constant expr gep that is effectively computing an
148 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
149 for (unsigned i = 1; i != NumOps; ++i)
150 if (!isa<ConstantInt>(Ops[i]))
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000151 return 0;
Chris Lattner3c894522008-05-08 04:54:43 +0000152
153 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
154 (Value**)Ops+1, NumOps-1);
Dan Gohman0b0ddfa2009-08-19 18:18:36 +0000155 // If the base value for this address is a literal integer value, fold the
156 // getelementptr to the resulting integer value casted to the pointer type.
157 if (BaseIsInt) {
158 Constant *C = ConstantInt::get(TD->getIntPtrType(Context), Offset+BasePtr);
159 return ConstantExpr::getIntToPtr(C, ResultTy);
160 }
161
162 // Otherwise form a regular getelementptr. Recompute the indices so that
163 // we eliminate over-indexing of the notional static type array bounds.
164 // This makes it easy to determine if the getelementptr is "inbounds".
165 // Also, this helps GlobalOpt do SROA on GlobalVariables.
166 const Type *Ty = Ptr->getType();
167 SmallVector<Constant*, 32> NewIdxs;
168 for (unsigned Index = 1; Index != NumOps; ++Index) {
169 if (const SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
170 // Determine which element of the array the offset points into.
171 uint64_t ElemSize = TD->getTypeAllocSize(ATy->getElementType());
172 if (ElemSize == 0)
173 return 0;
174 uint64_t NewIdx = Offset / ElemSize;
175 Offset -= NewIdx * ElemSize;
176 NewIdxs.push_back(ConstantInt::get(TD->getIntPtrType(Context), NewIdx));
177 Ty = ATy->getElementType();
178 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
179 // Determine which field of the struct the offset points into.
180 const StructLayout &SL = *TD->getStructLayout(STy);
181 unsigned ElIdx = SL.getElementContainingOffset(Offset);
182 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Context), ElIdx));
183 Offset -= SL.getElementOffset(ElIdx);
184 Ty = STy->getTypeAtIndex(ElIdx);
185 } else {
186 return 0;
187 }
188 }
189
190 // If the base is the start of a GlobalVariable and all the array indices
191 // remain in their static bounds, the GEP is inbounds. We can check that
192 // all indices are in bounds by just checking the first index only
193 // because we've just normalized all the indices.
194 if (isa<GlobalVariable>(Ptr) && NewIdxs[0]->isNullValue())
195 return ConstantExpr::getInBoundsGetElementPtr(Ptr,
196 &NewIdxs[0], NewIdxs.size());
197
198 // Otherwise it may not be inbounds.
199 return ConstantExpr::getGetElementPtr(Ptr, &NewIdxs[0], NewIdxs.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200}
201
Chris Lattner09d481b2007-12-11 07:29:44 +0000202/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
203/// targetdata. Return 0 if unfoldable.
204static Constant *FoldBitCast(Constant *C, const Type *DestTy,
Owen Anderson175b6542009-07-22 00:24:57 +0000205 const TargetData &TD, LLVMContext &Context) {
Chris Lattner09d481b2007-12-11 07:29:44 +0000206 // If this is a bitcast from constant vector -> vector, fold it.
207 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
208 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
209 // If the element types match, VMCore can fold it.
210 unsigned NumDstElt = DestVTy->getNumElements();
211 unsigned NumSrcElt = CV->getNumOperands();
212 if (NumDstElt == NumSrcElt)
213 return 0;
214
215 const Type *SrcEltTy = CV->getType()->getElementType();
216 const Type *DstEltTy = DestVTy->getElementType();
217
218 // Otherwise, we're changing the number of elements in a vector, which
219 // requires endianness information to do the right thing. For example,
220 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
221 // folds to (little endian):
222 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
223 // and to (big endian):
224 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
225
226 // First thing is first. We only want to think about integer here, so if
227 // we have something in FP form, recast it as integer.
228 if (DstEltTy->isFloatingPoint()) {
229 // Fold to an vector of integers with same size as our FP type.
230 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Owen Anderson6b6e2d92009-07-29 22:17:13 +0000231 const Type *DestIVTy = VectorType::get(
Owen Anderson35b47072009-08-13 21:58:54 +0000232 IntegerType::get(Context, FPWidth), NumDstElt);
Chris Lattner09d481b2007-12-11 07:29:44 +0000233 // Recursively handle this integer conversion, if possible.
Owen Andersond4d90a02009-07-06 18:42:36 +0000234 C = FoldBitCast(C, DestIVTy, TD, Context);
Chris Lattner09d481b2007-12-11 07:29:44 +0000235 if (!C) return 0;
236
237 // Finally, VMCore can handle this now that #elts line up.
Owen Anderson02b48c32009-07-29 18:55:55 +0000238 return ConstantExpr::getBitCast(C, DestTy);
Chris Lattner09d481b2007-12-11 07:29:44 +0000239 }
240
241 // Okay, we know the destination is integer, if the input is FP, convert
242 // it to integer first.
243 if (SrcEltTy->isFloatingPoint()) {
244 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Owen Anderson6b6e2d92009-07-29 22:17:13 +0000245 const Type *SrcIVTy = VectorType::get(
Owen Anderson35b47072009-08-13 21:58:54 +0000246 IntegerType::get(Context, FPWidth), NumSrcElt);
Chris Lattner09d481b2007-12-11 07:29:44 +0000247 // Ask VMCore to do the conversion now that #elts line up.
Owen Anderson02b48c32009-07-29 18:55:55 +0000248 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chris Lattner09d481b2007-12-11 07:29:44 +0000249 CV = dyn_cast<ConstantVector>(C);
250 if (!CV) return 0; // If VMCore wasn't able to fold it, bail out.
251 }
252
253 // Now we know that the input and output vectors are both integer vectors
254 // of the same size, and that their #elements is not the same. Do the
255 // conversion here, which depends on whether the input or output has
256 // more elements.
257 bool isLittleEndian = TD.isLittleEndian();
258
259 SmallVector<Constant*, 32> Result;
260 if (NumDstElt < NumSrcElt) {
261 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
Owen Andersonaac28372009-07-31 20:28:14 +0000262 Constant *Zero = Constant::getNullValue(DstEltTy);
Chris Lattner09d481b2007-12-11 07:29:44 +0000263 unsigned Ratio = NumSrcElt/NumDstElt;
264 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
265 unsigned SrcElt = 0;
266 for (unsigned i = 0; i != NumDstElt; ++i) {
267 // Build each element of the result.
268 Constant *Elt = Zero;
269 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
270 for (unsigned j = 0; j != Ratio; ++j) {
271 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
272 if (!Src) return 0; // Reject constantexpr elements.
273
274 // Zero extend the element to the right size.
Owen Anderson02b48c32009-07-29 18:55:55 +0000275 Src = ConstantExpr::getZExt(Src, Elt->getType());
Chris Lattner09d481b2007-12-11 07:29:44 +0000276
277 // Shift it to the right place, depending on endianness.
Owen Anderson02b48c32009-07-29 18:55:55 +0000278 Src = ConstantExpr::getShl(Src,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000279 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner09d481b2007-12-11 07:29:44 +0000280 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
281
282 // Mix it in.
Owen Anderson02b48c32009-07-29 18:55:55 +0000283 Elt = ConstantExpr::getOr(Elt, Src);
Chris Lattner09d481b2007-12-11 07:29:44 +0000284 }
285 Result.push_back(Elt);
286 }
287 } else {
288 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
289 unsigned Ratio = NumDstElt/NumSrcElt;
290 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
291
292 // Loop over each source value, expanding into multiple results.
293 for (unsigned i = 0; i != NumSrcElt; ++i) {
294 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
295 if (!Src) return 0; // Reject constantexpr elements.
296
297 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
298 for (unsigned j = 0; j != Ratio; ++j) {
299 // Shift the piece of the value into the right place, depending on
300 // endianness.
Owen Anderson02b48c32009-07-29 18:55:55 +0000301 Constant *Elt = ConstantExpr::getLShr(Src,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000302 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner09d481b2007-12-11 07:29:44 +0000303 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
304
305 // Truncate and remember this piece.
Owen Anderson02b48c32009-07-29 18:55:55 +0000306 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner09d481b2007-12-11 07:29:44 +0000307 }
308 }
309 }
310
Owen Anderson2f422e02009-07-28 21:19:26 +0000311 return ConstantVector::get(Result.data(), Result.size());
Chris Lattner09d481b2007-12-11 07:29:44 +0000312 }
313 }
314
315 return 0;
316}
317
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318
319//===----------------------------------------------------------------------===//
320// Constant Folding public APIs
321//===----------------------------------------------------------------------===//
322
323
324/// ConstantFoldInstruction - Attempt to constant fold the specified
325/// instruction. If successful, the constant result is returned, if not, null
326/// is returned. Note that this function can only fail when attempting to fold
327/// instructions like loads and stores, which have no constant expression form.
328///
Owen Anderson175b6542009-07-22 00:24:57 +0000329Constant *llvm::ConstantFoldInstruction(Instruction *I, LLVMContext &Context,
Owen Andersond4d90a02009-07-06 18:42:36 +0000330 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331 if (PHINode *PN = dyn_cast<PHINode>(I)) {
332 if (PN->getNumIncomingValues() == 0)
Owen Andersonb99ecca2009-07-30 23:03:37 +0000333 return UndefValue::get(PN->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334
335 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
336 if (Result == 0) return 0;
337
338 // Handle PHI nodes specially here...
339 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
340 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
341 return 0; // Not all the same incoming constants...
342
343 // If we reach here, all incoming values are the same constant.
344 return Result;
345 }
346
347 // Scan the operand list, checking to see if they are all constants, if so,
348 // hand off to ConstantFoldInstOperands.
349 SmallVector<Constant*, 8> Ops;
Gabor Greifece177d2008-05-22 06:43:33 +0000350 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
351 if (Constant *Op = dyn_cast<Constant>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000352 Ops.push_back(Op);
353 else
354 return 0; // All operands not constant!
355
Chris Lattnerd6e56912007-12-10 22:53:04 +0000356 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
357 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +0000358 Ops.data(), Ops.size(),
359 Context, TD);
Chris Lattnerd6e56912007-12-10 22:53:04 +0000360 else
361 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Andersond4d90a02009-07-06 18:42:36 +0000362 Ops.data(), Ops.size(), Context, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363}
364
Nick Lewyckyadb67922008-05-25 20:56:15 +0000365/// ConstantFoldConstantExpression - Attempt to fold the constant expression
366/// using the specified TargetData. If successful, the constant result is
367/// result is returned, if not, null is returned.
368Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
Owen Anderson175b6542009-07-22 00:24:57 +0000369 LLVMContext &Context,
Nick Lewyckyadb67922008-05-25 20:56:15 +0000370 const TargetData *TD) {
Nick Lewyckyadb67922008-05-25 20:56:15 +0000371 SmallVector<Constant*, 8> Ops;
372 for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
373 Ops.push_back(cast<Constant>(*i));
374
375 if (CE->isCompare())
376 return ConstantFoldCompareInstOperands(CE->getPredicate(),
Owen Andersond4d90a02009-07-06 18:42:36 +0000377 Ops.data(), Ops.size(),
378 Context, TD);
Nick Lewyckyadb67922008-05-25 20:56:15 +0000379 else
380 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
Owen Andersond4d90a02009-07-06 18:42:36 +0000381 Ops.data(), Ops.size(), Context, TD);
Nick Lewyckyadb67922008-05-25 20:56:15 +0000382}
383
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
385/// specified opcode and operands. If successful, the constant result is
386/// returned, if not, null is returned. Note that this function can fail when
387/// attempting to fold instructions like loads and stores, which have no
388/// constant expression form.
389///
Chris Lattnerd6e56912007-12-10 22:53:04 +0000390Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
391 Constant* const* Ops, unsigned NumOps,
Owen Anderson175b6542009-07-22 00:24:57 +0000392 LLVMContext &Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394 // Handle easy binops first.
Chris Lattnerd6e56912007-12-10 22:53:04 +0000395 if (Instruction::isBinaryOp(Opcode)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
Owen Andersond4d90a02009-07-06 18:42:36 +0000397 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD,
398 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399 return C;
400
Owen Anderson02b48c32009-07-29 18:55:55 +0000401 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 }
403
Chris Lattnerd6e56912007-12-10 22:53:04 +0000404 switch (Opcode) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405 default: return 0;
406 case Instruction::Call:
407 if (Function *F = dyn_cast<Function>(Ops[0]))
408 if (canConstantFoldCallTo(F))
409 return ConstantFoldCall(F, Ops+1, NumOps-1);
410 return 0;
411 case Instruction::ICmp:
412 case Instruction::FCmp:
Edwin Törökbd448e32009-07-14 16:55:14 +0000413 llvm_unreachable("This function is invalid for compares: no predicate specified");
Chris Lattner21a98652007-08-11 23:49:01 +0000414 case Instruction::PtrToInt:
415 // If the input is a inttoptr, eliminate the pair. This requires knowing
416 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
417 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
418 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
419 Constant *Input = CE->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +0000420 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Nick Lewycky2a890b42008-10-24 06:14:27 +0000421 if (TD->getPointerSizeInBits() < InWidth) {
422 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +0000423 ConstantInt::get(Context, APInt::getLowBitsSet(InWidth,
Nick Lewycky2a890b42008-10-24 06:14:27 +0000424 TD->getPointerSizeInBits()));
Owen Anderson02b48c32009-07-29 18:55:55 +0000425 Input = ConstantExpr::getAnd(Input, Mask);
Nick Lewycky2a890b42008-10-24 06:14:27 +0000426 }
Chris Lattner21a98652007-08-11 23:49:01 +0000427 // Do a zext or trunc to get to the dest size.
Owen Anderson02b48c32009-07-29 18:55:55 +0000428 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner21a98652007-08-11 23:49:01 +0000429 }
430 }
Owen Anderson02b48c32009-07-29 18:55:55 +0000431 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner21a98652007-08-11 23:49:01 +0000432 case Instruction::IntToPtr:
Duncan Sandsabe39132008-08-13 20:20:35 +0000433 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
434 // the int size is >= the ptr size. This requires knowing the width of a
435 // pointer, so it can't be done in ConstantExpr::getCast.
436 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
Dan Gohmand46dc022009-05-07 19:46:24 +0000437 if (TD &&
Duncan Sandsabe39132008-08-13 20:20:35 +0000438 TD->getPointerSizeInBits() <=
Dan Gohman8fd520a2009-06-15 22:12:54 +0000439 CE->getType()->getScalarSizeInBits()) {
Dan Gohmand46dc022009-05-07 19:46:24 +0000440 if (CE->getOpcode() == Instruction::PtrToInt) {
441 Constant *Input = CE->getOperand(0);
Owen Andersond4d90a02009-07-06 18:42:36 +0000442 Constant *C = FoldBitCast(Input, DestTy, *TD, Context);
Owen Anderson02b48c32009-07-29 18:55:55 +0000443 return C ? C : ConstantExpr::getBitCast(Input, DestTy);
Dan Gohmand46dc022009-05-07 19:46:24 +0000444 }
445 // If there's a constant offset added to the integer value before
446 // it is casted back to a pointer, see if the expression can be
447 // converted into a GEP.
448 if (CE->getOpcode() == Instruction::Add)
449 if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
450 if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
451 if (R->getOpcode() == Instruction::PtrToInt)
452 if (GlobalVariable *GV =
453 dyn_cast<GlobalVariable>(R->getOperand(0))) {
454 const PointerType *GVTy = cast<PointerType>(GV->getType());
455 if (const ArrayType *AT =
456 dyn_cast<ArrayType>(GVTy->getElementType())) {
457 const Type *ElTy = AT->getElementType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000458 uint64_t AllocSize = TD->getTypeAllocSize(ElTy);
459 APInt PSA(L->getValue().getBitWidth(), AllocSize);
Dan Gohmand46dc022009-05-07 19:46:24 +0000460 if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
461 L->getValue().urem(PSA) == 0) {
462 APInt ElemIdx = L->getValue().udiv(PSA);
463 if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
464 AT->getNumElements()))) {
465 Constant *Index[] = {
Owen Andersonaac28372009-07-31 20:28:14 +0000466 Constant::getNullValue(CE->getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +0000467 ConstantInt::get(Context, ElemIdx)
Dan Gohmand46dc022009-05-07 19:46:24 +0000468 };
Owen Andersond4d90a02009-07-06 18:42:36 +0000469 return
Owen Anderson02b48c32009-07-29 18:55:55 +0000470 ConstantExpr::getGetElementPtr(GV, &Index[0], 2);
Dan Gohmand46dc022009-05-07 19:46:24 +0000471 }
472 }
473 }
474 }
Duncan Sandsabe39132008-08-13 20:20:35 +0000475 }
476 }
Owen Anderson02b48c32009-07-29 18:55:55 +0000477 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000478 case Instruction::Trunc:
479 case Instruction::ZExt:
480 case Instruction::SExt:
481 case Instruction::FPTrunc:
482 case Instruction::FPExt:
483 case Instruction::UIToFP:
484 case Instruction::SIToFP:
485 case Instruction::FPToUI:
486 case Instruction::FPToSI:
Owen Anderson02b48c32009-07-29 18:55:55 +0000487 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000488 case Instruction::BitCast:
Chris Lattner09d481b2007-12-11 07:29:44 +0000489 if (TD)
Owen Andersond4d90a02009-07-06 18:42:36 +0000490 if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD, Context))
Chris Lattner09d481b2007-12-11 07:29:44 +0000491 return C;
Owen Anderson02b48c32009-07-29 18:55:55 +0000492 return ConstantExpr::getBitCast(Ops[0], DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000493 case Instruction::Select:
Owen Anderson02b48c32009-07-29 18:55:55 +0000494 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000495 case Instruction::ExtractElement:
Owen Anderson02b48c32009-07-29 18:55:55 +0000496 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 case Instruction::InsertElement:
Owen Anderson02b48c32009-07-29 18:55:55 +0000498 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000499 case Instruction::ShuffleVector:
Owen Anderson02b48c32009-07-29 18:55:55 +0000500 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501 case Instruction::GetElementPtr:
Owen Andersond4d90a02009-07-06 18:42:36 +0000502 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, Context, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503 return C;
504
Owen Anderson02b48c32009-07-29 18:55:55 +0000505 return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000506 }
507}
508
Chris Lattnerd6e56912007-12-10 22:53:04 +0000509/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
510/// instruction (icmp/fcmp) with the specified operands. If it fails, it
511/// returns a constant expression of the specified operands.
512///
513Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
514 Constant*const * Ops,
515 unsigned NumOps,
Owen Anderson175b6542009-07-22 00:24:57 +0000516 LLVMContext &Context,
Chris Lattnerd6e56912007-12-10 22:53:04 +0000517 const TargetData *TD) {
518 // fold: icmp (inttoptr x), null -> icmp x, 0
519 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewyckyadb67922008-05-25 20:56:15 +0000520 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd6e56912007-12-10 22:53:04 +0000521 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
522 //
523 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
524 // around to know if bit truncation is happening.
525 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
526 if (TD && Ops[1]->isNullValue()) {
Owen Anderson35b47072009-08-13 21:58:54 +0000527 const Type *IntPtrTy = TD->getIntPtrType(Context);
Chris Lattnerd6e56912007-12-10 22:53:04 +0000528 if (CE0->getOpcode() == Instruction::IntToPtr) {
529 // Convert the integer value to the right size to ensure we get the
530 // proper extension or truncation.
Owen Anderson02b48c32009-07-29 18:55:55 +0000531 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd6e56912007-12-10 22:53:04 +0000532 IntPtrTy, false);
Owen Andersonaac28372009-07-31 20:28:14 +0000533 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Owen Andersond4d90a02009-07-06 18:42:36 +0000534 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
535 Context, TD);
Chris Lattnerd6e56912007-12-10 22:53:04 +0000536 }
537
538 // Only do this transformation if the int is intptrty in size, otherwise
539 // there is a truncation or extension that we aren't modeling.
540 if (CE0->getOpcode() == Instruction::PtrToInt &&
541 CE0->getType() == IntPtrTy) {
542 Constant *C = CE0->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +0000543 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Chris Lattnerd6e56912007-12-10 22:53:04 +0000544 // FIXME!
Owen Andersond4d90a02009-07-06 18:42:36 +0000545 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
546 Context, TD);
Chris Lattnerd6e56912007-12-10 22:53:04 +0000547 }
548 }
549
Nick Lewyckyadb67922008-05-25 20:56:15 +0000550 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
551 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
Owen Anderson35b47072009-08-13 21:58:54 +0000552 const Type *IntPtrTy = TD->getIntPtrType(Context);
Nick Lewyckyadb67922008-05-25 20:56:15 +0000553
554 if (CE0->getOpcode() == Instruction::IntToPtr) {
555 // Convert the integer value to the right size to ensure we get the
556 // proper extension or truncation.
Owen Anderson02b48c32009-07-29 18:55:55 +0000557 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyadb67922008-05-25 20:56:15 +0000558 IntPtrTy, false);
Owen Anderson02b48c32009-07-29 18:55:55 +0000559 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyadb67922008-05-25 20:56:15 +0000560 IntPtrTy, false);
561 Constant *NewOps[] = { C0, C1 };
Owen Andersond4d90a02009-07-06 18:42:36 +0000562 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
563 Context, TD);
Nick Lewyckyadb67922008-05-25 20:56:15 +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 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
571 Constant *NewOps[] = {
572 CE0->getOperand(0), CE1->getOperand(0)
573 };
Owen Andersond4d90a02009-07-06 18:42:36 +0000574 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
575 Context, TD);
Nick Lewyckyadb67922008-05-25 20:56:15 +0000576 }
Chris Lattnerd6e56912007-12-10 22:53:04 +0000577 }
578 }
579 }
Owen Anderson02b48c32009-07-29 18:55:55 +0000580 return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
Chris Lattnerd6e56912007-12-10 22:53:04 +0000581}
582
583
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000584/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
585/// getelementptr constantexpr, return the constant value being addressed by the
586/// constant expression, or null if something is funny and we can't decide.
587Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Owen Andersond4d90a02009-07-06 18:42:36 +0000588 ConstantExpr *CE,
Owen Anderson175b6542009-07-22 00:24:57 +0000589 LLVMContext &Context) {
Owen Andersonaac28372009-07-31 20:28:14 +0000590 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000591 return 0; // Do not allow stepping over the value!
592
593 // Loop over all of the operands, tracking down which value we are
594 // addressing...
595 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
596 for (++I; I != E; ++I)
597 if (const StructType *STy = dyn_cast<StructType>(*I)) {
598 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
599 assert(CU->getZExtValue() < STy->getNumElements() &&
600 "Struct index out of range!");
601 unsigned El = (unsigned)CU->getZExtValue();
602 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
603 C = CS->getOperand(El);
604 } else if (isa<ConstantAggregateZero>(C)) {
Owen Andersonaac28372009-07-31 20:28:14 +0000605 C = Constant::getNullValue(STy->getElementType(El));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 } else if (isa<UndefValue>(C)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +0000607 C = UndefValue::get(STy->getElementType(El));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000608 } else {
609 return 0;
610 }
611 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
612 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
613 if (CI->getZExtValue() >= ATy->getNumElements())
614 return 0;
615 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
616 C = CA->getOperand(CI->getZExtValue());
617 else if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +0000618 C = Constant::getNullValue(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619 else if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +0000620 C = UndefValue::get(ATy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621 else
622 return 0;
623 } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
624 if (CI->getZExtValue() >= PTy->getNumElements())
625 return 0;
626 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
627 C = CP->getOperand(CI->getZExtValue());
628 else if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +0000629 C = Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 else if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +0000631 C = UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 else
633 return 0;
634 } else {
635 return 0;
636 }
637 } else {
638 return 0;
639 }
640 return C;
641}
642
643
644//===----------------------------------------------------------------------===//
645// Constant Folding for Calls
646//
647
648/// canConstantFoldCallTo - Return true if its even possible to fold a call to
649/// the specified function.
650bool
Dan Gohmane6e001f2008-01-31 01:05:10 +0000651llvm::canConstantFoldCallTo(const Function *F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 switch (F->getIntrinsicID()) {
Dale Johannesenc339d8e2007-10-02 17:43:59 +0000653 case Intrinsic::sqrt:
654 case Intrinsic::powi:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 case Intrinsic::bswap:
656 case Intrinsic::ctpop:
657 case Intrinsic::ctlz:
658 case Intrinsic::cttz:
659 return true;
660 default: break;
661 }
662
Chris Lattnerae15af62009-04-03 00:02:39 +0000663 if (!F->hasName()) return false;
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000664 StringRef Name = F->getName();
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000665
666 // In these cases, the check of the length is required. We don't want to
667 // return true for a name like "cos\0blah" which strcmp would return equal to
668 // "cos", but has length 8.
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000669 switch (Name[0]) {
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000670 default: return false;
671 case 'a':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000672 return Name == "acos" || Name == "asin" ||
673 Name == "atan" || Name == "atan2";
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000674 case 'c':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000675 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000676 case 'e':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000677 return Name == "exp";
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000678 case 'f':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000679 return Name == "fabs" || Name == "fmod" || Name == "floor";
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000680 case 'l':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000681 return Name == "log" || Name == "log10";
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000682 case 'p':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000683 return Name == "pow";
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000684 case 's':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000685 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
686 Name == "sinf" || Name == "sqrtf";
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000687 case 't':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000688 return Name == "tan" || Name == "tanh";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000689 }
690}
691
692static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
Owen Anderson175b6542009-07-22 00:24:57 +0000693 const Type *Ty, LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694 errno = 0;
695 V = NativeFP(V);
Chris Lattner6192ce02008-03-30 18:02:00 +0000696 if (errno != 0) {
697 errno = 0;
698 return 0;
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000699 }
Chris Lattner6192ce02008-03-30 18:02:00 +0000700
Owen Anderson35b47072009-08-13 21:58:54 +0000701 if (Ty == Type::getFloatTy(Context))
Owen Andersond363a0e2009-07-27 20:59:43 +0000702 return ConstantFP::get(Context, APFloat((float)V));
Owen Anderson35b47072009-08-13 21:58:54 +0000703 if (Ty == Type::getDoubleTy(Context))
Owen Andersond363a0e2009-07-27 20:59:43 +0000704 return ConstantFP::get(Context, APFloat(V));
Edwin Törökbd448e32009-07-14 16:55:14 +0000705 llvm_unreachable("Can only constant fold float/double");
Gabor Greif04a115e2008-05-21 14:07:30 +0000706 return 0; // dummy return to suppress warning
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707}
708
709static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
710 double V, double W,
Owen Andersond4d90a02009-07-06 18:42:36 +0000711 const Type *Ty,
Owen Anderson175b6542009-07-22 00:24:57 +0000712 LLVMContext &Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000713 errno = 0;
714 V = NativeFP(V, W);
Chris Lattner6192ce02008-03-30 18:02:00 +0000715 if (errno != 0) {
716 errno = 0;
717 return 0;
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000718 }
Chris Lattner6192ce02008-03-30 18:02:00 +0000719
Owen Anderson35b47072009-08-13 21:58:54 +0000720 if (Ty == Type::getFloatTy(Context))
Owen Andersond363a0e2009-07-27 20:59:43 +0000721 return ConstantFP::get(Context, APFloat((float)V));
Owen Anderson35b47072009-08-13 21:58:54 +0000722 if (Ty == Type::getDoubleTy(Context))
Owen Andersond363a0e2009-07-27 20:59:43 +0000723 return ConstantFP::get(Context, APFloat(V));
Edwin Törökbd448e32009-07-14 16:55:14 +0000724 llvm_unreachable("Can only constant fold float/double");
Gabor Greif04a115e2008-05-21 14:07:30 +0000725 return 0; // dummy return to suppress warning
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000726}
727
728/// ConstantFoldCall - Attempt to constant fold a call to the specified function
729/// with the specified arguments, returning null if unsuccessful.
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000730
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000731Constant *
Chris Lattnerd6e56912007-12-10 22:53:04 +0000732llvm::ConstantFoldCall(Function *F,
733 Constant* const* Operands, unsigned NumOperands) {
Chris Lattnerae15af62009-04-03 00:02:39 +0000734 if (!F->hasName()) return 0;
Owen Anderson175b6542009-07-22 00:24:57 +0000735 LLVMContext &Context = F->getContext();
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000736 StringRef Name = F->getName();
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000737
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738 const Type *Ty = F->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 if (NumOperands == 1) {
740 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Owen Anderson35b47072009-08-13 21:58:54 +0000741 if (Ty!=Type::getFloatTy(F->getContext()) &&
742 Ty!=Type::getDoubleTy(Context))
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000743 return 0;
744 /// Currently APFloat versions of these functions do not exist, so we use
745 /// the host native double versions. Float versions are not called
746 /// directly but for all these it is true (float)(f((double)arg)) ==
747 /// f(arg). Long double not supported yet.
Owen Anderson35b47072009-08-13 21:58:54 +0000748 double V = Ty==Type::getFloatTy(F->getContext()) ?
749 (double)Op->getValueAPF().convertToFloat():
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000750 Op->getValueAPF().convertToDouble();
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000751 switch (Name[0]) {
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000752 case 'a':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000753 if (Name == "acos")
Owen Andersond4d90a02009-07-06 18:42:36 +0000754 return ConstantFoldFP(acos, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000755 else if (Name == "asin")
Owen Andersond4d90a02009-07-06 18:42:36 +0000756 return ConstantFoldFP(asin, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000757 else if (Name == "atan")
Owen Andersond4d90a02009-07-06 18:42:36 +0000758 return ConstantFoldFP(atan, V, Ty, Context);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000759 break;
760 case 'c':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000761 if (Name == "ceil")
Owen Andersond4d90a02009-07-06 18:42:36 +0000762 return ConstantFoldFP(ceil, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000763 else if (Name == "cos")
Owen Andersond4d90a02009-07-06 18:42:36 +0000764 return ConstantFoldFP(cos, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000765 else if (Name == "cosh")
Owen Andersond4d90a02009-07-06 18:42:36 +0000766 return ConstantFoldFP(cosh, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000767 else if (Name == "cosf")
Owen Andersond4d90a02009-07-06 18:42:36 +0000768 return ConstantFoldFP(cos, V, Ty, Context);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000769 break;
770 case 'e':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000771 if (Name == "exp")
Owen Andersond4d90a02009-07-06 18:42:36 +0000772 return ConstantFoldFP(exp, V, Ty, Context);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000773 break;
774 case 'f':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000775 if (Name == "fabs")
Owen Andersond4d90a02009-07-06 18:42:36 +0000776 return ConstantFoldFP(fabs, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000777 else if (Name == "floor")
Owen Andersond4d90a02009-07-06 18:42:36 +0000778 return ConstantFoldFP(floor, V, Ty, Context);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000779 break;
780 case 'l':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000781 if (Name == "log" && V > 0)
Owen Andersond4d90a02009-07-06 18:42:36 +0000782 return ConstantFoldFP(log, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000783 else if (Name == "log10" && V > 0)
Owen Andersond4d90a02009-07-06 18:42:36 +0000784 return ConstantFoldFP(log10, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000785 else if (Name == "llvm.sqrt.f32" ||
786 Name == "llvm.sqrt.f64") {
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000787 if (V >= -0.0)
Owen Andersond4d90a02009-07-06 18:42:36 +0000788 return ConstantFoldFP(sqrt, V, Ty, Context);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000789 else // Undefined
Owen Andersonaac28372009-07-31 20:28:14 +0000790 return Constant::getNullValue(Ty);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000791 }
792 break;
793 case 's':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000794 if (Name == "sin")
Owen Andersond4d90a02009-07-06 18:42:36 +0000795 return ConstantFoldFP(sin, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000796 else if (Name == "sinh")
Owen Andersond4d90a02009-07-06 18:42:36 +0000797 return ConstantFoldFP(sinh, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000798 else if (Name == "sqrt" && V >= 0)
Owen Andersond4d90a02009-07-06 18:42:36 +0000799 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000800 else if (Name == "sqrtf" && V >= 0)
Owen Andersond4d90a02009-07-06 18:42:36 +0000801 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000802 else if (Name == "sinf")
Owen Andersond4d90a02009-07-06 18:42:36 +0000803 return ConstantFoldFP(sin, V, Ty, Context);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000804 break;
805 case 't':
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000806 if (Name == "tan")
Owen Andersond4d90a02009-07-06 18:42:36 +0000807 return ConstantFoldFP(tan, V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000808 else if (Name == "tanh")
Owen Andersond4d90a02009-07-06 18:42:36 +0000809 return ConstantFoldFP(tanh, V, Ty, Context);
Chris Lattnereb8fdd32007-08-08 06:55:43 +0000810 break;
811 default:
812 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000813 }
814 } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000815 if (Name.startswith("llvm.bswap"))
Owen Andersoneacb44d2009-07-24 23:12:02 +0000816 return ConstantInt::get(Context, Op->getValue().byteSwap());
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000817 else if (Name.startswith("llvm.ctpop"))
Owen Andersoneacb44d2009-07-24 23:12:02 +0000818 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000819 else if (Name.startswith("llvm.cttz"))
Owen Andersoneacb44d2009-07-24 23:12:02 +0000820 return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000821 else if (Name.startswith("llvm.ctlz"))
Owen Andersoneacb44d2009-07-24 23:12:02 +0000822 return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000823 }
824 } else if (NumOperands == 2) {
825 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Anderson35b47072009-08-13 21:58:54 +0000826 if (Ty!=Type::getFloatTy(F->getContext()) &&
827 Ty!=Type::getDoubleTy(Context))
Dale Johannesenc339d8e2007-10-02 17:43:59 +0000828 return 0;
Owen Anderson35b47072009-08-13 21:58:54 +0000829 double Op1V = Ty==Type::getFloatTy(F->getContext()) ?
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000830 (double)Op1->getValueAPF().convertToFloat():
831 Op1->getValueAPF().convertToDouble();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000832 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Owen Anderson35b47072009-08-13 21:58:54 +0000833 double Op2V = Ty==Type::getFloatTy(F->getContext()) ?
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000834 (double)Op2->getValueAPF().convertToFloat():
835 Op2->getValueAPF().convertToDouble();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000837 if (Name == "pow") {
Owen Andersond4d90a02009-07-06 18:42:36 +0000838 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000839 } else if (Name == "fmod") {
Owen Andersond4d90a02009-07-06 18:42:36 +0000840 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty, Context);
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000841 } else if (Name == "atan2") {
Owen Andersond4d90a02009-07-06 18:42:36 +0000842 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843 }
844 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000845 if (Name == "llvm.powi.f32") {
Owen Andersond363a0e2009-07-27 20:59:43 +0000846 return ConstantFP::get(Context, APFloat((float)std::pow((float)Op1V,
Chris Lattner5e0610f2008-04-20 00:41:09 +0000847 (int)Op2C->getZExtValue())));
Daniel Dunbar0653dc62009-07-26 08:34:35 +0000848 } else if (Name == "llvm.powi.f64") {
Owen Andersond363a0e2009-07-27 20:59:43 +0000849 return ConstantFP::get(Context, APFloat((double)std::pow((double)Op1V,
Chris Lattner5e0610f2008-04-20 00:41:09 +0000850 (int)Op2C->getZExtValue())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851 }
852 }
853 }
854 }
855 return 0;
856}
857