blob: 1f91ddf378917b814eafe6b4b339f115cc2df984 [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 Lattner62d327e2009-10-22 06:38:35 +000027#include "llvm/Analysis/ValueTracking.h"
28#include "llvm/Target/TargetData.h"
Chris Lattner55207322007-01-30 23:45:45 +000029#include "llvm/ADT/SmallVector.h"
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +000030#include "llvm/ADT/StringMap.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
John Criswellbd9d3702005-10-27 16:00:10 +000032#include "llvm/Support/GetElementPtrTypeIterator.h"
33#include "llvm/Support/MathExtras.h"
34#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 }
Chris Lattner62d327e2009-10-22 06:38:35 +0000114
115 // Instead of loading constant c string, use corresponding integer value
116 // directly if string length is small enough.
117 std::string Str;
118 if (TD && GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
119 unsigned len = Str.length();
120 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
121 unsigned numBits = Ty->getPrimitiveSizeInBits();
122 // Replace LI with immediate integer store.
123 if ((numBits >> 3) == len + 1) {
124 APInt StrVal(numBits, 0);
125 APInt SingleChar(numBits, 0);
126 if (TD->isLittleEndian()) {
127 for (signed i = len-1; i >= 0; i--) {
128 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
129 StrVal = (StrVal << 8) | SingleChar;
130 }
131 } else {
132 for (unsigned i = 0; i < len; i++) {
133 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
134 StrVal = (StrVal << 8) | SingleChar;
135 }
136 // Append NULL at the end.
137 SingleChar = 0;
138 StrVal = (StrVal << 8) | SingleChar;
139 }
140 return ConstantInt::get(CE->getContext(), StrVal);
141 }
142 }
Chris Lattner878e4942009-10-22 06:25:11 +0000143 }
144
145 return 0;
146}
147
148static Constant *ConstantFoldLoadInst(const LoadInst *LI, const TargetData *TD){
149 if (LI->isVolatile()) return 0;
150
151 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
152 return ConstantFoldLoadFromConstPtr(C, TD);
153
154 return 0;
155}
Chris Lattner03dd25c2007-01-31 00:51:48 +0000156
157/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
Nick Lewycky67e35662008-12-15 01:35:36 +0000158/// Attempt to symbolically evaluate the result of a binary operator merging
Chris Lattner03dd25c2007-01-31 00:51:48 +0000159/// these together. If target data info is available, it is provided as TD,
160/// otherwise TD is null.
161static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
Owen Anderson50895512009-07-06 18:42:36 +0000162 Constant *Op1, const TargetData *TD,
Owen Andersone922c022009-07-22 00:24:57 +0000163 LLVMContext &Context){
Chris Lattner03dd25c2007-01-31 00:51:48 +0000164 // SROA
165
166 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
167 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
168 // bits.
169
170
171 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
172 // constant. This happens frequently when iterating over a global array.
173 if (Opc == Instruction::Sub && TD) {
174 GlobalValue *GV1, *GV2;
175 int64_t Offs1, Offs2;
176
177 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
178 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
179 GV1 == GV2) {
180 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Owen Andersoneed707b2009-07-24 23:12:02 +0000181 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000182 }
183 }
184
Chris Lattner03dd25c2007-01-31 00:51:48 +0000185 return 0;
186}
187
188/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
189/// constant expression, do so.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000190static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000191 const Type *ResultTy,
Owen Andersone922c022009-07-22 00:24:57 +0000192 LLVMContext &Context,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000193 const TargetData *TD) {
194 Constant *Ptr = Ops[0];
Chris Lattner268e7d72008-05-08 04:54:43 +0000195 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +0000196 return 0;
Dan Gohmancda97062009-08-21 16:52:54 +0000197
198 unsigned BitWidth = TD->getTypeSizeInBits(TD->getIntPtrType(Context));
199 APInt BasePtr(BitWidth, 0);
Dan Gohmande0e5872009-08-19 18:18:36 +0000200 bool BaseIsInt = true;
Chris Lattner268e7d72008-05-08 04:54:43 +0000201 if (!Ptr->isNullValue()) {
202 // If this is a inttoptr from a constant int, we can fold this as the base,
203 // otherwise we can't.
204 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
205 if (CE->getOpcode() == Instruction::IntToPtr)
Dan Gohman71780102009-08-21 18:27:26 +0000206 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) {
Dan Gohmancda97062009-08-21 16:52:54 +0000207 BasePtr = Base->getValue();
Dan Gohman71780102009-08-21 18:27:26 +0000208 BasePtr.zextOrTrunc(BitWidth);
209 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000210
211 if (BasePtr == 0)
Dan Gohmande0e5872009-08-19 18:18:36 +0000212 BaseIsInt = false;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000213 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000214
215 // If this is a constant expr gep that is effectively computing an
216 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
217 for (unsigned i = 1; i != NumOps; ++i)
218 if (!isa<ConstantInt>(Ops[i]))
Dan Gohmande0e5872009-08-19 18:18:36 +0000219 return 0;
Chris Lattner268e7d72008-05-08 04:54:43 +0000220
Dan Gohmancda97062009-08-21 16:52:54 +0000221 APInt Offset = APInt(BitWidth,
222 TD->getIndexedOffset(Ptr->getType(),
223 (Value**)Ops+1, NumOps-1));
Dan Gohmande0e5872009-08-19 18:18:36 +0000224 // If the base value for this address is a literal integer value, fold the
225 // getelementptr to the resulting integer value casted to the pointer type.
226 if (BaseIsInt) {
Dan Gohmancda97062009-08-21 16:52:54 +0000227 Constant *C = ConstantInt::get(Context, Offset+BasePtr);
Dan Gohmande0e5872009-08-19 18:18:36 +0000228 return ConstantExpr::getIntToPtr(C, ResultTy);
229 }
230
231 // Otherwise form a regular getelementptr. Recompute the indices so that
232 // we eliminate over-indexing of the notional static type array bounds.
233 // This makes it easy to determine if the getelementptr is "inbounds".
234 // Also, this helps GlobalOpt do SROA on GlobalVariables.
235 const Type *Ty = Ptr->getType();
236 SmallVector<Constant*, 32> NewIdxs;
Dan Gohman3d013342009-08-19 22:46:59 +0000237 do {
Dan Gohmande0e5872009-08-19 18:18:36 +0000238 if (const SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
Dan Gohman3d013342009-08-19 22:46:59 +0000239 // The only pointer indexing we'll do is on the first index of the GEP.
Chris Lattnerf19f9342009-09-02 05:35:45 +0000240 if (isa<PointerType>(ATy) && !NewIdxs.empty())
Dan Gohman3d013342009-08-19 22:46:59 +0000241 break;
Dan Gohmande0e5872009-08-19 18:18:36 +0000242 // Determine which element of the array the offset points into.
Dan Gohmancda97062009-08-21 16:52:54 +0000243 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
Dan Gohmande0e5872009-08-19 18:18:36 +0000244 if (ElemSize == 0)
245 return 0;
Dan Gohmancda97062009-08-21 16:52:54 +0000246 APInt NewIdx = Offset.udiv(ElemSize);
Dan Gohmande0e5872009-08-19 18:18:36 +0000247 Offset -= NewIdx * ElemSize;
248 NewIdxs.push_back(ConstantInt::get(TD->getIntPtrType(Context), NewIdx));
249 Ty = ATy->getElementType();
250 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Dan Gohmancda97062009-08-21 16:52:54 +0000251 // Determine which field of the struct the offset points into. The
252 // getZExtValue is at least as safe as the StructLayout API because we
253 // know the offset is within the struct at this point.
Dan Gohmande0e5872009-08-19 18:18:36 +0000254 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohmancda97062009-08-21 16:52:54 +0000255 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Dan Gohmande0e5872009-08-19 18:18:36 +0000256 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Context), ElIdx));
Dan Gohmancda97062009-08-21 16:52:54 +0000257 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohmande0e5872009-08-19 18:18:36 +0000258 Ty = STy->getTypeAtIndex(ElIdx);
259 } else {
Dan Gohman3d013342009-08-19 22:46:59 +0000260 // We've reached some non-indexable type.
261 break;
Dan Gohmande0e5872009-08-19 18:18:36 +0000262 }
Dan Gohman3d013342009-08-19 22:46:59 +0000263 } while (Ty != cast<PointerType>(ResultTy)->getElementType());
264
265 // If we haven't used up the entire offset by descending the static
266 // type, then the offset is pointing into the middle of an indivisible
267 // member, so we can't simplify it.
268 if (Offset != 0)
269 return 0;
Dan Gohmande0e5872009-08-19 18:18:36 +0000270
Dan Gohman3bfbc452009-09-11 00:04:14 +0000271 // Create a GEP.
272 Constant *C =
Dan Gohman6e7ad952009-09-03 23:34:49 +0000273 ConstantExpr::getGetElementPtr(Ptr, &NewIdxs[0], NewIdxs.size());
274 assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
275 "Computed GetElementPtr has unexpected type!");
Dan Gohmande0e5872009-08-19 18:18:36 +0000276
Dan Gohman3d013342009-08-19 22:46:59 +0000277 // If we ended up indexing a member with a type that doesn't match
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000278 // the type of what the original indices indexed, add a cast.
Dan Gohman3d013342009-08-19 22:46:59 +0000279 if (Ty != cast<PointerType>(ResultTy)->getElementType())
280 C = ConstantExpr::getBitCast(C, ResultTy);
281
282 return C;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000283}
284
Chris Lattner1afab9c2007-12-11 07:29:44 +0000285/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
286/// targetdata. Return 0 if unfoldable.
287static Constant *FoldBitCast(Constant *C, const Type *DestTy,
Owen Andersone922c022009-07-22 00:24:57 +0000288 const TargetData &TD, LLVMContext &Context) {
Chris Lattner1afab9c2007-12-11 07:29:44 +0000289 // If this is a bitcast from constant vector -> vector, fold it.
290 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
291 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
292 // If the element types match, VMCore can fold it.
293 unsigned NumDstElt = DestVTy->getNumElements();
294 unsigned NumSrcElt = CV->getNumOperands();
295 if (NumDstElt == NumSrcElt)
296 return 0;
297
298 const Type *SrcEltTy = CV->getType()->getElementType();
299 const Type *DstEltTy = DestVTy->getElementType();
300
301 // Otherwise, we're changing the number of elements in a vector, which
302 // requires endianness information to do the right thing. For example,
303 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
304 // folds to (little endian):
305 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
306 // and to (big endian):
307 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
308
309 // First thing is first. We only want to think about integer here, so if
310 // we have something in FP form, recast it as integer.
311 if (DstEltTy->isFloatingPoint()) {
312 // Fold to an vector of integers with same size as our FP type.
313 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Owen Andersondebcb012009-07-29 22:17:13 +0000314 const Type *DestIVTy = VectorType::get(
Owen Anderson1d0be152009-08-13 21:58:54 +0000315 IntegerType::get(Context, FPWidth), NumDstElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000316 // Recursively handle this integer conversion, if possible.
Owen Anderson50895512009-07-06 18:42:36 +0000317 C = FoldBitCast(C, DestIVTy, TD, Context);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000318 if (!C) return 0;
319
320 // Finally, VMCore can handle this now that #elts line up.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000321 return ConstantExpr::getBitCast(C, DestTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000322 }
323
324 // Okay, we know the destination is integer, if the input is FP, convert
325 // it to integer first.
326 if (SrcEltTy->isFloatingPoint()) {
327 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Owen Andersondebcb012009-07-29 22:17:13 +0000328 const Type *SrcIVTy = VectorType::get(
Owen Anderson1d0be152009-08-13 21:58:54 +0000329 IntegerType::get(Context, FPWidth), NumSrcElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000330 // Ask VMCore to do the conversion now that #elts line up.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000331 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000332 CV = dyn_cast<ConstantVector>(C);
333 if (!CV) return 0; // If VMCore wasn't able to fold it, bail out.
334 }
335
336 // Now we know that the input and output vectors are both integer vectors
337 // of the same size, and that their #elements is not the same. Do the
338 // conversion here, which depends on whether the input or output has
339 // more elements.
340 bool isLittleEndian = TD.isLittleEndian();
341
342 SmallVector<Constant*, 32> Result;
343 if (NumDstElt < NumSrcElt) {
344 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
Owen Andersona7235ea2009-07-31 20:28:14 +0000345 Constant *Zero = Constant::getNullValue(DstEltTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000346 unsigned Ratio = NumSrcElt/NumDstElt;
347 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
348 unsigned SrcElt = 0;
349 for (unsigned i = 0; i != NumDstElt; ++i) {
350 // Build each element of the result.
351 Constant *Elt = Zero;
352 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
353 for (unsigned j = 0; j != Ratio; ++j) {
354 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
355 if (!Src) return 0; // Reject constantexpr elements.
356
357 // Zero extend the element to the right size.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000358 Src = ConstantExpr::getZExt(Src, Elt->getType());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000359
360 // Shift it to the right place, depending on endianness.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000361 Src = ConstantExpr::getShl(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000362 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000363 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
364
365 // Mix it in.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000366 Elt = ConstantExpr::getOr(Elt, Src);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000367 }
368 Result.push_back(Elt);
369 }
370 } else {
371 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
372 unsigned Ratio = NumDstElt/NumSrcElt;
373 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
374
375 // Loop over each source value, expanding into multiple results.
376 for (unsigned i = 0; i != NumSrcElt; ++i) {
377 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
378 if (!Src) return 0; // Reject constantexpr elements.
379
380 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
381 for (unsigned j = 0; j != Ratio; ++j) {
382 // Shift the piece of the value into the right place, depending on
383 // endianness.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000384 Constant *Elt = ConstantExpr::getLShr(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000385 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000386 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
387
388 // Truncate and remember this piece.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000389 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000390 }
391 }
392 }
393
Owen Andersonaf7ec972009-07-28 21:19:26 +0000394 return ConstantVector::get(Result.data(), Result.size());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000395 }
396 }
397
398 return 0;
399}
400
Chris Lattner03dd25c2007-01-31 00:51:48 +0000401
402//===----------------------------------------------------------------------===//
403// Constant Folding public APIs
404//===----------------------------------------------------------------------===//
405
406
Chris Lattner55207322007-01-30 23:45:45 +0000407/// ConstantFoldInstruction - Attempt to constant fold the specified
408/// instruction. If successful, the constant result is returned, if not, null
409/// is returned. Note that this function can only fail when attempting to fold
410/// instructions like loads and stores, which have no constant expression form.
411///
Owen Andersone922c022009-07-22 00:24:57 +0000412Constant *llvm::ConstantFoldInstruction(Instruction *I, LLVMContext &Context,
Owen Anderson50895512009-07-06 18:42:36 +0000413 const TargetData *TD) {
Chris Lattner55207322007-01-30 23:45:45 +0000414 if (PHINode *PN = dyn_cast<PHINode>(I)) {
415 if (PN->getNumIncomingValues() == 0)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000416 return UndefValue::get(PN->getType());
John Criswellbd9d3702005-10-27 16:00:10 +0000417
Chris Lattner55207322007-01-30 23:45:45 +0000418 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
419 if (Result == 0) return 0;
420
421 // Handle PHI nodes specially here...
422 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
423 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
424 return 0; // Not all the same incoming constants...
425
426 // If we reach here, all incoming values are the same constant.
427 return Result;
428 }
429
430 // Scan the operand list, checking to see if they are all constants, if so,
431 // hand off to ConstantFoldInstOperands.
432 SmallVector<Constant*, 8> Ops;
Gabor Greifde2d74b2008-05-22 06:43:33 +0000433 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
434 if (Constant *Op = dyn_cast<Constant>(*i))
Chris Lattner55207322007-01-30 23:45:45 +0000435 Ops.push_back(Op);
436 else
437 return 0; // All operands not constant!
438
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000439 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
440 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000441 Ops.data(), Ops.size(),
442 Context, TD);
Chris Lattner58665d42009-09-16 00:08:07 +0000443
Chris Lattner878e4942009-10-22 06:25:11 +0000444 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
445 return ConstantFoldLoadInst(LI, TD);
446
Chris Lattner58665d42009-09-16 00:08:07 +0000447 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
448 Ops.data(), Ops.size(), Context, TD);
Chris Lattner55207322007-01-30 23:45:45 +0000449}
450
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000451/// ConstantFoldConstantExpression - Attempt to fold the constant expression
452/// using the specified TargetData. If successful, the constant result is
453/// result is returned, if not, null is returned.
454Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
Owen Andersone922c022009-07-22 00:24:57 +0000455 LLVMContext &Context,
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000456 const TargetData *TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000457 SmallVector<Constant*, 8> Ops;
458 for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
459 Ops.push_back(cast<Constant>(*i));
460
461 if (CE->isCompare())
462 return ConstantFoldCompareInstOperands(CE->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000463 Ops.data(), Ops.size(),
464 Context, TD);
Chris Lattner58665d42009-09-16 00:08:07 +0000465 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
466 Ops.data(), Ops.size(), Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000467}
468
Chris Lattner55207322007-01-30 23:45:45 +0000469/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
470/// specified opcode and operands. If successful, the constant result is
471/// returned, if not, null is returned. Note that this function can fail when
472/// attempting to fold instructions like loads and stores, which have no
473/// constant expression form.
474///
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000475Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
476 Constant* const* Ops, unsigned NumOps,
Owen Andersone922c022009-07-22 00:24:57 +0000477 LLVMContext &Context,
Chris Lattner55207322007-01-30 23:45:45 +0000478 const TargetData *TD) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000479 // Handle easy binops first.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000480 if (Instruction::isBinaryOp(Opcode)) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000481 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
Owen Anderson50895512009-07-06 18:42:36 +0000482 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD,
483 Context))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000484 return C;
485
Owen Andersonbaf3c402009-07-29 18:55:55 +0000486 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000487 }
Chris Lattner55207322007-01-30 23:45:45 +0000488
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000489 switch (Opcode) {
Chris Lattner55207322007-01-30 23:45:45 +0000490 default: return 0;
491 case Instruction::Call:
492 if (Function *F = dyn_cast<Function>(Ops[0]))
493 if (canConstantFoldCallTo(F))
Chris Lattnerad58eb32007-01-31 18:04:55 +0000494 return ConstantFoldCall(F, Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000495 return 0;
496 case Instruction::ICmp:
497 case Instruction::FCmp:
Torok Edwinc23197a2009-07-14 16:55:14 +0000498 llvm_unreachable("This function is invalid for compares: no predicate specified");
Chris Lattner001f7532007-08-11 23:49:01 +0000499 case Instruction::PtrToInt:
500 // If the input is a inttoptr, eliminate the pair. This requires knowing
501 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
502 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
503 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
504 Constant *Input = CE->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +0000505 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000506 if (TD->getPointerSizeInBits() < InWidth) {
507 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +0000508 ConstantInt::get(Context, APInt::getLowBitsSet(InWidth,
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000509 TD->getPointerSizeInBits()));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000510 Input = ConstantExpr::getAnd(Input, Mask);
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000511 }
Chris Lattner001f7532007-08-11 23:49:01 +0000512 // Do a zext or trunc to get to the dest size.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000513 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner001f7532007-08-11 23:49:01 +0000514 }
515 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000516 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner001f7532007-08-11 23:49:01 +0000517 case Instruction::IntToPtr:
Duncan Sands81b06be2008-08-13 20:20:35 +0000518 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
519 // the int size is >= the ptr size. This requires knowing the width of a
520 // pointer, so it can't be done in ConstantExpr::getCast.
521 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000522 if (TD &&
Duncan Sands81b06be2008-08-13 20:20:35 +0000523 TD->getPointerSizeInBits() <=
Dan Gohman6de29f82009-06-15 22:12:54 +0000524 CE->getType()->getScalarSizeInBits()) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000525 if (CE->getOpcode() == Instruction::PtrToInt) {
526 Constant *Input = CE->getOperand(0);
Owen Anderson50895512009-07-06 18:42:36 +0000527 Constant *C = FoldBitCast(Input, DestTy, *TD, Context);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000528 return C ? C : ConstantExpr::getBitCast(Input, DestTy);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000529 }
530 // If there's a constant offset added to the integer value before
531 // it is casted back to a pointer, see if the expression can be
532 // converted into a GEP.
533 if (CE->getOpcode() == Instruction::Add)
534 if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
535 if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
536 if (R->getOpcode() == Instruction::PtrToInt)
537 if (GlobalVariable *GV =
538 dyn_cast<GlobalVariable>(R->getOperand(0))) {
539 const PointerType *GVTy = cast<PointerType>(GV->getType());
540 if (const ArrayType *AT =
541 dyn_cast<ArrayType>(GVTy->getElementType())) {
542 const Type *ElTy = AT->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000543 uint64_t AllocSize = TD->getTypeAllocSize(ElTy);
544 APInt PSA(L->getValue().getBitWidth(), AllocSize);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000545 if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
546 L->getValue().urem(PSA) == 0) {
547 APInt ElemIdx = L->getValue().udiv(PSA);
548 if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
549 AT->getNumElements()))) {
550 Constant *Index[] = {
Owen Andersona7235ea2009-07-31 20:28:14 +0000551 Constant::getNullValue(CE->getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +0000552 ConstantInt::get(Context, ElemIdx)
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000553 };
Owen Anderson50895512009-07-06 18:42:36 +0000554 return
Owen Andersonbaf3c402009-07-29 18:55:55 +0000555 ConstantExpr::getGetElementPtr(GV, &Index[0], 2);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000556 }
557 }
558 }
559 }
Duncan Sands81b06be2008-08-13 20:20:35 +0000560 }
561 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000562 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000563 case Instruction::Trunc:
564 case Instruction::ZExt:
565 case Instruction::SExt:
566 case Instruction::FPTrunc:
567 case Instruction::FPExt:
568 case Instruction::UIToFP:
569 case Instruction::SIToFP:
570 case Instruction::FPToUI:
571 case Instruction::FPToSI:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000572 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000573 case Instruction::BitCast:
Chris Lattner1afab9c2007-12-11 07:29:44 +0000574 if (TD)
Owen Anderson50895512009-07-06 18:42:36 +0000575 if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD, Context))
Chris Lattner1afab9c2007-12-11 07:29:44 +0000576 return C;
Owen Andersonbaf3c402009-07-29 18:55:55 +0000577 return ConstantExpr::getBitCast(Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000578 case Instruction::Select:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000579 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000580 case Instruction::ExtractElement:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000581 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner55207322007-01-30 23:45:45 +0000582 case Instruction::InsertElement:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000583 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000584 case Instruction::ShuffleVector:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000585 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000586 case Instruction::GetElementPtr:
Owen Anderson50895512009-07-06 18:42:36 +0000587 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, Context, TD))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000588 return C;
589
Owen Andersonbaf3c402009-07-29 18:55:55 +0000590 return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000591 }
592}
593
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000594/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
595/// instruction (icmp/fcmp) with the specified operands. If it fails, it
596/// returns a constant expression of the specified operands.
597///
598Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
599 Constant*const * Ops,
600 unsigned NumOps,
Owen Andersone922c022009-07-22 00:24:57 +0000601 LLVMContext &Context,
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000602 const TargetData *TD) {
603 // fold: icmp (inttoptr x), null -> icmp x, 0
604 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000605 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000606 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
607 //
608 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
609 // around to know if bit truncation is happening.
610 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
611 if (TD && Ops[1]->isNullValue()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000612 const Type *IntPtrTy = TD->getIntPtrType(Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000613 if (CE0->getOpcode() == Instruction::IntToPtr) {
614 // Convert the integer value to the right size to ensure we get the
615 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000616 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000617 IntPtrTy, false);
Owen Andersona7235ea2009-07-31 20:28:14 +0000618 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Owen Anderson50895512009-07-06 18:42:36 +0000619 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
620 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000621 }
622
623 // Only do this transformation if the int is intptrty in size, otherwise
624 // there is a truncation or extension that we aren't modeling.
625 if (CE0->getOpcode() == Instruction::PtrToInt &&
626 CE0->getType() == IntPtrTy) {
627 Constant *C = CE0->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +0000628 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000629 // FIXME!
Owen Anderson50895512009-07-06 18:42:36 +0000630 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
631 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000632 }
633 }
634
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000635 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
636 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000637 const Type *IntPtrTy = TD->getIntPtrType(Context);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000638
639 if (CE0->getOpcode() == Instruction::IntToPtr) {
640 // Convert the integer value to the right size to ensure we get the
641 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000642 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000643 IntPtrTy, false);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000644 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000645 IntPtrTy, false);
646 Constant *NewOps[] = { C0, C1 };
Owen Anderson50895512009-07-06 18:42:36 +0000647 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
648 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000649 }
650
651 // Only do this transformation if the int is intptrty in size, otherwise
652 // there is a truncation or extension that we aren't modeling.
653 if ((CE0->getOpcode() == Instruction::PtrToInt &&
654 CE0->getType() == IntPtrTy &&
655 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
656 Constant *NewOps[] = {
657 CE0->getOperand(0), CE1->getOperand(0)
658 };
Owen Anderson50895512009-07-06 18:42:36 +0000659 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
660 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000661 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000662 }
663 }
664 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000665 return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000666}
667
668
Chris Lattner55207322007-01-30 23:45:45 +0000669/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
670/// getelementptr constantexpr, return the constant value being addressed by the
671/// constant expression, or null if something is funny and we can't decide.
672Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000673 ConstantExpr *CE) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000674 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner55207322007-01-30 23:45:45 +0000675 return 0; // Do not allow stepping over the value!
676
677 // Loop over all of the operands, tracking down which value we are
678 // addressing...
679 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
680 for (++I; I != E; ++I)
681 if (const StructType *STy = dyn_cast<StructType>(*I)) {
682 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
683 assert(CU->getZExtValue() < STy->getNumElements() &&
684 "Struct index out of range!");
685 unsigned El = (unsigned)CU->getZExtValue();
686 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
687 C = CS->getOperand(El);
688 } else if (isa<ConstantAggregateZero>(C)) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000689 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000690 } else if (isa<UndefValue>(C)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000691 C = UndefValue::get(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000692 } else {
693 return 0;
694 }
695 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
696 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
697 if (CI->getZExtValue() >= ATy->getNumElements())
698 return 0;
699 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
700 C = CA->getOperand(CI->getZExtValue());
701 else if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +0000702 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000703 else if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000704 C = UndefValue::get(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000705 else
706 return 0;
Chris Lattner62d327e2009-10-22 06:38:35 +0000707 } else if (const VectorType *VTy = dyn_cast<VectorType>(*I)) {
708 if (CI->getZExtValue() >= VTy->getNumElements())
Chris Lattner55207322007-01-30 23:45:45 +0000709 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000710 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
Chris Lattner55207322007-01-30 23:45:45 +0000711 C = CP->getOperand(CI->getZExtValue());
712 else if (isa<ConstantAggregateZero>(C))
Chris Lattner62d327e2009-10-22 06:38:35 +0000713 C = Constant::getNullValue(VTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000714 else if (isa<UndefValue>(C))
Chris Lattner62d327e2009-10-22 06:38:35 +0000715 C = UndefValue::get(VTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000716 else
717 return 0;
718 } else {
719 return 0;
720 }
721 } else {
722 return 0;
723 }
724 return C;
725}
726
727
728//===----------------------------------------------------------------------===//
729// Constant Folding for Calls
730//
John Criswellbd9d3702005-10-27 16:00:10 +0000731
732/// canConstantFoldCallTo - Return true if its even possible to fold a call to
733/// the specified function.
734bool
Dan Gohmanfa9b80e2008-01-31 01:05:10 +0000735llvm::canConstantFoldCallTo(const Function *F) {
John Criswellbd9d3702005-10-27 16:00:10 +0000736 switch (F->getIntrinsicID()) {
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000737 case Intrinsic::sqrt:
738 case Intrinsic::powi:
Reid Spencere9391fd2007-04-01 07:35:23 +0000739 case Intrinsic::bswap:
740 case Intrinsic::ctpop:
741 case Intrinsic::ctlz:
742 case Intrinsic::cttz:
Chris Lattnere65cd402009-10-05 05:26:04 +0000743 case Intrinsic::uadd_with_overflow:
744 case Intrinsic::usub_with_overflow:
Evan Phoenix1614e502009-10-05 22:53:52 +0000745 case Intrinsic::sadd_with_overflow:
746 case Intrinsic::ssub_with_overflow:
John Criswellbd9d3702005-10-27 16:00:10 +0000747 return true;
Chris Lattner68a06032009-10-05 05:00:35 +0000748 default:
749 return false;
750 case 0: break;
John Criswellbd9d3702005-10-27 16:00:10 +0000751 }
752
Chris Lattner6f532a92009-04-03 00:02:39 +0000753 if (!F->hasName()) return false;
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000754 StringRef Name = F->getName();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000755
756 // In these cases, the check of the length is required. We don't want to
757 // return true for a name like "cos\0blah" which strcmp would return equal to
758 // "cos", but has length 8.
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000759 switch (Name[0]) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000760 default: return false;
761 case 'a':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000762 return Name == "acos" || Name == "asin" ||
763 Name == "atan" || Name == "atan2";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000764 case 'c':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000765 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000766 case 'e':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000767 return Name == "exp";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000768 case 'f':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000769 return Name == "fabs" || Name == "fmod" || Name == "floor";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000770 case 'l':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000771 return Name == "log" || Name == "log10";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000772 case 'p':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000773 return Name == "pow";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000774 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000775 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
776 Name == "sinf" || Name == "sqrtf";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000777 case 't':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000778 return Name == "tan" || Name == "tanh";
John Criswellbd9d3702005-10-27 16:00:10 +0000779 }
780}
781
Chris Lattner72d88ae2007-01-30 23:15:43 +0000782static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
Owen Andersone922c022009-07-22 00:24:57 +0000783 const Type *Ty, LLVMContext &Context) {
John Criswellbd9d3702005-10-27 16:00:10 +0000784 errno = 0;
785 V = NativeFP(V);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000786 if (errno != 0) {
787 errno = 0;
788 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000789 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000790
Chris Lattnerd0806a12009-10-05 05:06:24 +0000791 if (Ty->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000792 return ConstantFP::get(Context, APFloat((float)V));
Chris Lattnerd0806a12009-10-05 05:06:24 +0000793 if (Ty->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000794 return ConstantFP::get(Context, APFloat(V));
Torok Edwinc23197a2009-07-14 16:55:14 +0000795 llvm_unreachable("Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000796 return 0; // dummy return to suppress warning
John Criswellbd9d3702005-10-27 16:00:10 +0000797}
798
Dan Gohman38415242007-07-16 15:26:22 +0000799static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
800 double V, double W,
Owen Anderson50895512009-07-06 18:42:36 +0000801 const Type *Ty,
Owen Andersone922c022009-07-22 00:24:57 +0000802 LLVMContext &Context) {
Dan Gohman38415242007-07-16 15:26:22 +0000803 errno = 0;
804 V = NativeFP(V, W);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000805 if (errno != 0) {
806 errno = 0;
807 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000808 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000809
Chris Lattnerd0806a12009-10-05 05:06:24 +0000810 if (Ty->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000811 return ConstantFP::get(Context, APFloat((float)V));
Chris Lattnerd0806a12009-10-05 05:06:24 +0000812 if (Ty->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000813 return ConstantFP::get(Context, APFloat(V));
Torok Edwinc23197a2009-07-14 16:55:14 +0000814 llvm_unreachable("Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000815 return 0; // dummy return to suppress warning
Dan Gohman38415242007-07-16 15:26:22 +0000816}
817
John Criswellbd9d3702005-10-27 16:00:10 +0000818/// ConstantFoldCall - Attempt to constant fold a call to the specified function
819/// with the specified arguments, returning null if unsuccessful.
820Constant *
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000821llvm::ConstantFoldCall(Function *F,
Chris Lattner68a06032009-10-05 05:00:35 +0000822 Constant *const *Operands, unsigned NumOperands) {
Chris Lattner6f532a92009-04-03 00:02:39 +0000823 if (!F->hasName()) return 0;
Owen Andersone922c022009-07-22 00:24:57 +0000824 LLVMContext &Context = F->getContext();
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000825 StringRef Name = F->getName();
Chris Lattnere65cd402009-10-05 05:26:04 +0000826
John Criswellbd9d3702005-10-27 16:00:10 +0000827 const Type *Ty = F->getReturnType();
Chris Lattner72d88ae2007-01-30 23:15:43 +0000828 if (NumOperands == 1) {
John Criswellbd9d3702005-10-27 16:00:10 +0000829 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +0000830 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesen43421b32007-09-06 18:13:44 +0000831 return 0;
832 /// Currently APFloat versions of these functions do not exist, so we use
833 /// the host native double versions. Float versions are not called
834 /// directly but for all these it is true (float)(f((double)arg)) ==
835 /// f(arg). Long double not supported yet.
Chris Lattnerd0806a12009-10-05 05:06:24 +0000836 double V = Ty->isFloatTy() ? (double)Op->getValueAPF().convertToFloat() :
Dale Johannesen43421b32007-09-06 18:13:44 +0000837 Op->getValueAPF().convertToDouble();
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000838 switch (Name[0]) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000839 case 'a':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000840 if (Name == "acos")
Owen Anderson50895512009-07-06 18:42:36 +0000841 return ConstantFoldFP(acos, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000842 else if (Name == "asin")
Owen Anderson50895512009-07-06 18:42:36 +0000843 return ConstantFoldFP(asin, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000844 else if (Name == "atan")
Owen Anderson50895512009-07-06 18:42:36 +0000845 return ConstantFoldFP(atan, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000846 break;
847 case 'c':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000848 if (Name == "ceil")
Owen Anderson50895512009-07-06 18:42:36 +0000849 return ConstantFoldFP(ceil, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000850 else if (Name == "cos")
Owen Anderson50895512009-07-06 18:42:36 +0000851 return ConstantFoldFP(cos, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000852 else if (Name == "cosh")
Owen Anderson50895512009-07-06 18:42:36 +0000853 return ConstantFoldFP(cosh, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000854 else if (Name == "cosf")
Owen Anderson50895512009-07-06 18:42:36 +0000855 return ConstantFoldFP(cos, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000856 break;
857 case 'e':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000858 if (Name == "exp")
Owen Anderson50895512009-07-06 18:42:36 +0000859 return ConstantFoldFP(exp, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000860 break;
861 case 'f':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000862 if (Name == "fabs")
Owen Anderson50895512009-07-06 18:42:36 +0000863 return ConstantFoldFP(fabs, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000864 else if (Name == "floor")
Owen Anderson50895512009-07-06 18:42:36 +0000865 return ConstantFoldFP(floor, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000866 break;
867 case 'l':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000868 if (Name == "log" && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +0000869 return ConstantFoldFP(log, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000870 else if (Name == "log10" && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +0000871 return ConstantFoldFP(log10, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000872 else if (Name == "llvm.sqrt.f32" ||
873 Name == "llvm.sqrt.f64") {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000874 if (V >= -0.0)
Owen Anderson50895512009-07-06 18:42:36 +0000875 return ConstantFoldFP(sqrt, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000876 else // Undefined
Owen Andersona7235ea2009-07-31 20:28:14 +0000877 return Constant::getNullValue(Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000878 }
879 break;
880 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000881 if (Name == "sin")
Owen Anderson50895512009-07-06 18:42:36 +0000882 return ConstantFoldFP(sin, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000883 else if (Name == "sinh")
Owen Anderson50895512009-07-06 18:42:36 +0000884 return ConstantFoldFP(sinh, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000885 else if (Name == "sqrt" && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +0000886 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000887 else if (Name == "sqrtf" && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +0000888 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000889 else if (Name == "sinf")
Owen Anderson50895512009-07-06 18:42:36 +0000890 return ConstantFoldFP(sin, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000891 break;
892 case 't':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000893 if (Name == "tan")
Owen Anderson50895512009-07-06 18:42:36 +0000894 return ConstantFoldFP(tan, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000895 else if (Name == "tanh")
Owen Anderson50895512009-07-06 18:42:36 +0000896 return ConstantFoldFP(tanh, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000897 break;
898 default:
899 break;
John Criswellbd9d3702005-10-27 16:00:10 +0000900 }
Chris Lattner68a06032009-10-05 05:00:35 +0000901 return 0;
902 }
903
904
905 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000906 if (Name.startswith("llvm.bswap"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000907 return ConstantInt::get(Context, Op->getValue().byteSwap());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000908 else if (Name.startswith("llvm.ctpop"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000909 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000910 else if (Name.startswith("llvm.cttz"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000911 return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000912 else if (Name.startswith("llvm.ctlz"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000913 return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
Chris Lattner68a06032009-10-05 05:00:35 +0000914 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +0000915 }
Chris Lattner68a06032009-10-05 05:00:35 +0000916
917 return 0;
918 }
919
920 if (NumOperands == 2) {
John Criswellbd9d3702005-10-27 16:00:10 +0000921 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +0000922 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000923 return 0;
Chris Lattnerd0806a12009-10-05 05:06:24 +0000924 double Op1V = Ty->isFloatTy() ?
925 (double)Op1->getValueAPF().convertToFloat() :
Dale Johannesen43421b32007-09-06 18:13:44 +0000926 Op1->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000927 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +0000928 if (Op2->getType() != Op1->getType())
929 return 0;
930
931 double Op2V = Ty->isFloatTy() ?
Dale Johannesen43421b32007-09-06 18:13:44 +0000932 (double)Op2->getValueAPF().convertToFloat():
933 Op2->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000934
Chris Lattner68a06032009-10-05 05:00:35 +0000935 if (Name == "pow")
Owen Anderson50895512009-07-06 18:42:36 +0000936 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty, Context);
Chris Lattner68a06032009-10-05 05:00:35 +0000937 if (Name == "fmod")
Owen Anderson50895512009-07-06 18:42:36 +0000938 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty, Context);
Chris Lattner68a06032009-10-05 05:00:35 +0000939 if (Name == "atan2")
Owen Anderson50895512009-07-06 18:42:36 +0000940 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty, Context);
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000941 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Chris Lattner68a06032009-10-05 05:00:35 +0000942 if (Name == "llvm.powi.f32")
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000943 return ConstantFP::get(Context, APFloat((float)std::pow((float)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +0000944 (int)Op2C->getZExtValue())));
Chris Lattner68a06032009-10-05 05:00:35 +0000945 if (Name == "llvm.powi.f64")
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000946 return ConstantFP::get(Context, APFloat((double)std::pow((double)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +0000947 (int)Op2C->getZExtValue())));
John Criswellbd9d3702005-10-27 16:00:10 +0000948 }
Chris Lattner68a06032009-10-05 05:00:35 +0000949 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +0000950 }
Chris Lattnere65cd402009-10-05 05:26:04 +0000951
952
953 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
954 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
955 switch (F->getIntrinsicID()) {
956 default: break;
957 case Intrinsic::uadd_with_overflow: {
958 Constant *Res = ConstantExpr::getAdd(Op1, Op2); // result.
959 Constant *Ops[] = {
960 Res, ConstantExpr::getICmp(CmpInst::ICMP_ULT, Res, Op1) // overflow.
961 };
962 return ConstantStruct::get(F->getContext(), Ops, 2, false);
963 }
964 case Intrinsic::usub_with_overflow: {
965 Constant *Res = ConstantExpr::getSub(Op1, Op2); // result.
966 Constant *Ops[] = {
967 Res, ConstantExpr::getICmp(CmpInst::ICMP_UGT, Res, Op1) // overflow.
968 };
969 return ConstantStruct::get(F->getContext(), Ops, 2, false);
970 }
Evan Phoenix1614e502009-10-05 22:53:52 +0000971 case Intrinsic::sadd_with_overflow: {
972 Constant *Res = ConstantExpr::getAdd(Op1, Op2); // result.
973 Constant *Overflow = ConstantExpr::getSelect(
974 ConstantExpr::getICmp(CmpInst::ICMP_SGT,
975 ConstantInt::get(Op1->getType(), 0), Op1),
976 ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op2),
977 ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op2)); // overflow.
978
979 Constant *Ops[] = { Res, Overflow };
980 return ConstantStruct::get(F->getContext(), Ops, 2, false);
981 }
982 case Intrinsic::ssub_with_overflow: {
983 Constant *Res = ConstantExpr::getSub(Op1, Op2); // result.
984 Constant *Overflow = ConstantExpr::getSelect(
985 ConstantExpr::getICmp(CmpInst::ICMP_SGT,
986 ConstantInt::get(Op2->getType(), 0), Op2),
987 ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op1),
988 ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op1)); // overflow.
989
990 Constant *Ops[] = { Res, Overflow };
991 return ConstantStruct::get(F->getContext(), Ops, 2, false);
992 }
Chris Lattnere65cd402009-10-05 05:26:04 +0000993 }
994 }
995
996 return 0;
997 }
998 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +0000999 }
1000 return 0;
1001}
1002