blob: 3ef6d5594cadd47de89f881135ca119177783ba9 [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
Chris Lattnere00c43f2009-10-22 06:44:07 +0000106 // If the loaded value isn't a constant expr, we can't handle it.
107 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
108 if (!CE) return 0;
109
110 if (CE->getOpcode() == Instruction::GetElementPtr) {
111 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
112 if (GV->isConstant() && GV->hasDefinitiveInitializer())
113 if (Constant *V =
114 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
115 return V;
116 }
117
118 // Instead of loading constant c string, use corresponding integer value
119 // directly if string length is small enough.
120 std::string Str;
121 if (TD && GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
122 unsigned len = Str.length();
123 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
124 unsigned numBits = Ty->getPrimitiveSizeInBits();
125 // Replace LI with immediate integer store.
126 if ((numBits >> 3) == len + 1) {
127 APInt StrVal(numBits, 0);
128 APInt SingleChar(numBits, 0);
129 if (TD->isLittleEndian()) {
130 for (signed i = len-1; i >= 0; i--) {
131 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Chris Lattner62d327e2009-10-22 06:38:35 +0000132 StrVal = (StrVal << 8) | SingleChar;
133 }
Chris Lattnere00c43f2009-10-22 06:44:07 +0000134 } else {
135 for (unsigned i = 0; i < len; i++) {
136 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
137 StrVal = (StrVal << 8) | SingleChar;
138 }
139 // Append NULL at the end.
140 SingleChar = 0;
141 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner62d327e2009-10-22 06:38:35 +0000142 }
Chris Lattnere00c43f2009-10-22 06:44:07 +0000143 return ConstantInt::get(CE->getContext(), StrVal);
Chris Lattner62d327e2009-10-22 06:38:35 +0000144 }
Chris Lattner878e4942009-10-22 06:25:11 +0000145 }
Chris Lattnere00c43f2009-10-22 06:44:07 +0000146
147 // If this load comes from anywhere in a constant global, and if the global
148 // is all undef or zero, we know what it loads.
149 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getUnderlyingObject())){
150 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
151 const Type *ResTy = cast<PointerType>(C->getType())->getElementType();
152 if (GV->getInitializer()->isNullValue())
153 return Constant::getNullValue(ResTy);
154 if (isa<UndefValue>(GV->getInitializer()))
155 return UndefValue::get(ResTy);
156 }
157 }
158
Chris Lattner878e4942009-10-22 06:25:11 +0000159 return 0;
160}
161
162static Constant *ConstantFoldLoadInst(const LoadInst *LI, const TargetData *TD){
163 if (LI->isVolatile()) return 0;
164
165 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
166 return ConstantFoldLoadFromConstPtr(C, TD);
167
168 return 0;
169}
Chris Lattner03dd25c2007-01-31 00:51:48 +0000170
171/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
Nick Lewycky67e35662008-12-15 01:35:36 +0000172/// Attempt to symbolically evaluate the result of a binary operator merging
Chris Lattner03dd25c2007-01-31 00:51:48 +0000173/// these together. If target data info is available, it is provided as TD,
174/// otherwise TD is null.
175static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
Owen Anderson50895512009-07-06 18:42:36 +0000176 Constant *Op1, const TargetData *TD,
Owen Andersone922c022009-07-22 00:24:57 +0000177 LLVMContext &Context){
Chris Lattner03dd25c2007-01-31 00:51:48 +0000178 // SROA
179
180 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
181 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
182 // bits.
183
184
185 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
186 // constant. This happens frequently when iterating over a global array.
187 if (Opc == Instruction::Sub && TD) {
188 GlobalValue *GV1, *GV2;
189 int64_t Offs1, Offs2;
190
191 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
192 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
193 GV1 == GV2) {
194 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Owen Andersoneed707b2009-07-24 23:12:02 +0000195 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000196 }
197 }
198
Chris Lattner03dd25c2007-01-31 00:51:48 +0000199 return 0;
200}
201
202/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
203/// constant expression, do so.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000204static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000205 const Type *ResultTy,
Owen Andersone922c022009-07-22 00:24:57 +0000206 LLVMContext &Context,
Chris Lattner03dd25c2007-01-31 00:51:48 +0000207 const TargetData *TD) {
208 Constant *Ptr = Ops[0];
Chris Lattner268e7d72008-05-08 04:54:43 +0000209 if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
Chris Lattner03dd25c2007-01-31 00:51:48 +0000210 return 0;
Dan Gohmancda97062009-08-21 16:52:54 +0000211
212 unsigned BitWidth = TD->getTypeSizeInBits(TD->getIntPtrType(Context));
213 APInt BasePtr(BitWidth, 0);
Dan Gohmande0e5872009-08-19 18:18:36 +0000214 bool BaseIsInt = true;
Chris Lattner268e7d72008-05-08 04:54:43 +0000215 if (!Ptr->isNullValue()) {
216 // If this is a inttoptr from a constant int, we can fold this as the base,
217 // otherwise we can't.
218 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
219 if (CE->getOpcode() == Instruction::IntToPtr)
Dan Gohman71780102009-08-21 18:27:26 +0000220 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) {
Dan Gohmancda97062009-08-21 16:52:54 +0000221 BasePtr = Base->getValue();
Dan Gohman71780102009-08-21 18:27:26 +0000222 BasePtr.zextOrTrunc(BitWidth);
223 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000224
225 if (BasePtr == 0)
Dan Gohmande0e5872009-08-19 18:18:36 +0000226 BaseIsInt = false;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000227 }
Chris Lattner268e7d72008-05-08 04:54:43 +0000228
229 // If this is a constant expr gep that is effectively computing an
230 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
231 for (unsigned i = 1; i != NumOps; ++i)
232 if (!isa<ConstantInt>(Ops[i]))
Dan Gohmande0e5872009-08-19 18:18:36 +0000233 return 0;
Chris Lattner268e7d72008-05-08 04:54:43 +0000234
Dan Gohmancda97062009-08-21 16:52:54 +0000235 APInt Offset = APInt(BitWidth,
236 TD->getIndexedOffset(Ptr->getType(),
237 (Value**)Ops+1, NumOps-1));
Dan Gohmande0e5872009-08-19 18:18:36 +0000238 // If the base value for this address is a literal integer value, fold the
239 // getelementptr to the resulting integer value casted to the pointer type.
240 if (BaseIsInt) {
Dan Gohmancda97062009-08-21 16:52:54 +0000241 Constant *C = ConstantInt::get(Context, Offset+BasePtr);
Dan Gohmande0e5872009-08-19 18:18:36 +0000242 return ConstantExpr::getIntToPtr(C, ResultTy);
243 }
244
245 // Otherwise form a regular getelementptr. Recompute the indices so that
246 // we eliminate over-indexing of the notional static type array bounds.
247 // This makes it easy to determine if the getelementptr is "inbounds".
248 // Also, this helps GlobalOpt do SROA on GlobalVariables.
249 const Type *Ty = Ptr->getType();
250 SmallVector<Constant*, 32> NewIdxs;
Dan Gohman3d013342009-08-19 22:46:59 +0000251 do {
Dan Gohmande0e5872009-08-19 18:18:36 +0000252 if (const SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
Dan Gohman3d013342009-08-19 22:46:59 +0000253 // The only pointer indexing we'll do is on the first index of the GEP.
Chris Lattnerf19f9342009-09-02 05:35:45 +0000254 if (isa<PointerType>(ATy) && !NewIdxs.empty())
Dan Gohman3d013342009-08-19 22:46:59 +0000255 break;
Dan Gohmande0e5872009-08-19 18:18:36 +0000256 // Determine which element of the array the offset points into.
Dan Gohmancda97062009-08-21 16:52:54 +0000257 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
Dan Gohmande0e5872009-08-19 18:18:36 +0000258 if (ElemSize == 0)
259 return 0;
Dan Gohmancda97062009-08-21 16:52:54 +0000260 APInt NewIdx = Offset.udiv(ElemSize);
Dan Gohmande0e5872009-08-19 18:18:36 +0000261 Offset -= NewIdx * ElemSize;
262 NewIdxs.push_back(ConstantInt::get(TD->getIntPtrType(Context), NewIdx));
263 Ty = ATy->getElementType();
264 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Dan Gohmancda97062009-08-21 16:52:54 +0000265 // Determine which field of the struct the offset points into. The
266 // getZExtValue is at least as safe as the StructLayout API because we
267 // know the offset is within the struct at this point.
Dan Gohmande0e5872009-08-19 18:18:36 +0000268 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohmancda97062009-08-21 16:52:54 +0000269 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Dan Gohmande0e5872009-08-19 18:18:36 +0000270 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Context), ElIdx));
Dan Gohmancda97062009-08-21 16:52:54 +0000271 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohmande0e5872009-08-19 18:18:36 +0000272 Ty = STy->getTypeAtIndex(ElIdx);
273 } else {
Dan Gohman3d013342009-08-19 22:46:59 +0000274 // We've reached some non-indexable type.
275 break;
Dan Gohmande0e5872009-08-19 18:18:36 +0000276 }
Dan Gohman3d013342009-08-19 22:46:59 +0000277 } while (Ty != cast<PointerType>(ResultTy)->getElementType());
278
279 // If we haven't used up the entire offset by descending the static
280 // type, then the offset is pointing into the middle of an indivisible
281 // member, so we can't simplify it.
282 if (Offset != 0)
283 return 0;
Dan Gohmande0e5872009-08-19 18:18:36 +0000284
Dan Gohman3bfbc452009-09-11 00:04:14 +0000285 // Create a GEP.
286 Constant *C =
Dan Gohman6e7ad952009-09-03 23:34:49 +0000287 ConstantExpr::getGetElementPtr(Ptr, &NewIdxs[0], NewIdxs.size());
288 assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
289 "Computed GetElementPtr has unexpected type!");
Dan Gohmande0e5872009-08-19 18:18:36 +0000290
Dan Gohman3d013342009-08-19 22:46:59 +0000291 // If we ended up indexing a member with a type that doesn't match
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000292 // the type of what the original indices indexed, add a cast.
Dan Gohman3d013342009-08-19 22:46:59 +0000293 if (Ty != cast<PointerType>(ResultTy)->getElementType())
294 C = ConstantExpr::getBitCast(C, ResultTy);
295
296 return C;
Chris Lattner03dd25c2007-01-31 00:51:48 +0000297}
298
Chris Lattner1afab9c2007-12-11 07:29:44 +0000299/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
300/// targetdata. Return 0 if unfoldable.
301static Constant *FoldBitCast(Constant *C, const Type *DestTy,
Owen Andersone922c022009-07-22 00:24:57 +0000302 const TargetData &TD, LLVMContext &Context) {
Chris Lattner1afab9c2007-12-11 07:29:44 +0000303 // If this is a bitcast from constant vector -> vector, fold it.
304 if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
305 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
306 // If the element types match, VMCore can fold it.
307 unsigned NumDstElt = DestVTy->getNumElements();
308 unsigned NumSrcElt = CV->getNumOperands();
309 if (NumDstElt == NumSrcElt)
310 return 0;
311
312 const Type *SrcEltTy = CV->getType()->getElementType();
313 const Type *DstEltTy = DestVTy->getElementType();
314
315 // Otherwise, we're changing the number of elements in a vector, which
316 // requires endianness information to do the right thing. For example,
317 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
318 // folds to (little endian):
319 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
320 // and to (big endian):
321 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
322
323 // First thing is first. We only want to think about integer here, so if
324 // we have something in FP form, recast it as integer.
325 if (DstEltTy->isFloatingPoint()) {
326 // Fold to an vector of integers with same size as our FP type.
327 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Owen Andersondebcb012009-07-29 22:17:13 +0000328 const Type *DestIVTy = VectorType::get(
Owen Anderson1d0be152009-08-13 21:58:54 +0000329 IntegerType::get(Context, FPWidth), NumDstElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000330 // Recursively handle this integer conversion, if possible.
Owen Anderson50895512009-07-06 18:42:36 +0000331 C = FoldBitCast(C, DestIVTy, TD, Context);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000332 if (!C) return 0;
333
334 // Finally, VMCore can handle this now that #elts line up.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000335 return ConstantExpr::getBitCast(C, DestTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000336 }
337
338 // Okay, we know the destination is integer, if the input is FP, convert
339 // it to integer first.
340 if (SrcEltTy->isFloatingPoint()) {
341 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Owen Andersondebcb012009-07-29 22:17:13 +0000342 const Type *SrcIVTy = VectorType::get(
Owen Anderson1d0be152009-08-13 21:58:54 +0000343 IntegerType::get(Context, FPWidth), NumSrcElt);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000344 // Ask VMCore to do the conversion now that #elts line up.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000345 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000346 CV = dyn_cast<ConstantVector>(C);
347 if (!CV) return 0; // If VMCore wasn't able to fold it, bail out.
348 }
349
350 // Now we know that the input and output vectors are both integer vectors
351 // of the same size, and that their #elements is not the same. Do the
352 // conversion here, which depends on whether the input or output has
353 // more elements.
354 bool isLittleEndian = TD.isLittleEndian();
355
356 SmallVector<Constant*, 32> Result;
357 if (NumDstElt < NumSrcElt) {
358 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
Owen Andersona7235ea2009-07-31 20:28:14 +0000359 Constant *Zero = Constant::getNullValue(DstEltTy);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000360 unsigned Ratio = NumSrcElt/NumDstElt;
361 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
362 unsigned SrcElt = 0;
363 for (unsigned i = 0; i != NumDstElt; ++i) {
364 // Build each element of the result.
365 Constant *Elt = Zero;
366 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
367 for (unsigned j = 0; j != Ratio; ++j) {
368 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
369 if (!Src) return 0; // Reject constantexpr elements.
370
371 // Zero extend the element to the right size.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000372 Src = ConstantExpr::getZExt(Src, Elt->getType());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000373
374 // Shift it to the right place, depending on endianness.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000375 Src = ConstantExpr::getShl(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000376 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000377 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
378
379 // Mix it in.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000380 Elt = ConstantExpr::getOr(Elt, Src);
Chris Lattner1afab9c2007-12-11 07:29:44 +0000381 }
382 Result.push_back(Elt);
383 }
384 } else {
385 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
386 unsigned Ratio = NumDstElt/NumSrcElt;
387 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
388
389 // Loop over each source value, expanding into multiple results.
390 for (unsigned i = 0; i != NumSrcElt; ++i) {
391 Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
392 if (!Src) return 0; // Reject constantexpr elements.
393
394 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
395 for (unsigned j = 0; j != Ratio; ++j) {
396 // Shift the piece of the value into the right place, depending on
397 // endianness.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000398 Constant *Elt = ConstantExpr::getLShr(Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000399 ConstantInt::get(Src->getType(), ShiftAmt));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000400 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
401
402 // Truncate and remember this piece.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000403 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner1afab9c2007-12-11 07:29:44 +0000404 }
405 }
406 }
407
Owen Andersonaf7ec972009-07-28 21:19:26 +0000408 return ConstantVector::get(Result.data(), Result.size());
Chris Lattner1afab9c2007-12-11 07:29:44 +0000409 }
410 }
411
412 return 0;
413}
414
Chris Lattner03dd25c2007-01-31 00:51:48 +0000415
416//===----------------------------------------------------------------------===//
417// Constant Folding public APIs
418//===----------------------------------------------------------------------===//
419
420
Chris Lattner55207322007-01-30 23:45:45 +0000421/// ConstantFoldInstruction - Attempt to constant fold the specified
422/// instruction. If successful, the constant result is returned, if not, null
423/// is returned. Note that this function can only fail when attempting to fold
424/// instructions like loads and stores, which have no constant expression form.
425///
Owen Andersone922c022009-07-22 00:24:57 +0000426Constant *llvm::ConstantFoldInstruction(Instruction *I, LLVMContext &Context,
Owen Anderson50895512009-07-06 18:42:36 +0000427 const TargetData *TD) {
Chris Lattner55207322007-01-30 23:45:45 +0000428 if (PHINode *PN = dyn_cast<PHINode>(I)) {
429 if (PN->getNumIncomingValues() == 0)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000430 return UndefValue::get(PN->getType());
John Criswellbd9d3702005-10-27 16:00:10 +0000431
Chris Lattner55207322007-01-30 23:45:45 +0000432 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
433 if (Result == 0) return 0;
434
435 // Handle PHI nodes specially here...
436 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
437 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
438 return 0; // Not all the same incoming constants...
439
440 // If we reach here, all incoming values are the same constant.
441 return Result;
442 }
443
444 // Scan the operand list, checking to see if they are all constants, if so,
445 // hand off to ConstantFoldInstOperands.
446 SmallVector<Constant*, 8> Ops;
Gabor Greifde2d74b2008-05-22 06:43:33 +0000447 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
448 if (Constant *Op = dyn_cast<Constant>(*i))
Chris Lattner55207322007-01-30 23:45:45 +0000449 Ops.push_back(Op);
450 else
451 return 0; // All operands not constant!
452
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000453 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
454 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000455 Ops.data(), Ops.size(),
456 Context, TD);
Chris Lattner58665d42009-09-16 00:08:07 +0000457
Chris Lattner878e4942009-10-22 06:25:11 +0000458 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
459 return ConstantFoldLoadInst(LI, TD);
460
Chris Lattner58665d42009-09-16 00:08:07 +0000461 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
462 Ops.data(), Ops.size(), Context, TD);
Chris Lattner55207322007-01-30 23:45:45 +0000463}
464
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000465/// ConstantFoldConstantExpression - Attempt to fold the constant expression
466/// using the specified TargetData. If successful, the constant result is
467/// result is returned, if not, null is returned.
468Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
Owen Andersone922c022009-07-22 00:24:57 +0000469 LLVMContext &Context,
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000470 const TargetData *TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000471 SmallVector<Constant*, 8> Ops;
472 for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
473 Ops.push_back(cast<Constant>(*i));
474
475 if (CE->isCompare())
476 return ConstantFoldCompareInstOperands(CE->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +0000477 Ops.data(), Ops.size(),
478 Context, TD);
Chris Lattner58665d42009-09-16 00:08:07 +0000479 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
480 Ops.data(), Ops.size(), Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000481}
482
Chris Lattner55207322007-01-30 23:45:45 +0000483/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
484/// specified opcode and operands. If successful, the constant result is
485/// returned, if not, null is returned. Note that this function can fail when
486/// attempting to fold instructions like loads and stores, which have no
487/// constant expression form.
488///
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000489Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
490 Constant* const* Ops, unsigned NumOps,
Owen Andersone922c022009-07-22 00:24:57 +0000491 LLVMContext &Context,
Chris Lattner55207322007-01-30 23:45:45 +0000492 const TargetData *TD) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000493 // Handle easy binops first.
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000494 if (Instruction::isBinaryOp(Opcode)) {
Chris Lattner03dd25c2007-01-31 00:51:48 +0000495 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
Owen Anderson50895512009-07-06 18:42:36 +0000496 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD,
497 Context))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000498 return C;
499
Owen Andersonbaf3c402009-07-29 18:55:55 +0000500 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000501 }
Chris Lattner55207322007-01-30 23:45:45 +0000502
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000503 switch (Opcode) {
Chris Lattner55207322007-01-30 23:45:45 +0000504 default: return 0;
505 case Instruction::Call:
506 if (Function *F = dyn_cast<Function>(Ops[0]))
507 if (canConstantFoldCallTo(F))
Chris Lattnerad58eb32007-01-31 18:04:55 +0000508 return ConstantFoldCall(F, Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000509 return 0;
510 case Instruction::ICmp:
511 case Instruction::FCmp:
Torok Edwinc23197a2009-07-14 16:55:14 +0000512 llvm_unreachable("This function is invalid for compares: no predicate specified");
Chris Lattner001f7532007-08-11 23:49:01 +0000513 case Instruction::PtrToInt:
514 // If the input is a inttoptr, eliminate the pair. This requires knowing
515 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
516 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
517 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
518 Constant *Input = CE->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +0000519 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000520 if (TD->getPointerSizeInBits() < InWidth) {
521 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +0000522 ConstantInt::get(Context, APInt::getLowBitsSet(InWidth,
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000523 TD->getPointerSizeInBits()));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000524 Input = ConstantExpr::getAnd(Input, Mask);
Nick Lewycky04aa2c32008-10-24 06:14:27 +0000525 }
Chris Lattner001f7532007-08-11 23:49:01 +0000526 // Do a zext or trunc to get to the dest size.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000527 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner001f7532007-08-11 23:49:01 +0000528 }
529 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000530 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner001f7532007-08-11 23:49:01 +0000531 case Instruction::IntToPtr:
Duncan Sands81b06be2008-08-13 20:20:35 +0000532 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
533 // the int size is >= the ptr size. This requires knowing the width of a
534 // pointer, so it can't be done in ConstantExpr::getCast.
535 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000536 if (TD &&
Duncan Sands81b06be2008-08-13 20:20:35 +0000537 TD->getPointerSizeInBits() <=
Dan Gohman6de29f82009-06-15 22:12:54 +0000538 CE->getType()->getScalarSizeInBits()) {
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000539 if (CE->getOpcode() == Instruction::PtrToInt) {
540 Constant *Input = CE->getOperand(0);
Owen Anderson50895512009-07-06 18:42:36 +0000541 Constant *C = FoldBitCast(Input, DestTy, *TD, Context);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000542 return C ? C : ConstantExpr::getBitCast(Input, DestTy);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000543 }
544 // If there's a constant offset added to the integer value before
545 // it is casted back to a pointer, see if the expression can be
546 // converted into a GEP.
547 if (CE->getOpcode() == Instruction::Add)
548 if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
549 if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
550 if (R->getOpcode() == Instruction::PtrToInt)
551 if (GlobalVariable *GV =
552 dyn_cast<GlobalVariable>(R->getOperand(0))) {
553 const PointerType *GVTy = cast<PointerType>(GV->getType());
554 if (const ArrayType *AT =
555 dyn_cast<ArrayType>(GVTy->getElementType())) {
556 const Type *ElTy = AT->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000557 uint64_t AllocSize = TD->getTypeAllocSize(ElTy);
558 APInt PSA(L->getValue().getBitWidth(), AllocSize);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000559 if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
560 L->getValue().urem(PSA) == 0) {
561 APInt ElemIdx = L->getValue().udiv(PSA);
562 if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
563 AT->getNumElements()))) {
564 Constant *Index[] = {
Owen Andersona7235ea2009-07-31 20:28:14 +0000565 Constant::getNullValue(CE->getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +0000566 ConstantInt::get(Context, ElemIdx)
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000567 };
Owen Anderson50895512009-07-06 18:42:36 +0000568 return
Owen Andersonbaf3c402009-07-29 18:55:55 +0000569 ConstantExpr::getGetElementPtr(GV, &Index[0], 2);
Dan Gohman9a38e3e2009-05-07 19:46:24 +0000570 }
571 }
572 }
573 }
Duncan Sands81b06be2008-08-13 20:20:35 +0000574 }
575 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000576 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000577 case Instruction::Trunc:
578 case Instruction::ZExt:
579 case Instruction::SExt:
580 case Instruction::FPTrunc:
581 case Instruction::FPExt:
582 case Instruction::UIToFP:
583 case Instruction::SIToFP:
584 case Instruction::FPToUI:
585 case Instruction::FPToSI:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000586 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000587 case Instruction::BitCast:
Chris Lattner1afab9c2007-12-11 07:29:44 +0000588 if (TD)
Owen Anderson50895512009-07-06 18:42:36 +0000589 if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD, Context))
Chris Lattner1afab9c2007-12-11 07:29:44 +0000590 return C;
Owen Andersonbaf3c402009-07-29 18:55:55 +0000591 return ConstantExpr::getBitCast(Ops[0], DestTy);
Chris Lattner55207322007-01-30 23:45:45 +0000592 case Instruction::Select:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000593 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000594 case Instruction::ExtractElement:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000595 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner55207322007-01-30 23:45:45 +0000596 case Instruction::InsertElement:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000597 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000598 case Instruction::ShuffleVector:
Owen Andersonbaf3c402009-07-29 18:55:55 +0000599 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattner55207322007-01-30 23:45:45 +0000600 case Instruction::GetElementPtr:
Owen Anderson50895512009-07-06 18:42:36 +0000601 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, Context, TD))
Chris Lattner03dd25c2007-01-31 00:51:48 +0000602 return C;
603
Owen Andersonbaf3c402009-07-29 18:55:55 +0000604 return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000605 }
606}
607
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000608/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
609/// instruction (icmp/fcmp) with the specified operands. If it fails, it
610/// returns a constant expression of the specified operands.
611///
612Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
613 Constant*const * Ops,
614 unsigned NumOps,
Owen Andersone922c022009-07-22 00:24:57 +0000615 LLVMContext &Context,
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000616 const TargetData *TD) {
617 // fold: icmp (inttoptr x), null -> icmp x, 0
618 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000619 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000620 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
621 //
622 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
623 // around to know if bit truncation is happening.
624 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
625 if (TD && Ops[1]->isNullValue()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000626 const Type *IntPtrTy = TD->getIntPtrType(Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000627 if (CE0->getOpcode() == Instruction::IntToPtr) {
628 // Convert the integer value to the right size to ensure we get the
629 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000630 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000631 IntPtrTy, false);
Owen Andersona7235ea2009-07-31 20:28:14 +0000632 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Owen Anderson50895512009-07-06 18:42:36 +0000633 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
634 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000635 }
636
637 // Only do this transformation if the int is intptrty in size, otherwise
638 // there is a truncation or extension that we aren't modeling.
639 if (CE0->getOpcode() == Instruction::PtrToInt &&
640 CE0->getType() == IntPtrTy) {
641 Constant *C = CE0->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +0000642 Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000643 // FIXME!
Owen Anderson50895512009-07-06 18:42:36 +0000644 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
645 Context, TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000646 }
647 }
648
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000649 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
650 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000651 const Type *IntPtrTy = TD->getIntPtrType(Context);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000652
653 if (CE0->getOpcode() == Instruction::IntToPtr) {
654 // Convert the integer value to the right size to ensure we get the
655 // proper extension or truncation.
Owen Andersonbaf3c402009-07-29 18:55:55 +0000656 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000657 IntPtrTy, false);
Owen Andersonbaf3c402009-07-29 18:55:55 +0000658 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000659 IntPtrTy, false);
660 Constant *NewOps[] = { C0, C1 };
Owen Anderson50895512009-07-06 18:42:36 +0000661 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
662 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000663 }
664
665 // Only do this transformation if the int is intptrty in size, otherwise
666 // there is a truncation or extension that we aren't modeling.
667 if ((CE0->getOpcode() == Instruction::PtrToInt &&
668 CE0->getType() == IntPtrTy &&
669 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
670 Constant *NewOps[] = {
671 CE0->getOperand(0), CE1->getOperand(0)
672 };
Owen Anderson50895512009-07-06 18:42:36 +0000673 return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
674 Context, TD);
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +0000675 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000676 }
677 }
678 }
Owen Andersonbaf3c402009-07-29 18:55:55 +0000679 return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000680}
681
682
Chris Lattner55207322007-01-30 23:45:45 +0000683/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
684/// getelementptr constantexpr, return the constant value being addressed by the
685/// constant expression, or null if something is funny and we can't decide.
686Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmanc6f69e92009-10-05 16:36:26 +0000687 ConstantExpr *CE) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000688 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner55207322007-01-30 23:45:45 +0000689 return 0; // Do not allow stepping over the value!
690
691 // Loop over all of the operands, tracking down which value we are
692 // addressing...
693 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
694 for (++I; I != E; ++I)
695 if (const StructType *STy = dyn_cast<StructType>(*I)) {
696 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
697 assert(CU->getZExtValue() < STy->getNumElements() &&
698 "Struct index out of range!");
699 unsigned El = (unsigned)CU->getZExtValue();
700 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
701 C = CS->getOperand(El);
702 } else if (isa<ConstantAggregateZero>(C)) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000703 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000704 } else if (isa<UndefValue>(C)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000705 C = UndefValue::get(STy->getElementType(El));
Chris Lattner55207322007-01-30 23:45:45 +0000706 } else {
707 return 0;
708 }
709 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
710 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
711 if (CI->getZExtValue() >= ATy->getNumElements())
712 return 0;
713 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
714 C = CA->getOperand(CI->getZExtValue());
715 else if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +0000716 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000717 else if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000718 C = UndefValue::get(ATy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000719 else
720 return 0;
Chris Lattner62d327e2009-10-22 06:38:35 +0000721 } else if (const VectorType *VTy = dyn_cast<VectorType>(*I)) {
722 if (CI->getZExtValue() >= VTy->getNumElements())
Chris Lattner55207322007-01-30 23:45:45 +0000723 return 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000724 if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
Chris Lattner55207322007-01-30 23:45:45 +0000725 C = CP->getOperand(CI->getZExtValue());
726 else if (isa<ConstantAggregateZero>(C))
Chris Lattner62d327e2009-10-22 06:38:35 +0000727 C = Constant::getNullValue(VTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000728 else if (isa<UndefValue>(C))
Chris Lattner62d327e2009-10-22 06:38:35 +0000729 C = UndefValue::get(VTy->getElementType());
Chris Lattner55207322007-01-30 23:45:45 +0000730 else
731 return 0;
732 } else {
733 return 0;
734 }
735 } else {
736 return 0;
737 }
738 return C;
739}
740
741
742//===----------------------------------------------------------------------===//
743// Constant Folding for Calls
744//
John Criswellbd9d3702005-10-27 16:00:10 +0000745
746/// canConstantFoldCallTo - Return true if its even possible to fold a call to
747/// the specified function.
748bool
Dan Gohmanfa9b80e2008-01-31 01:05:10 +0000749llvm::canConstantFoldCallTo(const Function *F) {
John Criswellbd9d3702005-10-27 16:00:10 +0000750 switch (F->getIntrinsicID()) {
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000751 case Intrinsic::sqrt:
752 case Intrinsic::powi:
Reid Spencere9391fd2007-04-01 07:35:23 +0000753 case Intrinsic::bswap:
754 case Intrinsic::ctpop:
755 case Intrinsic::ctlz:
756 case Intrinsic::cttz:
Chris Lattnere65cd402009-10-05 05:26:04 +0000757 case Intrinsic::uadd_with_overflow:
758 case Intrinsic::usub_with_overflow:
Evan Phoenix1614e502009-10-05 22:53:52 +0000759 case Intrinsic::sadd_with_overflow:
760 case Intrinsic::ssub_with_overflow:
John Criswellbd9d3702005-10-27 16:00:10 +0000761 return true;
Chris Lattner68a06032009-10-05 05:00:35 +0000762 default:
763 return false;
764 case 0: break;
John Criswellbd9d3702005-10-27 16:00:10 +0000765 }
766
Chris Lattner6f532a92009-04-03 00:02:39 +0000767 if (!F->hasName()) return false;
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000768 StringRef Name = F->getName();
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000769
770 // In these cases, the check of the length is required. We don't want to
771 // return true for a name like "cos\0blah" which strcmp would return equal to
772 // "cos", but has length 8.
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000773 switch (Name[0]) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000774 default: return false;
775 case 'a':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000776 return Name == "acos" || Name == "asin" ||
777 Name == "atan" || Name == "atan2";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000778 case 'c':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000779 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000780 case 'e':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000781 return Name == "exp";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000782 case 'f':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000783 return Name == "fabs" || Name == "fmod" || Name == "floor";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000784 case 'l':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000785 return Name == "log" || Name == "log10";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000786 case 'p':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000787 return Name == "pow";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000788 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000789 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
790 Name == "sinf" || Name == "sqrtf";
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000791 case 't':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000792 return Name == "tan" || Name == "tanh";
John Criswellbd9d3702005-10-27 16:00:10 +0000793 }
794}
795
Chris Lattner72d88ae2007-01-30 23:15:43 +0000796static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
Owen Andersone922c022009-07-22 00:24:57 +0000797 const Type *Ty, LLVMContext &Context) {
John Criswellbd9d3702005-10-27 16:00:10 +0000798 errno = 0;
799 V = NativeFP(V);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000800 if (errno != 0) {
801 errno = 0;
802 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000803 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000804
Chris Lattnerd0806a12009-10-05 05:06:24 +0000805 if (Ty->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000806 return ConstantFP::get(Context, APFloat((float)V));
Chris Lattnerd0806a12009-10-05 05:06:24 +0000807 if (Ty->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000808 return ConstantFP::get(Context, APFloat(V));
Torok Edwinc23197a2009-07-14 16:55:14 +0000809 llvm_unreachable("Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000810 return 0; // dummy return to suppress warning
John Criswellbd9d3702005-10-27 16:00:10 +0000811}
812
Dan Gohman38415242007-07-16 15:26:22 +0000813static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
814 double V, double W,
Owen Anderson50895512009-07-06 18:42:36 +0000815 const Type *Ty,
Owen Andersone922c022009-07-22 00:24:57 +0000816 LLVMContext &Context) {
Dan Gohman38415242007-07-16 15:26:22 +0000817 errno = 0;
818 V = NativeFP(V, W);
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000819 if (errno != 0) {
820 errno = 0;
821 return 0;
Dale Johannesen43421b32007-09-06 18:13:44 +0000822 }
Chris Lattnerf19f58a2008-03-30 18:02:00 +0000823
Chris Lattnerd0806a12009-10-05 05:06:24 +0000824 if (Ty->isFloatTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000825 return ConstantFP::get(Context, APFloat((float)V));
Chris Lattnerd0806a12009-10-05 05:06:24 +0000826 if (Ty->isDoubleTy())
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000827 return ConstantFP::get(Context, APFloat(V));
Torok Edwinc23197a2009-07-14 16:55:14 +0000828 llvm_unreachable("Can only constant fold float/double");
Gabor Greif33e456d2008-05-21 14:07:30 +0000829 return 0; // dummy return to suppress warning
Dan Gohman38415242007-07-16 15:26:22 +0000830}
831
John Criswellbd9d3702005-10-27 16:00:10 +0000832/// ConstantFoldCall - Attempt to constant fold a call to the specified function
833/// with the specified arguments, returning null if unsuccessful.
834Constant *
Chris Lattnerf286f6f2007-12-10 22:53:04 +0000835llvm::ConstantFoldCall(Function *F,
Chris Lattner68a06032009-10-05 05:00:35 +0000836 Constant *const *Operands, unsigned NumOperands) {
Chris Lattner6f532a92009-04-03 00:02:39 +0000837 if (!F->hasName()) return 0;
Owen Andersone922c022009-07-22 00:24:57 +0000838 LLVMContext &Context = F->getContext();
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000839 StringRef Name = F->getName();
Chris Lattnere65cd402009-10-05 05:26:04 +0000840
John Criswellbd9d3702005-10-27 16:00:10 +0000841 const Type *Ty = F->getReturnType();
Chris Lattner72d88ae2007-01-30 23:15:43 +0000842 if (NumOperands == 1) {
John Criswellbd9d3702005-10-27 16:00:10 +0000843 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +0000844 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesen43421b32007-09-06 18:13:44 +0000845 return 0;
846 /// Currently APFloat versions of these functions do not exist, so we use
847 /// the host native double versions. Float versions are not called
848 /// directly but for all these it is true (float)(f((double)arg)) ==
849 /// f(arg). Long double not supported yet.
Chris Lattnerd0806a12009-10-05 05:06:24 +0000850 double V = Ty->isFloatTy() ? (double)Op->getValueAPF().convertToFloat() :
Dale Johannesen43421b32007-09-06 18:13:44 +0000851 Op->getValueAPF().convertToDouble();
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000852 switch (Name[0]) {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000853 case 'a':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000854 if (Name == "acos")
Owen Anderson50895512009-07-06 18:42:36 +0000855 return ConstantFoldFP(acos, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000856 else if (Name == "asin")
Owen Anderson50895512009-07-06 18:42:36 +0000857 return ConstantFoldFP(asin, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000858 else if (Name == "atan")
Owen Anderson50895512009-07-06 18:42:36 +0000859 return ConstantFoldFP(atan, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000860 break;
861 case 'c':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000862 if (Name == "ceil")
Owen Anderson50895512009-07-06 18:42:36 +0000863 return ConstantFoldFP(ceil, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000864 else if (Name == "cos")
Owen Anderson50895512009-07-06 18:42:36 +0000865 return ConstantFoldFP(cos, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000866 else if (Name == "cosh")
Owen Anderson50895512009-07-06 18:42:36 +0000867 return ConstantFoldFP(cosh, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000868 else if (Name == "cosf")
Owen Anderson50895512009-07-06 18:42:36 +0000869 return ConstantFoldFP(cos, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000870 break;
871 case 'e':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000872 if (Name == "exp")
Owen Anderson50895512009-07-06 18:42:36 +0000873 return ConstantFoldFP(exp, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000874 break;
875 case 'f':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000876 if (Name == "fabs")
Owen Anderson50895512009-07-06 18:42:36 +0000877 return ConstantFoldFP(fabs, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000878 else if (Name == "floor")
Owen Anderson50895512009-07-06 18:42:36 +0000879 return ConstantFoldFP(floor, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000880 break;
881 case 'l':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000882 if (Name == "log" && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +0000883 return ConstantFoldFP(log, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000884 else if (Name == "log10" && V > 0)
Owen Anderson50895512009-07-06 18:42:36 +0000885 return ConstantFoldFP(log10, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000886 else if (Name == "llvm.sqrt.f32" ||
887 Name == "llvm.sqrt.f64") {
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000888 if (V >= -0.0)
Owen Anderson50895512009-07-06 18:42:36 +0000889 return ConstantFoldFP(sqrt, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000890 else // Undefined
Owen Andersona7235ea2009-07-31 20:28:14 +0000891 return Constant::getNullValue(Ty);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000892 }
893 break;
894 case 's':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000895 if (Name == "sin")
Owen Anderson50895512009-07-06 18:42:36 +0000896 return ConstantFoldFP(sin, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000897 else if (Name == "sinh")
Owen Anderson50895512009-07-06 18:42:36 +0000898 return ConstantFoldFP(sinh, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000899 else if (Name == "sqrt" && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +0000900 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000901 else if (Name == "sqrtf" && V >= 0)
Owen Anderson50895512009-07-06 18:42:36 +0000902 return ConstantFoldFP(sqrt, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000903 else if (Name == "sinf")
Owen Anderson50895512009-07-06 18:42:36 +0000904 return ConstantFoldFP(sin, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000905 break;
906 case 't':
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000907 if (Name == "tan")
Owen Anderson50895512009-07-06 18:42:36 +0000908 return ConstantFoldFP(tan, V, Ty, Context);
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000909 else if (Name == "tanh")
Owen Anderson50895512009-07-06 18:42:36 +0000910 return ConstantFoldFP(tanh, V, Ty, Context);
Chris Lattnerc5f6a1f2007-08-08 06:55:43 +0000911 break;
912 default:
913 break;
John Criswellbd9d3702005-10-27 16:00:10 +0000914 }
Chris Lattner68a06032009-10-05 05:00:35 +0000915 return 0;
916 }
917
918
919 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000920 if (Name.startswith("llvm.bswap"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000921 return ConstantInt::get(Context, Op->getValue().byteSwap());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000922 else if (Name.startswith("llvm.ctpop"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000923 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000924 else if (Name.startswith("llvm.cttz"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000925 return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000926 else if (Name.startswith("llvm.ctlz"))
Owen Andersoneed707b2009-07-24 23:12:02 +0000927 return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
Chris Lattner68a06032009-10-05 05:00:35 +0000928 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +0000929 }
Chris Lattner68a06032009-10-05 05:00:35 +0000930
931 return 0;
932 }
933
934 if (NumOperands == 2) {
John Criswellbd9d3702005-10-27 16:00:10 +0000935 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +0000936 if (!Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesen9ab7fb32007-10-02 17:43:59 +0000937 return 0;
Chris Lattnerd0806a12009-10-05 05:06:24 +0000938 double Op1V = Ty->isFloatTy() ?
939 (double)Op1->getValueAPF().convertToFloat() :
Dale Johannesen43421b32007-09-06 18:13:44 +0000940 Op1->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000941 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattnerd0806a12009-10-05 05:06:24 +0000942 if (Op2->getType() != Op1->getType())
943 return 0;
944
945 double Op2V = Ty->isFloatTy() ?
Dale Johannesen43421b32007-09-06 18:13:44 +0000946 (double)Op2->getValueAPF().convertToFloat():
947 Op2->getValueAPF().convertToDouble();
John Criswellbd9d3702005-10-27 16:00:10 +0000948
Chris Lattner68a06032009-10-05 05:00:35 +0000949 if (Name == "pow")
Owen Anderson50895512009-07-06 18:42:36 +0000950 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty, Context);
Chris Lattner68a06032009-10-05 05:00:35 +0000951 if (Name == "fmod")
Owen Anderson50895512009-07-06 18:42:36 +0000952 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty, Context);
Chris Lattner68a06032009-10-05 05:00:35 +0000953 if (Name == "atan2")
Owen Anderson50895512009-07-06 18:42:36 +0000954 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty, Context);
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000955 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Chris Lattner68a06032009-10-05 05:00:35 +0000956 if (Name == "llvm.powi.f32")
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000957 return ConstantFP::get(Context, APFloat((float)std::pow((float)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +0000958 (int)Op2C->getZExtValue())));
Chris Lattner68a06032009-10-05 05:00:35 +0000959 if (Name == "llvm.powi.f64")
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000960 return ConstantFP::get(Context, APFloat((double)std::pow((double)Op1V,
Chris Lattner02a260a2008-04-20 00:41:09 +0000961 (int)Op2C->getZExtValue())));
John Criswellbd9d3702005-10-27 16:00:10 +0000962 }
Chris Lattner68a06032009-10-05 05:00:35 +0000963 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +0000964 }
Chris Lattnere65cd402009-10-05 05:26:04 +0000965
966
967 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
968 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
969 switch (F->getIntrinsicID()) {
970 default: break;
971 case Intrinsic::uadd_with_overflow: {
972 Constant *Res = ConstantExpr::getAdd(Op1, Op2); // result.
973 Constant *Ops[] = {
974 Res, ConstantExpr::getICmp(CmpInst::ICMP_ULT, Res, Op1) // overflow.
975 };
976 return ConstantStruct::get(F->getContext(), Ops, 2, false);
977 }
978 case Intrinsic::usub_with_overflow: {
979 Constant *Res = ConstantExpr::getSub(Op1, Op2); // result.
980 Constant *Ops[] = {
981 Res, ConstantExpr::getICmp(CmpInst::ICMP_UGT, Res, Op1) // overflow.
982 };
983 return ConstantStruct::get(F->getContext(), Ops, 2, false);
984 }
Evan Phoenix1614e502009-10-05 22:53:52 +0000985 case Intrinsic::sadd_with_overflow: {
986 Constant *Res = ConstantExpr::getAdd(Op1, Op2); // result.
987 Constant *Overflow = ConstantExpr::getSelect(
988 ConstantExpr::getICmp(CmpInst::ICMP_SGT,
989 ConstantInt::get(Op1->getType(), 0), Op1),
990 ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op2),
991 ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op2)); // overflow.
992
993 Constant *Ops[] = { Res, Overflow };
994 return ConstantStruct::get(F->getContext(), Ops, 2, false);
995 }
996 case Intrinsic::ssub_with_overflow: {
997 Constant *Res = ConstantExpr::getSub(Op1, Op2); // result.
998 Constant *Overflow = ConstantExpr::getSelect(
999 ConstantExpr::getICmp(CmpInst::ICMP_SGT,
1000 ConstantInt::get(Op2->getType(), 0), Op2),
1001 ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op1),
1002 ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op1)); // overflow.
1003
1004 Constant *Ops[] = { Res, Overflow };
1005 return ConstantStruct::get(F->getContext(), Ops, 2, false);
1006 }
Chris Lattnere65cd402009-10-05 05:26:04 +00001007 }
1008 }
1009
1010 return 0;
1011 }
1012 return 0;
John Criswellbd9d3702005-10-27 16:00:10 +00001013 }
1014 return 0;
1015}
1016