blob: da671c8f5d8277a6557240d6656d7f3e4940d8f7 [file] [log] [blame]
Dan Gohman83e3c4f2009-09-10 23:07:18 +00001//===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
John Criswellbd9d3702005-10-27 16:00:10 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
John Criswellbd9d3702005-10-27 16:00:10 +00007//
8//===----------------------------------------------------------------------===//
9//
Dan Gohman83e3c4f2009-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.
John Criswellbd9d3702005-10-27 16:00:10 +000016//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Analysis/ConstantFolding.h"
20#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
Chris Lattner55207322007-01-30 23:45:45 +000022#include "llvm/Function.h"
Dan Gohman9a38e3e2009-05-07 19:46:24 +000023#include "llvm/GlobalVariable.h"
John Criswellbd9d3702005-10-27 16:00:10 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Owen Anderson50895512009-07-06 18:42:36 +000026#include "llvm/LLVMContext.h"
Chris Lattner55207322007-01-30 23:45:45 +000027#include "llvm/ADT/SmallVector.h"
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +000028#include "llvm/ADT/StringMap.h"
Chris Lattner03dd25c2007-01-31 00:51:48 +000029#include "llvm/Target/TargetData.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
John Criswellbd9d3702005-10-27 16:00:10 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
32#include "llvm/Support/MathExtras.h"
Chris Lattner878e4942009-10-22 06:25:11 +000033#include "llvm/GlobalVariable.h"
John Criswellbd9d3702005-10-27 16:00:10 +000034#include <cerrno>
Jeff Cohen97af7512006-12-02 02:22:01 +000035#include <cmath>
John Criswellbd9d3702005-10-27 16:00:10 +000036using namespace llvm;
37
Chris Lattner03dd25c2007-01-31 00:51:48 +000038//===----------------------------------------------------------------------===//
39// Constant Folding internal helper functions
40//===----------------------------------------------------------------------===//
41
42/// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
43/// from a global, return the global and the constant. Because of
44/// constantexprs, this function is recursive.
45static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
46 int64_t &Offset, const TargetData &TD) {
47 // Trivial case, constant is the global.
48 if ((GV = dyn_cast<GlobalValue>(C))) {
49 Offset = 0;
50 return true;
51 }
52
53 // Otherwise, if this isn't a constant expr, bail out.
54 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
55 if (!CE) return false;
56
57 // Look through ptr->int and ptr->ptr casts.
58 if (CE->getOpcode() == Instruction::PtrToInt ||
59 CE->getOpcode() == Instruction::BitCast)
60 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
61
62 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
63 if (CE->getOpcode() == Instruction::GetElementPtr) {
64 // Cannot compute this if the element type of the pointer is missing size
65 // info.
Chris Lattnerf286f6f2007-12-10 22:53:04 +000066 if (!cast<PointerType>(CE->getOperand(0)->getType())
67 ->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +000068 return false;
69
70 // If the base isn't a global+constant, we aren't either.
71 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
72 return false;
73
74 // Otherwise, add any offset that our operands provide.
75 gep_type_iterator GTI = gep_type_begin(CE);
Gabor Greifde2d74b2008-05-22 06:43:33 +000076 for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
Gabor Greif785c6af2008-05-22 19:24:54 +000077 i != e; ++i, ++GTI) {
Gabor Greifde2d74b2008-05-22 06:43:33 +000078 ConstantInt *CI = dyn_cast<ConstantInt>(*i);
Chris Lattner03dd25c2007-01-31 00:51:48 +000079 if (!CI) return false; // Index isn't a simple constant?
80 if (CI->getZExtValue() == 0) continue; // Not adding anything.
81
82 if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
83 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +000084 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
Chris Lattner03dd25c2007-01-31 00:51:48 +000085 } else {
Jeff Cohenca5183d2007-03-05 00:00:42 +000086 const SequentialType *SQT = cast<SequentialType>(*GTI);
Duncan Sands777d2302009-05-09 07:06:46 +000087 Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
Chris Lattner03dd25c2007-01-31 00:51:48 +000088 }
89 }
90 return true;
91 }
92
93 return false;
94}
95
Chris Lattner878e4942009-10-22 06:25:11 +000096/// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
97/// produce if it is constant and determinable. If this is not determinable,
98/// return null.
99Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
100 const TargetData *TD) {
101 // First, try the easy cases:
102 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
103 if (GV->isConstant() && GV->hasDefinitiveInitializer())
104 return GV->getInitializer();
105
106 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
107 if (CE->getOpcode() == Instruction::GetElementPtr) {
108 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
109 if (GV->isConstant() && GV->hasDefinitiveInitializer())
110 if (Constant *V =
111 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
112 return V;
113 }
114 }
115
116 return 0;
117}
118
119static Constant *ConstantFoldLoadInst(const LoadInst *LI, const TargetData *TD){
120 if (LI->isVolatile()) return 0;
121
122 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
123 return ConstantFoldLoadFromConstPtr(C, TD);
124
125 return 0;
126}
Chris Lattner03dd25c2007-01-31 00:51:48 +0000127
128/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
Nick Lewycky67e35662008-12-15 01:35:36 +0000129/// Attempt to symbolically evaluate the result of a binary operator merging
Chris Lattner03dd25c2007-01-31 00:51:48 +0000130/// these together. If target data info is available, it is provided as TD,
131/// otherwise TD is null.
132static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
Owen Anderson50895512009-07-06 18:42:36 +0000133 Constant *Op1, const TargetData *TD,
Owen Andersone922c022009-07-22 00:24:57 +0000134 LLVMContext &Context){
Chris Lattner03dd25c2007-01-31 00:51:48 +0000135 // SROA
136
137 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
138 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
139 // bits.
140
141
142 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
143 // constant. This happens frequently when iterating over a global array.
144 if (Opc == Instruction::Sub && TD) {
145 GlobalValue *GV1, *GV2;
146 int64_t Offs1, Offs2;
147
148 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
149 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
150 GV1 == GV2) {
151 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Owen Andersoneed707b2009-07-24 23:12:02 +0000152 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000153 }
154 }
155
Chris Lattner03dd25c2007-01-31 00:51:48 +0000156 return 0;
157}
158
159/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
160/// constant expression, do so.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000161static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000162 const Type *ResultTy,
Owen Andersone922c022009-07-22 00:24:57 +0000163 LLVMContext &Context,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000164 const TargetData *TD) {
165 Constant *Ptr = Ops[0];
Chris Lattner268e7d72008-05-08 04:54:43 +0000166 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +0000167 return 0;
Dan Gohmancda97062009-08-21 16:52:54 +0000168
169 unsigned BitWidth = TD->getTypeSizeInBits(TD->getIntPtrType(Context));
170 APInt BasePtr(BitWidth, 0);
Dan Gohmande0e5872009-08-19 18:18:36 +0000171 bool BaseIsInt = true;
Chris Lattner268e7d72008-05-08 04:54:43 +0000172 if (!Ptr->isNullValue()) {
173 // If this is a inttoptr from a constant int, we can fold this as the base,
174 // otherwise we can't.
175 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
176 if (CE->getOpcode() == Instruction::IntToPtr)
Dan Gohman71780102009-08-21 18:27:26 +0000177 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) {
Dan Gohmancda97062009-08-21 16:52:54 +0000178 BasePtr = Base->getValue();
Dan Gohman71780102009-08-21 18:27:26 +0000179 BasePtr.zextOrTrunc(BitWidth);
180 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000181
182 if (BasePtr == 0)
Dan Gohmande0e5872009-08-19 18:18:36 +0000183 BaseIsInt = false;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000184 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000185
186 // If this is a constant expr gep that is effectively computing an
187 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
188 for (unsigned i = 1; i != NumOps; ++i)
189 if (!isa<ConstantInt>(Ops[i]))
Dan Gohmande0e5872009-08-19 18:18:36 +0000190 return 0;
Chris Lattner268e7d72008-05-08 04:54:43 +0000191
Dan Gohmancda97062009-08-21 16:52:54 +0000192 APInt Offset = APInt(BitWidth,
193 TD->getIndexedOffset(Ptr->getType(),
194 (Value**)Ops+1, NumOps-1));
Dan Gohmande0e5872009-08-19 18:18:36 +0000195 // If the base value for this address is a literal integer value, fold the
196 // getelementptr to the resulting integer value casted to the pointer type.
197 if (BaseIsInt) {
Dan Gohmancda97062009-08-21 16:52:54 +0000198 Constant *C = ConstantInt::get(Context, Offset+BasePtr);
Dan Gohmande0e5872009-08-19 18:18:36 +0000199 return ConstantExpr::getIntToPtr(C, ResultTy);
200 }
201
202 // Otherwise form a regular getelementptr. Recompute the indices so that
203 // we eliminate over-indexing of the notional static type array bounds.
204 // This makes it easy to determine if the getelementptr is "inbounds".
205 // Also, this helps GlobalOpt do SROA on GlobalVariables.
206 const Type *Ty = Ptr->getType();
207 SmallVector<Constant*, 32> NewIdxs;
Dan Gohman3d013342009-08-19 22:46:59 +0000208 do {
Dan Gohmande0e5872009-08-19 18:18:36 +0000209 if (const SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
Dan Gohman3d013342009-08-19 22:46:59 +0000210 // The only pointer indexing we'll do is on the first index of the GEP.
Chris Lattnerf19f9342009-09-02 05:35:45 +0000211 if (isa<PointerType>(ATy) && !NewIdxs.empty())
Dan Gohman3d013342009-08-19 22:46:59 +0000212 break;
Dan Gohmande0e5872009-08-19 18:18:36 +0000213 // Determine which element of the array the offset points into.
Dan Gohmancda97062009-08-21 16:52:54 +0000214 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
Dan Gohmande0e5872009-08-19 18:18:36 +0000215 if (ElemSize == 0)
216 return 0;
Dan Gohmancda97062009-08-21 16:52:54 +0000217 APInt NewIdx = Offset.udiv(ElemSize);
Dan Gohmande0e5872009-08-19 18:18:36 +0000218 Offset -= NewIdx * ElemSize;
219 NewIdxs.push_back(ConstantInt::get(TD->getIntPtrType(Context), NewIdx));
220 Ty = ATy->getElementType();
221 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Dan Gohmancda97062009-08-21 16:52:54 +0000222 // Determine which field of the struct the offset points into. The
223 // getZExtValue is at least as safe as the StructLayout API because we
224 // know the offset is within the struct at this point.
Dan Gohmande0e5872009-08-19 18:18:36 +0000225 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohmancda97062009-08-21 16:52:54 +0000226 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Dan Gohmande0e5872009-08-19 18:18:36 +0000227 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Context), ElIdx));
Dan Gohmancda97062009-08-21 16:52:54 +0000228 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohmande0e5872009-08-19 18:18:36 +0000229 Ty = STy->getTypeAtIndex(ElIdx);
230 } else {
Dan Gohman3d013342009-08-19 22:46:59 +0000231 // We've reached some non-indexable type.
232 break;
Dan Gohmande0e5872009-08-19 18:18:36 +0000233 }
Dan Gohman3d013342009-08-19 22:46:59 +0000234 } while (Ty != cast<PointerType>(ResultTy)->getElementType());
235
236 // If we haven't used up the entire offset by descending the static
237 // type, then the offset is pointing into the middle of an indivisible
238 // member, so we can't simplify it.
239 if (Offset != 0)
240 return 0;
Dan Gohmande0e5872009-08-19 18:18:36 +0000241
Dan Gohman3bfbc452009-09-11 00:04:14 +0000242 // Create a GEP.
243 Constant *C =
Dan Gohman6e7ad952009-09-03 23:34:49 +0000244 ConstantExpr::getGetElementPtr(Ptr, &NewIdxs[0], NewIdxs.size());
245 assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
246 "Computed GetElementPtr has unexpected type!");
Dan Gohmande0e5872009-08-19 18:18:36 +0000247
Dan Gohman3d013342009-08-19 22:46:59 +0000248 // If we ended up indexing a member with a type that doesn't match
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000249 // the type of what the original indices indexed, add a cast.
Dan Gohman3d013342009-08-19 22:46:59 +0000250 if (Ty != cast<PointerType>(ResultTy)->getElementType())
251 C = ConstantExpr::getBitCast(C, ResultTy);
252
253 return C;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000254}
255
Chris Lattner1afab9c2007-12-11 07:29:44 +0000256/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
257/// targetdata. Return 0 if unfoldable.
258static Constant *FoldBitCast(Constant *C, const Type *DestTy,
Owen Andersone922c022009-07-22 00:24:57 +0000259 const TargetData &TD, LLVMContext &Context) {
Chris Lattner1afab9c2007-12-11 07:29:44 +0000260 // If this is a bitcast from constant vector -> vector, fold it.
261 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
262 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
263 // If the element types match, VMCore can fold it.
264 unsigned NumDstElt = DestVTy->getNumElements();
265 unsigned NumSrcElt = CV->getNumOperands();
266 if (NumDstElt == NumSrcElt)
267 return 0;
268
269 const Type *SrcEltTy = CV->getType()->getElementType();
270 const Type *DstEltTy = DestVTy->getElementType();
271
272 // Otherwise, we're changing the number of elements in a vector, which
273 // requires endianness information to do the right thing. For example,
274 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
275 // folds to (little endian):
276 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
277 // and to (big endian):
278 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
279
280 // First thing is first. We only want to think about integer here, so if
281 // we have something in FP form, recast it as integer.
282 if (DstEltTy->isFloatingPoint()) {
283 // Fold to an vector of integers with same size as our FP type.
284 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Owen Andersondebcb012009-07-29 22:17:13 +0000285 const Type *DestIVTy = VectorType::get(
Owen Anderson1d0be152009-08-13 21:58:54 +0000286 IntegerType::get(Context, FPWidth), NumDstElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000287 // Recursively handle this integer conversion, if possible.
Owen Anderson50895512009-07-06 18:42:36 +0000288 C = FoldBitCast(C, DestIVTy, TD, Context);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000289 if (!C) return 0;
290
291 // Finally, VMCore can handle this now that #elts line up.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000292 return ConstantExpr::getBitCast(C, DestTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000293 }
294
295 // Okay, we know the destination is integer, if the input is FP, convert
296 // it to integer first.
297 if (SrcEltTy->isFloatingPoint()) {
298 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Owen Andersondebcb012009-07-29 22:17:13 +0000299 const Type *SrcIVTy = VectorType::get(
Owen Anderson1d0be152009-08-13 21:58:54 +0000300 IntegerType::get(Context, FPWidth), NumSrcElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000301 // Ask VMCore to do the conversion now that #elts line up.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000302 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000303 CV = dyn_cast<ConstantVector>(C);
304 if (!CV) return 0; // If VMCore wasn't able to fold it, bail out.
305 }
306
307 // Now we know that the input and output vectors are both integer vectors
308 // of the same size, and that their #elements is not the same. Do the
309 // conversion here, which depends on whether the input or output has
310 // more elements.
311 bool isLittleEndian = TD.isLittleEndian();
312
313 SmallVector<Constant*, 32> Result;
314 if (NumDstElt < NumSrcElt) {
315 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
Owen Andersona7235ea2009-07-31 20:28:14 +0000316 Constant *Zero = Constant::getNullValue(DstEltTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000317 unsigned Ratio = NumSrcElt/NumDstElt;
318 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
319 unsigned SrcElt = 0;
320 for (unsigned i = 0; i != NumDstElt; ++i) {
321 // Build each element of the result.
322 Constant *Elt = Zero;
323 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
324 for (unsigned j = 0; j != Ratio; ++j) {
325 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
326 if (!Src) return 0; // Reject constantexpr elements.
327
328 // Zero extend the element to the right size.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000329 Src = ConstantExpr::getZExt(Src, Elt->getType());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000330
331 // Shift it to the right place, depending on endianness.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000332 Src = ConstantExpr::getShl(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000333 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000334 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
335
336 // Mix it in.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000337 Elt = ConstantExpr::getOr(Elt, Src);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000338 }
339 Result.push_back(Elt);
340 }
341 } else {
342 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
343 unsigned Ratio = NumDstElt/NumSrcElt;
344 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
345
346 // Loop over each source value, expanding into multiple results.
347 for (unsigned i = 0; i != NumSrcElt; ++i) {
348 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
349 if (!Src) return 0; // Reject constantexpr elements.
350
351 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
352 for (unsigned j = 0; j != Ratio; ++j) {
353 // Shift the piece of the value into the right place, depending on
354 // endianness.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000355 Constant *Elt = ConstantExpr::getLShr(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000356 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000357 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
358
359 // Truncate and remember this piece.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000360 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000361 }
362 }
363 }
364
Owen Andersonaf7ec972009-07-28 21:19:26 +0000365 return ConstantVector::get(Result.data(), Result.size());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000366 }
367 }
368
369 return 0;
370}
371
Chris Lattner03dd25c2007-01-31 00:51:48 +0000372
373//===----------------------------------------------------------------------===//
374// Constant Folding public APIs
375//===----------------------------------------------------------------------===//
376
377
Chris Lattner55207322007-01-30 23:45:45 +0000378/// ConstantFoldInstruction - Attempt to constant fold the specified
379/// instruction. If successful, the constant result is returned, if not, null
380/// is returned. Note that this function can only fail when attempting to fold
381/// instructions like loads and stores, which have no constant expression form.
382///
Owen Andersone922c022009-07-22 00:24:57 +0000383Constant *llvm::ConstantFoldInstruction(Instruction *I, LLVMContext &Context,
Owen Anderson50895512009-07-06 18:42:36 +0000384 const TargetData *TD) {
Chris Lattner55207322007-01-30 23:45:45 +0000385 if (PHINode *PN = dyn_cast<PHINode>(I)) {
386 if (PN->getNumIncomingValues() == 0)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000387 return UndefValue::get(PN->getType());
John Criswellbd9d3702005-10-27 16:00:10 +0000388
Chris Lattner55207322007-01-30 23:45:45 +0000389 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
390 if (Result == 0) return 0;
391
392 // Handle PHI nodes specially here...
393 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
394 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
395 return 0; // Not all the same incoming constants...
396
397 // If we reach here, all incoming values are the same constant.
398 return Result;
399 }
400
401 // Scan the operand list, checking to see if they are all constants, if so,
402 // hand off to ConstantFoldInstOperands.
403 SmallVector<Constant*, 8> Ops;
Gabor Greifde2d74b2008-05-22 06:43:33 +0000404 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
405 if (Constant *Op = dyn_cast<Constant>(*i))
Chris Lattner55207322007-01-30 23:45:45 +0000406 Ops.push_back(Op);
407 else
408 return 0; // All operands not constant!
409
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000410 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
411 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000412 Ops.data(), Ops.size(),
413 Context, TD);
Chris Lattner58665d42009-09-16 00:08:07 +0000414
Chris Lattner878e4942009-10-22 06:25:11 +0000415 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
416 return ConstantFoldLoadInst(LI, TD);
417
Chris Lattner58665d42009-09-16 00:08:07 +0000418 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
419 Ops.data(), Ops.size(), Context, TD);
Chris Lattner55207322007-01-30 23:45:45 +0000420}
421
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000422/// ConstantFoldConstantExpression - Attempt to fold the constant expression
423/// using the specified TargetData. If successful, the constant result is
424/// result is returned, if not, null is returned.
425Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
Owen Andersone922c022009-07-22 00:24:57 +0000426 LLVMContext &Context,
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000427 const TargetData *TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000428 SmallVector<Constant*, 8> Ops;
429 for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
430 Ops.push_back(cast<Constant>(*i));
431
432 if (CE->isCompare())
433 return ConstantFoldCompareInstOperands(CE->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000434 Ops.data(), Ops.size(),
435 Context, TD);
Chris Lattner58665d42009-09-16 00:08:07 +0000436 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
437 Ops.data(), Ops.size(), Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000438}
439
Chris Lattner55207322007-01-30 23:45:45 +0000440/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
441/// specified opcode and operands. If successful, the constant result is
442/// returned, if not, null is returned. Note that this function can fail when
443/// attempting to fold instructions like loads and stores, which have no
444/// constant expression form.
445///
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000446Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
447 Constant* const* Ops, unsigned NumOps,
Owen Andersone922c022009-07-22 00:24:57 +0000448 LLVMContext &Context,
Chris Lattner55207322007-01-30 23:45:45 +0000449 const TargetData *TD) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000450 // Handle easy binops first.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000451 if (Instruction::isBinaryOp(Opcode)) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000452 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
Owen Anderson50895512009-07-06 18:42:36 +0000453 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD,
454 Context))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000455 return C;
456
Owen Andersonbaf3c402009-07-29 18:55:55 +0000457 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000458 }
Chris Lattner55207322007-01-30 23:45:45 +0000459
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000460 switch (Opcode) {
Chris Lattner55207322007-01-30 23:45:45 +0000461 default: return 0;
462 case Instruction::Call:
463 if (Function *F = dyn_cast<Function>(Ops[0]))
464 if (canConstantFoldCallTo(F))
Chris Lattnerad58eb32007-01-31 18:04:55 +0000465 return ConstantFoldCall(F, Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000466 return 0;
467 case Instruction::ICmp:
468 case Instruction::FCmp:
Torok Edwinc23197a2009-07-14 16:55:14 +0000469 llvm_unreachable("This function is invalid for compares: no predicate specified");
Chris Lattner001f7532007-08-11 23:49:01 +0000470 case Instruction::PtrToInt:
471 // If the input is a inttoptr, eliminate the pair. This requires knowing
472 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
473 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
474 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
475 Constant *Input = CE->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +0000476 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000477 if (TD->getPointerSizeInBits() < InWidth) {
478 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +0000479 ConstantInt::get(Context, APInt::getLowBitsSet(InWidth,
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000480 TD->getPointerSizeInBits()));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000481 Input = ConstantExpr::getAnd(Input, Mask);
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000482 }
Chris Lattner001f7532007-08-11 23:49:01 +0000483 // Do a zext or trunc to get to the dest size.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000484 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner001f7532007-08-11 23:49:01 +0000485 }
486 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000487 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner001f7532007-08-11 23:49:01 +0000488 case Instruction::IntToPtr:
Duncan Sands81b06be2008-08-13 20:20:35 +0000489 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
490 // the int size is >= the ptr size. This requires knowing the width of a
491 // pointer, so it can't be done in ConstantExpr::getCast.
492 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000493 if (TD &&
Duncan Sands81b06be2008-08-13 20:20:35 +0000494 TD->getPointerSizeInBits() <=
Dan Gohman6de29f82009-06-15 22:12:54 +0000495 CE->getType()->getScalarSizeInBits()) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000496 if (CE->getOpcode() == Instruction::PtrToInt) {
497 Constant *Input = CE->getOperand(0);
Owen Anderson50895512009-07-06 18:42:36 +0000498 Constant *C = FoldBitCast(Input, DestTy, *TD, Context);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000499 return C ? C : ConstantExpr::getBitCast(Input, DestTy);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000500 }
501 // If there's a constant offset added to the integer value before
502 // it is casted back to a pointer, see if the expression can be
503 // converted into a GEP.
504 if (CE->getOpcode() == Instruction::Add)
505 if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
506 if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
507 if (R->getOpcode() == Instruction::PtrToInt)
508 if (GlobalVariable *GV =
509 dyn_cast<GlobalVariable>(R->getOperand(0))) {
510 const PointerType *GVTy = cast<PointerType>(GV->getType());
511 if (const ArrayType *AT =
512 dyn_cast<ArrayType>(GVTy->getElementType())) {
513 const Type *ElTy = AT->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000514 uint64_t AllocSize = TD->getTypeAllocSize(ElTy);
515 APInt PSA(L->getValue().getBitWidth(), AllocSize);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000516 if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
517 L->getValue().urem(PSA) == 0) {
518 APInt ElemIdx = L->getValue().udiv(PSA);
519 if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
520 AT->getNumElements()))) {
521 Constant *Index[] = {
Owen Andersona7235ea2009-07-31 20:28:14 +0000522 Constant::getNullValue(CE->getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +0000523 ConstantInt::get(Context, ElemIdx)
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000524 };
Owen Anderson50895512009-07-06 18:42:36 +0000525 return
Owen Andersonbaf3c402009-07-29 18:55:55 +0000526 ConstantExpr::getGetElementPtr(GV, &Index[0], 2);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000527 }
528 }
529 }
530 }
Duncan Sands81b06be2008-08-13 20:20:35 +0000531 }
532 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000533 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000534 case Instruction::Trunc:
535 case Instruction::ZExt:
536 case Instruction::SExt:
537 case Instruction::FPTrunc:
538 case Instruction::FPExt:
539 case Instruction::UIToFP:
540 case Instruction::SIToFP:
541 case Instruction::FPToUI:
542 case Instruction::FPToSI:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000543 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000544 case Instruction::BitCast:
Chris Lattner1afab9c2007-12-11 07:29:44 +0000545 if (TD)
Owen Anderson50895512009-07-06 18:42:36 +0000546 if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD, Context))
Chris Lattner1afab9c2007-12-11 07:29:44 +0000547 return C;
Owen Andersonbaf3c402009-07-29 18:55:55 +0000548 return ConstantExpr::getBitCast(Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000549 case Instruction::Select:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000550 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000551 case Instruction::ExtractElement:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000552 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner55207322007-01-30 23:45:45 +0000553 case Instruction::InsertElement:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000554 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000555 case Instruction::ShuffleVector:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000556 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000557 case Instruction::GetElementPtr:
Owen Anderson50895512009-07-06 18:42:36 +0000558 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, Context, TD))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000559 return C;
560
Owen Andersonbaf3c402009-07-29 18:55:55 +0000561 return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000562 }
563}
564
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000565/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
566/// instruction (icmp/fcmp) with the specified operands. If it fails, it
567/// returns a constant expression of the specified operands.
568///
569Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
570 Constant*const * Ops,
571 unsigned NumOps,
Owen Andersone922c022009-07-22 00:24:57 +0000572 LLVMContext &Context,
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000573 const TargetData *TD) {
574 // fold: icmp (inttoptr x), null -> icmp x, 0
575 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000576 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000577 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
578 //
579 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
580 // around to know if bit truncation is happening.
581 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
582 if (TD && Ops[1]->isNullValue()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000583 const Type *IntPtrTy = TD->getIntPtrType(Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000584 if (CE0->getOpcode() == Instruction::IntToPtr) {
585 // Convert the integer value to the right size to ensure we get the
586 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000587 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000588 IntPtrTy, false);
Owen Andersona7235ea2009-07-31 20:28:14 +0000589 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Owen Anderson50895512009-07-06 18:42:36 +0000590 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
591 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000592 }
593
594 // Only do this transformation if the int is intptrty in size, otherwise
595 // there is a truncation or extension that we aren't modeling.
596 if (CE0->getOpcode() == Instruction::PtrToInt &&
597 CE0->getType() == IntPtrTy) {
598 Constant *C = CE0->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +0000599 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000600 // FIXME!
Owen Anderson50895512009-07-06 18:42:36 +0000601 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
602 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000603 }
604 }
605
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000606 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
607 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000608 const Type *IntPtrTy = TD->getIntPtrType(Context);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000609
610 if (CE0->getOpcode() == Instruction::IntToPtr) {
611 // Convert the integer value to the right size to ensure we get the
612 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000613 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000614 IntPtrTy, false);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000615 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000616 IntPtrTy, false);
617 Constant *NewOps[] = { C0, C1 };
Owen Anderson50895512009-07-06 18:42:36 +0000618 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
619 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000620 }
621
622 // Only do this transformation if the int is intptrty in size, otherwise
623 // there is a truncation or extension that we aren't modeling.
624 if ((CE0->getOpcode() == Instruction::PtrToInt &&
625 CE0->getType() == IntPtrTy &&
626 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
627 Constant *NewOps[] = {
628 CE0->getOperand(0), CE1->getOperand(0)
629 };
Owen Anderson50895512009-07-06 18:42:36 +0000630 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
631 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000632 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000633 }
634 }
635 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000636 return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000637}
638
639
Chris Lattner55207322007-01-30 23:45:45 +0000640/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
641/// getelementptr constantexpr, return the constant value being addressed by the
642/// constant expression, or null if something is funny and we can't decide.
643Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000644 ConstantExpr *CE) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000645 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner55207322007-01-30 23:45:45 +0000646 return 0; // Do not allow stepping over the value!
647
648 // Loop over all of the operands, tracking down which value we are
649 // addressing...
650 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
651 for (++I; I != E; ++I)
652 if (const StructType *STy = dyn_cast<StructType>(*I)) {
653 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
654 assert(CU->getZExtValue() < STy->getNumElements() &&
655 "Struct index out of range!");
656 unsigned El = (unsigned)CU->getZExtValue();
657 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
658 C = CS->getOperand(El);
659 } else if (isa<ConstantAggregateZero>(C)) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000660 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000661 } else if (isa<UndefValue>(C)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000662 C = UndefValue::get(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000663 } else {
664 return 0;
665 }
666 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
667 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
668 if (CI->getZExtValue() >= ATy->getNumElements())
669 return 0;
670 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
671 C = CA->getOperand(CI->getZExtValue());
672 else if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +0000673 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000674 else if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000675 C = UndefValue::get(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000676 else
677 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000678 } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
Chris Lattner55207322007-01-30 23:45:45 +0000679 if (CI->getZExtValue() >= PTy->getNumElements())
680 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000681 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
Chris Lattner55207322007-01-30 23:45:45 +0000682 C = CP->getOperand(CI->getZExtValue());
683 else if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +0000684 C = Constant::getNullValue(PTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000685 else if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000686 C = UndefValue::get(PTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000687 else
688 return 0;
689 } else {
690 return 0;
691 }
692 } else {
693 return 0;
694 }
695 return C;
696}
697
698
699//===----------------------------------------------------------------------===//
700// Constant Folding for Calls
701//
John Criswellbd9d3702005-10-27 16:00:10 +0000702
703/// canConstantFoldCallTo - Return true if its even possible to fold a call to
704/// the specified function.
705bool
Dan Gohmanfa9b80e2008-01-31 01:05:10 +0000706llvm::canConstantFoldCallTo(const Function *F) {
John Criswellbd9d3702005-10-27 16:00:10 +0000707 switch (F->getIntrinsicID()) {
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000708 case Intrinsic::sqrt:
709 case Intrinsic::powi:
Reid Spencere9391fd2007-04-01 07:35:23 +0000710 case Intrinsic::bswap:
711 case Intrinsic::ctpop:
712 case Intrinsic::ctlz:
713 case Intrinsic::cttz:
Chris Lattnere65cd402009-10-05 05:26:04 +0000714 case Intrinsic::uadd_with_overflow:
715 case Intrinsic::usub_with_overflow:
Evan Phoenix1614e502009-10-05 22:53:52 +0000716 case Intrinsic::sadd_with_overflow:
717 case Intrinsic::ssub_with_overflow:
John Criswellbd9d3702005-10-27 16:00:10 +0000718 return true;
Chris Lattner68a06032009-10-05 05:00:35 +0000719 default:
720 return false;
721 case 0: break;
John Criswellbd9d3702005-10-27 16:00:10 +0000722 }
723
Chris Lattner6f532a92009-04-03 00:02:39 +0000724 if (!F->hasName()) return false;
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000725 StringRef Name = F->getName();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000726
727 // In these cases, the check of the length is required. We don't want to
728 // return true for a name like "cos\0blah" which strcmp would return equal to
729 // "cos", but has length 8.
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000730 switch (Name[0]) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000731 default: return false;
732 case 'a':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000733 return Name == "acos" || Name == "asin" ||
734 Name == "atan" || Name == "atan2";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000735 case 'c':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000736 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000737 case 'e':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000738 return Name == "exp";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000739 case 'f':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000740 return Name == "fabs" || Name == "fmod" || Name == "floor";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000741 case 'l':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000742 return Name == "log" || Name == "log10";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000743 case 'p':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000744 return Name == "pow";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000745 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000746 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
747 Name == "sinf" || Name == "sqrtf";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000748 case 't':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000749 return Name == "tan" || Name == "tanh";
John Criswellbd9d3702005-10-27 16:00:10 +0000750 }
751}
752
Chris Lattner72d88ae2007-01-30 23:15:43 +0000753static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
Owen Andersone922c022009-07-22 00:24:57 +0000754 const Type *Ty, LLVMContext &Context) {
John Criswellbd9d3702005-10-27 16:00:10 +0000755 errno = 0;
756 V = NativeFP(V);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000757 if (errno != 0) {
758 errno = 0;
759 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000760 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000761
Chris Lattnerd0806a12009-10-05 05:06:24 +0000762 if (Ty->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000763 return ConstantFP::get(Context, APFloat((float)V));
Chris Lattnerd0806a12009-10-05 05:06:24 +0000764 if (Ty->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000765 return ConstantFP::get(Context, APFloat(V));
Torok Edwinc23197a2009-07-14 16:55:14 +0000766 llvm_unreachable("Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000767 return 0; // dummy return to suppress warning
John Criswellbd9d3702005-10-27 16:00:10 +0000768}
769
Dan Gohman38415242007-07-16 15:26:22 +0000770static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
771 double V, double W,
Owen Anderson50895512009-07-06 18:42:36 +0000772 const Type *Ty,
Owen Andersone922c022009-07-22 00:24:57 +0000773 LLVMContext &Context) {
Dan Gohman38415242007-07-16 15:26:22 +0000774 errno = 0;
775 V = NativeFP(V, W);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000776 if (errno != 0) {
777 errno = 0;
778 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000779 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000780
Chris Lattnerd0806a12009-10-05 05:06:24 +0000781 if (Ty->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000782 return ConstantFP::get(Context, APFloat((float)V));
Chris Lattnerd0806a12009-10-05 05:06:24 +0000783 if (Ty->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000784 return ConstantFP::get(Context, APFloat(V));
Torok Edwinc23197a2009-07-14 16:55:14 +0000785 llvm_unreachable("Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000786 return 0; // dummy return to suppress warning
Dan Gohman38415242007-07-16 15:26:22 +0000787}
788
John Criswellbd9d3702005-10-27 16:00:10 +0000789/// ConstantFoldCall - Attempt to constant fold a call to the specified function
790/// with the specified arguments, returning null if unsuccessful.
791Constant *
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000792llvm::ConstantFoldCall(Function *F,
Chris Lattner68a06032009-10-05 05:00:35 +0000793 Constant *const *Operands, unsigned NumOperands) {
Chris Lattner6f532a92009-04-03 00:02:39 +0000794 if (!F->hasName()) return 0;
Owen Andersone922c022009-07-22 00:24:57 +0000795 LLVMContext &Context = F->getContext();
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000796 StringRef Name = F->getName();
Chris Lattnere65cd402009-10-05 05:26:04 +0000797
John Criswellbd9d3702005-10-27 16:00:10 +0000798 const Type *Ty = F->getReturnType();
Chris Lattner72d88ae2007-01-30 23:15:43 +0000799 if (NumOperands == 1) {
John Criswellbd9d3702005-10-27 16:00:10 +0000800 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +0000801 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesen43421b32007-09-06 18:13:44 +0000802 return 0;
803 /// Currently APFloat versions of these functions do not exist, so we use
804 /// the host native double versions. Float versions are not called
805 /// directly but for all these it is true (float)(f((double)arg)) ==
806 /// f(arg). Long double not supported yet.
Chris Lattnerd0806a12009-10-05 05:06:24 +0000807 double V = Ty->isFloatTy() ? (double)Op->getValueAPF().convertToFloat() :
Dale Johannesen43421b32007-09-06 18:13:44 +0000808 Op->getValueAPF().convertToDouble();
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000809 switch (Name[0]) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000810 case 'a':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000811 if (Name == "acos")
Owen Anderson50895512009-07-06 18:42:36 +0000812 return ConstantFoldFP(acos, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000813 else if (Name == "asin")
Owen Anderson50895512009-07-06 18:42:36 +0000814 return ConstantFoldFP(asin, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000815 else if (Name == "atan")
Owen Anderson50895512009-07-06 18:42:36 +0000816 return ConstantFoldFP(atan, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000817 break;
818 case 'c':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000819 if (Name == "ceil")
Owen Anderson50895512009-07-06 18:42:36 +0000820 return ConstantFoldFP(ceil, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000821 else if (Name == "cos")
Owen Anderson50895512009-07-06 18:42:36 +0000822 return ConstantFoldFP(cos, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000823 else if (Name == "cosh")
Owen Anderson50895512009-07-06 18:42:36 +0000824 return ConstantFoldFP(cosh, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000825 else if (Name == "cosf")
Owen Anderson50895512009-07-06 18:42:36 +0000826 return ConstantFoldFP(cos, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000827 break;
828 case 'e':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000829 if (Name == "exp")
Owen Anderson50895512009-07-06 18:42:36 +0000830 return ConstantFoldFP(exp, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000831 break;
832 case 'f':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000833 if (Name == "fabs")
Owen Anderson50895512009-07-06 18:42:36 +0000834 return ConstantFoldFP(fabs, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000835 else if (Name == "floor")
Owen Anderson50895512009-07-06 18:42:36 +0000836 return ConstantFoldFP(floor, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000837 break;
838 case 'l':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000839 if (Name == "log" && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +0000840 return ConstantFoldFP(log, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000841 else if (Name == "log10" && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +0000842 return ConstantFoldFP(log10, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000843 else if (Name == "llvm.sqrt.f32" ||
844 Name == "llvm.sqrt.f64") {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000845 if (V >= -0.0)
Owen Anderson50895512009-07-06 18:42:36 +0000846 return ConstantFoldFP(sqrt, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000847 else // Undefined
Owen Andersona7235ea2009-07-31 20:28:14 +0000848 return Constant::getNullValue(Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000849 }
850 break;
851 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000852 if (Name == "sin")
Owen Anderson50895512009-07-06 18:42:36 +0000853 return ConstantFoldFP(sin, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000854 else if (Name == "sinh")
Owen Anderson50895512009-07-06 18:42:36 +0000855 return ConstantFoldFP(sinh, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000856 else if (Name == "sqrt" && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +0000857 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000858 else if (Name == "sqrtf" && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +0000859 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000860 else if (Name == "sinf")
Owen Anderson50895512009-07-06 18:42:36 +0000861 return ConstantFoldFP(sin, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000862 break;
863 case 't':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000864 if (Name == "tan")
Owen Anderson50895512009-07-06 18:42:36 +0000865 return ConstantFoldFP(tan, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000866 else if (Name == "tanh")
Owen Anderson50895512009-07-06 18:42:36 +0000867 return ConstantFoldFP(tanh, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000868 break;
869 default:
870 break;
John Criswellbd9d3702005-10-27 16:00:10 +0000871 }
Chris Lattner68a06032009-10-05 05:00:35 +0000872 return 0;
873 }
874
875
876 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000877 if (Name.startswith("llvm.bswap"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000878 return ConstantInt::get(Context, Op->getValue().byteSwap());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000879 else if (Name.startswith("llvm.ctpop"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000880 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000881 else if (Name.startswith("llvm.cttz"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000882 return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000883 else if (Name.startswith("llvm.ctlz"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000884 return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
Chris Lattner68a06032009-10-05 05:00:35 +0000885 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +0000886 }
Chris Lattner68a06032009-10-05 05:00:35 +0000887
888 return 0;
889 }
890
891 if (NumOperands == 2) {
John Criswellbd9d3702005-10-27 16:00:10 +0000892 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +0000893 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000894 return 0;
Chris Lattnerd0806a12009-10-05 05:06:24 +0000895 double Op1V = Ty->isFloatTy() ?
896 (double)Op1->getValueAPF().convertToFloat() :
Dale Johannesen43421b32007-09-06 18:13:44 +0000897 Op1->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000898 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +0000899 if (Op2->getType() != Op1->getType())
900 return 0;
901
902 double Op2V = Ty->isFloatTy() ?
Dale Johannesen43421b32007-09-06 18:13:44 +0000903 (double)Op2->getValueAPF().convertToFloat():
904 Op2->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000905
Chris Lattner68a06032009-10-05 05:00:35 +0000906 if (Name == "pow")
Owen Anderson50895512009-07-06 18:42:36 +0000907 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty, Context);
Chris Lattner68a06032009-10-05 05:00:35 +0000908 if (Name == "fmod")
Owen Anderson50895512009-07-06 18:42:36 +0000909 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty, Context);
Chris Lattner68a06032009-10-05 05:00:35 +0000910 if (Name == "atan2")
Owen Anderson50895512009-07-06 18:42:36 +0000911 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty, Context);
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000912 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Chris Lattner68a06032009-10-05 05:00:35 +0000913 if (Name == "llvm.powi.f32")
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000914 return ConstantFP::get(Context, APFloat((float)std::pow((float)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +0000915 (int)Op2C->getZExtValue())));
Chris Lattner68a06032009-10-05 05:00:35 +0000916 if (Name == "llvm.powi.f64")
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000917 return ConstantFP::get(Context, APFloat((double)std::pow((double)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +0000918 (int)Op2C->getZExtValue())));
John Criswellbd9d3702005-10-27 16:00:10 +0000919 }
Chris Lattner68a06032009-10-05 05:00:35 +0000920 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +0000921 }
Chris Lattnere65cd402009-10-05 05:26:04 +0000922
923
924 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
925 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
926 switch (F->getIntrinsicID()) {
927 default: break;
928 case Intrinsic::uadd_with_overflow: {
929 Constant *Res = ConstantExpr::getAdd(Op1, Op2); // result.
930 Constant *Ops[] = {
931 Res, ConstantExpr::getICmp(CmpInst::ICMP_ULT, Res, Op1) // overflow.
932 };
933 return ConstantStruct::get(F->getContext(), Ops, 2, false);
934 }
935 case Intrinsic::usub_with_overflow: {
936 Constant *Res = ConstantExpr::getSub(Op1, Op2); // result.
937 Constant *Ops[] = {
938 Res, ConstantExpr::getICmp(CmpInst::ICMP_UGT, Res, Op1) // overflow.
939 };
940 return ConstantStruct::get(F->getContext(), Ops, 2, false);
941 }
Evan Phoenix1614e502009-10-05 22:53:52 +0000942 case Intrinsic::sadd_with_overflow: {
943 Constant *Res = ConstantExpr::getAdd(Op1, Op2); // result.
944 Constant *Overflow = ConstantExpr::getSelect(
945 ConstantExpr::getICmp(CmpInst::ICMP_SGT,
946 ConstantInt::get(Op1->getType(), 0), Op1),
947 ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op2),
948 ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op2)); // overflow.
949
950 Constant *Ops[] = { Res, Overflow };
951 return ConstantStruct::get(F->getContext(), Ops, 2, false);
952 }
953 case Intrinsic::ssub_with_overflow: {
954 Constant *Res = ConstantExpr::getSub(Op1, Op2); // result.
955 Constant *Overflow = ConstantExpr::getSelect(
956 ConstantExpr::getICmp(CmpInst::ICMP_SGT,
957 ConstantInt::get(Op2->getType(), 0), Op2),
958 ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op1),
959 ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op1)); // overflow.
960
961 Constant *Ops[] = { Res, Overflow };
962 return ConstantStruct::get(F->getContext(), Ops, 2, false);
963 }
Chris Lattnere65cd402009-10-05 05:26:04 +0000964 }
965 }
966
967 return 0;
968 }
969 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +0000970 }
971 return 0;
972}
973