blob: 24b78ae969af66ee7f6b5a5011459ff29bc0541f [file] [log] [blame]
Reid Spencer81658a82007-02-27 06:23:51 +00001//===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2f7c9632001-06-06 20:29:01 +00009//
Chris Lattner5a945e32004-01-12 21:13:12 +000010// This file implements folding of constants for LLVM. This implements the
Reid Spencer81658a82007-02-27 06:23:51 +000011// (internal) ConstantFold.h interface, which is used by the
Chris Lattner5a945e32004-01-12 21:13:12 +000012// ConstantExpr::get* methods to automatically fold constants when possible.
Chris Lattner2f7c9632001-06-06 20:29:01 +000013//
Chris Lattner1dd054c2004-01-12 22:07:24 +000014// The current constant folding implementation is implemented in two pieces: the
Dan Gohman21c62162009-09-11 00:04:14 +000015// pieces that don't need TargetData, and the pieces that do. This is to avoid
16// a dependence in VMCore on Target.
Chris Lattner1dd054c2004-01-12 22:07:24 +000017//
Chris Lattner2f7c9632001-06-06 20:29:01 +000018//===----------------------------------------------------------------------===//
19
Chris Lattner33e93b82007-02-27 03:05:06 +000020#include "ConstantFold.h"
Chris Lattner6ff6cea2004-01-12 21:02:29 +000021#include "llvm/Constants.h"
Chris Lattnera9eddae2004-02-22 06:25:38 +000022#include "llvm/Instructions.h"
Chris Lattner1f0049c2003-04-17 19:24:18 +000023#include "llvm/DerivedTypes.h"
Chris Lattnerea0789c2004-03-08 06:17:35 +000024#include "llvm/Function.h"
Chris Lattner52fe8692007-09-10 23:42:42 +000025#include "llvm/GlobalAlias.h"
Dan Gohman21c62162009-09-11 00:04:14 +000026#include "llvm/GlobalVariable.h"
Owen Anderson53a52212009-07-13 04:09:18 +000027#include "llvm/LLVMContext.h"
Chris Lattner302116a2007-01-31 04:40:28 +000028#include "llvm/ADT/SmallVector.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000029#include "llvm/Support/Compiler.h"
Torok Edwin56d06592009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Chris Lattner057083f2006-10-13 17:22:21 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
32#include "llvm/Support/ManagedStatic.h"
33#include "llvm/Support/MathExtras.h"
Jeff Cohen4e3aede2005-05-03 03:13:01 +000034#include <limits>
Chris Lattner9d9cbcf2003-11-17 19:05:17 +000035using namespace llvm;
Chris Lattner61607ee2001-09-09 21:01:20 +000036
Chris Lattner1dd054c2004-01-12 22:07:24 +000037//===----------------------------------------------------------------------===//
38// ConstantFold*Instruction Implementations
39//===----------------------------------------------------------------------===//
Chris Lattner1dd054c2004-01-12 22:07:24 +000040
Chris Lattner5c6399e2007-12-11 06:07:39 +000041/// BitCastConstantVector - Convert the specified ConstantVector node to the
Reid Spencer09575ba2007-02-15 03:39:18 +000042/// specified vector type. At this point, we know that the elements of the
Dan Gohman06c60b62007-07-16 14:29:03 +000043/// input vector constant are all simple integer or FP values.
Owen Anderson53a52212009-07-13 04:09:18 +000044static Constant *BitCastConstantVector(LLVMContext &Context, ConstantVector *CV,
Owen Anderson0d2de8c2009-06-20 00:24:58 +000045 const VectorType *DstTy) {
Chris Lattner5c6399e2007-12-11 06:07:39 +000046 // If this cast changes element count then we can't handle it here:
47 // doing so requires endianness information. This should be handled by
48 // Analysis/ConstantFolding.cpp
49 unsigned NumElts = DstTy->getNumElements();
50 if (NumElts != CV->getNumOperands())
51 return 0;
Dan Gohman062d3782009-08-29 23:35:16 +000052
Chris Lattner5c6399e2007-12-11 06:07:39 +000053 // Check to verify that all elements of the input are simple.
54 for (unsigned i = 0; i != NumElts; ++i) {
55 if (!isa<ConstantInt>(CV->getOperand(i)) &&
56 !isa<ConstantFP>(CV->getOperand(i)))
57 return 0;
Chris Lattner6b3f4752006-04-02 01:38:28 +000058 }
Chris Lattner5c6399e2007-12-11 06:07:39 +000059
60 // Bitcast each element now.
61 std::vector<Constant*> Result;
62 const Type *DstEltTy = DstTy->getElementType();
63 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson487375e2009-07-29 18:55:55 +000064 Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i),
Owen Anderson53a52212009-07-13 04:09:18 +000065 DstEltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +000066 return ConstantVector::get(Result);
Chris Lattner6b3f4752006-04-02 01:38:28 +000067}
68
Reid Spencer6c38f0b2006-11-27 01:05:10 +000069/// This function determines which opcode to use to fold two constant cast
70/// expressions together. It uses CastInst::isEliminableCastPair to determine
71/// the opcode. Consequently its just a wrapper around that function.
Reid Spencer05d55b32007-08-05 19:27:01 +000072/// @brief Determine if it is valid to fold a cast of a cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +000073static unsigned
74foldConstantCastPair(
75 unsigned opc, ///< opcode of the second cast constant expression
Nick Lewyckye0332982009-09-20 01:35:59 +000076 ConstantExpr *Op, ///< the first cast constant expression
Reid Spencer6c38f0b2006-11-27 01:05:10 +000077 const Type *DstTy ///< desintation type of the first cast
78) {
79 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
80 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
81 assert(CastInst::isCast(opc) && "Invalid cast opcode");
Dan Gohman062d3782009-08-29 23:35:16 +000082
Reid Spencer6c38f0b2006-11-27 01:05:10 +000083 // The the types and opcodes for the two Cast constant expressions
84 const Type *SrcTy = Op->getOperand(0)->getType();
85 const Type *MidTy = Op->getType();
86 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
87 Instruction::CastOps secondOp = Instruction::CastOps(opc);
Chris Lattner6b3f4752006-04-02 01:38:28 +000088
Reid Spencer6c38f0b2006-11-27 01:05:10 +000089 // Let CastInst::isEliminableCastPair do the heavy lifting.
90 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
Owen Anderson55f1c092009-08-13 21:58:54 +000091 Type::getInt64Ty(DstTy->getContext()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +000092}
93
Owen Anderson53a52212009-07-13 04:09:18 +000094static Constant *FoldBitCast(LLVMContext &Context,
95 Constant *V, const Type *DestTy) {
Chris Lattnere8ea0372007-12-11 05:55:02 +000096 const Type *SrcTy = V->getType();
97 if (SrcTy == DestTy)
98 return V; // no-op cast
Dan Gohman062d3782009-08-29 23:35:16 +000099
Chris Lattnere8ea0372007-12-11 05:55:02 +0000100 // Check to see if we are casting a pointer to an aggregate to a pointer to
101 // the first element. If so, return the appropriate GEP instruction.
102 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000103 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy))
104 if (PTy->getAddressSpace() == DPTy->getAddressSpace()) {
105 SmallVector<Value*, 8> IdxList;
Owen Anderson55f1c092009-08-13 21:58:54 +0000106 Value *Zero = Constant::getNullValue(Type::getInt32Ty(Context));
Dan Gohman76733742009-08-12 00:32:55 +0000107 IdxList.push_back(Zero);
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000108 const Type *ElTy = PTy->getElementType();
109 while (ElTy != DPTy->getElementType()) {
110 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
111 if (STy->getNumElements() == 0) break;
112 ElTy = STy->getElementType(0);
Dan Gohman76733742009-08-12 00:32:55 +0000113 IdxList.push_back(Zero);
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000114 } else if (const SequentialType *STy =
115 dyn_cast<SequentialType>(ElTy)) {
116 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
117 ElTy = STy->getElementType();
Dan Gohman76733742009-08-12 00:32:55 +0000118 IdxList.push_back(Zero);
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000119 } else {
120 break;
121 }
Chris Lattnere8ea0372007-12-11 05:55:02 +0000122 }
Dan Gohman062d3782009-08-29 23:35:16 +0000123
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000124 if (ElTy == DPTy->getElementType())
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000125 // This GEP is inbounds because all indices are zero.
126 return ConstantExpr::getInBoundsGetElementPtr(V, &IdxList[0],
127 IdxList.size());
Chris Lattnere8ea0372007-12-11 05:55:02 +0000128 }
Dan Gohman062d3782009-08-29 23:35:16 +0000129
Chris Lattnere8ea0372007-12-11 05:55:02 +0000130 // Handle casts from one vector constant to another. We know that the src
131 // and dest type have the same size (otherwise its an illegal cast).
132 if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
133 if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
134 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
135 "Not cast between same sized vectors!");
Devang Pateld26344d2008-11-03 23:20:04 +0000136 SrcTy = NULL;
Chris Lattnere8ea0372007-12-11 05:55:02 +0000137 // First, check for null. Undef is already handled.
138 if (isa<ConstantAggregateZero>(V))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000139 return Constant::getNullValue(DestTy);
Dan Gohman062d3782009-08-29 23:35:16 +0000140
Chris Lattner5c6399e2007-12-11 06:07:39 +0000141 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
Owen Anderson53a52212009-07-13 04:09:18 +0000142 return BitCastConstantVector(Context, CV, DestPTy);
Chris Lattnere8ea0372007-12-11 05:55:02 +0000143 }
Chris Lattner1baace02008-10-16 05:26:51 +0000144
145 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
146 // This allows for other simplifications (although some of them
147 // can only be handled by Analysis/ConstantFolding.cpp).
148 if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000149 return ConstantExpr::getBitCast(
Owen Anderson4aa32952009-07-28 21:19:26 +0000150 ConstantVector::get(&V, 1), DestPTy);
Chris Lattnere8ea0372007-12-11 05:55:02 +0000151 }
Dan Gohman062d3782009-08-29 23:35:16 +0000152
Chris Lattnere8ea0372007-12-11 05:55:02 +0000153 // Finally, implement bitcast folding now. The code below doesn't handle
154 // bitcast right.
155 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
Owen Andersonb292b8c2009-07-30 23:03:37 +0000156 return ConstantPointerNull::get(cast<PointerType>(DestTy));
Dan Gohman062d3782009-08-29 23:35:16 +0000157
Chris Lattnere8ea0372007-12-11 05:55:02 +0000158 // Handle integral constant input.
Nick Lewyckye0332982009-09-20 01:35:59 +0000159 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattnere8ea0372007-12-11 05:55:02 +0000160 if (DestTy->isInteger())
161 // Integral -> Integral. This is a no-op because the bit widths must
162 // be the same. Consequently, we just fold to V.
163 return V;
Duncan Sands1ea11732009-02-04 10:17:14 +0000164
165 if (DestTy->isFloatingPoint())
Owen Anderson69c464d2009-07-27 20:59:43 +0000166 return ConstantFP::get(Context, APFloat(CI->getValue(),
Owen Anderson55f1c092009-08-13 21:58:54 +0000167 DestTy != Type::getPPC_FP128Ty(Context)));
Duncan Sands1ea11732009-02-04 10:17:14 +0000168
Chris Lattnere8ea0372007-12-11 05:55:02 +0000169 // Otherwise, can't fold this (vector?)
170 return 0;
171 }
Duncan Sandse7d54792009-02-04 11:17:06 +0000172
Chris Lattnere8ea0372007-12-11 05:55:02 +0000173 // Handle ConstantFP input.
Nick Lewyckye0332982009-09-20 01:35:59 +0000174 if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
Chris Lattnere8ea0372007-12-11 05:55:02 +0000175 // FP -> Integral.
Owen Andersonedb4a702009-07-24 23:12:02 +0000176 return ConstantInt::get(Context, FP->getValueAPF().bitcastToAPInt());
Duncan Sandse7d54792009-02-04 11:17:06 +0000177
Chris Lattnere8ea0372007-12-11 05:55:02 +0000178 return 0;
179}
180
181
Chris Lattnerf67d2972009-10-17 21:53:27 +0000182/// ExtractConstantBytes - V is an integer constant which only has a subset of
183/// its bytes used. The bytes used are indicated by ByteStart (which is the
184/// first byte used, counting from the least significant byte) and ByteSize,
185/// which is the number of bytes used.
186///
187/// This function analyzes the specified constant to see if the specified byte
188/// range can be returned as a simplified constant. If so, the constant is
189/// returned, otherwise null is returned.
190///
191static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
192 unsigned ByteSize) {
193 assert(isa<IntegerType>(C->getType()) &&
194 (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
195 "Non-byte sized integer input");
196 unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
197 assert(ByteSize && "Must be accessing some piece");
198 assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
199 assert(ByteSize != CSize && "Should not extract everything");
200
201 // Constant Integers are simple.
202 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
203 APInt V = CI->getValue();
204 if (ByteStart)
205 V = V.lshr(ByteStart*8);
206 V.trunc(ByteSize*8);
207 return ConstantInt::get(CI->getContext(), V);
208 }
209
210 // In the input is a constant expr, we might be able to recursively simplify.
211 // If not, we definitely can't do anything.
212 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
213 if (CE == 0) return 0;
214
215 switch (CE->getOpcode()) {
216 default: return 0;
217 case Instruction::Or: {
Chris Lattnera91a5632009-10-28 05:14:34 +0000218 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000219 if (RHS == 0)
220 return 0;
221
222 // X | -1 -> -1.
223 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
224 if (RHSC->isAllOnesValue())
225 return RHSC;
226
Chris Lattnera91a5632009-10-28 05:14:34 +0000227 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000228 if (LHS == 0)
229 return 0;
230 return ConstantExpr::getOr(LHS, RHS);
231 }
232 case Instruction::And: {
Chris Lattnera91a5632009-10-28 05:14:34 +0000233 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000234 if (RHS == 0)
235 return 0;
236
237 // X & 0 -> 0.
238 if (RHS->isNullValue())
239 return RHS;
240
Chris Lattnera91a5632009-10-28 05:14:34 +0000241 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000242 if (LHS == 0)
243 return 0;
244 return ConstantExpr::getAnd(LHS, RHS);
245 }
246 case Instruction::LShr: {
247 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
248 if (Amt == 0)
249 return 0;
250 unsigned ShAmt = Amt->getZExtValue();
251 // Cannot analyze non-byte shifts.
252 if ((ShAmt & 7) != 0)
253 return 0;
254 ShAmt >>= 3;
255
256 // If the extract is known to be all zeros, return zero.
257 if (ByteStart >= CSize-ShAmt)
258 return Constant::getNullValue(IntegerType::get(CE->getContext(),
259 ByteSize*8));
260 // If the extract is known to be fully in the input, extract it.
261 if (ByteStart+ByteSize+ShAmt <= CSize)
Chris Lattnera91a5632009-10-28 05:14:34 +0000262 return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000263
264 // TODO: Handle the 'partially zero' case.
265 return 0;
266 }
267
268 case Instruction::Shl: {
269 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
270 if (Amt == 0)
271 return 0;
272 unsigned ShAmt = Amt->getZExtValue();
273 // Cannot analyze non-byte shifts.
274 if ((ShAmt & 7) != 0)
275 return 0;
276 ShAmt >>= 3;
277
278 // If the extract is known to be all zeros, return zero.
279 if (ByteStart+ByteSize <= ShAmt)
280 return Constant::getNullValue(IntegerType::get(CE->getContext(),
281 ByteSize*8));
282 // If the extract is known to be fully in the input, extract it.
283 if (ByteStart >= ShAmt)
Chris Lattnera91a5632009-10-28 05:14:34 +0000284 return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000285
286 // TODO: Handle the 'partially zero' case.
287 return 0;
288 }
289
290 case Instruction::ZExt: {
291 unsigned SrcBitSize =
Chris Lattnera91a5632009-10-28 05:14:34 +0000292 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
Chris Lattnerf67d2972009-10-17 21:53:27 +0000293
294 // If extracting something that is completely zero, return 0.
295 if (ByteStart*8 >= SrcBitSize)
296 return Constant::getNullValue(IntegerType::get(CE->getContext(),
297 ByteSize*8));
298
299 // If exactly extracting the input, return it.
300 if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
Chris Lattnera91a5632009-10-28 05:14:34 +0000301 return CE->getOperand(0);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000302
303 // If extracting something completely in the input, if if the input is a
304 // multiple of 8 bits, recurse.
305 if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
Chris Lattnera91a5632009-10-28 05:14:34 +0000306 return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000307
308 // Otherwise, if extracting a subset of the input, which is not multiple of
309 // 8 bits, do a shift and trunc to get the bits.
310 if ((ByteStart+ByteSize)*8 < SrcBitSize) {
311 assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
Chris Lattnera91a5632009-10-28 05:14:34 +0000312 Constant *Res = CE->getOperand(0);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000313 if (ByteStart)
314 Res = ConstantExpr::getLShr(Res,
315 ConstantInt::get(Res->getType(), ByteStart*8));
316 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
317 ByteSize*8));
318 }
319
320 // TODO: Handle the 'partially zero' case.
321 return 0;
322 }
323 }
324}
325
326
Owen Anderson53a52212009-07-13 04:09:18 +0000327Constant *llvm::ConstantFoldCastInstruction(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +0000328 unsigned opc, Constant *V,
Owen Anderson0d2de8c2009-06-20 00:24:58 +0000329 const Type *DestTy) {
Chris Lattner363485d2007-07-20 22:09:02 +0000330 if (isa<UndefValue>(V)) {
331 // zext(undef) = 0, because the top bits will be zero.
332 // sext(undef) = 0, because the top bits will all be the same.
Chris Lattnerb4c6cc92008-02-19 06:22:12 +0000333 // [us]itofp(undef) = 0, because the result value is bounded.
334 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
335 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
Owen Anderson5a1acd92009-07-31 20:28:14 +0000336 return Constant::getNullValue(DestTy);
Owen Andersonb292b8c2009-07-30 23:03:37 +0000337 return UndefValue::get(DestTy);
Chris Lattner363485d2007-07-20 22:09:02 +0000338 }
Dale Johannesen19db0932007-10-14 01:56:47 +0000339 // No compile-time operations on this type yet.
Chris Lattnerfdd87902009-10-05 05:54:46 +0000340 if (V->getType()->isPPC_FP128Ty() || DestTy->isPPC_FP128Ty())
Dale Johannesen19db0932007-10-14 01:56:47 +0000341 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000342
343 // If the cast operand is a constant expression, there's a few things we can
344 // do to try to simplify it.
Nick Lewyckye0332982009-09-20 01:35:59 +0000345 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000346 if (CE->isCast()) {
Reid Spencer1a063892006-12-04 02:46:44 +0000347 // Try hard to fold cast of cast because they are often eliminable.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000348 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
Owen Anderson487375e2009-07-29 18:55:55 +0000349 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
Chris Lattner1dd054c2004-01-12 22:07:24 +0000350 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
351 // If all of the indexes in the GEP are null values, there is no pointer
352 // adjustment going on. We might as well cast the source pointer.
353 bool isAllNull = true;
354 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
355 if (!CE->getOperand(i)->isNullValue()) {
356 isAllNull = false;
357 break;
358 }
359 if (isAllNull)
Reid Spencer1a063892006-12-04 02:46:44 +0000360 // This is casting one pointer type to another, always BitCast
Owen Anderson487375e2009-07-29 18:55:55 +0000361 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
Chris Lattner1dd054c2004-01-12 22:07:24 +0000362 }
Chris Lattnerfd7bf722004-10-16 23:31:32 +0000363 }
Chris Lattner1dd054c2004-01-12 22:07:24 +0000364
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000365 // If the cast operand is a constant vector, perform the cast by
366 // operating on each element. In the cast of bitcasts, the element
367 // count may be mismatched; don't attempt to handle that here.
Nick Lewyckye0332982009-09-20 01:35:59 +0000368 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000369 if (isa<VectorType>(DestTy) &&
370 cast<VectorType>(DestTy)->getNumElements() ==
371 CV->getType()->getNumElements()) {
372 std::vector<Constant*> res;
373 const VectorType *DestVecTy = cast<VectorType>(DestTy);
374 const Type *DstEltTy = DestVecTy->getElementType();
375 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
Owen Anderson487375e2009-07-29 18:55:55 +0000376 res.push_back(ConstantExpr::getCast(opc,
Owen Anderson0d2de8c2009-06-20 00:24:58 +0000377 CV->getOperand(i), DstEltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +0000378 return ConstantVector::get(DestVecTy, res);
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000379 }
380
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000381 // We actually have to do a cast now. Perform the cast according to the
382 // opcode specified.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000383 switch (opc) {
Chris Lattnerf67d2972009-10-17 21:53:27 +0000384 default:
385 llvm_unreachable("Failed to cast constant expression");
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000386 case Instruction::FPTrunc:
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000387 case Instruction::FPExt:
Nick Lewyckye0332982009-09-20 01:35:59 +0000388 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000389 bool ignored;
Dale Johannesenf4bad972007-09-19 14:22:58 +0000390 APFloat Val = FPC->getValueAPF();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000391 Val.convert(DestTy->isFloatTy() ? APFloat::IEEEsingle :
392 DestTy->isDoubleTy() ? APFloat::IEEEdouble :
393 DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
394 DestTy->isFP128Ty() ? APFloat::IEEEquad :
Dale Johannesenf4bad972007-09-19 14:22:58 +0000395 APFloat::Bogus,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000396 APFloat::rmNearestTiesToEven, &ignored);
Owen Anderson69c464d2009-07-27 20:59:43 +0000397 return ConstantFP::get(Context, Val);
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000398 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000399 return 0; // Can't fold.
400 case Instruction::FPToUI:
Reid Spencer8dabca42006-12-19 07:41:40 +0000401 case Instruction::FPToSI:
Nick Lewyckye0332982009-09-20 01:35:59 +0000402 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
Chris Lattner2b827fd2007-10-15 05:34:10 +0000403 const APFloat &V = FPC->getValueAPF();
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000404 bool ignored;
Dale Johannesenf4bad972007-09-19 14:22:58 +0000405 uint64_t x[2];
Reid Spencer81658a82007-02-27 06:23:51 +0000406 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
Dale Johannesen17663f42007-09-25 23:32:20 +0000407 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000408 APFloat::rmTowardZero, &ignored);
Dale Johannesenf4bad972007-09-19 14:22:58 +0000409 APInt Val(DestBitWidth, 2, x);
Owen Andersonedb4a702009-07-24 23:12:02 +0000410 return ConstantInt::get(Context, Val);
Reid Spencer81658a82007-02-27 06:23:51 +0000411 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000412 return 0; // Can't fold.
413 case Instruction::IntToPtr: //always treated as unsigned
414 if (V->isNullValue()) // Is it an integral null value?
Owen Andersonb292b8c2009-07-30 23:03:37 +0000415 return ConstantPointerNull::get(cast<PointerType>(DestTy));
Reid Spencer8dabca42006-12-19 07:41:40 +0000416 return 0; // Other pointer types cannot be casted
417 case Instruction::PtrToInt: // always treated as unsigned
Dan Gohmancf913832010-01-28 02:15:55 +0000418 // Is it a null pointer value?
419 if (V->isNullValue())
Owen Andersonedb4a702009-07-24 23:12:02 +0000420 return ConstantInt::get(DestTy, 0);
Dan Gohmancf913832010-01-28 02:15:55 +0000421 // If this is a sizeof of an array or vector, pull out a multiplication
422 // by the element size to expose it to subsequent folding.
423 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
424 if (CE->getOpcode() == Instruction::GetElementPtr &&
425 CE->getNumOperands() == 2 &&
426 CE->getOperand(0)->isNullValue())
427 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
428 if (CI->isOne()) {
429 const Type *Ty =
430 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
431 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
432 Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
433 Constant *E = ConstantExpr::getSizeOf(ATy->getElementType());
434 E = ConstantExpr::getCast(CastInst::getCastOpcode(E, false,
435 DestTy, false),
436 E, DestTy);
437 return ConstantExpr::getMul(N, E);
438 }
439 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
440 Constant *N = ConstantInt::get(DestTy, VTy->getNumElements());
441 Constant *E = ConstantExpr::getSizeOf(VTy->getElementType());
442 E = ConstantExpr::getCast(CastInst::getCastOpcode(E, false,
443 DestTy, false),
444 E, DestTy);
445 return ConstantExpr::getMul(N, E);
446 }
447 }
448 // Other pointer types cannot be casted
449 return 0;
Reid Spencer8dabca42006-12-19 07:41:40 +0000450 case Instruction::UIToFP:
Reid Spencer8dabca42006-12-19 07:41:40 +0000451 case Instruction::SIToFP:
Nick Lewyckye0332982009-09-20 01:35:59 +0000452 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Dale Johannesen91506522007-09-30 18:19:03 +0000453 APInt api = CI->getValue();
454 const uint64_t zero[] = {0, 0};
Dale Johannesen91506522007-09-30 18:19:03 +0000455 APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
456 2, zero));
Dan Gohman06c45d52008-02-29 01:42:52 +0000457 (void)apf.convertFromAPInt(api,
458 opc==Instruction::SIToFP,
459 APFloat::rmNearestTiesToEven);
Owen Anderson69c464d2009-07-27 20:59:43 +0000460 return ConstantFP::get(Context, apf);
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000461 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000462 return 0;
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000463 case Instruction::ZExt:
Nick Lewyckye0332982009-09-20 01:35:59 +0000464 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Reid Spencer81658a82007-02-27 06:23:51 +0000465 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
466 APInt Result(CI->getValue());
467 Result.zext(BitWidth);
Owen Andersonedb4a702009-07-24 23:12:02 +0000468 return ConstantInt::get(Context, Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000469 }
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000470 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000471 case Instruction::SExt:
Nick Lewyckye0332982009-09-20 01:35:59 +0000472 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Reid Spencer81658a82007-02-27 06:23:51 +0000473 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
474 APInt Result(CI->getValue());
475 Result.sext(BitWidth);
Owen Andersonedb4a702009-07-24 23:12:02 +0000476 return ConstantInt::get(Context, Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000477 }
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000478 return 0;
Chris Lattnerf67d2972009-10-17 21:53:27 +0000479 case Instruction::Trunc: {
480 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
Nick Lewyckye0332982009-09-20 01:35:59 +0000481 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Reid Spencer81658a82007-02-27 06:23:51 +0000482 APInt Result(CI->getValue());
Chris Lattnerf67d2972009-10-17 21:53:27 +0000483 Result.trunc(DestBitWidth);
Owen Andersonedb4a702009-07-24 23:12:02 +0000484 return ConstantInt::get(Context, Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000485 }
Chris Lattnerf67d2972009-10-17 21:53:27 +0000486
487 // The input must be a constantexpr. See if we can simplify this based on
488 // the bytes we are demanding. Only do this if the source and dest are an
489 // even multiple of a byte.
490 if ((DestBitWidth & 7) == 0 &&
491 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
492 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
493 return Res;
494
Chris Lattner710ebaf2006-12-01 19:22:41 +0000495 return 0;
Chris Lattnerf67d2972009-10-17 21:53:27 +0000496 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000497 case Instruction::BitCast:
Nick Lewyckye0332982009-09-20 01:35:59 +0000498 return FoldBitCast(Context, V, DestTy);
Chris Lattner6b3f4752006-04-02 01:38:28 +0000499 }
Chris Lattner1dd054c2004-01-12 22:07:24 +0000500}
501
Owen Anderson53a52212009-07-13 04:09:18 +0000502Constant *llvm::ConstantFoldSelectInstruction(LLVMContext&,
Nick Lewyckye0332982009-09-20 01:35:59 +0000503 Constant *Cond,
504 Constant *V1, Constant *V2) {
505 if (ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
506 return CB->getZExtValue() ? V1 : V2;
Chris Lattnerfd7bf722004-10-16 23:31:32 +0000507
Nick Lewyckye0332982009-09-20 01:35:59 +0000508 if (isa<UndefValue>(V1)) return V2;
509 if (isa<UndefValue>(V2)) return V1;
510 if (isa<UndefValue>(Cond)) return V1;
511 if (V1 == V2) return V1;
Chris Lattner6ea4b522004-03-12 05:53:32 +0000512 return 0;
513}
514
Owen Anderson53a52212009-07-13 04:09:18 +0000515Constant *llvm::ConstantFoldExtractElementInstruction(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +0000516 Constant *Val,
517 Constant *Idx) {
Chris Lattnere52f29b2006-03-31 18:31:40 +0000518 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
Owen Andersonb292b8c2009-07-30 23:03:37 +0000519 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
Chris Lattnere4f9d7b2006-04-07 04:44:06 +0000520 if (Val->isNullValue()) // ee(zero, x) -> zero
Owen Anderson5a1acd92009-07-31 20:28:14 +0000521 return Constant::getNullValue(
Reid Spencerd84d35b2007-02-15 02:26:10 +0000522 cast<VectorType>(Val->getType())->getElementType());
Dan Gohman062d3782009-08-29 23:35:16 +0000523
Nick Lewyckye0332982009-09-20 01:35:59 +0000524 if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
525 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
Gabor Greiff6caff662008-05-10 08:32:32 +0000526 return CVal->getOperand(CIdx->getZExtValue());
Chris Lattnere52f29b2006-03-31 18:31:40 +0000527 } else if (isa<UndefValue>(Idx)) {
528 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
Gabor Greiff6caff662008-05-10 08:32:32 +0000529 return CVal->getOperand(0);
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000530 }
Chris Lattnere52f29b2006-03-31 18:31:40 +0000531 }
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000532 return 0;
533}
534
Owen Anderson53a52212009-07-13 04:09:18 +0000535Constant *llvm::ConstantFoldInsertElementInstruction(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +0000536 Constant *Val,
537 Constant *Elt,
538 Constant *Idx) {
539 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000540 if (!CIdx) return 0;
Reid Spencer81658a82007-02-27 06:23:51 +0000541 APInt idxVal = CIdx->getValue();
Reid Spencer3054b142006-11-02 08:18:15 +0000542 if (isa<UndefValue>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000543 // Insertion of scalar constant into vector undef
Robert Bocchinoca27f032006-01-17 20:07:22 +0000544 // Optimize away insertion of undef
545 if (isa<UndefValue>(Elt))
Nick Lewyckye0332982009-09-20 01:35:59 +0000546 return Val;
Robert Bocchinoca27f032006-01-17 20:07:22 +0000547 // Otherwise break the aggregate undef into multiple undefs and do
548 // the insertion
549 unsigned numOps =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000550 cast<VectorType>(Val->getType())->getNumElements();
Robert Bocchinoca27f032006-01-17 20:07:22 +0000551 std::vector<Constant*> Ops;
552 Ops.reserve(numOps);
553 for (unsigned i = 0; i < numOps; ++i) {
Nick Lewyckye0332982009-09-20 01:35:59 +0000554 Constant *Op =
Owen Andersonb292b8c2009-07-30 23:03:37 +0000555 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
Nick Lewyckye0332982009-09-20 01:35:59 +0000556 Ops.push_back(Op);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000557 }
Owen Anderson4aa32952009-07-28 21:19:26 +0000558 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000559 }
Reid Spencer3054b142006-11-02 08:18:15 +0000560 if (isa<ConstantAggregateZero>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000561 // Insertion of scalar constant into vector aggregate zero
Robert Bocchinoca27f032006-01-17 20:07:22 +0000562 // Optimize away insertion of zero
563 if (Elt->isNullValue())
Nick Lewyckye0332982009-09-20 01:35:59 +0000564 return Val;
Robert Bocchinoca27f032006-01-17 20:07:22 +0000565 // Otherwise break the aggregate zero into multiple zeros and do
566 // the insertion
567 unsigned numOps =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000568 cast<VectorType>(Val->getType())->getNumElements();
Robert Bocchinoca27f032006-01-17 20:07:22 +0000569 std::vector<Constant*> Ops;
570 Ops.reserve(numOps);
571 for (unsigned i = 0; i < numOps; ++i) {
Nick Lewyckye0332982009-09-20 01:35:59 +0000572 Constant *Op =
Owen Anderson5a1acd92009-07-31 20:28:14 +0000573 (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
Nick Lewyckye0332982009-09-20 01:35:59 +0000574 Ops.push_back(Op);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000575 }
Owen Anderson4aa32952009-07-28 21:19:26 +0000576 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000577 }
Nick Lewyckye0332982009-09-20 01:35:59 +0000578 if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000579 // Insertion of scalar constant into vector constant
Robert Bocchinoca27f032006-01-17 20:07:22 +0000580 std::vector<Constant*> Ops;
581 Ops.reserve(CVal->getNumOperands());
582 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
Nick Lewyckye0332982009-09-20 01:35:59 +0000583 Constant *Op =
Reid Spencer81658a82007-02-27 06:23:51 +0000584 (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
Nick Lewyckye0332982009-09-20 01:35:59 +0000585 Ops.push_back(Op);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000586 }
Owen Anderson4aa32952009-07-28 21:19:26 +0000587 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000588 }
Dan Gohman3db11c22008-06-03 00:15:20 +0000589
Robert Bocchinoca27f032006-01-17 20:07:22 +0000590 return 0;
591}
592
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000593/// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
594/// return the specified element value. Otherwise return null.
Nick Lewyckye0332982009-09-20 01:35:59 +0000595static Constant *GetVectorElement(LLVMContext &Context, Constant *C,
Owen Anderson53a52212009-07-13 04:09:18 +0000596 unsigned EltNo) {
Nick Lewyckye0332982009-09-20 01:35:59 +0000597 if (ConstantVector *CV = dyn_cast<ConstantVector>(C))
Gabor Greiff6caff662008-05-10 08:32:32 +0000598 return CV->getOperand(EltNo);
Dan Gohman062d3782009-08-29 23:35:16 +0000599
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000600 const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
601 if (isa<ConstantAggregateZero>(C))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000602 return Constant::getNullValue(EltTy);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000603 if (isa<UndefValue>(C))
Owen Andersonb292b8c2009-07-30 23:03:37 +0000604 return UndefValue::get(EltTy);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000605 return 0;
606}
607
Owen Anderson53a52212009-07-13 04:09:18 +0000608Constant *llvm::ConstantFoldShuffleVectorInstruction(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +0000609 Constant *V1,
610 Constant *V2,
611 Constant *Mask) {
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000612 // Undefined shuffle mask -> undefined value.
Owen Andersonb292b8c2009-07-30 23:03:37 +0000613 if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
Mon P Wang25f01062008-11-10 04:46:22 +0000614
615 unsigned MaskNumElts = cast<VectorType>(Mask->getType())->getNumElements();
616 unsigned SrcNumElts = cast<VectorType>(V1->getType())->getNumElements();
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000617 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
Mon P Wang25f01062008-11-10 04:46:22 +0000618
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000619 // Loop over the shuffle mask, evaluating each element.
620 SmallVector<Constant*, 32> Result;
Mon P Wang25f01062008-11-10 04:46:22 +0000621 for (unsigned i = 0; i != MaskNumElts; ++i) {
Owen Anderson53a52212009-07-13 04:09:18 +0000622 Constant *InElt = GetVectorElement(Context, Mask, i);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000623 if (InElt == 0) return 0;
Mon P Wang25f01062008-11-10 04:46:22 +0000624
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000625 if (isa<UndefValue>(InElt))
Owen Andersonb292b8c2009-07-30 23:03:37 +0000626 InElt = UndefValue::get(EltTy);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000627 else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
628 unsigned Elt = CI->getZExtValue();
Mon P Wang25f01062008-11-10 04:46:22 +0000629 if (Elt >= SrcNumElts*2)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000630 InElt = UndefValue::get(EltTy);
Mon P Wang25f01062008-11-10 04:46:22 +0000631 else if (Elt >= SrcNumElts)
Owen Anderson53a52212009-07-13 04:09:18 +0000632 InElt = GetVectorElement(Context, V2, Elt - SrcNumElts);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000633 else
Owen Anderson53a52212009-07-13 04:09:18 +0000634 InElt = GetVectorElement(Context, V1, Elt);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000635 if (InElt == 0) return 0;
636 } else {
637 // Unknown value.
638 return 0;
639 }
640 Result.push_back(InElt);
641 }
Mon P Wang25f01062008-11-10 04:46:22 +0000642
Owen Anderson4aa32952009-07-28 21:19:26 +0000643 return ConstantVector::get(&Result[0], Result.size());
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000644}
645
Owen Anderson53a52212009-07-13 04:09:18 +0000646Constant *llvm::ConstantFoldExtractValueInstruction(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +0000647 Constant *Agg,
Dan Gohman3db11c22008-06-03 00:15:20 +0000648 const unsigned *Idxs,
649 unsigned NumIdx) {
650 // Base case: no indices, so return the entire value.
651 if (NumIdx == 0)
Nick Lewyckye0332982009-09-20 01:35:59 +0000652 return Agg;
Dan Gohman3db11c22008-06-03 00:15:20 +0000653
654 if (isa<UndefValue>(Agg)) // ev(undef, x) -> undef
Owen Andersonb292b8c2009-07-30 23:03:37 +0000655 return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
Dan Gohman3db11c22008-06-03 00:15:20 +0000656 Idxs,
657 Idxs + NumIdx));
658
659 if (isa<ConstantAggregateZero>(Agg)) // ev(0, x) -> 0
660 return
Owen Anderson5a1acd92009-07-31 20:28:14 +0000661 Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
Dan Gohman3db11c22008-06-03 00:15:20 +0000662 Idxs,
663 Idxs + NumIdx));
664
665 // Otherwise recurse.
Chris Lattnera91a5632009-10-28 05:14:34 +0000666 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg))
667 return ConstantFoldExtractValueInstruction(Context, CS->getOperand(*Idxs),
668 Idxs+1, NumIdx-1);
669
670 if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg))
671 return ConstantFoldExtractValueInstruction(Context, CA->getOperand(*Idxs),
672 Idxs+1, NumIdx-1);
673 ConstantVector *CV = cast<ConstantVector>(Agg);
674 return ConstantFoldExtractValueInstruction(Context, CV->getOperand(*Idxs),
Dan Gohman3db11c22008-06-03 00:15:20 +0000675 Idxs+1, NumIdx-1);
Dan Gohman12fce772008-05-15 19:50:34 +0000676}
677
Owen Anderson53a52212009-07-13 04:09:18 +0000678Constant *llvm::ConstantFoldInsertValueInstruction(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +0000679 Constant *Agg,
680 Constant *Val,
Dan Gohman3db11c22008-06-03 00:15:20 +0000681 const unsigned *Idxs,
682 unsigned NumIdx) {
683 // Base case: no indices, so replace the entire value.
684 if (NumIdx == 0)
Nick Lewyckye0332982009-09-20 01:35:59 +0000685 return Val;
Dan Gohman3db11c22008-06-03 00:15:20 +0000686
687 if (isa<UndefValue>(Agg)) {
688 // Insertion of constant into aggregate undef
Chris Lattneree8f74f2009-09-15 06:28:12 +0000689 // Optimize away insertion of undef.
Dan Gohman3db11c22008-06-03 00:15:20 +0000690 if (isa<UndefValue>(Val))
Nick Lewyckye0332982009-09-20 01:35:59 +0000691 return Agg;
Chris Lattneree8f74f2009-09-15 06:28:12 +0000692
Dan Gohman3db11c22008-06-03 00:15:20 +0000693 // Otherwise break the aggregate undef into multiple undefs and do
Chris Lattneree8f74f2009-09-15 06:28:12 +0000694 // the insertion.
Dan Gohman3db11c22008-06-03 00:15:20 +0000695 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
696 unsigned numOps;
697 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
698 numOps = AR->getNumElements();
699 else
700 numOps = cast<StructType>(AggTy)->getNumElements();
Chris Lattneree8f74f2009-09-15 06:28:12 +0000701
Dan Gohman3db11c22008-06-03 00:15:20 +0000702 std::vector<Constant*> Ops(numOps);
703 for (unsigned i = 0; i < numOps; ++i) {
704 const Type *MemberTy = AggTy->getTypeAtIndex(i);
Nick Lewyckye0332982009-09-20 01:35:59 +0000705 Constant *Op =
Dan Gohman3db11c22008-06-03 00:15:20 +0000706 (*Idxs == i) ?
Owen Andersonb292b8c2009-07-30 23:03:37 +0000707 ConstantFoldInsertValueInstruction(Context, UndefValue::get(MemberTy),
Dan Gohman3db11c22008-06-03 00:15:20 +0000708 Val, Idxs+1, NumIdx-1) :
Owen Andersonb292b8c2009-07-30 23:03:37 +0000709 UndefValue::get(MemberTy);
Nick Lewyckye0332982009-09-20 01:35:59 +0000710 Ops[i] = Op;
Dan Gohman3db11c22008-06-03 00:15:20 +0000711 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000712
713 if (const StructType* ST = dyn_cast<StructType>(AggTy))
714 return ConstantStruct::get(Context, Ops, ST->isPacked());
715 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
Dan Gohman3db11c22008-06-03 00:15:20 +0000716 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000717
Dan Gohman3db11c22008-06-03 00:15:20 +0000718 if (isa<ConstantAggregateZero>(Agg)) {
719 // Insertion of constant into aggregate zero
Chris Lattneree8f74f2009-09-15 06:28:12 +0000720 // Optimize away insertion of zero.
Dan Gohman3db11c22008-06-03 00:15:20 +0000721 if (Val->isNullValue())
Nick Lewyckye0332982009-09-20 01:35:59 +0000722 return Agg;
Chris Lattneree8f74f2009-09-15 06:28:12 +0000723
Dan Gohman3db11c22008-06-03 00:15:20 +0000724 // Otherwise break the aggregate zero into multiple zeros and do
Chris Lattneree8f74f2009-09-15 06:28:12 +0000725 // the insertion.
Dan Gohman3db11c22008-06-03 00:15:20 +0000726 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
727 unsigned numOps;
728 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
729 numOps = AR->getNumElements();
730 else
731 numOps = cast<StructType>(AggTy)->getNumElements();
Chris Lattneree8f74f2009-09-15 06:28:12 +0000732
Dan Gohman3db11c22008-06-03 00:15:20 +0000733 std::vector<Constant*> Ops(numOps);
734 for (unsigned i = 0; i < numOps; ++i) {
735 const Type *MemberTy = AggTy->getTypeAtIndex(i);
Nick Lewyckye0332982009-09-20 01:35:59 +0000736 Constant *Op =
Dan Gohman3db11c22008-06-03 00:15:20 +0000737 (*Idxs == i) ?
Owen Anderson53a52212009-07-13 04:09:18 +0000738 ConstantFoldInsertValueInstruction(Context,
Owen Anderson5a1acd92009-07-31 20:28:14 +0000739 Constant::getNullValue(MemberTy),
Dan Gohman3db11c22008-06-03 00:15:20 +0000740 Val, Idxs+1, NumIdx-1) :
Owen Anderson5a1acd92009-07-31 20:28:14 +0000741 Constant::getNullValue(MemberTy);
Nick Lewyckye0332982009-09-20 01:35:59 +0000742 Ops[i] = Op;
Dan Gohman3db11c22008-06-03 00:15:20 +0000743 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000744
745 if (const StructType* ST = dyn_cast<StructType>(AggTy))
746 return ConstantStruct::get(Context, Ops, ST->isPacked());
747 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
Dan Gohman3db11c22008-06-03 00:15:20 +0000748 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000749
Dan Gohman3db11c22008-06-03 00:15:20 +0000750 if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
Chris Lattneree8f74f2009-09-15 06:28:12 +0000751 // Insertion of constant into aggregate constant.
Dan Gohman3db11c22008-06-03 00:15:20 +0000752 std::vector<Constant*> Ops(Agg->getNumOperands());
753 for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
Chris Lattnera91a5632009-10-28 05:14:34 +0000754 Constant *Op = cast<Constant>(Agg->getOperand(i));
755 if (*Idxs == i)
756 Op = ConstantFoldInsertValueInstruction(Context, Op,
757 Val, Idxs+1, NumIdx-1);
Nick Lewyckye0332982009-09-20 01:35:59 +0000758 Ops[i] = Op;
Dan Gohman3db11c22008-06-03 00:15:20 +0000759 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000760
761 if (const StructType* ST = dyn_cast<StructType>(Agg->getType()))
762 return ConstantStruct::get(Context, Ops, ST->isPacked());
763 return ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
Dan Gohman3db11c22008-06-03 00:15:20 +0000764 }
765
Dan Gohman12fce772008-05-15 19:50:34 +0000766 return 0;
767}
768
Reid Spencer266e42b2006-12-23 06:05:41 +0000769
Owen Anderson53a52212009-07-13 04:09:18 +0000770Constant *llvm::ConstantFoldBinaryInstruction(LLVMContext &Context,
771 unsigned Opcode,
Nick Lewyckye0332982009-09-20 01:35:59 +0000772 Constant *C1, Constant *C2) {
Dale Johannesene5facd52007-10-16 23:38:29 +0000773 // No compile-time operations on this type yet.
Chris Lattnerfdd87902009-10-05 05:54:46 +0000774 if (C1->getType()->isPPC_FP128Ty())
Dale Johannesene5facd52007-10-16 23:38:29 +0000775 return 0;
776
Chris Lattneree8f74f2009-09-15 06:28:12 +0000777 // Handle UndefValue up front.
Reid Spencer266e42b2006-12-23 06:05:41 +0000778 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
779 switch (Opcode) {
Evan Chengdf1690d2008-03-25 20:08:07 +0000780 case Instruction::Xor:
781 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
782 // Handle undef ^ undef -> 0 special case. This is a common
783 // idiom (misuse).
Owen Anderson5a1acd92009-07-31 20:28:14 +0000784 return Constant::getNullValue(C1->getType());
Evan Chengdf1690d2008-03-25 20:08:07 +0000785 // Fallthrough
Reid Spencer266e42b2006-12-23 06:05:41 +0000786 case Instruction::Add:
787 case Instruction::Sub:
Owen Andersonb292b8c2009-07-30 23:03:37 +0000788 return UndefValue::get(C1->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +0000789 case Instruction::Mul:
790 case Instruction::And:
Owen Anderson5a1acd92009-07-31 20:28:14 +0000791 return Constant::getNullValue(C1->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +0000792 case Instruction::UDiv:
793 case Instruction::SDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +0000794 case Instruction::URem:
795 case Instruction::SRem:
Reid Spencer266e42b2006-12-23 06:05:41 +0000796 if (!isa<UndefValue>(C2)) // undef / X -> 0
Owen Anderson5a1acd92009-07-31 20:28:14 +0000797 return Constant::getNullValue(C1->getType());
Nick Lewyckye0332982009-09-20 01:35:59 +0000798 return C2; // X / undef -> undef
Reid Spencer266e42b2006-12-23 06:05:41 +0000799 case Instruction::Or: // X | undef -> -1
Reid Spencerd84d35b2007-02-15 02:26:10 +0000800 if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000801 return Constant::getAllOnesValue(PTy);
802 return Constant::getAllOnesValue(C1->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +0000803 case Instruction::LShr:
804 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
Nick Lewyckye0332982009-09-20 01:35:59 +0000805 return C1; // undef lshr undef -> undef
Owen Anderson5a1acd92009-07-31 20:28:14 +0000806 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +0000807 // undef lshr X -> 0
808 case Instruction::AShr:
809 if (!isa<UndefValue>(C2))
Nick Lewyckye0332982009-09-20 01:35:59 +0000810 return C1; // undef ashr X --> undef
Reid Spencer266e42b2006-12-23 06:05:41 +0000811 else if (isa<UndefValue>(C1))
Nick Lewyckye0332982009-09-20 01:35:59 +0000812 return C1; // undef ashr undef -> undef
Reid Spencer266e42b2006-12-23 06:05:41 +0000813 else
Nick Lewyckye0332982009-09-20 01:35:59 +0000814 return C1; // X ashr undef --> X
Reid Spencer266e42b2006-12-23 06:05:41 +0000815 case Instruction::Shl:
816 // undef << X -> 0 or X << undef -> 0
Owen Anderson5a1acd92009-07-31 20:28:14 +0000817 return Constant::getNullValue(C1->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +0000818 }
819 }
820
Nick Lewycky6b8320f2009-06-21 01:56:41 +0000821 // Handle simplifications when the RHS is a constant int.
Nick Lewyckye0332982009-09-20 01:35:59 +0000822 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
Chris Lattner334d33c2008-04-19 21:58:19 +0000823 switch (Opcode) {
824 case Instruction::Add:
Nick Lewyckye0332982009-09-20 01:35:59 +0000825 if (CI2->equalsInt(0)) return C1; // X + 0 == X
Chris Lattner334d33c2008-04-19 21:58:19 +0000826 break;
827 case Instruction::Sub:
Nick Lewyckye0332982009-09-20 01:35:59 +0000828 if (CI2->equalsInt(0)) return C1; // X - 0 == X
Chris Lattner334d33c2008-04-19 21:58:19 +0000829 break;
830 case Instruction::Mul:
Nick Lewyckye0332982009-09-20 01:35:59 +0000831 if (CI2->equalsInt(0)) return C2; // X * 0 == 0
Chris Lattner334d33c2008-04-19 21:58:19 +0000832 if (CI2->equalsInt(1))
Nick Lewyckye0332982009-09-20 01:35:59 +0000833 return C1; // X * 1 == X
Chris Lattner334d33c2008-04-19 21:58:19 +0000834 break;
835 case Instruction::UDiv:
836 case Instruction::SDiv:
837 if (CI2->equalsInt(1))
Nick Lewyckye0332982009-09-20 01:35:59 +0000838 return C1; // X / 1 == X
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +0000839 if (CI2->equalsInt(0))
Owen Andersonb292b8c2009-07-30 23:03:37 +0000840 return UndefValue::get(CI2->getType()); // X / 0 == undef
Chris Lattner334d33c2008-04-19 21:58:19 +0000841 break;
842 case Instruction::URem:
843 case Instruction::SRem:
844 if (CI2->equalsInt(1))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000845 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +0000846 if (CI2->equalsInt(0))
Owen Andersonb292b8c2009-07-30 23:03:37 +0000847 return UndefValue::get(CI2->getType()); // X % 0 == undef
Chris Lattner334d33c2008-04-19 21:58:19 +0000848 break;
849 case Instruction::And:
Nick Lewyckye0332982009-09-20 01:35:59 +0000850 if (CI2->isZero()) return C2; // X & 0 == 0
Chris Lattner334d33c2008-04-19 21:58:19 +0000851 if (CI2->isAllOnesValue())
Nick Lewyckye0332982009-09-20 01:35:59 +0000852 return C1; // X & -1 == X
Dan Gohman062d3782009-08-29 23:35:16 +0000853
Nick Lewyckye0332982009-09-20 01:35:59 +0000854 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
Chris Lattnerbc26e1b2008-04-19 22:17:26 +0000855 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
Chris Lattner334d33c2008-04-19 21:58:19 +0000856 if (CE1->getOpcode() == Instruction::ZExt) {
857 unsigned DstWidth = CI2->getType()->getBitWidth();
858 unsigned SrcWidth =
859 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
860 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
861 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
Nick Lewyckye0332982009-09-20 01:35:59 +0000862 return C1;
Chris Lattner6d94bb72007-03-25 05:47:04 +0000863 }
Dan Gohman062d3782009-08-29 23:35:16 +0000864
Chris Lattnerbc26e1b2008-04-19 22:17:26 +0000865 // If and'ing the address of a global with a constant, fold it.
Chris Lattner334d33c2008-04-19 21:58:19 +0000866 if (CE1->getOpcode() == Instruction::PtrToInt &&
867 isa<GlobalValue>(CE1->getOperand(0))) {
Chris Lattnerbc26e1b2008-04-19 22:17:26 +0000868 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
Dan Gohman062d3782009-08-29 23:35:16 +0000869
Chris Lattnerbc26e1b2008-04-19 22:17:26 +0000870 // Functions are at least 4-byte aligned.
871 unsigned GVAlign = GV->getAlignment();
872 if (isa<Function>(GV))
873 GVAlign = std::max(GVAlign, 4U);
Dan Gohman062d3782009-08-29 23:35:16 +0000874
Chris Lattnerbc26e1b2008-04-19 22:17:26 +0000875 if (GVAlign > 1) {
876 unsigned DstWidth = CI2->getType()->getBitWidth();
Chris Lattner912bec72008-04-20 19:59:12 +0000877 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
Chris Lattnerbc26e1b2008-04-19 22:17:26 +0000878 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
879
880 // If checking bits we know are clear, return zero.
881 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
Owen Anderson5a1acd92009-07-31 20:28:14 +0000882 return Constant::getNullValue(CI2->getType());
Chris Lattnerbc26e1b2008-04-19 22:17:26 +0000883 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000884 }
Chris Lattner334d33c2008-04-19 21:58:19 +0000885 }
886 break;
887 case Instruction::Or:
Nick Lewyckye0332982009-09-20 01:35:59 +0000888 if (CI2->equalsInt(0)) return C1; // X | 0 == X
Chris Lattner334d33c2008-04-19 21:58:19 +0000889 if (CI2->isAllOnesValue())
Nick Lewyckye0332982009-09-20 01:35:59 +0000890 return C2; // X | -1 == -1
Chris Lattner334d33c2008-04-19 21:58:19 +0000891 break;
892 case Instruction::Xor:
Nick Lewyckye0332982009-09-20 01:35:59 +0000893 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X
Nick Lewycky28260402009-09-20 06:24:51 +0000894
895 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
896 switch (CE1->getOpcode()) {
897 default: break;
898 case Instruction::ICmp:
899 case Instruction::FCmp:
Nick Lewyckyff550aa2009-09-20 06:27:35 +0000900 // cmp pred ^ true -> cmp !pred
Nick Lewycky28260402009-09-20 06:24:51 +0000901 assert(CI2->equalsInt(1));
Nick Lewycky0f8348e2009-09-20 06:26:34 +0000902 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
Nick Lewycky28260402009-09-20 06:24:51 +0000903 pred = CmpInst::getInversePredicate(pred);
904 return ConstantExpr::getCompare(pred, CE1->getOperand(0),
905 CE1->getOperand(1));
906 }
907 }
Chris Lattner334d33c2008-04-19 21:58:19 +0000908 break;
909 case Instruction::AShr:
910 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
Nick Lewyckye0332982009-09-20 01:35:59 +0000911 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
Chris Lattner6d94bb72007-03-25 05:47:04 +0000912 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
Nick Lewyckye0332982009-09-20 01:35:59 +0000913 return ConstantExpr::getLShr(C1, C2);
Chris Lattner334d33c2008-04-19 21:58:19 +0000914 break;
Reid Spencer266e42b2006-12-23 06:05:41 +0000915 }
Chris Lattner334d33c2008-04-19 21:58:19 +0000916 }
Dan Gohman062d3782009-08-29 23:35:16 +0000917
Chris Lattner6b056052008-04-20 18:24:14 +0000918 // At this point we know neither constant is an UndefValue.
Nick Lewyckye0332982009-09-20 01:35:59 +0000919 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
920 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
Reid Spencer81658a82007-02-27 06:23:51 +0000921 using namespace APIntOps;
Chris Lattner6b056052008-04-20 18:24:14 +0000922 const APInt &C1V = CI1->getValue();
923 const APInt &C2V = CI2->getValue();
Chris Lattner344da522007-01-12 18:42:52 +0000924 switch (Opcode) {
925 default:
926 break;
927 case Instruction::Add:
Owen Andersonedb4a702009-07-24 23:12:02 +0000928 return ConstantInt::get(Context, C1V + C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000929 case Instruction::Sub:
Owen Andersonedb4a702009-07-24 23:12:02 +0000930 return ConstantInt::get(Context, C1V - C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000931 case Instruction::Mul:
Owen Andersonedb4a702009-07-24 23:12:02 +0000932 return ConstantInt::get(Context, C1V * C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000933 case Instruction::UDiv:
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +0000934 assert(!CI2->isNullValue() && "Div by zero handled above");
Owen Andersonedb4a702009-07-24 23:12:02 +0000935 return ConstantInt::get(Context, C1V.udiv(C2V));
Chris Lattner344da522007-01-12 18:42:52 +0000936 case Instruction::SDiv:
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +0000937 assert(!CI2->isNullValue() && "Div by zero handled above");
Reid Spencer81658a82007-02-27 06:23:51 +0000938 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +0000939 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
Owen Andersonedb4a702009-07-24 23:12:02 +0000940 return ConstantInt::get(Context, C1V.sdiv(C2V));
Reid Spencer81658a82007-02-27 06:23:51 +0000941 case Instruction::URem:
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +0000942 assert(!CI2->isNullValue() && "Div by zero handled above");
Owen Andersonedb4a702009-07-24 23:12:02 +0000943 return ConstantInt::get(Context, C1V.urem(C2V));
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +0000944 case Instruction::SRem:
945 assert(!CI2->isNullValue() && "Div by zero handled above");
Reid Spencer81658a82007-02-27 06:23:51 +0000946 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +0000947 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
Owen Andersonedb4a702009-07-24 23:12:02 +0000948 return ConstantInt::get(Context, C1V.srem(C2V));
Chris Lattner344da522007-01-12 18:42:52 +0000949 case Instruction::And:
Owen Andersonedb4a702009-07-24 23:12:02 +0000950 return ConstantInt::get(Context, C1V & C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000951 case Instruction::Or:
Owen Andersonedb4a702009-07-24 23:12:02 +0000952 return ConstantInt::get(Context, C1V | C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000953 case Instruction::Xor:
Owen Andersonedb4a702009-07-24 23:12:02 +0000954 return ConstantInt::get(Context, C1V ^ C2V);
Chris Lattner6b056052008-04-20 18:24:14 +0000955 case Instruction::Shl: {
956 uint32_t shiftAmt = C2V.getZExtValue();
957 if (shiftAmt < C1V.getBitWidth())
Owen Andersonedb4a702009-07-24 23:12:02 +0000958 return ConstantInt::get(Context, C1V.shl(shiftAmt));
Chris Lattner6b056052008-04-20 18:24:14 +0000959 else
Owen Andersonb292b8c2009-07-30 23:03:37 +0000960 return UndefValue::get(C1->getType()); // too big shift is undef
Chris Lattner6b056052008-04-20 18:24:14 +0000961 }
962 case Instruction::LShr: {
963 uint32_t shiftAmt = C2V.getZExtValue();
964 if (shiftAmt < C1V.getBitWidth())
Owen Andersonedb4a702009-07-24 23:12:02 +0000965 return ConstantInt::get(Context, C1V.lshr(shiftAmt));
Chris Lattner6b056052008-04-20 18:24:14 +0000966 else
Owen Andersonb292b8c2009-07-30 23:03:37 +0000967 return UndefValue::get(C1->getType()); // too big shift is undef
Chris Lattner6b056052008-04-20 18:24:14 +0000968 }
969 case Instruction::AShr: {
970 uint32_t shiftAmt = C2V.getZExtValue();
971 if (shiftAmt < C1V.getBitWidth())
Owen Andersonedb4a702009-07-24 23:12:02 +0000972 return ConstantInt::get(Context, C1V.ashr(shiftAmt));
Chris Lattner6b056052008-04-20 18:24:14 +0000973 else
Owen Andersonb292b8c2009-07-30 23:03:37 +0000974 return UndefValue::get(C1->getType()); // too big shift is undef
Chris Lattner6b056052008-04-20 18:24:14 +0000975 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000976 }
977 }
Nick Lewycky6b8320f2009-06-21 01:56:41 +0000978
979 switch (Opcode) {
980 case Instruction::SDiv:
981 case Instruction::UDiv:
982 case Instruction::URem:
983 case Instruction::SRem:
984 case Instruction::LShr:
985 case Instruction::AShr:
986 case Instruction::Shl:
Nick Lewyckye0332982009-09-20 01:35:59 +0000987 if (CI1->equalsInt(0)) return C1;
Nick Lewycky6b8320f2009-06-21 01:56:41 +0000988 break;
989 default:
990 break;
991 }
Nick Lewyckye0332982009-09-20 01:35:59 +0000992 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
993 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000994 APFloat C1V = CFP1->getValueAPF();
995 APFloat C2V = CFP2->getValueAPF();
996 APFloat C3V = C1V; // copy for modification
Reid Spencer266e42b2006-12-23 06:05:41 +0000997 switch (Opcode) {
998 default:
999 break;
Dan Gohmana5b96452009-06-04 22:49:04 +00001000 case Instruction::FAdd:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001001 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
Owen Anderson69c464d2009-07-27 20:59:43 +00001002 return ConstantFP::get(Context, C3V);
Dan Gohmana5b96452009-06-04 22:49:04 +00001003 case Instruction::FSub:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001004 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
Owen Anderson69c464d2009-07-27 20:59:43 +00001005 return ConstantFP::get(Context, C3V);
Dan Gohmana5b96452009-06-04 22:49:04 +00001006 case Instruction::FMul:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001007 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
Owen Anderson69c464d2009-07-27 20:59:43 +00001008 return ConstantFP::get(Context, C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +00001009 case Instruction::FDiv:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001010 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
Owen Anderson69c464d2009-07-27 20:59:43 +00001011 return ConstantFP::get(Context, C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +00001012 case Instruction::FRem:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001013 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
Owen Anderson69c464d2009-07-27 20:59:43 +00001014 return ConstantFP::get(Context, C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +00001015 }
1016 }
Dan Gohman9f396602007-10-30 19:00:49 +00001017 } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
Nick Lewyckye0332982009-09-20 01:35:59 +00001018 ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
1019 ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
Dan Gohmanb43e0202007-10-31 21:36:31 +00001020 if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
1021 (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
Owen Anderson85f86dc2009-07-13 22:41:06 +00001022 std::vector<Constant*> Res;
1023 const Type* EltTy = VTy->getElementType();
Nick Lewyckye0332982009-09-20 01:35:59 +00001024 Constant *C1 = 0;
1025 Constant *C2 = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00001026 switch (Opcode) {
Chris Lattner6072ead2008-04-19 21:13:00 +00001027 default:
1028 break;
Dan Gohmana5b96452009-06-04 22:49:04 +00001029 case Instruction::Add:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001030 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001031 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1032 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001033 Res.push_back(ConstantExpr::getAdd(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001034 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001035 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001036 case Instruction::FAdd:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001037 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001038 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1039 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001040 Res.push_back(ConstantExpr::getFAdd(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001041 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001042 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001043 case Instruction::Sub:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001044 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001045 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1046 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001047 Res.push_back(ConstantExpr::getSub(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001048 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001049 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001050 case Instruction::FSub:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001051 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001052 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1053 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001054 Res.push_back(ConstantExpr::getFSub(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001055 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001056 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001057 case Instruction::Mul:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001058 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001059 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1060 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001061 Res.push_back(ConstantExpr::getMul(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001062 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001063 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001064 case Instruction::FMul:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001065 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001066 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1067 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001068 Res.push_back(ConstantExpr::getFMul(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001069 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001070 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001071 case Instruction::UDiv:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001072 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001073 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1074 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001075 Res.push_back(ConstantExpr::getUDiv(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001076 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001077 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001078 case Instruction::SDiv:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001079 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001080 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1081 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001082 Res.push_back(ConstantExpr::getSDiv(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001083 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001084 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001085 case Instruction::FDiv:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001086 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001087 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1088 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001089 Res.push_back(ConstantExpr::getFDiv(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001090 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001091 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001092 case Instruction::URem:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001093 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001094 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1095 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001096 Res.push_back(ConstantExpr::getURem(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001097 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001098 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001099 case Instruction::SRem:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001100 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001101 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1102 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001103 Res.push_back(ConstantExpr::getSRem(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001104 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001105 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001106 case Instruction::FRem:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001107 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001108 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1109 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001110 Res.push_back(ConstantExpr::getFRem(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001111 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001112 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001113 case Instruction::And:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001114 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001115 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1116 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001117 Res.push_back(ConstantExpr::getAnd(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001118 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001119 return ConstantVector::get(Res);
Owen Anderson85f86dc2009-07-13 22:41:06 +00001120 case Instruction::Or:
1121 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001122 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1123 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001124 Res.push_back(ConstantExpr::getOr(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001125 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001126 return ConstantVector::get(Res);
Owen Anderson85f86dc2009-07-13 22:41:06 +00001127 case Instruction::Xor:
1128 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001129 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1130 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001131 Res.push_back(ConstantExpr::getXor(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001132 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001133 return ConstantVector::get(Res);
Dan Gohman79975d52009-03-14 17:09:17 +00001134 case Instruction::LShr:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001135 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001136 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1137 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001138 Res.push_back(ConstantExpr::getLShr(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001139 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001140 return ConstantVector::get(Res);
Dan Gohman79975d52009-03-14 17:09:17 +00001141 case Instruction::AShr:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001142 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001143 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1144 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001145 Res.push_back(ConstantExpr::getAShr(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001146 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001147 return ConstantVector::get(Res);
Dan Gohman79975d52009-03-14 17:09:17 +00001148 case Instruction::Shl:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001149 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001150 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1151 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001152 Res.push_back(ConstantExpr::getShl(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001153 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001154 return ConstantVector::get(Res);
Dan Gohmanb43e0202007-10-31 21:36:31 +00001155 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001156 }
1157 }
1158
Chris Lattner6b056052008-04-20 18:24:14 +00001159 if (isa<ConstantExpr>(C1)) {
1160 // There are many possible foldings we could do here. We should probably
1161 // at least fold add of a pointer with an integer into the appropriate
1162 // getelementptr. This will improve alias analysis a bit.
1163 } else if (isa<ConstantExpr>(C2)) {
1164 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1165 // other way if possible.
1166 switch (Opcode) {
1167 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +00001168 case Instruction::FAdd:
Chris Lattner6b056052008-04-20 18:24:14 +00001169 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +00001170 case Instruction::FMul:
Chris Lattner6b056052008-04-20 18:24:14 +00001171 case Instruction::And:
1172 case Instruction::Or:
1173 case Instruction::Xor:
1174 // No change of opcode required.
Owen Anderson53a52212009-07-13 04:09:18 +00001175 return ConstantFoldBinaryInstruction(Context, Opcode, C2, C1);
Dan Gohman062d3782009-08-29 23:35:16 +00001176
Chris Lattner6b056052008-04-20 18:24:14 +00001177 case Instruction::Shl:
1178 case Instruction::LShr:
1179 case Instruction::AShr:
1180 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +00001181 case Instruction::FSub:
Chris Lattner6b056052008-04-20 18:24:14 +00001182 case Instruction::SDiv:
1183 case Instruction::UDiv:
1184 case Instruction::FDiv:
1185 case Instruction::URem:
1186 case Instruction::SRem:
1187 case Instruction::FRem:
1188 default: // These instructions cannot be flopped around.
1189 break;
1190 }
1191 }
Dan Gohman062d3782009-08-29 23:35:16 +00001192
Nick Lewycky605109d2009-09-20 00:04:02 +00001193 // i1 can be simplified in many cases.
Benjamin Kramera81a6df2010-01-05 20:07:06 +00001194 if (C1->getType()->isInteger(1)) {
Nick Lewycky605109d2009-09-20 00:04:02 +00001195 switch (Opcode) {
1196 case Instruction::Add:
1197 case Instruction::Sub:
Nick Lewyckye0332982009-09-20 01:35:59 +00001198 return ConstantExpr::getXor(C1, C2);
Nick Lewycky605109d2009-09-20 00:04:02 +00001199 case Instruction::Mul:
Nick Lewyckye0332982009-09-20 01:35:59 +00001200 return ConstantExpr::getAnd(C1, C2);
Nick Lewycky605109d2009-09-20 00:04:02 +00001201 case Instruction::Shl:
1202 case Instruction::LShr:
1203 case Instruction::AShr:
1204 // We can assume that C2 == 0. If it were one the result would be
1205 // undefined because the shift value is as large as the bitwidth.
Nick Lewyckye0332982009-09-20 01:35:59 +00001206 return C1;
Nick Lewycky605109d2009-09-20 00:04:02 +00001207 case Instruction::SDiv:
1208 case Instruction::UDiv:
1209 // We can assume that C2 == 1. If it were zero the result would be
1210 // undefined through division by zero.
Nick Lewyckye0332982009-09-20 01:35:59 +00001211 return C1;
Nick Lewycky605109d2009-09-20 00:04:02 +00001212 case Instruction::URem:
1213 case Instruction::SRem:
1214 // We can assume that C2 == 1. If it were zero the result would be
1215 // undefined through division by zero.
1216 return ConstantInt::getFalse(Context);
1217 default:
1218 break;
1219 }
1220 }
1221
Chris Lattner6b056052008-04-20 18:24:14 +00001222 // We don't know how to fold this.
Reid Spencer266e42b2006-12-23 06:05:41 +00001223 return 0;
1224}
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001225
Chris Lattner60c47262005-01-28 19:09:51 +00001226/// isZeroSizedType - This type is zero sized if its an array or structure of
1227/// zero sized types. The only leaf zero sized type is an empty structure.
1228static bool isMaybeZeroSizedType(const Type *Ty) {
1229 if (isa<OpaqueType>(Ty)) return true; // Can't say.
1230 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1231
1232 // If all of elements have zero size, this does too.
1233 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerfeaf92f2005-01-28 23:17:27 +00001234 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
Chris Lattner60c47262005-01-28 19:09:51 +00001235 return true;
1236
1237 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1238 return isMaybeZeroSizedType(ATy->getElementType());
1239 }
1240 return false;
1241}
Chris Lattner6ea4b522004-03-12 05:53:32 +00001242
Chris Lattner061da2f2004-01-13 05:51:55 +00001243/// IdxCompare - Compare the two constants as though they were getelementptr
1244/// indices. This allows coersion of the types to be the same thing.
1245///
1246/// If the two constants are the "same" (after coersion), return 0. If the
1247/// first is less than the second, return -1, if the second is less than the
1248/// first, return 1. If the constants are not integral, return -2.
1249///
Owen Anderson53a52212009-07-13 04:09:18 +00001250static int IdxCompare(LLVMContext &Context, Constant *C1, Constant *C2,
1251 const Type *ElTy) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001252 if (C1 == C2) return 0;
1253
Reid Spencerc90cf772006-12-31 21:43:30 +00001254 // Ok, we found a different index. If they are not ConstantInt, we can't do
1255 // anything with them.
Chris Lattner061da2f2004-01-13 05:51:55 +00001256 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1257 return -2; // don't know!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001258
Chris Lattner69193f92004-04-05 01:30:19 +00001259 // Ok, we have two differing integer indices. Sign extend them to be the same
1260 // type. Long is always big enough, so we use it.
Benjamin Kramerd2564e32010-01-05 21:05:54 +00001261 if (!C1->getType()->isInteger(64))
Owen Anderson55f1c092009-08-13 21:58:54 +00001262 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(Context));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001263
Benjamin Kramerd2564e32010-01-05 21:05:54 +00001264 if (!C2->getType()->isInteger(64))
Owen Anderson55f1c092009-08-13 21:58:54 +00001265 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(Context));
Reid Spencer8d9336d2006-12-31 05:26:44 +00001266
1267 if (C1 == C2) return 0; // They are equal
Chris Lattner061da2f2004-01-13 05:51:55 +00001268
Chris Lattner60c47262005-01-28 19:09:51 +00001269 // If the type being indexed over is really just a zero sized type, there is
1270 // no pointer difference being made here.
1271 if (isMaybeZeroSizedType(ElTy))
1272 return -2; // dunno.
1273
Chris Lattner061da2f2004-01-13 05:51:55 +00001274 // If they are really different, now that they are the same type, then we
1275 // found a difference!
Reid Spencere0fc4df2006-10-20 07:07:24 +00001276 if (cast<ConstantInt>(C1)->getSExtValue() <
1277 cast<ConstantInt>(C2)->getSExtValue())
Chris Lattner061da2f2004-01-13 05:51:55 +00001278 return -1;
1279 else
1280 return 1;
1281}
1282
Chris Lattner858f4e92007-01-04 02:13:20 +00001283/// evaluateFCmpRelation - This function determines if there is anything we can
Reid Spencer266e42b2006-12-23 06:05:41 +00001284/// decide about the two constants provided. This doesn't need to handle simple
1285/// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1286/// If we can determine that the two constants have a particular relation to
1287/// each other, we should return the corresponding FCmpInst predicate,
Reid Spencer9d36acf2006-12-24 18:52:08 +00001288/// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1289/// ConstantFoldCompareInstruction.
Reid Spencer266e42b2006-12-23 06:05:41 +00001290///
1291/// To simplify this code we canonicalize the relation so that the first
Reid Spencer9d36acf2006-12-24 18:52:08 +00001292/// operand is always the most "complex" of the two. We consider ConstantFP
1293/// to be the simplest, and ConstantExprs to be the most complex.
Owen Anderson53a52212009-07-13 04:09:18 +00001294static FCmpInst::Predicate evaluateFCmpRelation(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +00001295 Constant *V1, Constant *V2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001296 assert(V1->getType() == V2->getType() &&
Reid Spencer9d36acf2006-12-24 18:52:08 +00001297 "Cannot compare values of different types!");
Dale Johannesen19db0932007-10-14 01:56:47 +00001298
1299 // No compile-time operations on this type yet.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001300 if (V1->getType()->isPPC_FP128Ty())
Dale Johannesen19db0932007-10-14 01:56:47 +00001301 return FCmpInst::BAD_FCMP_PREDICATE;
1302
Reid Spencer9d36acf2006-12-24 18:52:08 +00001303 // Handle degenerate case quickly
Reid Spencer266e42b2006-12-23 06:05:41 +00001304 if (V1 == V2) return FCmpInst::FCMP_OEQ;
1305
Reid Spencer9d36acf2006-12-24 18:52:08 +00001306 if (!isa<ConstantExpr>(V1)) {
1307 if (!isa<ConstantExpr>(V2)) {
1308 // We distilled thisUse the standard constant folder for a few cases
Zhou Sheng75b871f2007-01-11 12:24:14 +00001309 ConstantInt *R = 0;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001310 R = dyn_cast<ConstantInt>(
Nick Lewyckye0332982009-09-20 01:35:59 +00001311 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001312 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001313 return FCmpInst::FCMP_OEQ;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001314 R = dyn_cast<ConstantInt>(
Nick Lewyckye0332982009-09-20 01:35:59 +00001315 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001316 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001317 return FCmpInst::FCMP_OLT;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001318 R = dyn_cast<ConstantInt>(
Nick Lewyckye0332982009-09-20 01:35:59 +00001319 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001320 if (R && !R->isZero())
Reid Spencer9d36acf2006-12-24 18:52:08 +00001321 return FCmpInst::FCMP_OGT;
1322
1323 // Nothing more we can do
Reid Spencer266e42b2006-12-23 06:05:41 +00001324 return FCmpInst::BAD_FCMP_PREDICATE;
1325 }
Dan Gohman062d3782009-08-29 23:35:16 +00001326
Reid Spencer9d36acf2006-12-24 18:52:08 +00001327 // If the first operand is simple and second is ConstantExpr, swap operands.
Owen Anderson53a52212009-07-13 04:09:18 +00001328 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(Context, V2, V1);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001329 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1330 return FCmpInst::getSwappedPredicate(SwappedRelation);
1331 } else {
1332 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1333 // constantexpr or a simple constant.
Nick Lewyckye0332982009-09-20 01:35:59 +00001334 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001335 switch (CE1->getOpcode()) {
1336 case Instruction::FPTrunc:
1337 case Instruction::FPExt:
1338 case Instruction::UIToFP:
1339 case Instruction::SIToFP:
1340 // We might be able to do something with these but we don't right now.
1341 break;
1342 default:
1343 break;
1344 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001345 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001346 // There are MANY other foldings that we could perform here. They will
1347 // probably be added on demand, as they seem needed.
1348 return FCmpInst::BAD_FCMP_PREDICATE;
1349}
1350
1351/// evaluateICmpRelation - This function determines if there is anything we can
Chris Lattner061da2f2004-01-13 05:51:55 +00001352/// decide about the two constants provided. This doesn't need to handle simple
Reid Spenceraccd7c72004-07-17 23:47:01 +00001353/// things like integer comparisons, but should instead handle ConstantExprs
Chris Lattner8410beb2006-12-11 02:16:58 +00001354/// and GlobalValues. If we can determine that the two constants have a
Reid Spencer266e42b2006-12-23 06:05:41 +00001355/// particular relation to each other, we should return the corresponding ICmp
1356/// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
Chris Lattner061da2f2004-01-13 05:51:55 +00001357///
1358/// To simplify this code we canonicalize the relation so that the first
1359/// operand is always the most "complex" of the two. We consider simple
1360/// constants (like ConstantInt) to be the simplest, followed by
Reid Spenceraccd7c72004-07-17 23:47:01 +00001361/// GlobalValues, followed by ConstantExpr's (the most complex).
Chris Lattner061da2f2004-01-13 05:51:55 +00001362///
Owen Anderson53a52212009-07-13 04:09:18 +00001363static ICmpInst::Predicate evaluateICmpRelation(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +00001364 Constant *V1,
1365 Constant *V2,
Reid Spencer266e42b2006-12-23 06:05:41 +00001366 bool isSigned) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001367 assert(V1->getType() == V2->getType() &&
1368 "Cannot compare different types of values!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001369 if (V1 == V2) return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001370
Reid Spenceraccd7c72004-07-17 23:47:01 +00001371 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
Chris Lattnerfed8ceb2006-01-05 07:49:30 +00001372 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
1373 // We distilled this down to a simple case, use the standard constant
1374 // folder.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001375 ConstantInt *R = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00001376 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
Nick Lewyckye0332982009-09-20 01:35:59 +00001377 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001378 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001379 return pred;
1380 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Nick Lewyckye0332982009-09-20 01:35:59 +00001381 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001382 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001383 return pred;
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001384 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Nick Lewyckye0332982009-09-20 01:35:59 +00001385 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001386 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001387 return pred;
Dan Gohman062d3782009-08-29 23:35:16 +00001388
Chris Lattnerfed8ceb2006-01-05 07:49:30 +00001389 // If we couldn't figure it out, bail.
Reid Spencer266e42b2006-12-23 06:05:41 +00001390 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerfed8ceb2006-01-05 07:49:30 +00001391 }
Dan Gohman062d3782009-08-29 23:35:16 +00001392
Chris Lattner061da2f2004-01-13 05:51:55 +00001393 // If the first operand is simple, swap operands.
Reid Spencer266e42b2006-12-23 06:05:41 +00001394 ICmpInst::Predicate SwappedRelation =
Owen Anderson53a52212009-07-13 04:09:18 +00001395 evaluateICmpRelation(Context, V2, V1, isSigned);
Reid Spencer266e42b2006-12-23 06:05:41 +00001396 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1397 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner061da2f2004-01-13 05:51:55 +00001398
Chris Lattner0f7e9f52006-01-05 07:19:51 +00001399 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
Chris Lattner125ed542004-02-01 01:23:19 +00001400 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
Reid Spencer266e42b2006-12-23 06:05:41 +00001401 ICmpInst::Predicate SwappedRelation =
Owen Anderson53a52212009-07-13 04:09:18 +00001402 evaluateICmpRelation(Context, V2, V1, isSigned);
Reid Spencer266e42b2006-12-23 06:05:41 +00001403 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1404 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner0f7e9f52006-01-05 07:19:51 +00001405 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001406 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner125ed542004-02-01 01:23:19 +00001407 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001408
Reid Spenceraccd7c72004-07-17 23:47:01 +00001409 // Now we know that the RHS is a GlobalValue or simple constant,
Chris Lattner061da2f2004-01-13 05:51:55 +00001410 // which (since the types must match) means that it's a ConstantPointerNull.
Reid Spenceraccd7c72004-07-17 23:47:01 +00001411 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattner52fe8692007-09-10 23:42:42 +00001412 // Don't try to decide equality of aliases.
1413 if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
1414 if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
1415 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001416 } else {
1417 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
Chris Lattner52fe8692007-09-10 23:42:42 +00001418 // GlobalVals can never be null. Don't try to evaluate aliases.
1419 if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
Reid Spencer266e42b2006-12-23 06:05:41 +00001420 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001421 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001422 } else {
1423 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1424 // constantexpr, a CPR, or a simple constant.
Nick Lewyckye0332982009-09-20 01:35:59 +00001425 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1426 Constant *CE1Op0 = CE1->getOperand(0);
Chris Lattner061da2f2004-01-13 05:51:55 +00001427
1428 switch (CE1->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001429 case Instruction::Trunc:
1430 case Instruction::FPTrunc:
1431 case Instruction::FPExt:
1432 case Instruction::FPToUI:
1433 case Instruction::FPToSI:
Reid Spencer266e42b2006-12-23 06:05:41 +00001434 break; // We can't evaluate floating point casts or truncations.
1435
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001436 case Instruction::UIToFP:
1437 case Instruction::SIToFP:
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001438 case Instruction::BitCast:
Reid Spencer266e42b2006-12-23 06:05:41 +00001439 case Instruction::ZExt:
1440 case Instruction::SExt:
Chris Lattner061da2f2004-01-13 05:51:55 +00001441 // If the cast is not actually changing bits, and the second operand is a
1442 // null pointer, do the comparison with the pre-casted value.
1443 if (V2->isNullValue() &&
Chris Lattner03c49532007-01-15 02:27:26 +00001444 (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001445 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1446 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
Owen Anderson53a52212009-07-13 04:09:18 +00001447 return evaluateICmpRelation(Context, CE1Op0,
Owen Anderson5a1acd92009-07-31 20:28:14 +00001448 Constant::getNullValue(CE1Op0->getType()),
Nick Lewycky2949a232009-09-20 03:48:46 +00001449 isSigned);
Reid Spencer266e42b2006-12-23 06:05:41 +00001450 }
Chris Lattner192e3262004-04-11 01:29:30 +00001451 break;
Chris Lattner061da2f2004-01-13 05:51:55 +00001452
1453 case Instruction::GetElementPtr:
1454 // Ok, since this is a getelementptr, we know that the constant has a
1455 // pointer type. Check the various cases.
1456 if (isa<ConstantPointerNull>(V2)) {
1457 // If we are comparing a GEP to a null pointer, check to see if the base
1458 // of the GEP equals the null pointer.
Reid Spencer9d36acf2006-12-24 18:52:08 +00001459 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
Reid Spencer876f7222006-12-06 00:25:09 +00001460 if (GV->hasExternalWeakLinkage())
1461 // Weak linkage GVals could be zero or not. We're comparing that
1462 // to null pointer so its greater-or-equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001463 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
Reid Spencer876f7222006-12-06 00:25:09 +00001464 else
1465 // If its not weak linkage, the GVal must have a non-zero address
1466 // so the result is greater-than
Nick Lewycky9e085542009-09-20 04:27:06 +00001467 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001468 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1469 // If we are indexing from a null pointer, check to see if we have any
1470 // non-zero indices.
1471 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1472 if (!CE1->getOperand(i)->isNullValue())
1473 // Offsetting from null, must not be equal.
Reid Spencer266e42b2006-12-23 06:05:41 +00001474 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001475 // Only zero indexes from null, must still be zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00001476 return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001477 }
1478 // Otherwise, we can't really say if the first operand is null or not.
Reid Spenceraccd7c72004-07-17 23:47:01 +00001479 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001480 if (isa<ConstantPointerNull>(CE1Op0)) {
Reid Spencer876f7222006-12-06 00:25:09 +00001481 if (CPR2->hasExternalWeakLinkage())
1482 // Weak linkage GVals could be zero or not. We're comparing it to
1483 // a null pointer, so its less-or-equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001484 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
Reid Spencer876f7222006-12-06 00:25:09 +00001485 else
1486 // If its not weak linkage, the GVal must have a non-zero address
1487 // so the result is less-than
Reid Spencer266e42b2006-12-23 06:05:41 +00001488 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Reid Spenceraccd7c72004-07-17 23:47:01 +00001489 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001490 if (CPR1 == CPR2) {
1491 // If this is a getelementptr of the same global, then it must be
1492 // different. Because the types must match, the getelementptr could
1493 // only have at most one index, and because we fold getelementptr's
1494 // with a single zero index, it must be nonzero.
1495 assert(CE1->getNumOperands() == 2 &&
1496 !CE1->getOperand(1)->isNullValue() &&
1497 "Suprising getelementptr!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001498 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001499 } else {
1500 // If they are different globals, we don't know what the value is,
1501 // but they can't be equal.
Reid Spencer266e42b2006-12-23 06:05:41 +00001502 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001503 }
1504 }
1505 } else {
Nick Lewyckye0332982009-09-20 01:35:59 +00001506 ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1507 Constant *CE2Op0 = CE2->getOperand(0);
Chris Lattner061da2f2004-01-13 05:51:55 +00001508
1509 // There are MANY other foldings that we could perform here. They will
1510 // probably be added on demand, as they seem needed.
1511 switch (CE2->getOpcode()) {
1512 default: break;
1513 case Instruction::GetElementPtr:
1514 // By far the most common case to handle is when the base pointers are
1515 // obviously to the same or different globals.
Reid Spenceraccd7c72004-07-17 23:47:01 +00001516 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001517 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001518 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001519 // Ok, we know that both getelementptr instructions are based on the
1520 // same global. From this, we can precisely determine the relative
1521 // ordering of the resultant pointers.
1522 unsigned i = 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001523
Dan Gohman7190d482009-09-10 23:37:55 +00001524 // The logic below assumes that the result of the comparison
1525 // can be determined by finding the first index that differs.
1526 // This doesn't work if there is over-indexing in any
1527 // subsequent indices, so check for that case first.
1528 if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1529 !CE2->isGEPWithNoNotionalOverIndexing())
1530 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1531
Chris Lattner061da2f2004-01-13 05:51:55 +00001532 // Compare all of the operands the GEP's have in common.
Chris Lattner60c47262005-01-28 19:09:51 +00001533 gep_type_iterator GTI = gep_type_begin(CE1);
1534 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1535 ++i, ++GTI)
Owen Anderson53a52212009-07-13 04:09:18 +00001536 switch (IdxCompare(Context, CE1->getOperand(i),
1537 CE2->getOperand(i), GTI.getIndexedType())) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001538 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1539 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1540 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001541 }
1542
1543 // Ok, we ran out of things they have in common. If any leftovers
1544 // are non-zero then we have a difference, otherwise we are equal.
1545 for (; i < CE1->getNumOperands(); ++i)
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001546 if (!CE1->getOperand(i)->isNullValue()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001547 if (isa<ConstantInt>(CE1->getOperand(i)))
Reid Spencer266e42b2006-12-23 06:05:41 +00001548 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner60c47262005-01-28 19:09:51 +00001549 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001550 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001551 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001552
Chris Lattner061da2f2004-01-13 05:51:55 +00001553 for (; i < CE2->getNumOperands(); ++i)
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001554 if (!CE2->getOperand(i)->isNullValue()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001555 if (isa<ConstantInt>(CE2->getOperand(i)))
Reid Spencer266e42b2006-12-23 06:05:41 +00001556 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Chris Lattner60c47262005-01-28 19:09:51 +00001557 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001558 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001559 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001560 return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001561 }
1562 }
1563 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001564 default:
1565 break;
1566 }
1567 }
1568
Reid Spencer266e42b2006-12-23 06:05:41 +00001569 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001570}
1571
Owen Anderson53a52212009-07-13 04:09:18 +00001572Constant *llvm::ConstantFoldCompareInstruction(LLVMContext &Context,
1573 unsigned short pred,
Nick Lewyckye0332982009-09-20 01:35:59 +00001574 Constant *C1, Constant *C2) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001575 const Type *ResultTy;
1576 if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
Owen Anderson55f1c092009-08-13 21:58:54 +00001577 ResultTy = VectorType::get(Type::getInt1Ty(Context), VT->getNumElements());
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001578 else
Owen Anderson55f1c092009-08-13 21:58:54 +00001579 ResultTy = Type::getInt1Ty(Context);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001580
Chris Lattnerd137a082008-07-08 05:46:34 +00001581 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001582 if (pred == FCmpInst::FCMP_FALSE)
Owen Anderson5a1acd92009-07-31 20:28:14 +00001583 return Constant::getNullValue(ResultTy);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001584
1585 if (pred == FCmpInst::FCMP_TRUE)
Owen Anderson5a1acd92009-07-31 20:28:14 +00001586 return Constant::getAllOnesValue(ResultTy);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001587
Reid Spencer266e42b2006-12-23 06:05:41 +00001588 // Handle some degenerate cases first
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001589 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
Owen Andersonb292b8c2009-07-30 23:03:37 +00001590 return UndefValue::get(ResultTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00001591
Dale Johannesen19db0932007-10-14 01:56:47 +00001592 // No compile-time operations on this type yet.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001593 if (C1->getType()->isPPC_FP128Ty())
Dale Johannesen19db0932007-10-14 01:56:47 +00001594 return 0;
1595
Reid Spencer266e42b2006-12-23 06:05:41 +00001596 // icmp eq/ne(null,GV) -> false/true
1597 if (C1->isNullValue()) {
1598 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
Duncan Sandsa38e5272007-09-19 10:16:17 +00001599 // Don't try to evaluate aliases. External weak GV can be null.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001600 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
Reid Spencer9d36acf2006-12-24 18:52:08 +00001601 if (pred == ICmpInst::ICMP_EQ)
Owen Anderson23a204d2009-07-31 17:39:07 +00001602 return ConstantInt::getFalse(Context);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001603 else if (pred == ICmpInst::ICMP_NE)
Owen Anderson23a204d2009-07-31 17:39:07 +00001604 return ConstantInt::getTrue(Context);
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001605 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001606 // icmp eq/ne(GV,null) -> false/true
1607 } else if (C2->isNullValue()) {
1608 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
Duncan Sandsa38e5272007-09-19 10:16:17 +00001609 // Don't try to evaluate aliases. External weak GV can be null.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001610 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
Reid Spencer9d36acf2006-12-24 18:52:08 +00001611 if (pred == ICmpInst::ICMP_EQ)
Owen Anderson23a204d2009-07-31 17:39:07 +00001612 return ConstantInt::getFalse(Context);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001613 else if (pred == ICmpInst::ICMP_NE)
Owen Anderson23a204d2009-07-31 17:39:07 +00001614 return ConstantInt::getTrue(Context);
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001615 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00001616 }
1617
Nick Lewyckyb0225ba2009-09-20 07:21:39 +00001618 // If the comparison is a comparison between two i1's, simplify it.
Benjamin Kramera81a6df2010-01-05 20:07:06 +00001619 if (C1->getType()->isInteger(1)) {
Nick Lewyckyb0225ba2009-09-20 07:21:39 +00001620 switch(pred) {
1621 case ICmpInst::ICMP_EQ:
1622 if (isa<ConstantInt>(C2))
1623 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1624 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1625 case ICmpInst::ICMP_NE:
1626 return ConstantExpr::getXor(C1, C2);
1627 default:
1628 break;
1629 }
1630 }
1631
Chris Lattner344da522007-01-12 18:42:52 +00001632 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
Reid Spencer81658a82007-02-27 06:23:51 +00001633 APInt V1 = cast<ConstantInt>(C1)->getValue();
1634 APInt V2 = cast<ConstantInt>(C2)->getValue();
1635 switch (pred) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001636 default: llvm_unreachable("Invalid ICmp Predicate"); return 0;
Owen Anderson53a52212009-07-13 04:09:18 +00001637 case ICmpInst::ICMP_EQ:
Owen Anderson55f1c092009-08-13 21:58:54 +00001638 return ConstantInt::get(Type::getInt1Ty(Context), V1 == V2);
Owen Anderson53a52212009-07-13 04:09:18 +00001639 case ICmpInst::ICMP_NE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001640 return ConstantInt::get(Type::getInt1Ty(Context), V1 != V2);
Owen Anderson53a52212009-07-13 04:09:18 +00001641 case ICmpInst::ICMP_SLT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001642 return ConstantInt::get(Type::getInt1Ty(Context), V1.slt(V2));
Owen Anderson53a52212009-07-13 04:09:18 +00001643 case ICmpInst::ICMP_SGT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001644 return ConstantInt::get(Type::getInt1Ty(Context), V1.sgt(V2));
Owen Anderson53a52212009-07-13 04:09:18 +00001645 case ICmpInst::ICMP_SLE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001646 return ConstantInt::get(Type::getInt1Ty(Context), V1.sle(V2));
Owen Anderson53a52212009-07-13 04:09:18 +00001647 case ICmpInst::ICMP_SGE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001648 return ConstantInt::get(Type::getInt1Ty(Context), V1.sge(V2));
Owen Anderson53a52212009-07-13 04:09:18 +00001649 case ICmpInst::ICMP_ULT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001650 return ConstantInt::get(Type::getInt1Ty(Context), V1.ult(V2));
Owen Anderson53a52212009-07-13 04:09:18 +00001651 case ICmpInst::ICMP_UGT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001652 return ConstantInt::get(Type::getInt1Ty(Context), V1.ugt(V2));
Owen Anderson53a52212009-07-13 04:09:18 +00001653 case ICmpInst::ICMP_ULE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001654 return ConstantInt::get(Type::getInt1Ty(Context), V1.ule(V2));
Owen Anderson53a52212009-07-13 04:09:18 +00001655 case ICmpInst::ICMP_UGE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001656 return ConstantInt::get(Type::getInt1Ty(Context), V1.uge(V2));
Chris Lattner061da2f2004-01-13 05:51:55 +00001657 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001658 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001659 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1660 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1661 APFloat::cmpResult R = C1V.compare(C2V);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001662 switch (pred) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001663 default: llvm_unreachable("Invalid FCmp Predicate"); return 0;
Owen Anderson23a204d2009-07-31 17:39:07 +00001664 case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse(Context);
1665 case FCmpInst::FCMP_TRUE: return ConstantInt::getTrue(Context);
Reid Spencer266e42b2006-12-23 06:05:41 +00001666 case FCmpInst::FCMP_UNO:
Owen Anderson55f1c092009-08-13 21:58:54 +00001667 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered);
Reid Spencer74bd0362007-01-11 00:25:45 +00001668 case FCmpInst::FCMP_ORD:
Owen Anderson55f1c092009-08-13 21:58:54 +00001669 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpUnordered);
Reid Spencer266e42b2006-12-23 06:05:41 +00001670 case FCmpInst::FCMP_UEQ:
Owen Anderson55f1c092009-08-13 21:58:54 +00001671 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001672 R==APFloat::cmpEqual);
Reid Spencercddc9df2007-01-12 04:24:46 +00001673 case FCmpInst::FCMP_OEQ:
Owen Anderson55f1c092009-08-13 21:58:54 +00001674 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpEqual);
Reid Spencer74bd0362007-01-11 00:25:45 +00001675 case FCmpInst::FCMP_UNE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001676 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpEqual);
Reid Spencercddc9df2007-01-12 04:24:46 +00001677 case FCmpInst::FCMP_ONE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001678 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan ||
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001679 R==APFloat::cmpGreaterThan);
Reid Spencer74bd0362007-01-11 00:25:45 +00001680 case FCmpInst::FCMP_ULT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001681 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001682 R==APFloat::cmpLessThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001683 case FCmpInst::FCMP_OLT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001684 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan);
Reid Spencer266e42b2006-12-23 06:05:41 +00001685 case FCmpInst::FCMP_UGT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001686 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpUnordered ||
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001687 R==APFloat::cmpGreaterThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001688 case FCmpInst::FCMP_OGT:
Owen Anderson55f1c092009-08-13 21:58:54 +00001689 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpGreaterThan);
Reid Spencer74bd0362007-01-11 00:25:45 +00001690 case FCmpInst::FCMP_ULE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001691 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpGreaterThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001692 case FCmpInst::FCMP_OLE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001693 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpLessThan ||
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001694 R==APFloat::cmpEqual);
Reid Spencer266e42b2006-12-23 06:05:41 +00001695 case FCmpInst::FCMP_UGE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001696 return ConstantInt::get(Type::getInt1Ty(Context), R!=APFloat::cmpLessThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001697 case FCmpInst::FCMP_OGE:
Owen Anderson55f1c092009-08-13 21:58:54 +00001698 return ConstantInt::get(Type::getInt1Ty(Context), R==APFloat::cmpGreaterThan ||
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001699 R==APFloat::cmpEqual);
Reid Spencer266e42b2006-12-23 06:05:41 +00001700 }
Chris Lattner67136cf2008-07-10 00:29:28 +00001701 } else if (isa<VectorType>(C1->getType())) {
1702 SmallVector<Constant*, 16> C1Elts, C2Elts;
Owen Anderson53a52212009-07-13 04:09:18 +00001703 C1->getVectorElements(Context, C1Elts);
1704 C2->getVectorElements(Context, C2Elts);
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001705 if (C1Elts.empty() || C2Elts.empty())
1706 return 0;
Dan Gohman062d3782009-08-29 23:35:16 +00001707
Chris Lattner67136cf2008-07-10 00:29:28 +00001708 // If we can constant fold the comparison of each element, constant fold
1709 // the whole vector comparison.
1710 SmallVector<Constant*, 4> ResElts;
Chris Lattner67136cf2008-07-10 00:29:28 +00001711 for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
1712 // Compare the elements, producing an i1 result or constant expr.
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001713 ResElts.push_back(ConstantExpr::getCompare(pred, C1Elts[i], C2Elts[i]));
Reid Spencer266e42b2006-12-23 06:05:41 +00001714 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001715 return ConstantVector::get(&ResElts[0], ResElts.size());
Reid Spencer266e42b2006-12-23 06:05:41 +00001716 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001717
Reid Spencer9d36acf2006-12-24 18:52:08 +00001718 if (C1->getType()->isFloatingPoint()) {
Chris Lattner350e4172008-07-08 18:47:38 +00001719 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
Owen Anderson53a52212009-07-13 04:09:18 +00001720 switch (evaluateFCmpRelation(Context, C1, C2)) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001721 default: llvm_unreachable("Unknown relation!");
Reid Spencer9d36acf2006-12-24 18:52:08 +00001722 case FCmpInst::FCMP_UNO:
1723 case FCmpInst::FCMP_ORD:
1724 case FCmpInst::FCMP_UEQ:
1725 case FCmpInst::FCMP_UNE:
1726 case FCmpInst::FCMP_ULT:
1727 case FCmpInst::FCMP_UGT:
1728 case FCmpInst::FCMP_ULE:
1729 case FCmpInst::FCMP_UGE:
1730 case FCmpInst::FCMP_TRUE:
1731 case FCmpInst::FCMP_FALSE:
1732 case FCmpInst::BAD_FCMP_PREDICATE:
1733 break; // Couldn't determine anything about these constants.
1734 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
Chris Lattnerd137a082008-07-08 05:46:34 +00001735 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1736 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1737 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1738 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001739 case FCmpInst::FCMP_OLT: // We know that C1 < C2
Chris Lattnerd137a082008-07-08 05:46:34 +00001740 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1741 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1742 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1743 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001744 case FCmpInst::FCMP_OGT: // We know that C1 > C2
Chris Lattnerd137a082008-07-08 05:46:34 +00001745 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1746 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1747 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1748 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001749 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1750 // We can only partially decide this relation.
1751 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
Chris Lattnerd137a082008-07-08 05:46:34 +00001752 Result = 0;
1753 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1754 Result = 1;
Chris Lattner061da2f2004-01-13 05:51:55 +00001755 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001756 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1757 // We can only partially decide this relation.
1758 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
Chris Lattnerd137a082008-07-08 05:46:34 +00001759 Result = 0;
1760 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1761 Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001762 break;
1763 case ICmpInst::ICMP_NE: // We know that C1 != C2
1764 // We can only partially decide this relation.
1765 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
Chris Lattnerd137a082008-07-08 05:46:34 +00001766 Result = 0;
1767 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1768 Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001769 break;
1770 }
Dan Gohman062d3782009-08-29 23:35:16 +00001771
Chris Lattnerd137a082008-07-08 05:46:34 +00001772 // If we evaluated the result, return it now.
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001773 if (Result != -1)
Owen Anderson55f1c092009-08-13 21:58:54 +00001774 return ConstantInt::get(Type::getInt1Ty(Context), Result);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001775
Reid Spencer9d36acf2006-12-24 18:52:08 +00001776 } else {
1777 // Evaluate the relation between the two constants, per the predicate.
Chris Lattnerd137a082008-07-08 05:46:34 +00001778 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
Owen Anderson53a52212009-07-13 04:09:18 +00001779 switch (evaluateICmpRelation(Context, C1, C2, CmpInst::isSigned(pred))) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001780 default: llvm_unreachable("Unknown relational!");
Reid Spencer9d36acf2006-12-24 18:52:08 +00001781 case ICmpInst::BAD_ICMP_PREDICATE:
1782 break; // Couldn't determine anything about these constants.
1783 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1784 // If we know the constants are equal, we can decide the result of this
1785 // computation precisely.
Nick Lewycky9e085542009-09-20 04:27:06 +00001786 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
Chris Lattnerd137a082008-07-08 05:46:34 +00001787 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001788 case ICmpInst::ICMP_ULT:
Nick Lewycky9e085542009-09-20 04:27:06 +00001789 switch (pred) {
1790 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001791 Result = 1; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001792 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001793 Result = 0; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001794 }
Chris Lattnerd137a082008-07-08 05:46:34 +00001795 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001796 case ICmpInst::ICMP_SLT:
Nick Lewycky9e085542009-09-20 04:27:06 +00001797 switch (pred) {
1798 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001799 Result = 1; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001800 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001801 Result = 0; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001802 }
Chris Lattnerd137a082008-07-08 05:46:34 +00001803 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001804 case ICmpInst::ICMP_UGT:
Nick Lewycky9e085542009-09-20 04:27:06 +00001805 switch (pred) {
1806 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001807 Result = 1; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001808 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001809 Result = 0; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001810 }
Chris Lattnerd137a082008-07-08 05:46:34 +00001811 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001812 case ICmpInst::ICMP_SGT:
Nick Lewycky9e085542009-09-20 04:27:06 +00001813 switch (pred) {
1814 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001815 Result = 1; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001816 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00001817 Result = 0; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00001818 }
Chris Lattnerd137a082008-07-08 05:46:34 +00001819 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001820 case ICmpInst::ICMP_ULE:
Chris Lattnerd137a082008-07-08 05:46:34 +00001821 if (pred == ICmpInst::ICMP_UGT) Result = 0;
Nick Lewycky9e085542009-09-20 04:27:06 +00001822 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001823 break;
1824 case ICmpInst::ICMP_SLE:
Chris Lattnerd137a082008-07-08 05:46:34 +00001825 if (pred == ICmpInst::ICMP_SGT) Result = 0;
Nick Lewycky9e085542009-09-20 04:27:06 +00001826 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001827 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001828 case ICmpInst::ICMP_UGE:
Chris Lattnerd137a082008-07-08 05:46:34 +00001829 if (pred == ICmpInst::ICMP_ULT) Result = 0;
Nick Lewycky9e085542009-09-20 04:27:06 +00001830 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001831 break;
1832 case ICmpInst::ICMP_SGE:
Chris Lattnerd137a082008-07-08 05:46:34 +00001833 if (pred == ICmpInst::ICMP_SLT) Result = 0;
Nick Lewycky9e085542009-09-20 04:27:06 +00001834 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001835 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001836 case ICmpInst::ICMP_NE:
Chris Lattnerd137a082008-07-08 05:46:34 +00001837 if (pred == ICmpInst::ICMP_EQ) Result = 0;
1838 if (pred == ICmpInst::ICMP_NE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001839 break;
1840 }
Dan Gohman062d3782009-08-29 23:35:16 +00001841
Chris Lattnerd137a082008-07-08 05:46:34 +00001842 // If we evaluated the result, return it now.
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001843 if (Result != -1)
Owen Anderson55f1c092009-08-13 21:58:54 +00001844 return ConstantInt::get(Type::getInt1Ty(Context), Result);
Dan Gohman062d3782009-08-29 23:35:16 +00001845
Nick Lewycky4a034522009-09-20 05:48:50 +00001846 // If the right hand side is a bitcast, try using its inverse to simplify
1847 // it by moving it to the left hand side.
1848 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1849 if (CE2->getOpcode() == Instruction::BitCast) {
1850 Constant *CE2Op0 = CE2->getOperand(0);
1851 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1852 return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1853 }
1854 }
1855
Nick Lewycky9b3ed872009-09-20 07:31:25 +00001856 // If the left hand side is an extension, try eliminating it.
1857 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1858 if (CE1->getOpcode() == Instruction::SExt ||
1859 CE1->getOpcode() == Instruction::ZExt) {
1860 Constant *CE1Op0 = CE1->getOperand(0);
1861 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
1862 if (CE1Inverse == CE1Op0) {
1863 // Check whether we can safely truncate the right hand side.
1864 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
1865 if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
1866 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
1867 }
1868 }
1869 }
1870 }
1871
Eli Friedmane67cae32009-12-17 06:07:04 +00001872 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1873 (C1->isNullValue() && !C2->isNullValue())) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001874 // If C2 is a constant expr and C1 isn't, flip them around and fold the
Reid Spencer9d36acf2006-12-24 18:52:08 +00001875 // other way if possible.
Eli Friedmane67cae32009-12-17 06:07:04 +00001876 // Also, if C1 is null and C2 isn't, flip them around.
Reid Spencer9d36acf2006-12-24 18:52:08 +00001877 switch (pred) {
1878 case ICmpInst::ICMP_EQ:
1879 case ICmpInst::ICMP_NE:
1880 // No change of predicate required.
Eli Friedmane67cae32009-12-17 06:07:04 +00001881 return ConstantExpr::getICmp(pred, C2, C1);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001882
1883 case ICmpInst::ICMP_ULT:
1884 case ICmpInst::ICMP_SLT:
1885 case ICmpInst::ICMP_UGT:
1886 case ICmpInst::ICMP_SGT:
1887 case ICmpInst::ICMP_ULE:
1888 case ICmpInst::ICMP_SLE:
1889 case ICmpInst::ICMP_UGE:
1890 case ICmpInst::ICMP_SGE:
1891 // Change the predicate as necessary to swap the operands.
1892 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
Eli Friedmane67cae32009-12-17 06:07:04 +00001893 return ConstantExpr::getICmp(pred, C2, C1);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001894
1895 default: // These predicates cannot be flopped around.
1896 break;
1897 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001898 }
1899 }
1900 return 0;
Dan Gohman062d3782009-08-29 23:35:16 +00001901}
Chris Lattner1dd054c2004-01-12 22:07:24 +00001902
Dan Gohman21c62162009-09-11 00:04:14 +00001903/// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1904/// is "inbounds".
1905static bool isInBoundsIndices(Constant *const *Idxs, size_t NumIdx) {
1906 // No indices means nothing that could be out of bounds.
1907 if (NumIdx == 0) return true;
1908
1909 // If the first index is zero, it's in bounds.
1910 if (Idxs[0]->isNullValue()) return true;
1911
1912 // If the first index is one and all the rest are zero, it's in bounds,
1913 // by the one-past-the-end rule.
1914 if (!cast<ConstantInt>(Idxs[0])->isOne())
1915 return false;
1916 for (unsigned i = 1, e = NumIdx; i != e; ++i)
1917 if (!Idxs[i]->isNullValue())
1918 return false;
1919 return true;
1920}
1921
Owen Anderson53a52212009-07-13 04:09:18 +00001922Constant *llvm::ConstantFoldGetElementPtr(LLVMContext &Context,
Nick Lewyckye0332982009-09-20 01:35:59 +00001923 Constant *C,
Dan Gohman21c62162009-09-11 00:04:14 +00001924 bool inBounds,
David Greenec656cbb2007-09-04 15:46:09 +00001925 Constant* const *Idxs,
Owen Anderson0d2de8c2009-06-20 00:24:58 +00001926 unsigned NumIdx) {
Chris Lattner302116a2007-01-31 04:40:28 +00001927 if (NumIdx == 0 ||
1928 (NumIdx == 1 && Idxs[0]->isNullValue()))
Nick Lewyckye0332982009-09-20 01:35:59 +00001929 return C;
Chris Lattner1dd054c2004-01-12 22:07:24 +00001930
Chris Lattnerf6013752004-10-17 21:54:55 +00001931 if (isa<UndefValue>(C)) {
Christopher Lambedf07882007-12-17 01:12:55 +00001932 const PointerType *Ptr = cast<PointerType>(C->getType());
1933 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
David Greenec656cbb2007-09-04 15:46:09 +00001934 (Value **)Idxs,
Dan Gohman12fce772008-05-15 19:50:34 +00001935 (Value **)Idxs+NumIdx);
Chris Lattnerf6013752004-10-17 21:54:55 +00001936 assert(Ty != 0 && "Invalid indices for GEP!");
Owen Andersonb292b8c2009-07-30 23:03:37 +00001937 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
Chris Lattnerf6013752004-10-17 21:54:55 +00001938 }
1939
Chris Lattner302116a2007-01-31 04:40:28 +00001940 Constant *Idx0 = Idxs[0];
Chris Lattner04b60fe2004-02-16 20:46:13 +00001941 if (C->isNullValue()) {
1942 bool isNull = true;
Chris Lattner302116a2007-01-31 04:40:28 +00001943 for (unsigned i = 0, e = NumIdx; i != e; ++i)
1944 if (!Idxs[i]->isNullValue()) {
Chris Lattner04b60fe2004-02-16 20:46:13 +00001945 isNull = false;
1946 break;
1947 }
1948 if (isNull) {
Christopher Lambedf07882007-12-17 01:12:55 +00001949 const PointerType *Ptr = cast<PointerType>(C->getType());
1950 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
David Greenec656cbb2007-09-04 15:46:09 +00001951 (Value**)Idxs,
Dan Gohman12fce772008-05-15 19:50:34 +00001952 (Value**)Idxs+NumIdx);
Chris Lattner04b60fe2004-02-16 20:46:13 +00001953 assert(Ty != 0 && "Invalid indices for GEP!");
Owen Andersonb292b8c2009-07-30 23:03:37 +00001954 return ConstantPointerNull::get(
Owen Anderson4056ca92009-07-29 22:17:13 +00001955 PointerType::get(Ty,Ptr->getAddressSpace()));
Chris Lattner04b60fe2004-02-16 20:46:13 +00001956 }
1957 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00001958
Nick Lewyckye0332982009-09-20 01:35:59 +00001959 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner1dd054c2004-01-12 22:07:24 +00001960 // Combine Indices - If the source pointer to this getelementptr instruction
1961 // is a getelementptr instruction, combine the indices of the two
1962 // getelementptr instructions into a single instruction.
1963 //
1964 if (CE->getOpcode() == Instruction::GetElementPtr) {
1965 const Type *LastTy = 0;
1966 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1967 I != E; ++I)
1968 LastTy = *I;
1969
Chris Lattner13128ab2004-10-11 22:52:25 +00001970 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
Chris Lattner302116a2007-01-31 04:40:28 +00001971 SmallVector<Value*, 16> NewIndices;
1972 NewIndices.reserve(NumIdx + CE->getNumOperands());
Chris Lattner1dd054c2004-01-12 22:07:24 +00001973 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
Chris Lattner13128ab2004-10-11 22:52:25 +00001974 NewIndices.push_back(CE->getOperand(i));
Chris Lattner1dd054c2004-01-12 22:07:24 +00001975
1976 // Add the last index of the source with the first index of the new GEP.
1977 // Make sure to handle the case when they are actually different types.
1978 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
Chris Lattner13128ab2004-10-11 22:52:25 +00001979 // Otherwise it must be an array.
1980 if (!Idx0->isNullValue()) {
Chris Lattner71068a02004-07-07 04:45:13 +00001981 const Type *IdxTy = Combined->getType();
Reid Spencer1a063892006-12-04 02:46:44 +00001982 if (IdxTy != Idx0->getType()) {
Owen Anderson53a52212009-07-13 04:09:18 +00001983 Constant *C1 =
Owen Anderson55f1c092009-08-13 21:58:54 +00001984 ConstantExpr::getSExtOrBitCast(Idx0, Type::getInt64Ty(Context));
Owen Anderson487375e2009-07-29 18:55:55 +00001985 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
Owen Anderson55f1c092009-08-13 21:58:54 +00001986 Type::getInt64Ty(Context));
Owen Anderson487375e2009-07-29 18:55:55 +00001987 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
Reid Spencer1a063892006-12-04 02:46:44 +00001988 } else {
1989 Combined =
Owen Anderson487375e2009-07-29 18:55:55 +00001990 ConstantExpr::get(Instruction::Add, Idx0, Combined);
Reid Spencer1a063892006-12-04 02:46:44 +00001991 }
Chris Lattner71068a02004-07-07 04:45:13 +00001992 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001993
Chris Lattner1dd054c2004-01-12 22:07:24 +00001994 NewIndices.push_back(Combined);
Chris Lattner302116a2007-01-31 04:40:28 +00001995 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
Dan Gohman21c62162009-09-11 00:04:14 +00001996 return (inBounds && cast<GEPOperator>(CE)->isInBounds()) ?
1997 ConstantExpr::getInBoundsGetElementPtr(CE->getOperand(0),
1998 &NewIndices[0],
1999 NewIndices.size()) :
2000 ConstantExpr::getGetElementPtr(CE->getOperand(0),
2001 &NewIndices[0],
2002 NewIndices.size());
Chris Lattner1dd054c2004-01-12 22:07:24 +00002003 }
2004 }
2005
2006 // Implement folding of:
2007 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
2008 // long 0, long 0)
2009 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
2010 //
Chris Lattneraadc7782007-08-13 17:09:08 +00002011 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002012 if (const PointerType *SPT =
Chris Lattner1dd054c2004-01-12 22:07:24 +00002013 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
2014 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
2015 if (const ArrayType *CAT =
Chris Lattner02157b02006-06-28 21:38:54 +00002016 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
Chris Lattner1dd054c2004-01-12 22:07:24 +00002017 if (CAT->getElementType() == SAT->getElementType())
Dan Gohman21c62162009-09-11 00:04:14 +00002018 return inBounds ?
2019 ConstantExpr::getInBoundsGetElementPtr(
2020 (Constant*)CE->getOperand(0), Idxs, NumIdx) :
2021 ConstantExpr::getGetElementPtr(
Owen Anderson0d2de8c2009-06-20 00:24:58 +00002022 (Constant*)CE->getOperand(0), Idxs, NumIdx);
Chris Lattneraadc7782007-08-13 17:09:08 +00002023 }
Dan Gohman062d3782009-08-29 23:35:16 +00002024
Chris Lattneraadc7782007-08-13 17:09:08 +00002025 // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
2026 // Into: inttoptr (i64 0 to i8*)
2027 // This happens with pointers to member functions in C++.
2028 if (CE->getOpcode() == Instruction::IntToPtr && NumIdx == 1 &&
2029 isa<ConstantInt>(CE->getOperand(0)) && isa<ConstantInt>(Idxs[0]) &&
Chris Lattnerfdd87902009-10-05 05:54:46 +00002030 cast<PointerType>(CE->getType())->getElementType() ==
2031 Type::getInt8Ty(Context)) {
Chris Lattneraadc7782007-08-13 17:09:08 +00002032 Constant *Base = CE->getOperand(0);
2033 Constant *Offset = Idxs[0];
Dan Gohman062d3782009-08-29 23:35:16 +00002034
Chris Lattneraadc7782007-08-13 17:09:08 +00002035 // Convert the smaller integer to the larger type.
2036 if (Offset->getType()->getPrimitiveSizeInBits() <
2037 Base->getType()->getPrimitiveSizeInBits())
Owen Anderson487375e2009-07-29 18:55:55 +00002038 Offset = ConstantExpr::getSExt(Offset, Base->getType());
Chris Lattneraadc7782007-08-13 17:09:08 +00002039 else if (Base->getType()->getPrimitiveSizeInBits() <
2040 Offset->getType()->getPrimitiveSizeInBits())
Owen Anderson487375e2009-07-29 18:55:55 +00002041 Base = ConstantExpr::getZExt(Base, Offset->getType());
Dan Gohman062d3782009-08-29 23:35:16 +00002042
Owen Anderson487375e2009-07-29 18:55:55 +00002043 Base = ConstantExpr::getAdd(Base, Offset);
2044 return ConstantExpr::getIntToPtr(Base, CE->getType());
Chris Lattneraadc7782007-08-13 17:09:08 +00002045 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00002046 }
Dan Gohman21c62162009-09-11 00:04:14 +00002047
2048 // Check to see if any array indices are not within the corresponding
2049 // notional array bounds. If so, try to determine if they can be factored
2050 // out into preceding dimensions.
2051 bool Unknown = false;
2052 SmallVector<Constant *, 8> NewIdxs;
2053 const Type *Ty = C->getType();
2054 const Type *Prev = 0;
2055 for (unsigned i = 0; i != NumIdx;
2056 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2057 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2058 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2059 if (ATy->getNumElements() <= INT64_MAX &&
2060 ATy->getNumElements() != 0 &&
2061 CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2062 if (isa<SequentialType>(Prev)) {
2063 // It's out of range, but we can factor it into the prior
2064 // dimension.
2065 NewIdxs.resize(NumIdx);
2066 ConstantInt *Factor = ConstantInt::get(CI->getType(),
2067 ATy->getNumElements());
2068 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2069
2070 Constant *PrevIdx = Idxs[i-1];
2071 Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2072
2073 // Before adding, extend both operands to i64 to avoid
2074 // overflow trouble.
Benjamin Kramerd2564e32010-01-05 21:05:54 +00002075 if (!PrevIdx->getType()->isInteger(64))
Dan Gohman21c62162009-09-11 00:04:14 +00002076 PrevIdx = ConstantExpr::getSExt(PrevIdx,
2077 Type::getInt64Ty(Context));
Benjamin Kramerd2564e32010-01-05 21:05:54 +00002078 if (!Div->getType()->isInteger(64))
Dan Gohman21c62162009-09-11 00:04:14 +00002079 Div = ConstantExpr::getSExt(Div,
2080 Type::getInt64Ty(Context));
2081
2082 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2083 } else {
2084 // It's out of range, but the prior dimension is a struct
2085 // so we can't do anything about it.
2086 Unknown = true;
2087 }
2088 }
2089 } else {
2090 // We don't know if it's in range or not.
2091 Unknown = true;
2092 }
2093 }
2094
2095 // If we did any factoring, start over with the adjusted indices.
2096 if (!NewIdxs.empty()) {
2097 for (unsigned i = 0; i != NumIdx; ++i)
2098 if (!NewIdxs[i]) NewIdxs[i] = Idxs[i];
2099 return inBounds ?
Nick Lewyckye0332982009-09-20 01:35:59 +00002100 ConstantExpr::getInBoundsGetElementPtr(C, NewIdxs.data(),
2101 NewIdxs.size()) :
2102 ConstantExpr::getGetElementPtr(C, NewIdxs.data(), NewIdxs.size());
Dan Gohman21c62162009-09-11 00:04:14 +00002103 }
2104
2105 // If all indices are known integers and normalized, we can do a simple
2106 // check for the "inbounds" property.
2107 if (!Unknown && !inBounds &&
2108 isa<GlobalVariable>(C) && isInBoundsIndices(Idxs, NumIdx))
Nick Lewyckye0332982009-09-20 01:35:59 +00002109 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs, NumIdx);
Dan Gohman21c62162009-09-11 00:04:14 +00002110
Chris Lattner1dd054c2004-01-12 22:07:24 +00002111 return 0;
2112}