blob: 47244a0e323973962e93aa654b1f50be9b8fbcae [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"
Chris Lattner302116a2007-01-31 04:40:28 +000027#include "llvm/ADT/SmallVector.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000028#include "llvm/Support/Compiler.h"
Torok Edwin56d06592009-07-11 20:10:48 +000029#include "llvm/Support/ErrorHandling.h"
Chris Lattner057083f2006-10-13 17:22:21 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
31#include "llvm/Support/ManagedStatic.h"
32#include "llvm/Support/MathExtras.h"
Jeff Cohen4e3aede2005-05-03 03:13:01 +000033#include <limits>
Chris Lattner9d9cbcf2003-11-17 19:05:17 +000034using namespace llvm;
Chris Lattner61607ee2001-09-09 21:01:20 +000035
Chris Lattner1dd054c2004-01-12 22:07:24 +000036//===----------------------------------------------------------------------===//
37// ConstantFold*Instruction Implementations
38//===----------------------------------------------------------------------===//
Chris Lattner1dd054c2004-01-12 22:07:24 +000039
Chris Lattner5c6399e2007-12-11 06:07:39 +000040/// BitCastConstantVector - Convert the specified ConstantVector node to the
Reid Spencer09575ba2007-02-15 03:39:18 +000041/// specified vector type. At this point, we know that the elements of the
Dan Gohman06c60b62007-07-16 14:29:03 +000042/// input vector constant are all simple integer or FP values.
Chris Lattnerf5edeeb2010-02-01 20:48:08 +000043static Constant *BitCastConstantVector(ConstantVector *CV,
Owen Anderson0d2de8c2009-06-20 00:24:58 +000044 const VectorType *DstTy) {
Chris Lattner5c6399e2007-12-11 06:07:39 +000045 // If this cast changes element count then we can't handle it here:
46 // doing so requires endianness information. This should be handled by
47 // Analysis/ConstantFolding.cpp
48 unsigned NumElts = DstTy->getNumElements();
49 if (NumElts != CV->getNumOperands())
50 return 0;
Dan Gohman062d3782009-08-29 23:35:16 +000051
Chris Lattner5c6399e2007-12-11 06:07:39 +000052 // Check to verify that all elements of the input are simple.
53 for (unsigned i = 0; i != NumElts; ++i) {
54 if (!isa<ConstantInt>(CV->getOperand(i)) &&
55 !isa<ConstantFP>(CV->getOperand(i)))
56 return 0;
Chris Lattner6b3f4752006-04-02 01:38:28 +000057 }
Chris Lattner5c6399e2007-12-11 06:07:39 +000058
59 // Bitcast each element now.
60 std::vector<Constant*> Result;
61 const Type *DstEltTy = DstTy->getElementType();
62 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson487375e2009-07-29 18:55:55 +000063 Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i),
Owen Anderson53a52212009-07-13 04:09:18 +000064 DstEltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +000065 return ConstantVector::get(Result);
Chris Lattner6b3f4752006-04-02 01:38:28 +000066}
67
Reid Spencer6c38f0b2006-11-27 01:05:10 +000068/// This function determines which opcode to use to fold two constant cast
69/// expressions together. It uses CastInst::isEliminableCastPair to determine
70/// the opcode. Consequently its just a wrapper around that function.
Reid Spencer05d55b32007-08-05 19:27:01 +000071/// @brief Determine if it is valid to fold a cast of a cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +000072static unsigned
73foldConstantCastPair(
74 unsigned opc, ///< opcode of the second cast constant expression
Nick Lewyckye0332982009-09-20 01:35:59 +000075 ConstantExpr *Op, ///< the first cast constant expression
Reid Spencer6c38f0b2006-11-27 01:05:10 +000076 const Type *DstTy ///< desintation type of the first cast
77) {
78 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
79 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
80 assert(CastInst::isCast(opc) && "Invalid cast opcode");
Dan Gohman062d3782009-08-29 23:35:16 +000081
Reid Spencer6c38f0b2006-11-27 01:05:10 +000082 // The the types and opcodes for the two Cast constant expressions
83 const Type *SrcTy = Op->getOperand(0)->getType();
84 const Type *MidTy = Op->getType();
85 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
86 Instruction::CastOps secondOp = Instruction::CastOps(opc);
Chris Lattner6b3f4752006-04-02 01:38:28 +000087
Reid Spencer6c38f0b2006-11-27 01:05:10 +000088 // Let CastInst::isEliminableCastPair do the heavy lifting.
89 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
Owen Anderson55f1c092009-08-13 21:58:54 +000090 Type::getInt64Ty(DstTy->getContext()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +000091}
92
Chris Lattnerf5edeeb2010-02-01 20:48:08 +000093static Constant *FoldBitCast(Constant *V, const Type *DestTy) {
Chris Lattnere8ea0372007-12-11 05:55:02 +000094 const Type *SrcTy = V->getType();
95 if (SrcTy == DestTy)
96 return V; // no-op cast
Dan Gohman062d3782009-08-29 23:35:16 +000097
Chris Lattnere8ea0372007-12-11 05:55:02 +000098 // Check to see if we are casting a pointer to an aggregate to a pointer to
99 // the first element. If so, return the appropriate GEP instruction.
100 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000101 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy))
102 if (PTy->getAddressSpace() == DPTy->getAddressSpace()) {
103 SmallVector<Value*, 8> IdxList;
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000104 Value *Zero =
105 Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
Dan Gohman76733742009-08-12 00:32:55 +0000106 IdxList.push_back(Zero);
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000107 const Type *ElTy = PTy->getElementType();
108 while (ElTy != DPTy->getElementType()) {
109 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
110 if (STy->getNumElements() == 0) break;
111 ElTy = STy->getElementType(0);
Dan Gohman76733742009-08-12 00:32:55 +0000112 IdxList.push_back(Zero);
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000113 } else if (const SequentialType *STy =
114 dyn_cast<SequentialType>(ElTy)) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000115 if (ElTy->isPointerTy()) break; // Can't index into pointers!
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000116 ElTy = STy->getElementType();
Dan Gohman76733742009-08-12 00:32:55 +0000117 IdxList.push_back(Zero);
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000118 } else {
119 break;
120 }
Chris Lattnere8ea0372007-12-11 05:55:02 +0000121 }
Dan Gohman062d3782009-08-29 23:35:16 +0000122
Nate Begemanf2b0b0e2008-03-31 00:22:16 +0000123 if (ElTy == DPTy->getElementType())
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000124 // This GEP is inbounds because all indices are zero.
125 return ConstantExpr::getInBoundsGetElementPtr(V, &IdxList[0],
126 IdxList.size());
Chris Lattnere8ea0372007-12-11 05:55:02 +0000127 }
Dan Gohman062d3782009-08-29 23:35:16 +0000128
Chris Lattnere8ea0372007-12-11 05:55:02 +0000129 // Handle casts from one vector constant to another. We know that the src
130 // and dest type have the same size (otherwise its an illegal cast).
131 if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
132 if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
133 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
134 "Not cast between same sized vectors!");
Devang Pateld26344d2008-11-03 23:20:04 +0000135 SrcTy = NULL;
Chris Lattnere8ea0372007-12-11 05:55:02 +0000136 // First, check for null. Undef is already handled.
137 if (isa<ConstantAggregateZero>(V))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000138 return Constant::getNullValue(DestTy);
Dan Gohman062d3782009-08-29 23:35:16 +0000139
Chris Lattner5c6399e2007-12-11 06:07:39 +0000140 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000141 return BitCastConstantVector(CV, DestPTy);
Chris Lattnere8ea0372007-12-11 05:55:02 +0000142 }
Chris Lattner1baace02008-10-16 05:26:51 +0000143
144 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
145 // This allows for other simplifications (although some of them
146 // can only be handled by Analysis/ConstantFolding.cpp).
147 if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000148 return ConstantExpr::getBitCast(ConstantVector::get(&V, 1), DestPTy);
Chris Lattnere8ea0372007-12-11 05:55:02 +0000149 }
Dan Gohman062d3782009-08-29 23:35:16 +0000150
Chris Lattnere8ea0372007-12-11 05:55:02 +0000151 // Finally, implement bitcast folding now. The code below doesn't handle
152 // bitcast right.
153 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
Owen Andersonb292b8c2009-07-30 23:03:37 +0000154 return ConstantPointerNull::get(cast<PointerType>(DestTy));
Dan Gohman062d3782009-08-29 23:35:16 +0000155
Chris Lattnere8ea0372007-12-11 05:55:02 +0000156 // Handle integral constant input.
Nick Lewyckye0332982009-09-20 01:35:59 +0000157 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Duncan Sands9dff9be2010-02-15 16:12:20 +0000158 if (DestTy->isIntegerTy())
Chris Lattnere8ea0372007-12-11 05:55:02 +0000159 // Integral -> Integral. This is a no-op because the bit widths must
160 // be the same. Consequently, we just fold to V.
161 return V;
Duncan Sands1ea11732009-02-04 10:17:14 +0000162
Duncan Sands9dff9be2010-02-15 16:12:20 +0000163 if (DestTy->isFloatingPointTy())
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000164 return ConstantFP::get(DestTy->getContext(),
165 APFloat(CI->getValue(),
166 !DestTy->isPPC_FP128Ty()));
Duncan Sands1ea11732009-02-04 10:17:14 +0000167
Chris Lattnere8ea0372007-12-11 05:55:02 +0000168 // Otherwise, can't fold this (vector?)
169 return 0;
170 }
Duncan Sandse7d54792009-02-04 11:17:06 +0000171
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000172 // Handle ConstantFP input: FP -> Integral.
Nick Lewyckye0332982009-09-20 01:35:59 +0000173 if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000174 return ConstantInt::get(FP->getContext(),
175 FP->getValueAPF().bitcastToAPInt());
Duncan Sandse7d54792009-02-04 11:17:06 +0000176
Chris Lattnere8ea0372007-12-11 05:55:02 +0000177 return 0;
178}
179
180
Chris Lattnerf67d2972009-10-17 21:53:27 +0000181/// ExtractConstantBytes - V is an integer constant which only has a subset of
182/// its bytes used. The bytes used are indicated by ByteStart (which is the
183/// first byte used, counting from the least significant byte) and ByteSize,
184/// which is the number of bytes used.
185///
186/// This function analyzes the specified constant to see if the specified byte
187/// range can be returned as a simplified constant. If so, the constant is
188/// returned, otherwise null is returned.
189///
190static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
191 unsigned ByteSize) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000192 assert(C->getType()->isIntegerTy() &&
Chris Lattnerf67d2972009-10-17 21:53:27 +0000193 (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
194 "Non-byte sized integer input");
195 unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
196 assert(ByteSize && "Must be accessing some piece");
197 assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
198 assert(ByteSize != CSize && "Should not extract everything");
199
200 // Constant Integers are simple.
201 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
202 APInt V = CI->getValue();
203 if (ByteStart)
204 V = V.lshr(ByteStart*8);
205 V.trunc(ByteSize*8);
206 return ConstantInt::get(CI->getContext(), V);
207 }
208
209 // In the input is a constant expr, we might be able to recursively simplify.
210 // If not, we definitely can't do anything.
211 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
212 if (CE == 0) return 0;
213
214 switch (CE->getOpcode()) {
215 default: return 0;
216 case Instruction::Or: {
Chris Lattnera91a5632009-10-28 05:14:34 +0000217 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000218 if (RHS == 0)
219 return 0;
220
221 // X | -1 -> -1.
222 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
223 if (RHSC->isAllOnesValue())
224 return RHSC;
225
Chris Lattnera91a5632009-10-28 05:14:34 +0000226 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000227 if (LHS == 0)
228 return 0;
229 return ConstantExpr::getOr(LHS, RHS);
230 }
231 case Instruction::And: {
Chris Lattnera91a5632009-10-28 05:14:34 +0000232 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000233 if (RHS == 0)
234 return 0;
235
236 // X & 0 -> 0.
237 if (RHS->isNullValue())
238 return RHS;
239
Chris Lattnera91a5632009-10-28 05:14:34 +0000240 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000241 if (LHS == 0)
242 return 0;
243 return ConstantExpr::getAnd(LHS, RHS);
244 }
245 case Instruction::LShr: {
246 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
247 if (Amt == 0)
248 return 0;
249 unsigned ShAmt = Amt->getZExtValue();
250 // Cannot analyze non-byte shifts.
251 if ((ShAmt & 7) != 0)
252 return 0;
253 ShAmt >>= 3;
254
255 // If the extract is known to be all zeros, return zero.
256 if (ByteStart >= CSize-ShAmt)
257 return Constant::getNullValue(IntegerType::get(CE->getContext(),
258 ByteSize*8));
259 // If the extract is known to be fully in the input, extract it.
260 if (ByteStart+ByteSize+ShAmt <= CSize)
Chris Lattnera91a5632009-10-28 05:14:34 +0000261 return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000262
263 // TODO: Handle the 'partially zero' case.
264 return 0;
265 }
266
267 case Instruction::Shl: {
268 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
269 if (Amt == 0)
270 return 0;
271 unsigned ShAmt = Amt->getZExtValue();
272 // Cannot analyze non-byte shifts.
273 if ((ShAmt & 7) != 0)
274 return 0;
275 ShAmt >>= 3;
276
277 // If the extract is known to be all zeros, return zero.
278 if (ByteStart+ByteSize <= ShAmt)
279 return Constant::getNullValue(IntegerType::get(CE->getContext(),
280 ByteSize*8));
281 // If the extract is known to be fully in the input, extract it.
282 if (ByteStart >= ShAmt)
Chris Lattnera91a5632009-10-28 05:14:34 +0000283 return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000284
285 // TODO: Handle the 'partially zero' case.
286 return 0;
287 }
288
289 case Instruction::ZExt: {
290 unsigned SrcBitSize =
Chris Lattnera91a5632009-10-28 05:14:34 +0000291 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
Chris Lattnerf67d2972009-10-17 21:53:27 +0000292
293 // If extracting something that is completely zero, return 0.
294 if (ByteStart*8 >= SrcBitSize)
295 return Constant::getNullValue(IntegerType::get(CE->getContext(),
296 ByteSize*8));
297
298 // If exactly extracting the input, return it.
299 if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
Chris Lattnera91a5632009-10-28 05:14:34 +0000300 return CE->getOperand(0);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000301
302 // If extracting something completely in the input, if if the input is a
303 // multiple of 8 bits, recurse.
304 if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
Chris Lattnera91a5632009-10-28 05:14:34 +0000305 return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000306
307 // Otherwise, if extracting a subset of the input, which is not multiple of
308 // 8 bits, do a shift and trunc to get the bits.
309 if ((ByteStart+ByteSize)*8 < SrcBitSize) {
310 assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
Chris Lattnera91a5632009-10-28 05:14:34 +0000311 Constant *Res = CE->getOperand(0);
Chris Lattnerf67d2972009-10-17 21:53:27 +0000312 if (ByteStart)
313 Res = ConstantExpr::getLShr(Res,
314 ConstantInt::get(Res->getType(), ByteStart*8));
315 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
316 ByteSize*8));
317 }
318
319 // TODO: Handle the 'partially zero' case.
320 return 0;
321 }
322 }
323}
324
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000325/// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
326/// on Ty, with any known factors factored out. If Folded is false,
327/// return null if no factoring was possible, to avoid endlessly
328/// bouncing an unfoldable expression back into the top-level folder.
329///
330static Constant *getFoldedSizeOf(const Type *Ty, const Type *DestTy,
331 bool Folded) {
332 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
333 Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
334 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
335 return ConstantExpr::getNUWMul(E, N);
336 }
Dan Gohman935faff2010-02-25 16:05:33 +0000337
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000338 if (const StructType *STy = dyn_cast<StructType>(Ty))
339 if (!STy->isPacked()) {
340 unsigned NumElems = STy->getNumElements();
341 // An empty struct has size zero.
342 if (NumElems == 0)
343 return ConstantExpr::getNullValue(DestTy);
Dan Gohmanf644af8b2010-02-02 01:41:39 +0000344 // Check for a struct with all members having the same size.
345 Constant *MemberSize =
346 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000347 bool AllSame = true;
348 for (unsigned i = 1; i != NumElems; ++i)
Dan Gohmanf644af8b2010-02-02 01:41:39 +0000349 if (MemberSize !=
350 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000351 AllSame = false;
352 break;
353 }
354 if (AllSame) {
355 Constant *N = ConstantInt::get(DestTy, NumElems);
Dan Gohmanf644af8b2010-02-02 01:41:39 +0000356 return ConstantExpr::getNUWMul(MemberSize, N);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000357 }
358 }
359
Dan Gohmana2684db2010-02-25 16:45:19 +0000360 if (const UnionType *UTy = dyn_cast<UnionType>(Ty)) {
361 unsigned NumElems = UTy->getNumElements();
362 // Check for a union with all members having the same size.
363 Constant *MemberSize =
364 getFoldedSizeOf(UTy->getElementType(0), DestTy, true);
365 bool AllSame = true;
366 for (unsigned i = 1; i != NumElems; ++i)
367 if (MemberSize !=
368 getFoldedSizeOf(UTy->getElementType(i), DestTy, true)) {
369 AllSame = false;
370 break;
371 }
372 if (AllSame)
373 return MemberSize;
374 }
375
Dan Gohman183a4232010-02-10 06:13:07 +0000376 // Pointer size doesn't depend on the pointee type, so canonicalize them
377 // to an arbitrary pointee.
378 if (const PointerType *PTy = dyn_cast<PointerType>(Ty))
Duncan Sands9dff9be2010-02-15 16:12:20 +0000379 if (!PTy->getElementType()->isIntegerTy(1))
Dan Gohman183a4232010-02-10 06:13:07 +0000380 return
381 getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
382 PTy->getAddressSpace()),
383 DestTy, true);
384
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000385 // If there's no interesting folding happening, bail so that we don't create
386 // a constant that looks like it needs folding but really doesn't.
387 if (!Folded)
388 return 0;
389
390 // Base case: Get a regular sizeof expression.
391 Constant *C = ConstantExpr::getSizeOf(Ty);
392 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
393 DestTy, false),
394 C, DestTy);
395 return C;
396}
397
Dan Gohmanf644af8b2010-02-02 01:41:39 +0000398/// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
399/// on Ty, with any known factors factored out. If Folded is false,
400/// return null if no factoring was possible, to avoid endlessly
401/// bouncing an unfoldable expression back into the top-level folder.
402///
403static Constant *getFoldedAlignOf(const Type *Ty, const Type *DestTy,
404 bool Folded) {
405 // The alignment of an array is equal to the alignment of the
406 // array element. Note that this is not always true for vectors.
407 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
408 Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
409 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
410 DestTy,
411 false),
412 C, DestTy);
413 return C;
414 }
415
416 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
417 // Packed structs always have an alignment of 1.
418 if (STy->isPacked())
419 return ConstantInt::get(DestTy, 1);
420
421 // Otherwise, struct alignment is the maximum alignment of any member.
422 // Without target data, we can't compare much, but we can check to see
423 // if all the members have the same alignment.
424 unsigned NumElems = STy->getNumElements();
425 // An empty struct has minimal alignment.
426 if (NumElems == 0)
427 return ConstantInt::get(DestTy, 1);
428 // Check for a struct with all members having the same alignment.
429 Constant *MemberAlign =
430 getFoldedAlignOf(STy->getElementType(0), DestTy, true);
431 bool AllSame = true;
432 for (unsigned i = 1; i != NumElems; ++i)
433 if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
434 AllSame = false;
435 break;
436 }
437 if (AllSame)
438 return MemberAlign;
439 }
440
Dan Gohmana2684db2010-02-25 16:45:19 +0000441 if (const UnionType *UTy = dyn_cast<UnionType>(Ty)) {
442 // Union alignment is the maximum alignment of any member.
443 // Without target data, we can't compare much, but we can check to see
444 // if all the members have the same alignment.
445 unsigned NumElems = UTy->getNumElements();
446 // Check for a union with all members having the same alignment.
447 Constant *MemberAlign =
448 getFoldedAlignOf(UTy->getElementType(0), DestTy, true);
449 bool AllSame = true;
450 for (unsigned i = 1; i != NumElems; ++i)
451 if (MemberAlign != getFoldedAlignOf(UTy->getElementType(i), DestTy, true)) {
452 AllSame = false;
453 break;
454 }
455 if (AllSame)
456 return MemberAlign;
457 }
458
Dan Gohman183a4232010-02-10 06:13:07 +0000459 // Pointer alignment doesn't depend on the pointee type, so canonicalize them
460 // to an arbitrary pointee.
461 if (const PointerType *PTy = dyn_cast<PointerType>(Ty))
Duncan Sands9dff9be2010-02-15 16:12:20 +0000462 if (!PTy->getElementType()->isIntegerTy(1))
Dan Gohman183a4232010-02-10 06:13:07 +0000463 return
464 getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
465 1),
466 PTy->getAddressSpace()),
467 DestTy, true);
468
Dan Gohmanf644af8b2010-02-02 01:41:39 +0000469 // If there's no interesting folding happening, bail so that we don't create
470 // a constant that looks like it needs folding but really doesn't.
471 if (!Folded)
472 return 0;
473
474 // Base case: Get a regular alignof expression.
475 Constant *C = ConstantExpr::getAlignOf(Ty);
476 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
477 DestTy, false),
478 C, DestTy);
479 return C;
480}
481
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000482/// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
483/// on Ty and FieldNo, with any known factors factored out. If Folded is false,
484/// return null if no factoring was possible, to avoid endlessly
485/// bouncing an unfoldable expression back into the top-level folder.
486///
487static Constant *getFoldedOffsetOf(const Type *Ty, Constant *FieldNo,
488 const Type *DestTy,
489 bool Folded) {
490 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
491 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
492 DestTy, false),
493 FieldNo, DestTy);
494 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
495 return ConstantExpr::getNUWMul(E, N);
496 }
Dan Gohman935faff2010-02-25 16:05:33 +0000497
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000498 if (const StructType *STy = dyn_cast<StructType>(Ty))
499 if (!STy->isPacked()) {
500 unsigned NumElems = STy->getNumElements();
501 // An empty struct has no members.
502 if (NumElems == 0)
503 return 0;
Dan Gohmanf644af8b2010-02-02 01:41:39 +0000504 // Check for a struct with all members having the same size.
505 Constant *MemberSize =
506 getFoldedSizeOf(STy->getElementType(0), DestTy, true);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000507 bool AllSame = true;
508 for (unsigned i = 1; i != NumElems; ++i)
Dan Gohmanf644af8b2010-02-02 01:41:39 +0000509 if (MemberSize !=
510 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000511 AllSame = false;
512 break;
513 }
514 if (AllSame) {
515 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
516 false,
517 DestTy,
518 false),
519 FieldNo, DestTy);
Dan Gohmanf644af8b2010-02-02 01:41:39 +0000520 return ConstantExpr::getNUWMul(MemberSize, N);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000521 }
522 }
523
524 // If there's no interesting folding happening, bail so that we don't create
525 // a constant that looks like it needs folding but really doesn't.
526 if (!Folded)
527 return 0;
528
529 // Base case: Get a regular offsetof expression.
530 Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
531 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
532 DestTy, false),
533 C, DestTy);
534 return C;
535}
Chris Lattnerf67d2972009-10-17 21:53:27 +0000536
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000537Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
Owen Anderson0d2de8c2009-06-20 00:24:58 +0000538 const Type *DestTy) {
Chris Lattner363485d2007-07-20 22:09:02 +0000539 if (isa<UndefValue>(V)) {
540 // zext(undef) = 0, because the top bits will be zero.
541 // sext(undef) = 0, because the top bits will all be the same.
Chris Lattnerb4c6cc92008-02-19 06:22:12 +0000542 // [us]itofp(undef) = 0, because the result value is bounded.
543 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
544 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
Owen Anderson5a1acd92009-07-31 20:28:14 +0000545 return Constant::getNullValue(DestTy);
Owen Andersonb292b8c2009-07-30 23:03:37 +0000546 return UndefValue::get(DestTy);
Chris Lattner363485d2007-07-20 22:09:02 +0000547 }
Dale Johannesen19db0932007-10-14 01:56:47 +0000548 // No compile-time operations on this type yet.
Chris Lattnerfdd87902009-10-05 05:54:46 +0000549 if (V->getType()->isPPC_FP128Ty() || DestTy->isPPC_FP128Ty())
Dale Johannesen19db0932007-10-14 01:56:47 +0000550 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000551
552 // If the cast operand is a constant expression, there's a few things we can
553 // do to try to simplify it.
Nick Lewyckye0332982009-09-20 01:35:59 +0000554 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000555 if (CE->isCast()) {
Reid Spencer1a063892006-12-04 02:46:44 +0000556 // Try hard to fold cast of cast because they are often eliminable.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000557 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
Owen Anderson487375e2009-07-29 18:55:55 +0000558 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
Chris Lattner1dd054c2004-01-12 22:07:24 +0000559 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
560 // If all of the indexes in the GEP are null values, there is no pointer
561 // adjustment going on. We might as well cast the source pointer.
562 bool isAllNull = true;
563 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
564 if (!CE->getOperand(i)->isNullValue()) {
565 isAllNull = false;
566 break;
567 }
568 if (isAllNull)
Reid Spencer1a063892006-12-04 02:46:44 +0000569 // This is casting one pointer type to another, always BitCast
Owen Anderson487375e2009-07-29 18:55:55 +0000570 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
Chris Lattner1dd054c2004-01-12 22:07:24 +0000571 }
Chris Lattnerfd7bf722004-10-16 23:31:32 +0000572 }
Chris Lattner1dd054c2004-01-12 22:07:24 +0000573
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000574 // If the cast operand is a constant vector, perform the cast by
575 // operating on each element. In the cast of bitcasts, the element
576 // count may be mismatched; don't attempt to handle that here.
Nick Lewyckye0332982009-09-20 01:35:59 +0000577 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
Duncan Sands19d0b472010-02-16 11:11:14 +0000578 if (DestTy->isVectorTy() &&
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000579 cast<VectorType>(DestTy)->getNumElements() ==
580 CV->getType()->getNumElements()) {
581 std::vector<Constant*> res;
582 const VectorType *DestVecTy = cast<VectorType>(DestTy);
583 const Type *DstEltTy = DestVecTy->getElementType();
584 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
Owen Anderson487375e2009-07-29 18:55:55 +0000585 res.push_back(ConstantExpr::getCast(opc,
Owen Anderson0d2de8c2009-06-20 00:24:58 +0000586 CV->getOperand(i), DstEltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +0000587 return ConstantVector::get(DestVecTy, res);
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000588 }
589
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000590 // We actually have to do a cast now. Perform the cast according to the
591 // opcode specified.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000592 switch (opc) {
Chris Lattnerf67d2972009-10-17 21:53:27 +0000593 default:
594 llvm_unreachable("Failed to cast constant expression");
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000595 case Instruction::FPTrunc:
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000596 case Instruction::FPExt:
Nick Lewyckye0332982009-09-20 01:35:59 +0000597 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000598 bool ignored;
Dale Johannesenf4bad972007-09-19 14:22:58 +0000599 APFloat Val = FPC->getValueAPF();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000600 Val.convert(DestTy->isFloatTy() ? APFloat::IEEEsingle :
601 DestTy->isDoubleTy() ? APFloat::IEEEdouble :
602 DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
603 DestTy->isFP128Ty() ? APFloat::IEEEquad :
Dale Johannesenf4bad972007-09-19 14:22:58 +0000604 APFloat::Bogus,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000605 APFloat::rmNearestTiesToEven, &ignored);
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000606 return ConstantFP::get(V->getContext(), Val);
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000607 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000608 return 0; // Can't fold.
609 case Instruction::FPToUI:
Reid Spencer8dabca42006-12-19 07:41:40 +0000610 case Instruction::FPToSI:
Nick Lewyckye0332982009-09-20 01:35:59 +0000611 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
Chris Lattner2b827fd2007-10-15 05:34:10 +0000612 const APFloat &V = FPC->getValueAPF();
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000613 bool ignored;
Dale Johannesenf4bad972007-09-19 14:22:58 +0000614 uint64_t x[2];
Reid Spencer81658a82007-02-27 06:23:51 +0000615 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
Dale Johannesen17663f42007-09-25 23:32:20 +0000616 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000617 APFloat::rmTowardZero, &ignored);
Dale Johannesenf4bad972007-09-19 14:22:58 +0000618 APInt Val(DestBitWidth, 2, x);
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000619 return ConstantInt::get(FPC->getContext(), Val);
Reid Spencer81658a82007-02-27 06:23:51 +0000620 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000621 return 0; // Can't fold.
622 case Instruction::IntToPtr: //always treated as unsigned
623 if (V->isNullValue()) // Is it an integral null value?
Owen Andersonb292b8c2009-07-30 23:03:37 +0000624 return ConstantPointerNull::get(cast<PointerType>(DestTy));
Reid Spencer8dabca42006-12-19 07:41:40 +0000625 return 0; // Other pointer types cannot be casted
626 case Instruction::PtrToInt: // always treated as unsigned
Dan Gohmancf913832010-01-28 02:15:55 +0000627 // Is it a null pointer value?
628 if (V->isNullValue())
Owen Andersonedb4a702009-07-24 23:12:02 +0000629 return ConstantInt::get(DestTy, 0);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000630 // If this is a sizeof-like expression, pull out multiplications by
631 // known factors to expose them to subsequent folding. If it's an
632 // alignof-like expression, factor out known factors.
Dan Gohmancf913832010-01-28 02:15:55 +0000633 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
634 if (CE->getOpcode() == Instruction::GetElementPtr &&
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000635 CE->getOperand(0)->isNullValue()) {
636 const Type *Ty =
637 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
638 if (CE->getNumOperands() == 2) {
639 // Handle a sizeof-like expression.
640 Constant *Idx = CE->getOperand(1);
641 bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
642 if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
643 Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
Dan Gohmancf913832010-01-28 02:15:55 +0000644 DestTy, false),
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000645 Idx, DestTy);
646 return ConstantExpr::getMul(C, Idx);
Dan Gohmancf913832010-01-28 02:15:55 +0000647 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000648 } else if (CE->getNumOperands() == 3 &&
649 CE->getOperand(1)->isNullValue()) {
650 // Handle an alignof-like expression.
651 if (const StructType *STy = dyn_cast<StructType>(Ty))
652 if (!STy->isPacked()) {
653 ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
654 if (CI->isOne() &&
655 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000656 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohmanf644af8b2010-02-02 01:41:39 +0000657 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000658 }
659 }
660 // Handle an offsetof-like expression.
Duncan Sands19d0b472010-02-16 11:11:14 +0000661 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()){
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000662 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
663 DestTy, false))
664 return C;
665 }
666 }
667 }
Dan Gohmancf913832010-01-28 02:15:55 +0000668 // Other pointer types cannot be casted
669 return 0;
Reid Spencer8dabca42006-12-19 07:41:40 +0000670 case Instruction::UIToFP:
Reid Spencer8dabca42006-12-19 07:41:40 +0000671 case Instruction::SIToFP:
Nick Lewyckye0332982009-09-20 01:35:59 +0000672 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Dale Johannesen91506522007-09-30 18:19:03 +0000673 APInt api = CI->getValue();
674 const uint64_t zero[] = {0, 0};
Dale Johannesen91506522007-09-30 18:19:03 +0000675 APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
676 2, zero));
Dan Gohman06c45d52008-02-29 01:42:52 +0000677 (void)apf.convertFromAPInt(api,
678 opc==Instruction::SIToFP,
679 APFloat::rmNearestTiesToEven);
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000680 return ConstantFP::get(V->getContext(), apf);
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000681 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000682 return 0;
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000683 case Instruction::ZExt:
Nick Lewyckye0332982009-09-20 01:35:59 +0000684 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Reid Spencer81658a82007-02-27 06:23:51 +0000685 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
686 APInt Result(CI->getValue());
687 Result.zext(BitWidth);
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000688 return ConstantInt::get(V->getContext(), Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000689 }
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000690 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000691 case Instruction::SExt:
Nick Lewyckye0332982009-09-20 01:35:59 +0000692 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Reid Spencer81658a82007-02-27 06:23:51 +0000693 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
694 APInt Result(CI->getValue());
695 Result.sext(BitWidth);
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000696 return ConstantInt::get(V->getContext(), Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000697 }
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000698 return 0;
Chris Lattnerf67d2972009-10-17 21:53:27 +0000699 case Instruction::Trunc: {
700 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
Nick Lewyckye0332982009-09-20 01:35:59 +0000701 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Reid Spencer81658a82007-02-27 06:23:51 +0000702 APInt Result(CI->getValue());
Chris Lattnerf67d2972009-10-17 21:53:27 +0000703 Result.trunc(DestBitWidth);
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000704 return ConstantInt::get(V->getContext(), Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000705 }
Chris Lattnerf67d2972009-10-17 21:53:27 +0000706
707 // The input must be a constantexpr. See if we can simplify this based on
708 // the bytes we are demanding. Only do this if the source and dest are an
709 // even multiple of a byte.
710 if ((DestBitWidth & 7) == 0 &&
711 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
712 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
713 return Res;
714
Chris Lattner710ebaf2006-12-01 19:22:41 +0000715 return 0;
Chris Lattnerf67d2972009-10-17 21:53:27 +0000716 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000717 case Instruction::BitCast:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000718 return FoldBitCast(V, DestTy);
Chris Lattner6b3f4752006-04-02 01:38:28 +0000719 }
Chris Lattner1dd054c2004-01-12 22:07:24 +0000720}
721
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000722Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
Nick Lewyckye0332982009-09-20 01:35:59 +0000723 Constant *V1, Constant *V2) {
724 if (ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
725 return CB->getZExtValue() ? V1 : V2;
Chris Lattnerfd7bf722004-10-16 23:31:32 +0000726
Nick Lewyckye0332982009-09-20 01:35:59 +0000727 if (isa<UndefValue>(V1)) return V2;
728 if (isa<UndefValue>(V2)) return V1;
729 if (isa<UndefValue>(Cond)) return V1;
730 if (V1 == V2) return V1;
Chris Lattner6ea4b522004-03-12 05:53:32 +0000731 return 0;
732}
733
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000734Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
Nick Lewyckye0332982009-09-20 01:35:59 +0000735 Constant *Idx) {
Chris Lattnere52f29b2006-03-31 18:31:40 +0000736 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
Owen Andersonb292b8c2009-07-30 23:03:37 +0000737 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
Chris Lattnere4f9d7b2006-04-07 04:44:06 +0000738 if (Val->isNullValue()) // ee(zero, x) -> zero
Owen Anderson5a1acd92009-07-31 20:28:14 +0000739 return Constant::getNullValue(
Reid Spencerd84d35b2007-02-15 02:26:10 +0000740 cast<VectorType>(Val->getType())->getElementType());
Dan Gohman062d3782009-08-29 23:35:16 +0000741
Nick Lewyckye0332982009-09-20 01:35:59 +0000742 if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
743 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
Gabor Greiff6caff662008-05-10 08:32:32 +0000744 return CVal->getOperand(CIdx->getZExtValue());
Chris Lattnere52f29b2006-03-31 18:31:40 +0000745 } else if (isa<UndefValue>(Idx)) {
746 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
Gabor Greiff6caff662008-05-10 08:32:32 +0000747 return CVal->getOperand(0);
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000748 }
Chris Lattnere52f29b2006-03-31 18:31:40 +0000749 }
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000750 return 0;
751}
752
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000753Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
Nick Lewyckye0332982009-09-20 01:35:59 +0000754 Constant *Elt,
755 Constant *Idx) {
756 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000757 if (!CIdx) return 0;
Reid Spencer81658a82007-02-27 06:23:51 +0000758 APInt idxVal = CIdx->getValue();
Reid Spencer3054b142006-11-02 08:18:15 +0000759 if (isa<UndefValue>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000760 // Insertion of scalar constant into vector undef
Robert Bocchinoca27f032006-01-17 20:07:22 +0000761 // Optimize away insertion of undef
762 if (isa<UndefValue>(Elt))
Nick Lewyckye0332982009-09-20 01:35:59 +0000763 return Val;
Robert Bocchinoca27f032006-01-17 20:07:22 +0000764 // Otherwise break the aggregate undef into multiple undefs and do
765 // the insertion
766 unsigned numOps =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000767 cast<VectorType>(Val->getType())->getNumElements();
Robert Bocchinoca27f032006-01-17 20:07:22 +0000768 std::vector<Constant*> Ops;
769 Ops.reserve(numOps);
770 for (unsigned i = 0; i < numOps; ++i) {
Nick Lewyckye0332982009-09-20 01:35:59 +0000771 Constant *Op =
Owen Andersonb292b8c2009-07-30 23:03:37 +0000772 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
Nick Lewyckye0332982009-09-20 01:35:59 +0000773 Ops.push_back(Op);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000774 }
Owen Anderson4aa32952009-07-28 21:19:26 +0000775 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000776 }
Reid Spencer3054b142006-11-02 08:18:15 +0000777 if (isa<ConstantAggregateZero>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000778 // Insertion of scalar constant into vector aggregate zero
Robert Bocchinoca27f032006-01-17 20:07:22 +0000779 // Optimize away insertion of zero
780 if (Elt->isNullValue())
Nick Lewyckye0332982009-09-20 01:35:59 +0000781 return Val;
Robert Bocchinoca27f032006-01-17 20:07:22 +0000782 // Otherwise break the aggregate zero into multiple zeros and do
783 // the insertion
784 unsigned numOps =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000785 cast<VectorType>(Val->getType())->getNumElements();
Robert Bocchinoca27f032006-01-17 20:07:22 +0000786 std::vector<Constant*> Ops;
787 Ops.reserve(numOps);
788 for (unsigned i = 0; i < numOps; ++i) {
Nick Lewyckye0332982009-09-20 01:35:59 +0000789 Constant *Op =
Owen Anderson5a1acd92009-07-31 20:28:14 +0000790 (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
Nick Lewyckye0332982009-09-20 01:35:59 +0000791 Ops.push_back(Op);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000792 }
Owen Anderson4aa32952009-07-28 21:19:26 +0000793 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000794 }
Nick Lewyckye0332982009-09-20 01:35:59 +0000795 if (ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000796 // Insertion of scalar constant into vector constant
Robert Bocchinoca27f032006-01-17 20:07:22 +0000797 std::vector<Constant*> Ops;
798 Ops.reserve(CVal->getNumOperands());
799 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
Nick Lewyckye0332982009-09-20 01:35:59 +0000800 Constant *Op =
Reid Spencer81658a82007-02-27 06:23:51 +0000801 (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
Nick Lewyckye0332982009-09-20 01:35:59 +0000802 Ops.push_back(Op);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000803 }
Owen Anderson4aa32952009-07-28 21:19:26 +0000804 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000805 }
Dan Gohman3db11c22008-06-03 00:15:20 +0000806
Robert Bocchinoca27f032006-01-17 20:07:22 +0000807 return 0;
808}
809
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000810/// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
811/// return the specified element value. Otherwise return null.
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000812static Constant *GetVectorElement(Constant *C, unsigned EltNo) {
Nick Lewyckye0332982009-09-20 01:35:59 +0000813 if (ConstantVector *CV = dyn_cast<ConstantVector>(C))
Gabor Greiff6caff662008-05-10 08:32:32 +0000814 return CV->getOperand(EltNo);
Dan Gohman062d3782009-08-29 23:35:16 +0000815
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000816 const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
817 if (isa<ConstantAggregateZero>(C))
Owen Anderson5a1acd92009-07-31 20:28:14 +0000818 return Constant::getNullValue(EltTy);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000819 if (isa<UndefValue>(C))
Owen Andersonb292b8c2009-07-30 23:03:37 +0000820 return UndefValue::get(EltTy);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000821 return 0;
822}
823
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000824Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
Nick Lewyckye0332982009-09-20 01:35:59 +0000825 Constant *V2,
826 Constant *Mask) {
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000827 // Undefined shuffle mask -> undefined value.
Owen Andersonb292b8c2009-07-30 23:03:37 +0000828 if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
Mon P Wang25f01062008-11-10 04:46:22 +0000829
830 unsigned MaskNumElts = cast<VectorType>(Mask->getType())->getNumElements();
831 unsigned SrcNumElts = cast<VectorType>(V1->getType())->getNumElements();
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000832 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
Mon P Wang25f01062008-11-10 04:46:22 +0000833
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000834 // Loop over the shuffle mask, evaluating each element.
835 SmallVector<Constant*, 32> Result;
Mon P Wang25f01062008-11-10 04:46:22 +0000836 for (unsigned i = 0; i != MaskNumElts; ++i) {
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000837 Constant *InElt = GetVectorElement(Mask, i);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000838 if (InElt == 0) return 0;
Mon P Wang25f01062008-11-10 04:46:22 +0000839
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000840 if (isa<UndefValue>(InElt))
Owen Andersonb292b8c2009-07-30 23:03:37 +0000841 InElt = UndefValue::get(EltTy);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000842 else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
843 unsigned Elt = CI->getZExtValue();
Mon P Wang25f01062008-11-10 04:46:22 +0000844 if (Elt >= SrcNumElts*2)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000845 InElt = UndefValue::get(EltTy);
Mon P Wang25f01062008-11-10 04:46:22 +0000846 else if (Elt >= SrcNumElts)
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000847 InElt = GetVectorElement(V2, Elt - SrcNumElts);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000848 else
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000849 InElt = GetVectorElement(V1, Elt);
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000850 if (InElt == 0) return 0;
851 } else {
852 // Unknown value.
853 return 0;
854 }
855 Result.push_back(InElt);
856 }
Mon P Wang25f01062008-11-10 04:46:22 +0000857
Owen Anderson4aa32952009-07-28 21:19:26 +0000858 return ConstantVector::get(&Result[0], Result.size());
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000859}
860
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000861Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
Dan Gohman3db11c22008-06-03 00:15:20 +0000862 const unsigned *Idxs,
863 unsigned NumIdx) {
864 // Base case: no indices, so return the entire value.
865 if (NumIdx == 0)
Nick Lewyckye0332982009-09-20 01:35:59 +0000866 return Agg;
Dan Gohman3db11c22008-06-03 00:15:20 +0000867
868 if (isa<UndefValue>(Agg)) // ev(undef, x) -> undef
Owen Andersonb292b8c2009-07-30 23:03:37 +0000869 return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
Dan Gohman3db11c22008-06-03 00:15:20 +0000870 Idxs,
871 Idxs + NumIdx));
872
873 if (isa<ConstantAggregateZero>(Agg)) // ev(0, x) -> 0
874 return
Owen Anderson5a1acd92009-07-31 20:28:14 +0000875 Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
Dan Gohman3db11c22008-06-03 00:15:20 +0000876 Idxs,
877 Idxs + NumIdx));
878
879 // Otherwise recurse.
Chris Lattnera91a5632009-10-28 05:14:34 +0000880 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg))
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000881 return ConstantFoldExtractValueInstruction(CS->getOperand(*Idxs),
Chris Lattnera91a5632009-10-28 05:14:34 +0000882 Idxs+1, NumIdx-1);
883
884 if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg))
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000885 return ConstantFoldExtractValueInstruction(CA->getOperand(*Idxs),
Chris Lattnera91a5632009-10-28 05:14:34 +0000886 Idxs+1, NumIdx-1);
887 ConstantVector *CV = cast<ConstantVector>(Agg);
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000888 return ConstantFoldExtractValueInstruction(CV->getOperand(*Idxs),
Dan Gohman3db11c22008-06-03 00:15:20 +0000889 Idxs+1, NumIdx-1);
Dan Gohman12fce772008-05-15 19:50:34 +0000890}
891
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000892Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
Nick Lewyckye0332982009-09-20 01:35:59 +0000893 Constant *Val,
Dan Gohman3db11c22008-06-03 00:15:20 +0000894 const unsigned *Idxs,
895 unsigned NumIdx) {
896 // Base case: no indices, so replace the entire value.
897 if (NumIdx == 0)
Nick Lewyckye0332982009-09-20 01:35:59 +0000898 return Val;
Dan Gohman3db11c22008-06-03 00:15:20 +0000899
900 if (isa<UndefValue>(Agg)) {
901 // Insertion of constant into aggregate undef
Chris Lattneree8f74f2009-09-15 06:28:12 +0000902 // Optimize away insertion of undef.
Dan Gohman3db11c22008-06-03 00:15:20 +0000903 if (isa<UndefValue>(Val))
Nick Lewyckye0332982009-09-20 01:35:59 +0000904 return Agg;
Chris Lattneree8f74f2009-09-15 06:28:12 +0000905
Dan Gohman3db11c22008-06-03 00:15:20 +0000906 // Otherwise break the aggregate undef into multiple undefs and do
Chris Lattneree8f74f2009-09-15 06:28:12 +0000907 // the insertion.
Dan Gohman3db11c22008-06-03 00:15:20 +0000908 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
909 unsigned numOps;
910 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
911 numOps = AR->getNumElements();
Duncan Sands19d0b472010-02-16 11:11:14 +0000912 else if (AggTy->isUnionTy())
Chris Lattner392be582010-02-12 20:49:41 +0000913 numOps = 1;
Dan Gohman3db11c22008-06-03 00:15:20 +0000914 else
915 numOps = cast<StructType>(AggTy)->getNumElements();
Chris Lattneree8f74f2009-09-15 06:28:12 +0000916
Dan Gohman3db11c22008-06-03 00:15:20 +0000917 std::vector<Constant*> Ops(numOps);
918 for (unsigned i = 0; i < numOps; ++i) {
919 const Type *MemberTy = AggTy->getTypeAtIndex(i);
Nick Lewyckye0332982009-09-20 01:35:59 +0000920 Constant *Op =
Dan Gohman3db11c22008-06-03 00:15:20 +0000921 (*Idxs == i) ?
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000922 ConstantFoldInsertValueInstruction(UndefValue::get(MemberTy),
Dan Gohman3db11c22008-06-03 00:15:20 +0000923 Val, Idxs+1, NumIdx-1) :
Owen Andersonb292b8c2009-07-30 23:03:37 +0000924 UndefValue::get(MemberTy);
Nick Lewyckye0332982009-09-20 01:35:59 +0000925 Ops[i] = Op;
Dan Gohman3db11c22008-06-03 00:15:20 +0000926 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000927
928 if (const StructType* ST = dyn_cast<StructType>(AggTy))
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000929 return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
Chris Lattner392be582010-02-12 20:49:41 +0000930 if (const UnionType* UT = dyn_cast<UnionType>(AggTy)) {
931 assert(Ops.size() == 1 && "Union can only contain a single value!");
932 return ConstantUnion::get(UT, Ops[0]);
933 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000934 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
Dan Gohman3db11c22008-06-03 00:15:20 +0000935 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000936
Dan Gohman3db11c22008-06-03 00:15:20 +0000937 if (isa<ConstantAggregateZero>(Agg)) {
938 // Insertion of constant into aggregate zero
Chris Lattneree8f74f2009-09-15 06:28:12 +0000939 // Optimize away insertion of zero.
Dan Gohman3db11c22008-06-03 00:15:20 +0000940 if (Val->isNullValue())
Nick Lewyckye0332982009-09-20 01:35:59 +0000941 return Agg;
Chris Lattneree8f74f2009-09-15 06:28:12 +0000942
Dan Gohman3db11c22008-06-03 00:15:20 +0000943 // Otherwise break the aggregate zero into multiple zeros and do
Chris Lattneree8f74f2009-09-15 06:28:12 +0000944 // the insertion.
Dan Gohman3db11c22008-06-03 00:15:20 +0000945 const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
946 unsigned numOps;
947 if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
948 numOps = AR->getNumElements();
949 else
950 numOps = cast<StructType>(AggTy)->getNumElements();
Chris Lattneree8f74f2009-09-15 06:28:12 +0000951
Dan Gohman3db11c22008-06-03 00:15:20 +0000952 std::vector<Constant*> Ops(numOps);
953 for (unsigned i = 0; i < numOps; ++i) {
954 const Type *MemberTy = AggTy->getTypeAtIndex(i);
Nick Lewyckye0332982009-09-20 01:35:59 +0000955 Constant *Op =
Dan Gohman3db11c22008-06-03 00:15:20 +0000956 (*Idxs == i) ?
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000957 ConstantFoldInsertValueInstruction(Constant::getNullValue(MemberTy),
Dan Gohman3db11c22008-06-03 00:15:20 +0000958 Val, Idxs+1, NumIdx-1) :
Owen Anderson5a1acd92009-07-31 20:28:14 +0000959 Constant::getNullValue(MemberTy);
Nick Lewyckye0332982009-09-20 01:35:59 +0000960 Ops[i] = Op;
Dan Gohman3db11c22008-06-03 00:15:20 +0000961 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000962
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000963 if (const StructType *ST = dyn_cast<StructType>(AggTy))
964 return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
Chris Lattneree8f74f2009-09-15 06:28:12 +0000965 return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
Dan Gohman3db11c22008-06-03 00:15:20 +0000966 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000967
Dan Gohman3db11c22008-06-03 00:15:20 +0000968 if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
Chris Lattneree8f74f2009-09-15 06:28:12 +0000969 // Insertion of constant into aggregate constant.
Dan Gohman3db11c22008-06-03 00:15:20 +0000970 std::vector<Constant*> Ops(Agg->getNumOperands());
971 for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
Chris Lattnera91a5632009-10-28 05:14:34 +0000972 Constant *Op = cast<Constant>(Agg->getOperand(i));
973 if (*Idxs == i)
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000974 Op = ConstantFoldInsertValueInstruction(Op, Val, Idxs+1, NumIdx-1);
Nick Lewyckye0332982009-09-20 01:35:59 +0000975 Ops[i] = Op;
Dan Gohman3db11c22008-06-03 00:15:20 +0000976 }
Chris Lattneree8f74f2009-09-15 06:28:12 +0000977
978 if (const StructType* ST = dyn_cast<StructType>(Agg->getType()))
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000979 return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
Chris Lattneree8f74f2009-09-15 06:28:12 +0000980 return ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
Dan Gohman3db11c22008-06-03 00:15:20 +0000981 }
982
Dan Gohman12fce772008-05-15 19:50:34 +0000983 return 0;
984}
985
Reid Spencer266e42b2006-12-23 06:05:41 +0000986
Chris Lattnerf5edeeb2010-02-01 20:48:08 +0000987Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
Nick Lewyckye0332982009-09-20 01:35:59 +0000988 Constant *C1, Constant *C2) {
Dale Johannesene5facd52007-10-16 23:38:29 +0000989 // No compile-time operations on this type yet.
Chris Lattnerfdd87902009-10-05 05:54:46 +0000990 if (C1->getType()->isPPC_FP128Ty())
Dale Johannesene5facd52007-10-16 23:38:29 +0000991 return 0;
992
Chris Lattneree8f74f2009-09-15 06:28:12 +0000993 // Handle UndefValue up front.
Reid Spencer266e42b2006-12-23 06:05:41 +0000994 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
995 switch (Opcode) {
Evan Chengdf1690d2008-03-25 20:08:07 +0000996 case Instruction::Xor:
997 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
998 // Handle undef ^ undef -> 0 special case. This is a common
999 // idiom (misuse).
Owen Anderson5a1acd92009-07-31 20:28:14 +00001000 return Constant::getNullValue(C1->getType());
Evan Chengdf1690d2008-03-25 20:08:07 +00001001 // Fallthrough
Reid Spencer266e42b2006-12-23 06:05:41 +00001002 case Instruction::Add:
1003 case Instruction::Sub:
Owen Andersonb292b8c2009-07-30 23:03:37 +00001004 return UndefValue::get(C1->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00001005 case Instruction::Mul:
1006 case Instruction::And:
Owen Anderson5a1acd92009-07-31 20:28:14 +00001007 return Constant::getNullValue(C1->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00001008 case Instruction::UDiv:
1009 case Instruction::SDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00001010 case Instruction::URem:
1011 case Instruction::SRem:
Reid Spencer266e42b2006-12-23 06:05:41 +00001012 if (!isa<UndefValue>(C2)) // undef / X -> 0
Owen Anderson5a1acd92009-07-31 20:28:14 +00001013 return Constant::getNullValue(C1->getType());
Nick Lewyckye0332982009-09-20 01:35:59 +00001014 return C2; // X / undef -> undef
Reid Spencer266e42b2006-12-23 06:05:41 +00001015 case Instruction::Or: // X | undef -> -1
Reid Spencerd84d35b2007-02-15 02:26:10 +00001016 if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
Owen Anderson5a1acd92009-07-31 20:28:14 +00001017 return Constant::getAllOnesValue(PTy);
1018 return Constant::getAllOnesValue(C1->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00001019 case Instruction::LShr:
1020 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
Nick Lewyckye0332982009-09-20 01:35:59 +00001021 return C1; // undef lshr undef -> undef
Owen Anderson5a1acd92009-07-31 20:28:14 +00001022 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00001023 // undef lshr X -> 0
1024 case Instruction::AShr:
1025 if (!isa<UndefValue>(C2))
Nick Lewyckye0332982009-09-20 01:35:59 +00001026 return C1; // undef ashr X --> undef
Reid Spencer266e42b2006-12-23 06:05:41 +00001027 else if (isa<UndefValue>(C1))
Nick Lewyckye0332982009-09-20 01:35:59 +00001028 return C1; // undef ashr undef -> undef
Reid Spencer266e42b2006-12-23 06:05:41 +00001029 else
Nick Lewyckye0332982009-09-20 01:35:59 +00001030 return C1; // X ashr undef --> X
Reid Spencer266e42b2006-12-23 06:05:41 +00001031 case Instruction::Shl:
1032 // undef << X -> 0 or X << undef -> 0
Owen Anderson5a1acd92009-07-31 20:28:14 +00001033 return Constant::getNullValue(C1->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00001034 }
1035 }
1036
Nick Lewycky6b8320f2009-06-21 01:56:41 +00001037 // Handle simplifications when the RHS is a constant int.
Nick Lewyckye0332982009-09-20 01:35:59 +00001038 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
Chris Lattner334d33c2008-04-19 21:58:19 +00001039 switch (Opcode) {
1040 case Instruction::Add:
Nick Lewyckye0332982009-09-20 01:35:59 +00001041 if (CI2->equalsInt(0)) return C1; // X + 0 == X
Chris Lattner334d33c2008-04-19 21:58:19 +00001042 break;
1043 case Instruction::Sub:
Nick Lewyckye0332982009-09-20 01:35:59 +00001044 if (CI2->equalsInt(0)) return C1; // X - 0 == X
Chris Lattner334d33c2008-04-19 21:58:19 +00001045 break;
1046 case Instruction::Mul:
Nick Lewyckye0332982009-09-20 01:35:59 +00001047 if (CI2->equalsInt(0)) return C2; // X * 0 == 0
Chris Lattner334d33c2008-04-19 21:58:19 +00001048 if (CI2->equalsInt(1))
Nick Lewyckye0332982009-09-20 01:35:59 +00001049 return C1; // X * 1 == X
Chris Lattner334d33c2008-04-19 21:58:19 +00001050 break;
1051 case Instruction::UDiv:
1052 case Instruction::SDiv:
1053 if (CI2->equalsInt(1))
Nick Lewyckye0332982009-09-20 01:35:59 +00001054 return C1; // X / 1 == X
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +00001055 if (CI2->equalsInt(0))
Owen Andersonb292b8c2009-07-30 23:03:37 +00001056 return UndefValue::get(CI2->getType()); // X / 0 == undef
Chris Lattner334d33c2008-04-19 21:58:19 +00001057 break;
1058 case Instruction::URem:
1059 case Instruction::SRem:
1060 if (CI2->equalsInt(1))
Owen Anderson5a1acd92009-07-31 20:28:14 +00001061 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +00001062 if (CI2->equalsInt(0))
Owen Andersonb292b8c2009-07-30 23:03:37 +00001063 return UndefValue::get(CI2->getType()); // X % 0 == undef
Chris Lattner334d33c2008-04-19 21:58:19 +00001064 break;
1065 case Instruction::And:
Nick Lewyckye0332982009-09-20 01:35:59 +00001066 if (CI2->isZero()) return C2; // X & 0 == 0
Chris Lattner334d33c2008-04-19 21:58:19 +00001067 if (CI2->isAllOnesValue())
Nick Lewyckye0332982009-09-20 01:35:59 +00001068 return C1; // X & -1 == X
Dan Gohman062d3782009-08-29 23:35:16 +00001069
Nick Lewyckye0332982009-09-20 01:35:59 +00001070 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
Chris Lattnerbc26e1b2008-04-19 22:17:26 +00001071 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
Chris Lattner334d33c2008-04-19 21:58:19 +00001072 if (CE1->getOpcode() == Instruction::ZExt) {
1073 unsigned DstWidth = CI2->getType()->getBitWidth();
1074 unsigned SrcWidth =
1075 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
1076 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
1077 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
Nick Lewyckye0332982009-09-20 01:35:59 +00001078 return C1;
Chris Lattner6d94bb72007-03-25 05:47:04 +00001079 }
Dan Gohman062d3782009-08-29 23:35:16 +00001080
Chris Lattnerbc26e1b2008-04-19 22:17:26 +00001081 // If and'ing the address of a global with a constant, fold it.
Chris Lattner334d33c2008-04-19 21:58:19 +00001082 if (CE1->getOpcode() == Instruction::PtrToInt &&
1083 isa<GlobalValue>(CE1->getOperand(0))) {
Chris Lattnerbc26e1b2008-04-19 22:17:26 +00001084 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
Dan Gohman062d3782009-08-29 23:35:16 +00001085
Chris Lattnerbc26e1b2008-04-19 22:17:26 +00001086 // Functions are at least 4-byte aligned.
1087 unsigned GVAlign = GV->getAlignment();
1088 if (isa<Function>(GV))
1089 GVAlign = std::max(GVAlign, 4U);
Dan Gohman062d3782009-08-29 23:35:16 +00001090
Chris Lattnerbc26e1b2008-04-19 22:17:26 +00001091 if (GVAlign > 1) {
1092 unsigned DstWidth = CI2->getType()->getBitWidth();
Chris Lattner912bec72008-04-20 19:59:12 +00001093 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
Chris Lattnerbc26e1b2008-04-19 22:17:26 +00001094 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1095
1096 // If checking bits we know are clear, return zero.
1097 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
Owen Anderson5a1acd92009-07-31 20:28:14 +00001098 return Constant::getNullValue(CI2->getType());
Chris Lattnerbc26e1b2008-04-19 22:17:26 +00001099 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001100 }
Chris Lattner334d33c2008-04-19 21:58:19 +00001101 }
1102 break;
1103 case Instruction::Or:
Nick Lewyckye0332982009-09-20 01:35:59 +00001104 if (CI2->equalsInt(0)) return C1; // X | 0 == X
Chris Lattner334d33c2008-04-19 21:58:19 +00001105 if (CI2->isAllOnesValue())
Nick Lewyckye0332982009-09-20 01:35:59 +00001106 return C2; // X | -1 == -1
Chris Lattner334d33c2008-04-19 21:58:19 +00001107 break;
1108 case Instruction::Xor:
Nick Lewyckye0332982009-09-20 01:35:59 +00001109 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X
Nick Lewycky28260402009-09-20 06:24:51 +00001110
1111 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1112 switch (CE1->getOpcode()) {
1113 default: break;
1114 case Instruction::ICmp:
1115 case Instruction::FCmp:
Nick Lewyckyff550aa2009-09-20 06:27:35 +00001116 // cmp pred ^ true -> cmp !pred
Nick Lewycky28260402009-09-20 06:24:51 +00001117 assert(CI2->equalsInt(1));
Nick Lewycky0f8348e2009-09-20 06:26:34 +00001118 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
Nick Lewycky28260402009-09-20 06:24:51 +00001119 pred = CmpInst::getInversePredicate(pred);
1120 return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1121 CE1->getOperand(1));
1122 }
1123 }
Chris Lattner334d33c2008-04-19 21:58:19 +00001124 break;
1125 case Instruction::AShr:
1126 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
Nick Lewyckye0332982009-09-20 01:35:59 +00001127 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
Chris Lattner6d94bb72007-03-25 05:47:04 +00001128 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
Nick Lewyckye0332982009-09-20 01:35:59 +00001129 return ConstantExpr::getLShr(C1, C2);
Chris Lattner334d33c2008-04-19 21:58:19 +00001130 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00001131 }
Dan Gohman6c5ac6d2010-02-22 22:43:23 +00001132 } else if (isa<ConstantInt>(C1)) {
1133 // If C1 is a ConstantInt and C2 is not, swap the operands.
1134 if (Instruction::isCommutative(Opcode))
1135 return ConstantExpr::get(Opcode, C2, C1);
Chris Lattner334d33c2008-04-19 21:58:19 +00001136 }
Dan Gohman062d3782009-08-29 23:35:16 +00001137
Chris Lattner6b056052008-04-20 18:24:14 +00001138 // At this point we know neither constant is an UndefValue.
Nick Lewyckye0332982009-09-20 01:35:59 +00001139 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1140 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
Reid Spencer81658a82007-02-27 06:23:51 +00001141 using namespace APIntOps;
Chris Lattner6b056052008-04-20 18:24:14 +00001142 const APInt &C1V = CI1->getValue();
1143 const APInt &C2V = CI2->getValue();
Chris Lattner344da522007-01-12 18:42:52 +00001144 switch (Opcode) {
1145 default:
1146 break;
1147 case Instruction::Add:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001148 return ConstantInt::get(CI1->getContext(), C1V + C2V);
Chris Lattner344da522007-01-12 18:42:52 +00001149 case Instruction::Sub:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001150 return ConstantInt::get(CI1->getContext(), C1V - C2V);
Chris Lattner344da522007-01-12 18:42:52 +00001151 case Instruction::Mul:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001152 return ConstantInt::get(CI1->getContext(), C1V * C2V);
Chris Lattner344da522007-01-12 18:42:52 +00001153 case Instruction::UDiv:
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +00001154 assert(!CI2->isNullValue() && "Div by zero handled above");
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001155 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
Chris Lattner344da522007-01-12 18:42:52 +00001156 case Instruction::SDiv:
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +00001157 assert(!CI2->isNullValue() && "Div by zero handled above");
Reid Spencer81658a82007-02-27 06:23:51 +00001158 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00001159 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001160 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
Reid Spencer81658a82007-02-27 06:23:51 +00001161 case Instruction::URem:
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +00001162 assert(!CI2->isNullValue() && "Div by zero handled above");
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001163 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
Chris Lattnerdd8ef1b2009-01-19 21:55:26 +00001164 case Instruction::SRem:
1165 assert(!CI2->isNullValue() && "Div by zero handled above");
Reid Spencer81658a82007-02-27 06:23:51 +00001166 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
Owen Andersonb292b8c2009-07-30 23:03:37 +00001167 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001168 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
Chris Lattner344da522007-01-12 18:42:52 +00001169 case Instruction::And:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001170 return ConstantInt::get(CI1->getContext(), C1V & C2V);
Chris Lattner344da522007-01-12 18:42:52 +00001171 case Instruction::Or:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001172 return ConstantInt::get(CI1->getContext(), C1V | C2V);
Chris Lattner344da522007-01-12 18:42:52 +00001173 case Instruction::Xor:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001174 return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
Chris Lattner6b056052008-04-20 18:24:14 +00001175 case Instruction::Shl: {
1176 uint32_t shiftAmt = C2V.getZExtValue();
1177 if (shiftAmt < C1V.getBitWidth())
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001178 return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
Chris Lattner6b056052008-04-20 18:24:14 +00001179 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00001180 return UndefValue::get(C1->getType()); // too big shift is undef
Chris Lattner6b056052008-04-20 18:24:14 +00001181 }
1182 case Instruction::LShr: {
1183 uint32_t shiftAmt = C2V.getZExtValue();
1184 if (shiftAmt < C1V.getBitWidth())
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001185 return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
Chris Lattner6b056052008-04-20 18:24:14 +00001186 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00001187 return UndefValue::get(C1->getType()); // too big shift is undef
Chris Lattner6b056052008-04-20 18:24:14 +00001188 }
1189 case Instruction::AShr: {
1190 uint32_t shiftAmt = C2V.getZExtValue();
1191 if (shiftAmt < C1V.getBitWidth())
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001192 return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
Chris Lattner6b056052008-04-20 18:24:14 +00001193 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00001194 return UndefValue::get(C1->getType()); // too big shift is undef
Chris Lattner6b056052008-04-20 18:24:14 +00001195 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001196 }
1197 }
Nick Lewycky6b8320f2009-06-21 01:56:41 +00001198
1199 switch (Opcode) {
1200 case Instruction::SDiv:
1201 case Instruction::UDiv:
1202 case Instruction::URem:
1203 case Instruction::SRem:
1204 case Instruction::LShr:
1205 case Instruction::AShr:
1206 case Instruction::Shl:
Nick Lewyckye0332982009-09-20 01:35:59 +00001207 if (CI1->equalsInt(0)) return C1;
Nick Lewycky6b8320f2009-06-21 01:56:41 +00001208 break;
1209 default:
1210 break;
1211 }
Nick Lewyckye0332982009-09-20 01:35:59 +00001212 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1213 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001214 APFloat C1V = CFP1->getValueAPF();
1215 APFloat C2V = CFP2->getValueAPF();
1216 APFloat C3V = C1V; // copy for modification
Reid Spencer266e42b2006-12-23 06:05:41 +00001217 switch (Opcode) {
1218 default:
1219 break;
Dan Gohmana5b96452009-06-04 22:49:04 +00001220 case Instruction::FAdd:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001221 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001222 return ConstantFP::get(C1->getContext(), C3V);
Dan Gohmana5b96452009-06-04 22:49:04 +00001223 case Instruction::FSub:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001224 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001225 return ConstantFP::get(C1->getContext(), C3V);
Dan Gohmana5b96452009-06-04 22:49:04 +00001226 case Instruction::FMul:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001227 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001228 return ConstantFP::get(C1->getContext(), C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +00001229 case Instruction::FDiv:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001230 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001231 return ConstantFP::get(C1->getContext(), C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +00001232 case Instruction::FRem:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001233 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001234 return ConstantFP::get(C1->getContext(), C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +00001235 }
1236 }
Dan Gohman9f396602007-10-30 19:00:49 +00001237 } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
Nick Lewyckye0332982009-09-20 01:35:59 +00001238 ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
1239 ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
Dan Gohmanb43e0202007-10-31 21:36:31 +00001240 if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
1241 (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
Owen Anderson85f86dc2009-07-13 22:41:06 +00001242 std::vector<Constant*> Res;
1243 const Type* EltTy = VTy->getElementType();
Nick Lewyckye0332982009-09-20 01:35:59 +00001244 Constant *C1 = 0;
1245 Constant *C2 = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00001246 switch (Opcode) {
Chris Lattner6072ead2008-04-19 21:13:00 +00001247 default:
1248 break;
Dan Gohmana5b96452009-06-04 22:49:04 +00001249 case Instruction::Add:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001250 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001251 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1252 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001253 Res.push_back(ConstantExpr::getAdd(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001254 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001255 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001256 case Instruction::FAdd:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001257 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001258 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1259 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001260 Res.push_back(ConstantExpr::getFAdd(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001261 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001262 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001263 case Instruction::Sub:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001264 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001265 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1266 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001267 Res.push_back(ConstantExpr::getSub(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001268 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001269 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001270 case Instruction::FSub:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001271 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001272 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1273 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001274 Res.push_back(ConstantExpr::getFSub(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001275 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001276 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001277 case Instruction::Mul:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001278 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001279 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1280 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001281 Res.push_back(ConstantExpr::getMul(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001282 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001283 return ConstantVector::get(Res);
Dan Gohmana5b96452009-06-04 22:49:04 +00001284 case Instruction::FMul:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001285 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001286 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1287 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001288 Res.push_back(ConstantExpr::getFMul(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001289 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001290 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001291 case Instruction::UDiv:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001292 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001293 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1294 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001295 Res.push_back(ConstantExpr::getUDiv(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001296 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001297 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001298 case Instruction::SDiv:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001299 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001300 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1301 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001302 Res.push_back(ConstantExpr::getSDiv(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001303 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001304 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001305 case Instruction::FDiv:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001306 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001307 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1308 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001309 Res.push_back(ConstantExpr::getFDiv(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001310 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001311 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001312 case Instruction::URem:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001313 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001314 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1315 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001316 Res.push_back(ConstantExpr::getURem(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001317 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001318 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001319 case Instruction::SRem:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001320 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001321 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1322 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001323 Res.push_back(ConstantExpr::getSRem(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001324 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001325 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001326 case Instruction::FRem:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001327 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001328 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1329 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001330 Res.push_back(ConstantExpr::getFRem(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001331 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001332 return ConstantVector::get(Res);
Chris Lattner6072ead2008-04-19 21:13:00 +00001333 case Instruction::And:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001334 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001335 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1336 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001337 Res.push_back(ConstantExpr::getAnd(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001338 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001339 return ConstantVector::get(Res);
Owen Anderson85f86dc2009-07-13 22:41:06 +00001340 case Instruction::Or:
1341 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001342 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1343 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001344 Res.push_back(ConstantExpr::getOr(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001345 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001346 return ConstantVector::get(Res);
Owen Anderson85f86dc2009-07-13 22:41:06 +00001347 case Instruction::Xor:
1348 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001349 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1350 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001351 Res.push_back(ConstantExpr::getXor(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001352 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001353 return ConstantVector::get(Res);
Dan Gohman79975d52009-03-14 17:09:17 +00001354 case Instruction::LShr:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001355 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001356 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1357 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001358 Res.push_back(ConstantExpr::getLShr(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001359 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001360 return ConstantVector::get(Res);
Dan Gohman79975d52009-03-14 17:09:17 +00001361 case Instruction::AShr:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001362 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001363 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1364 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001365 Res.push_back(ConstantExpr::getAShr(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001366 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001367 return ConstantVector::get(Res);
Dan Gohman79975d52009-03-14 17:09:17 +00001368 case Instruction::Shl:
Owen Anderson85f86dc2009-07-13 22:41:06 +00001369 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00001370 C1 = CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
1371 C2 = CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
Nick Lewyckye0332982009-09-20 01:35:59 +00001372 Res.push_back(ConstantExpr::getShl(C1, C2));
Owen Anderson85f86dc2009-07-13 22:41:06 +00001373 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001374 return ConstantVector::get(Res);
Dan Gohmanb43e0202007-10-31 21:36:31 +00001375 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001376 }
1377 }
1378
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00001379 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
Chris Lattner6b056052008-04-20 18:24:14 +00001380 // There are many possible foldings we could do here. We should probably
1381 // at least fold add of a pointer with an integer into the appropriate
1382 // getelementptr. This will improve alias analysis a bit.
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00001383
1384 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1385 // (a + (b + c)).
1386 if (Instruction::isAssociative(Opcode, C1->getType()) &&
1387 CE1->getOpcode() == Opcode) {
1388 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1389 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1390 return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1391 }
Chris Lattner6b056052008-04-20 18:24:14 +00001392 } else if (isa<ConstantExpr>(C2)) {
1393 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1394 // other way if possible.
Dan Gohman6eeabaa2010-02-22 22:05:18 +00001395 if (Instruction::isCommutative(Opcode))
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001396 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
Chris Lattner6b056052008-04-20 18:24:14 +00001397 }
Dan Gohman062d3782009-08-29 23:35:16 +00001398
Nick Lewycky605109d2009-09-20 00:04:02 +00001399 // i1 can be simplified in many cases.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001400 if (C1->getType()->isIntegerTy(1)) {
Nick Lewycky605109d2009-09-20 00:04:02 +00001401 switch (Opcode) {
1402 case Instruction::Add:
1403 case Instruction::Sub:
Nick Lewyckye0332982009-09-20 01:35:59 +00001404 return ConstantExpr::getXor(C1, C2);
Nick Lewycky605109d2009-09-20 00:04:02 +00001405 case Instruction::Mul:
Nick Lewyckye0332982009-09-20 01:35:59 +00001406 return ConstantExpr::getAnd(C1, C2);
Nick Lewycky605109d2009-09-20 00:04:02 +00001407 case Instruction::Shl:
1408 case Instruction::LShr:
1409 case Instruction::AShr:
1410 // We can assume that C2 == 0. If it were one the result would be
1411 // undefined because the shift value is as large as the bitwidth.
Nick Lewyckye0332982009-09-20 01:35:59 +00001412 return C1;
Nick Lewycky605109d2009-09-20 00:04:02 +00001413 case Instruction::SDiv:
1414 case Instruction::UDiv:
1415 // We can assume that C2 == 1. If it were zero the result would be
1416 // undefined through division by zero.
Nick Lewyckye0332982009-09-20 01:35:59 +00001417 return C1;
Nick Lewycky605109d2009-09-20 00:04:02 +00001418 case Instruction::URem:
1419 case Instruction::SRem:
1420 // We can assume that C2 == 1. If it were zero the result would be
1421 // undefined through division by zero.
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001422 return ConstantInt::getFalse(C1->getContext());
Nick Lewycky605109d2009-09-20 00:04:02 +00001423 default:
1424 break;
1425 }
1426 }
1427
Chris Lattner6b056052008-04-20 18:24:14 +00001428 // We don't know how to fold this.
Reid Spencer266e42b2006-12-23 06:05:41 +00001429 return 0;
1430}
Chris Lattnerbbe0a422006-04-08 01:18:18 +00001431
Chris Lattner60c47262005-01-28 19:09:51 +00001432/// isZeroSizedType - This type is zero sized if its an array or structure of
1433/// zero sized types. The only leaf zero sized type is an empty structure.
1434static bool isMaybeZeroSizedType(const Type *Ty) {
Duncan Sandscbd43f82010-02-16 14:50:09 +00001435 if (Ty->isOpaqueTy()) return true; // Can't say.
Chris Lattner60c47262005-01-28 19:09:51 +00001436 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1437
1438 // If all of elements have zero size, this does too.
1439 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerfeaf92f2005-01-28 23:17:27 +00001440 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
Chris Lattner60c47262005-01-28 19:09:51 +00001441 return true;
1442
1443 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1444 return isMaybeZeroSizedType(ATy->getElementType());
1445 }
1446 return false;
1447}
Chris Lattner6ea4b522004-03-12 05:53:32 +00001448
Chris Lattner061da2f2004-01-13 05:51:55 +00001449/// IdxCompare - Compare the two constants as though they were getelementptr
1450/// indices. This allows coersion of the types to be the same thing.
1451///
1452/// If the two constants are the "same" (after coersion), return 0. If the
1453/// first is less than the second, return -1, if the second is less than the
1454/// first, return 1. If the constants are not integral, return -2.
1455///
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001456static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001457 if (C1 == C2) return 0;
1458
Reid Spencerc90cf772006-12-31 21:43:30 +00001459 // Ok, we found a different index. If they are not ConstantInt, we can't do
1460 // anything with them.
Chris Lattner061da2f2004-01-13 05:51:55 +00001461 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1462 return -2; // don't know!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001463
Chris Lattner69193f92004-04-05 01:30:19 +00001464 // Ok, we have two differing integer indices. Sign extend them to be the same
1465 // type. Long is always big enough, so we use it.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001466 if (!C1->getType()->isIntegerTy(64))
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001467 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001468
Duncan Sands9dff9be2010-02-15 16:12:20 +00001469 if (!C2->getType()->isIntegerTy(64))
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001470 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
Reid Spencer8d9336d2006-12-31 05:26:44 +00001471
1472 if (C1 == C2) return 0; // They are equal
Chris Lattner061da2f2004-01-13 05:51:55 +00001473
Chris Lattner60c47262005-01-28 19:09:51 +00001474 // If the type being indexed over is really just a zero sized type, there is
1475 // no pointer difference being made here.
1476 if (isMaybeZeroSizedType(ElTy))
1477 return -2; // dunno.
1478
Chris Lattner061da2f2004-01-13 05:51:55 +00001479 // If they are really different, now that they are the same type, then we
1480 // found a difference!
Reid Spencere0fc4df2006-10-20 07:07:24 +00001481 if (cast<ConstantInt>(C1)->getSExtValue() <
1482 cast<ConstantInt>(C2)->getSExtValue())
Chris Lattner061da2f2004-01-13 05:51:55 +00001483 return -1;
1484 else
1485 return 1;
1486}
1487
Chris Lattner858f4e92007-01-04 02:13:20 +00001488/// evaluateFCmpRelation - This function determines if there is anything we can
Reid Spencer266e42b2006-12-23 06:05:41 +00001489/// decide about the two constants provided. This doesn't need to handle simple
1490/// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1491/// If we can determine that the two constants have a particular relation to
1492/// each other, we should return the corresponding FCmpInst predicate,
Reid Spencer9d36acf2006-12-24 18:52:08 +00001493/// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1494/// ConstantFoldCompareInstruction.
Reid Spencer266e42b2006-12-23 06:05:41 +00001495///
1496/// To simplify this code we canonicalize the relation so that the first
Reid Spencer9d36acf2006-12-24 18:52:08 +00001497/// operand is always the most "complex" of the two. We consider ConstantFP
1498/// to be the simplest, and ConstantExprs to be the most complex.
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001499static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001500 assert(V1->getType() == V2->getType() &&
Reid Spencer9d36acf2006-12-24 18:52:08 +00001501 "Cannot compare values of different types!");
Dale Johannesen19db0932007-10-14 01:56:47 +00001502
1503 // No compile-time operations on this type yet.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001504 if (V1->getType()->isPPC_FP128Ty())
Dale Johannesen19db0932007-10-14 01:56:47 +00001505 return FCmpInst::BAD_FCMP_PREDICATE;
1506
Reid Spencer9d36acf2006-12-24 18:52:08 +00001507 // Handle degenerate case quickly
Reid Spencer266e42b2006-12-23 06:05:41 +00001508 if (V1 == V2) return FCmpInst::FCMP_OEQ;
1509
Reid Spencer9d36acf2006-12-24 18:52:08 +00001510 if (!isa<ConstantExpr>(V1)) {
1511 if (!isa<ConstantExpr>(V2)) {
1512 // We distilled thisUse the standard constant folder for a few cases
Zhou Sheng75b871f2007-01-11 12:24:14 +00001513 ConstantInt *R = 0;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001514 R = dyn_cast<ConstantInt>(
Nick Lewyckye0332982009-09-20 01:35:59 +00001515 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001516 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001517 return FCmpInst::FCMP_OEQ;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001518 R = dyn_cast<ConstantInt>(
Nick Lewyckye0332982009-09-20 01:35:59 +00001519 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001520 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001521 return FCmpInst::FCMP_OLT;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001522 R = dyn_cast<ConstantInt>(
Nick Lewyckye0332982009-09-20 01:35:59 +00001523 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001524 if (R && !R->isZero())
Reid Spencer9d36acf2006-12-24 18:52:08 +00001525 return FCmpInst::FCMP_OGT;
1526
1527 // Nothing more we can do
Reid Spencer266e42b2006-12-23 06:05:41 +00001528 return FCmpInst::BAD_FCMP_PREDICATE;
1529 }
Dan Gohman062d3782009-08-29 23:35:16 +00001530
Reid Spencer9d36acf2006-12-24 18:52:08 +00001531 // If the first operand is simple and second is ConstantExpr, swap operands.
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001532 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001533 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1534 return FCmpInst::getSwappedPredicate(SwappedRelation);
1535 } else {
1536 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1537 // constantexpr or a simple constant.
Nick Lewyckye0332982009-09-20 01:35:59 +00001538 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001539 switch (CE1->getOpcode()) {
1540 case Instruction::FPTrunc:
1541 case Instruction::FPExt:
1542 case Instruction::UIToFP:
1543 case Instruction::SIToFP:
1544 // We might be able to do something with these but we don't right now.
1545 break;
1546 default:
1547 break;
1548 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001549 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001550 // There are MANY other foldings that we could perform here. They will
1551 // probably be added on demand, as they seem needed.
1552 return FCmpInst::BAD_FCMP_PREDICATE;
1553}
1554
1555/// evaluateICmpRelation - This function determines if there is anything we can
Chris Lattner061da2f2004-01-13 05:51:55 +00001556/// decide about the two constants provided. This doesn't need to handle simple
Reid Spenceraccd7c72004-07-17 23:47:01 +00001557/// things like integer comparisons, but should instead handle ConstantExprs
Chris Lattner8410beb2006-12-11 02:16:58 +00001558/// and GlobalValues. If we can determine that the two constants have a
Reid Spencer266e42b2006-12-23 06:05:41 +00001559/// particular relation to each other, we should return the corresponding ICmp
1560/// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
Chris Lattner061da2f2004-01-13 05:51:55 +00001561///
1562/// To simplify this code we canonicalize the relation so that the first
1563/// operand is always the most "complex" of the two. We consider simple
1564/// constants (like ConstantInt) to be the simplest, followed by
Reid Spenceraccd7c72004-07-17 23:47:01 +00001565/// GlobalValues, followed by ConstantExpr's (the most complex).
Chris Lattner061da2f2004-01-13 05:51:55 +00001566///
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001567static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
Reid Spencer266e42b2006-12-23 06:05:41 +00001568 bool isSigned) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001569 assert(V1->getType() == V2->getType() &&
1570 "Cannot compare different types of values!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001571 if (V1 == V2) return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001572
Chris Lattner3c46e142010-02-01 19:35:08 +00001573 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1574 !isa<BlockAddress>(V1)) {
1575 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1576 !isa<BlockAddress>(V2)) {
Chris Lattnerfed8ceb2006-01-05 07:49:30 +00001577 // We distilled this down to a simple case, use the standard constant
1578 // folder.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001579 ConstantInt *R = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00001580 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
Nick Lewyckye0332982009-09-20 01:35:59 +00001581 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001582 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001583 return pred;
1584 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Nick Lewyckye0332982009-09-20 01:35:59 +00001585 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001586 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001587 return pred;
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001588 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Nick Lewyckye0332982009-09-20 01:35:59 +00001589 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
Reid Spencer2e54a152007-03-02 00:28:52 +00001590 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +00001591 return pred;
Dan Gohman062d3782009-08-29 23:35:16 +00001592
Chris Lattnerfed8ceb2006-01-05 07:49:30 +00001593 // If we couldn't figure it out, bail.
Reid Spencer266e42b2006-12-23 06:05:41 +00001594 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerfed8ceb2006-01-05 07:49:30 +00001595 }
Dan Gohman062d3782009-08-29 23:35:16 +00001596
Chris Lattner061da2f2004-01-13 05:51:55 +00001597 // If the first operand is simple, swap operands.
Reid Spencer266e42b2006-12-23 06:05:41 +00001598 ICmpInst::Predicate SwappedRelation =
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001599 evaluateICmpRelation(V2, V1, isSigned);
Reid Spencer266e42b2006-12-23 06:05:41 +00001600 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1601 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner061da2f2004-01-13 05:51:55 +00001602
Chris Lattner3c46e142010-02-01 19:35:08 +00001603 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
Chris Lattner125ed542004-02-01 01:23:19 +00001604 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
Reid Spencer266e42b2006-12-23 06:05:41 +00001605 ICmpInst::Predicate SwappedRelation =
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001606 evaluateICmpRelation(V2, V1, isSigned);
Reid Spencer266e42b2006-12-23 06:05:41 +00001607 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1608 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner3c46e142010-02-01 19:35:08 +00001609 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner125ed542004-02-01 01:23:19 +00001610 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001611
Chris Lattner3c46e142010-02-01 19:35:08 +00001612 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1613 // constant (which, since the types must match, means that it's a
1614 // ConstantPointerNull).
1615 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattner52fe8692007-09-10 23:42:42 +00001616 // Don't try to decide equality of aliases.
Chris Lattner3c46e142010-02-01 19:35:08 +00001617 if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
1618 if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
Chris Lattner52fe8692007-09-10 23:42:42 +00001619 return ICmpInst::ICMP_NE;
Chris Lattner3c46e142010-02-01 19:35:08 +00001620 } else if (isa<BlockAddress>(V2)) {
1621 return ICmpInst::ICMP_NE; // Globals never equal labels.
Chris Lattner061da2f2004-01-13 05:51:55 +00001622 } else {
1623 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
Chris Lattner3c46e142010-02-01 19:35:08 +00001624 // GlobalVals can never be null unless they have external weak linkage.
1625 // We don't try to evaluate aliases here.
1626 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
Reid Spencer266e42b2006-12-23 06:05:41 +00001627 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001628 }
Chris Lattner3c46e142010-02-01 19:35:08 +00001629 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1630 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1631 ICmpInst::Predicate SwappedRelation =
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001632 evaluateICmpRelation(V2, V1, isSigned);
Chris Lattner3c46e142010-02-01 19:35:08 +00001633 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1634 return ICmpInst::getSwappedPredicate(SwappedRelation);
1635 return ICmpInst::BAD_ICMP_PREDICATE;
1636 }
1637
1638 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1639 // constant (which, since the types must match, means that it is a
1640 // ConstantPointerNull).
1641 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1642 // Block address in another function can't equal this one, but block
1643 // addresses in the current function might be the same if blocks are
1644 // empty.
1645 if (BA2->getFunction() != BA->getFunction())
1646 return ICmpInst::ICMP_NE;
1647 } else {
1648 // Block addresses aren't null, don't equal the address of globals.
1649 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1650 "Canonicalization guarantee!");
1651 return ICmpInst::ICMP_NE;
1652 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001653 } else {
1654 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
Chris Lattner3c46e142010-02-01 19:35:08 +00001655 // constantexpr, a global, block address, or a simple constant.
Nick Lewyckye0332982009-09-20 01:35:59 +00001656 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1657 Constant *CE1Op0 = CE1->getOperand(0);
Chris Lattner061da2f2004-01-13 05:51:55 +00001658
1659 switch (CE1->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001660 case Instruction::Trunc:
1661 case Instruction::FPTrunc:
1662 case Instruction::FPExt:
1663 case Instruction::FPToUI:
1664 case Instruction::FPToSI:
Reid Spencer266e42b2006-12-23 06:05:41 +00001665 break; // We can't evaluate floating point casts or truncations.
1666
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001667 case Instruction::UIToFP:
1668 case Instruction::SIToFP:
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001669 case Instruction::BitCast:
Reid Spencer266e42b2006-12-23 06:05:41 +00001670 case Instruction::ZExt:
1671 case Instruction::SExt:
Chris Lattner061da2f2004-01-13 05:51:55 +00001672 // If the cast is not actually changing bits, and the second operand is a
1673 // null pointer, do the comparison with the pre-casted value.
1674 if (V2->isNullValue() &&
Duncan Sands19d0b472010-02-16 11:11:14 +00001675 (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001676 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1677 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001678 return evaluateICmpRelation(CE1Op0,
Owen Anderson5a1acd92009-07-31 20:28:14 +00001679 Constant::getNullValue(CE1Op0->getType()),
Nick Lewycky2949a232009-09-20 03:48:46 +00001680 isSigned);
Reid Spencer266e42b2006-12-23 06:05:41 +00001681 }
Chris Lattner192e3262004-04-11 01:29:30 +00001682 break;
Chris Lattner061da2f2004-01-13 05:51:55 +00001683
1684 case Instruction::GetElementPtr:
1685 // Ok, since this is a getelementptr, we know that the constant has a
1686 // pointer type. Check the various cases.
1687 if (isa<ConstantPointerNull>(V2)) {
1688 // If we are comparing a GEP to a null pointer, check to see if the base
1689 // of the GEP equals the null pointer.
Reid Spencer9d36acf2006-12-24 18:52:08 +00001690 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
Reid Spencer876f7222006-12-06 00:25:09 +00001691 if (GV->hasExternalWeakLinkage())
1692 // Weak linkage GVals could be zero or not. We're comparing that
1693 // to null pointer so its greater-or-equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001694 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
Reid Spencer876f7222006-12-06 00:25:09 +00001695 else
1696 // If its not weak linkage, the GVal must have a non-zero address
1697 // so the result is greater-than
Nick Lewycky9e085542009-09-20 04:27:06 +00001698 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001699 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1700 // If we are indexing from a null pointer, check to see if we have any
1701 // non-zero indices.
1702 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1703 if (!CE1->getOperand(i)->isNullValue())
1704 // Offsetting from null, must not be equal.
Reid Spencer266e42b2006-12-23 06:05:41 +00001705 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001706 // Only zero indexes from null, must still be zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00001707 return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001708 }
1709 // Otherwise, we can't really say if the first operand is null or not.
Chris Lattner3c46e142010-02-01 19:35:08 +00001710 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001711 if (isa<ConstantPointerNull>(CE1Op0)) {
Chris Lattner3c46e142010-02-01 19:35:08 +00001712 if (GV2->hasExternalWeakLinkage())
Reid Spencer876f7222006-12-06 00:25:09 +00001713 // Weak linkage GVals could be zero or not. We're comparing it to
1714 // a null pointer, so its less-or-equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001715 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
Reid Spencer876f7222006-12-06 00:25:09 +00001716 else
1717 // If its not weak linkage, the GVal must have a non-zero address
1718 // so the result is less-than
Reid Spencer266e42b2006-12-23 06:05:41 +00001719 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Chris Lattner3c46e142010-02-01 19:35:08 +00001720 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1721 if (GV == GV2) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001722 // If this is a getelementptr of the same global, then it must be
1723 // different. Because the types must match, the getelementptr could
1724 // only have at most one index, and because we fold getelementptr's
1725 // with a single zero index, it must be nonzero.
1726 assert(CE1->getNumOperands() == 2 &&
1727 !CE1->getOperand(1)->isNullValue() &&
1728 "Suprising getelementptr!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001729 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001730 } else {
1731 // If they are different globals, we don't know what the value is,
1732 // but they can't be equal.
Reid Spencer266e42b2006-12-23 06:05:41 +00001733 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001734 }
1735 }
1736 } else {
Nick Lewyckye0332982009-09-20 01:35:59 +00001737 ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1738 Constant *CE2Op0 = CE2->getOperand(0);
Chris Lattner061da2f2004-01-13 05:51:55 +00001739
1740 // There are MANY other foldings that we could perform here. They will
1741 // probably be added on demand, as they seem needed.
1742 switch (CE2->getOpcode()) {
1743 default: break;
1744 case Instruction::GetElementPtr:
1745 // By far the most common case to handle is when the base pointers are
1746 // obviously to the same or different globals.
Reid Spenceraccd7c72004-07-17 23:47:01 +00001747 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001748 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001749 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001750 // Ok, we know that both getelementptr instructions are based on the
1751 // same global. From this, we can precisely determine the relative
1752 // ordering of the resultant pointers.
1753 unsigned i = 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001754
Dan Gohman7190d482009-09-10 23:37:55 +00001755 // The logic below assumes that the result of the comparison
1756 // can be determined by finding the first index that differs.
1757 // This doesn't work if there is over-indexing in any
1758 // subsequent indices, so check for that case first.
1759 if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1760 !CE2->isGEPWithNoNotionalOverIndexing())
1761 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1762
Chris Lattner061da2f2004-01-13 05:51:55 +00001763 // Compare all of the operands the GEP's have in common.
Chris Lattner60c47262005-01-28 19:09:51 +00001764 gep_type_iterator GTI = gep_type_begin(CE1);
1765 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1766 ++i, ++GTI)
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001767 switch (IdxCompare(CE1->getOperand(i),
Owen Anderson53a52212009-07-13 04:09:18 +00001768 CE2->getOperand(i), GTI.getIndexedType())) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001769 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1770 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1771 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001772 }
1773
1774 // Ok, we ran out of things they have in common. If any leftovers
1775 // are non-zero then we have a difference, otherwise we are equal.
1776 for (; i < CE1->getNumOperands(); ++i)
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001777 if (!CE1->getOperand(i)->isNullValue()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001778 if (isa<ConstantInt>(CE1->getOperand(i)))
Reid Spencer266e42b2006-12-23 06:05:41 +00001779 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner60c47262005-01-28 19:09:51 +00001780 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001781 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001782 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001783
Chris Lattner061da2f2004-01-13 05:51:55 +00001784 for (; i < CE2->getNumOperands(); ++i)
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001785 if (!CE2->getOperand(i)->isNullValue()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001786 if (isa<ConstantInt>(CE2->getOperand(i)))
Reid Spencer266e42b2006-12-23 06:05:41 +00001787 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Chris Lattner60c47262005-01-28 19:09:51 +00001788 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001789 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001790 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001791 return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001792 }
1793 }
1794 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001795 default:
1796 break;
1797 }
1798 }
1799
Reid Spencer266e42b2006-12-23 06:05:41 +00001800 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001801}
1802
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001803Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
Nick Lewyckye0332982009-09-20 01:35:59 +00001804 Constant *C1, Constant *C2) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001805 const Type *ResultTy;
1806 if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001807 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1808 VT->getNumElements());
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001809 else
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001810 ResultTy = Type::getInt1Ty(C1->getContext());
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001811
Chris Lattnerd137a082008-07-08 05:46:34 +00001812 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001813 if (pred == FCmpInst::FCMP_FALSE)
Owen Anderson5a1acd92009-07-31 20:28:14 +00001814 return Constant::getNullValue(ResultTy);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001815
1816 if (pred == FCmpInst::FCMP_TRUE)
Owen Anderson5a1acd92009-07-31 20:28:14 +00001817 return Constant::getAllOnesValue(ResultTy);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001818
Reid Spencer266e42b2006-12-23 06:05:41 +00001819 // Handle some degenerate cases first
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001820 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
Chris Lattner3afc0722010-03-03 19:46:03 +00001821 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
Reid Spencer266e42b2006-12-23 06:05:41 +00001822
Dale Johannesen19db0932007-10-14 01:56:47 +00001823 // No compile-time operations on this type yet.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001824 if (C1->getType()->isPPC_FP128Ty())
Dale Johannesen19db0932007-10-14 01:56:47 +00001825 return 0;
1826
Reid Spencer266e42b2006-12-23 06:05:41 +00001827 // icmp eq/ne(null,GV) -> false/true
1828 if (C1->isNullValue()) {
1829 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
Duncan Sandsa38e5272007-09-19 10:16:17 +00001830 // Don't try to evaluate aliases. External weak GV can be null.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001831 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
Reid Spencer9d36acf2006-12-24 18:52:08 +00001832 if (pred == ICmpInst::ICMP_EQ)
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001833 return ConstantInt::getFalse(C1->getContext());
Reid Spencer9d36acf2006-12-24 18:52:08 +00001834 else if (pred == ICmpInst::ICMP_NE)
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001835 return ConstantInt::getTrue(C1->getContext());
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001836 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001837 // icmp eq/ne(GV,null) -> false/true
1838 } else if (C2->isNullValue()) {
1839 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
Duncan Sandsa38e5272007-09-19 10:16:17 +00001840 // Don't try to evaluate aliases. External weak GV can be null.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001841 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
Reid Spencer9d36acf2006-12-24 18:52:08 +00001842 if (pred == ICmpInst::ICMP_EQ)
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001843 return ConstantInt::getFalse(C1->getContext());
Reid Spencer9d36acf2006-12-24 18:52:08 +00001844 else if (pred == ICmpInst::ICMP_NE)
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001845 return ConstantInt::getTrue(C1->getContext());
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001846 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00001847 }
1848
Nick Lewyckyb0225ba2009-09-20 07:21:39 +00001849 // If the comparison is a comparison between two i1's, simplify it.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001850 if (C1->getType()->isIntegerTy(1)) {
Nick Lewyckyb0225ba2009-09-20 07:21:39 +00001851 switch(pred) {
1852 case ICmpInst::ICMP_EQ:
1853 if (isa<ConstantInt>(C2))
1854 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1855 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1856 case ICmpInst::ICMP_NE:
1857 return ConstantExpr::getXor(C1, C2);
1858 default:
1859 break;
1860 }
1861 }
1862
Chris Lattner344da522007-01-12 18:42:52 +00001863 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
Reid Spencer81658a82007-02-27 06:23:51 +00001864 APInt V1 = cast<ConstantInt>(C1)->getValue();
1865 APInt V2 = cast<ConstantInt>(C2)->getValue();
1866 switch (pred) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001867 default: llvm_unreachable("Invalid ICmp Predicate"); return 0;
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001868 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2);
1869 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2);
1870 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1871 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1872 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1873 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1874 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1875 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1876 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1877 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
Chris Lattner061da2f2004-01-13 05:51:55 +00001878 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001879 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001880 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1881 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1882 APFloat::cmpResult R = C1V.compare(C2V);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001883 switch (pred) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001884 default: llvm_unreachable("Invalid FCmp Predicate"); return 0;
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001885 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1886 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00001887 case FCmpInst::FCMP_UNO:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001888 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
Reid Spencer74bd0362007-01-11 00:25:45 +00001889 case FCmpInst::FCMP_ORD:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001890 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
Reid Spencer266e42b2006-12-23 06:05:41 +00001891 case FCmpInst::FCMP_UEQ:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001892 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1893 R==APFloat::cmpEqual);
Reid Spencercddc9df2007-01-12 04:24:46 +00001894 case FCmpInst::FCMP_OEQ:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001895 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
Reid Spencer74bd0362007-01-11 00:25:45 +00001896 case FCmpInst::FCMP_UNE:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001897 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
Reid Spencercddc9df2007-01-12 04:24:46 +00001898 case FCmpInst::FCMP_ONE:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001899 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1900 R==APFloat::cmpGreaterThan);
Reid Spencer74bd0362007-01-11 00:25:45 +00001901 case FCmpInst::FCMP_ULT:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001902 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1903 R==APFloat::cmpLessThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001904 case FCmpInst::FCMP_OLT:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001905 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
Reid Spencer266e42b2006-12-23 06:05:41 +00001906 case FCmpInst::FCMP_UGT:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001907 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1908 R==APFloat::cmpGreaterThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001909 case FCmpInst::FCMP_OGT:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001910 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
Reid Spencer74bd0362007-01-11 00:25:45 +00001911 case FCmpInst::FCMP_ULE:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001912 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001913 case FCmpInst::FCMP_OLE:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001914 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1915 R==APFloat::cmpEqual);
Reid Spencer266e42b2006-12-23 06:05:41 +00001916 case FCmpInst::FCMP_UGE:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001917 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001918 case FCmpInst::FCMP_OGE:
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001919 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1920 R==APFloat::cmpEqual);
Reid Spencer266e42b2006-12-23 06:05:41 +00001921 }
Duncan Sands19d0b472010-02-16 11:11:14 +00001922 } else if (C1->getType()->isVectorTy()) {
Chris Lattner67136cf2008-07-10 00:29:28 +00001923 SmallVector<Constant*, 16> C1Elts, C2Elts;
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001924 C1->getVectorElements(C1Elts);
1925 C2->getVectorElements(C2Elts);
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001926 if (C1Elts.empty() || C2Elts.empty())
1927 return 0;
Dan Gohman062d3782009-08-29 23:35:16 +00001928
Chris Lattner67136cf2008-07-10 00:29:28 +00001929 // If we can constant fold the comparison of each element, constant fold
1930 // the whole vector comparison.
1931 SmallVector<Constant*, 4> ResElts;
Chris Lattner67136cf2008-07-10 00:29:28 +00001932 for (unsigned i = 0, e = C1Elts.size(); i != e; ++i) {
1933 // Compare the elements, producing an i1 result or constant expr.
Nick Lewycky9e26c1c2010-01-21 07:03:21 +00001934 ResElts.push_back(ConstantExpr::getCompare(pred, C1Elts[i], C2Elts[i]));
Reid Spencer266e42b2006-12-23 06:05:41 +00001935 }
Owen Anderson4aa32952009-07-28 21:19:26 +00001936 return ConstantVector::get(&ResElts[0], ResElts.size());
Reid Spencer266e42b2006-12-23 06:05:41 +00001937 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001938
Duncan Sands9dff9be2010-02-15 16:12:20 +00001939 if (C1->getType()->isFloatingPointTy()) {
Chris Lattner350e4172008-07-08 18:47:38 +00001940 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001941 switch (evaluateFCmpRelation(C1, C2)) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001942 default: llvm_unreachable("Unknown relation!");
Reid Spencer9d36acf2006-12-24 18:52:08 +00001943 case FCmpInst::FCMP_UNO:
1944 case FCmpInst::FCMP_ORD:
1945 case FCmpInst::FCMP_UEQ:
1946 case FCmpInst::FCMP_UNE:
1947 case FCmpInst::FCMP_ULT:
1948 case FCmpInst::FCMP_UGT:
1949 case FCmpInst::FCMP_ULE:
1950 case FCmpInst::FCMP_UGE:
1951 case FCmpInst::FCMP_TRUE:
1952 case FCmpInst::FCMP_FALSE:
1953 case FCmpInst::BAD_FCMP_PREDICATE:
1954 break; // Couldn't determine anything about these constants.
1955 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
Chris Lattnerd137a082008-07-08 05:46:34 +00001956 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1957 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1958 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1959 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001960 case FCmpInst::FCMP_OLT: // We know that C1 < C2
Chris Lattnerd137a082008-07-08 05:46:34 +00001961 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1962 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1963 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1964 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001965 case FCmpInst::FCMP_OGT: // We know that C1 > C2
Chris Lattnerd137a082008-07-08 05:46:34 +00001966 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1967 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1968 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1969 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001970 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1971 // We can only partially decide this relation.
1972 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
Chris Lattnerd137a082008-07-08 05:46:34 +00001973 Result = 0;
1974 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1975 Result = 1;
Chris Lattner061da2f2004-01-13 05:51:55 +00001976 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001977 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1978 // We can only partially decide this relation.
1979 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
Chris Lattnerd137a082008-07-08 05:46:34 +00001980 Result = 0;
1981 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1982 Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001983 break;
1984 case ICmpInst::ICMP_NE: // We know that C1 != C2
1985 // We can only partially decide this relation.
1986 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
Chris Lattnerd137a082008-07-08 05:46:34 +00001987 Result = 0;
1988 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1989 Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001990 break;
1991 }
Dan Gohman062d3782009-08-29 23:35:16 +00001992
Chris Lattnerd137a082008-07-08 05:46:34 +00001993 // If we evaluated the result, return it now.
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001994 if (Result != -1)
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00001995 return ConstantInt::get(ResultTy, Result);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00001996
Reid Spencer9d36acf2006-12-24 18:52:08 +00001997 } else {
1998 // Evaluate the relation between the two constants, per the predicate.
Chris Lattnerd137a082008-07-08 05:46:34 +00001999 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002000 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00002001 default: llvm_unreachable("Unknown relational!");
Reid Spencer9d36acf2006-12-24 18:52:08 +00002002 case ICmpInst::BAD_ICMP_PREDICATE:
2003 break; // Couldn't determine anything about these constants.
2004 case ICmpInst::ICMP_EQ: // We know the constants are equal!
2005 // If we know the constants are equal, we can decide the result of this
2006 // computation precisely.
Nick Lewycky9e085542009-09-20 04:27:06 +00002007 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
Chris Lattnerd137a082008-07-08 05:46:34 +00002008 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002009 case ICmpInst::ICMP_ULT:
Nick Lewycky9e085542009-09-20 04:27:06 +00002010 switch (pred) {
2011 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00002012 Result = 1; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00002013 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00002014 Result = 0; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00002015 }
Chris Lattnerd137a082008-07-08 05:46:34 +00002016 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002017 case ICmpInst::ICMP_SLT:
Nick Lewycky9e085542009-09-20 04:27:06 +00002018 switch (pred) {
2019 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00002020 Result = 1; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00002021 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00002022 Result = 0; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00002023 }
Chris Lattnerd137a082008-07-08 05:46:34 +00002024 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002025 case ICmpInst::ICMP_UGT:
Nick Lewycky9e085542009-09-20 04:27:06 +00002026 switch (pred) {
2027 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00002028 Result = 1; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00002029 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00002030 Result = 0; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00002031 }
Chris Lattnerd137a082008-07-08 05:46:34 +00002032 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002033 case ICmpInst::ICMP_SGT:
Nick Lewycky9e085542009-09-20 04:27:06 +00002034 switch (pred) {
2035 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00002036 Result = 1; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00002037 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
Nick Lewycky2b31b532009-09-20 05:47:45 +00002038 Result = 0; break;
Nick Lewycky9e085542009-09-20 04:27:06 +00002039 }
Chris Lattnerd137a082008-07-08 05:46:34 +00002040 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002041 case ICmpInst::ICMP_ULE:
Chris Lattnerd137a082008-07-08 05:46:34 +00002042 if (pred == ICmpInst::ICMP_UGT) Result = 0;
Nick Lewycky9e085542009-09-20 04:27:06 +00002043 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002044 break;
2045 case ICmpInst::ICMP_SLE:
Chris Lattnerd137a082008-07-08 05:46:34 +00002046 if (pred == ICmpInst::ICMP_SGT) Result = 0;
Nick Lewycky9e085542009-09-20 04:27:06 +00002047 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002048 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002049 case ICmpInst::ICMP_UGE:
Chris Lattnerd137a082008-07-08 05:46:34 +00002050 if (pred == ICmpInst::ICMP_ULT) Result = 0;
Nick Lewycky9e085542009-09-20 04:27:06 +00002051 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002052 break;
2053 case ICmpInst::ICMP_SGE:
Chris Lattnerd137a082008-07-08 05:46:34 +00002054 if (pred == ICmpInst::ICMP_SLT) Result = 0;
Nick Lewycky9e085542009-09-20 04:27:06 +00002055 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002056 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002057 case ICmpInst::ICMP_NE:
Chris Lattnerd137a082008-07-08 05:46:34 +00002058 if (pred == ICmpInst::ICMP_EQ) Result = 0;
2059 if (pred == ICmpInst::ICMP_NE) Result = 1;
Reid Spencer9d36acf2006-12-24 18:52:08 +00002060 break;
2061 }
Dan Gohman062d3782009-08-29 23:35:16 +00002062
Chris Lattnerd137a082008-07-08 05:46:34 +00002063 // If we evaluated the result, return it now.
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002064 if (Result != -1)
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002065 return ConstantInt::get(ResultTy, Result);
Dan Gohman062d3782009-08-29 23:35:16 +00002066
Nick Lewycky4a034522009-09-20 05:48:50 +00002067 // If the right hand side is a bitcast, try using its inverse to simplify
Chris Lattner94eb4b22010-02-01 20:04:40 +00002068 // it by moving it to the left hand side. We can't do this if it would turn
Duncan Sandsdddba062010-02-01 20:42:02 +00002069 // a vector compare into a scalar compare or visa versa.
Nick Lewycky4a034522009-09-20 05:48:50 +00002070 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
Chris Lattner94eb4b22010-02-01 20:04:40 +00002071 Constant *CE2Op0 = CE2->getOperand(0);
2072 if (CE2->getOpcode() == Instruction::BitCast &&
Duncan Sands19d0b472010-02-16 11:11:14 +00002073 CE2->getType()->isVectorTy()==CE2Op0->getType()->isVectorTy()) {
Nick Lewycky4a034522009-09-20 05:48:50 +00002074 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
2075 return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
2076 }
2077 }
2078
Nick Lewycky9b3ed872009-09-20 07:31:25 +00002079 // If the left hand side is an extension, try eliminating it.
2080 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
2081 if (CE1->getOpcode() == Instruction::SExt ||
2082 CE1->getOpcode() == Instruction::ZExt) {
2083 Constant *CE1Op0 = CE1->getOperand(0);
2084 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
2085 if (CE1Inverse == CE1Op0) {
2086 // Check whether we can safely truncate the right hand side.
2087 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
2088 if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
2089 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
2090 }
2091 }
2092 }
2093 }
2094
Eli Friedmane67cae32009-12-17 06:07:04 +00002095 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
2096 (C1->isNullValue() && !C2->isNullValue())) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002097 // If C2 is a constant expr and C1 isn't, flip them around and fold the
Reid Spencer9d36acf2006-12-24 18:52:08 +00002098 // other way if possible.
Eli Friedmane67cae32009-12-17 06:07:04 +00002099 // Also, if C1 is null and C2 isn't, flip them around.
Reid Spencer9d36acf2006-12-24 18:52:08 +00002100 switch (pred) {
2101 case ICmpInst::ICMP_EQ:
2102 case ICmpInst::ICMP_NE:
2103 // No change of predicate required.
Eli Friedmane67cae32009-12-17 06:07:04 +00002104 return ConstantExpr::getICmp(pred, C2, C1);
Reid Spencer9d36acf2006-12-24 18:52:08 +00002105
2106 case ICmpInst::ICMP_ULT:
2107 case ICmpInst::ICMP_SLT:
2108 case ICmpInst::ICMP_UGT:
2109 case ICmpInst::ICMP_SGT:
2110 case ICmpInst::ICMP_ULE:
2111 case ICmpInst::ICMP_SLE:
2112 case ICmpInst::ICMP_UGE:
2113 case ICmpInst::ICMP_SGE:
2114 // Change the predicate as necessary to swap the operands.
2115 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
Eli Friedmane67cae32009-12-17 06:07:04 +00002116 return ConstantExpr::getICmp(pred, C2, C1);
Reid Spencer9d36acf2006-12-24 18:52:08 +00002117
2118 default: // These predicates cannot be flopped around.
2119 break;
2120 }
Chris Lattner061da2f2004-01-13 05:51:55 +00002121 }
2122 }
2123 return 0;
Dan Gohman062d3782009-08-29 23:35:16 +00002124}
Chris Lattner1dd054c2004-01-12 22:07:24 +00002125
Dan Gohman21c62162009-09-11 00:04:14 +00002126/// isInBoundsIndices - Test whether the given sequence of *normalized* indices
2127/// is "inbounds".
2128static bool isInBoundsIndices(Constant *const *Idxs, size_t NumIdx) {
2129 // No indices means nothing that could be out of bounds.
2130 if (NumIdx == 0) return true;
2131
2132 // If the first index is zero, it's in bounds.
2133 if (Idxs[0]->isNullValue()) return true;
2134
2135 // If the first index is one and all the rest are zero, it's in bounds,
2136 // by the one-past-the-end rule.
2137 if (!cast<ConstantInt>(Idxs[0])->isOne())
2138 return false;
2139 for (unsigned i = 1, e = NumIdx; i != e; ++i)
2140 if (!Idxs[i]->isNullValue())
2141 return false;
2142 return true;
2143}
2144
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002145Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
Dan Gohman21c62162009-09-11 00:04:14 +00002146 bool inBounds,
David Greenec656cbb2007-09-04 15:46:09 +00002147 Constant* const *Idxs,
Owen Anderson0d2de8c2009-06-20 00:24:58 +00002148 unsigned NumIdx) {
Chris Lattner302116a2007-01-31 04:40:28 +00002149 if (NumIdx == 0 ||
2150 (NumIdx == 1 && Idxs[0]->isNullValue()))
Nick Lewyckye0332982009-09-20 01:35:59 +00002151 return C;
Chris Lattner1dd054c2004-01-12 22:07:24 +00002152
Chris Lattnerf6013752004-10-17 21:54:55 +00002153 if (isa<UndefValue>(C)) {
Christopher Lambedf07882007-12-17 01:12:55 +00002154 const PointerType *Ptr = cast<PointerType>(C->getType());
2155 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
David Greenec656cbb2007-09-04 15:46:09 +00002156 (Value **)Idxs,
Dan Gohman12fce772008-05-15 19:50:34 +00002157 (Value **)Idxs+NumIdx);
Chris Lattnerf6013752004-10-17 21:54:55 +00002158 assert(Ty != 0 && "Invalid indices for GEP!");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002159 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
Chris Lattnerf6013752004-10-17 21:54:55 +00002160 }
2161
Chris Lattner302116a2007-01-31 04:40:28 +00002162 Constant *Idx0 = Idxs[0];
Chris Lattner04b60fe2004-02-16 20:46:13 +00002163 if (C->isNullValue()) {
2164 bool isNull = true;
Chris Lattner302116a2007-01-31 04:40:28 +00002165 for (unsigned i = 0, e = NumIdx; i != e; ++i)
2166 if (!Idxs[i]->isNullValue()) {
Chris Lattner04b60fe2004-02-16 20:46:13 +00002167 isNull = false;
2168 break;
2169 }
2170 if (isNull) {
Christopher Lambedf07882007-12-17 01:12:55 +00002171 const PointerType *Ptr = cast<PointerType>(C->getType());
2172 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
David Greenec656cbb2007-09-04 15:46:09 +00002173 (Value**)Idxs,
Dan Gohman12fce772008-05-15 19:50:34 +00002174 (Value**)Idxs+NumIdx);
Chris Lattner04b60fe2004-02-16 20:46:13 +00002175 assert(Ty != 0 && "Invalid indices for GEP!");
Owen Andersonb292b8c2009-07-30 23:03:37 +00002176 return ConstantPointerNull::get(
Owen Anderson4056ca92009-07-29 22:17:13 +00002177 PointerType::get(Ty,Ptr->getAddressSpace()));
Chris Lattner04b60fe2004-02-16 20:46:13 +00002178 }
2179 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00002180
Nick Lewyckye0332982009-09-20 01:35:59 +00002181 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner1dd054c2004-01-12 22:07:24 +00002182 // Combine Indices - If the source pointer to this getelementptr instruction
2183 // is a getelementptr instruction, combine the indices of the two
2184 // getelementptr instructions into a single instruction.
2185 //
2186 if (CE->getOpcode() == Instruction::GetElementPtr) {
2187 const Type *LastTy = 0;
2188 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2189 I != E; ++I)
2190 LastTy = *I;
2191
Duncan Sands19d0b472010-02-16 11:11:14 +00002192 if ((LastTy && LastTy->isArrayTy()) || Idx0->isNullValue()) {
Chris Lattner302116a2007-01-31 04:40:28 +00002193 SmallVector<Value*, 16> NewIndices;
2194 NewIndices.reserve(NumIdx + CE->getNumOperands());
Chris Lattner1dd054c2004-01-12 22:07:24 +00002195 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
Chris Lattner13128ab2004-10-11 22:52:25 +00002196 NewIndices.push_back(CE->getOperand(i));
Chris Lattner1dd054c2004-01-12 22:07:24 +00002197
2198 // Add the last index of the source with the first index of the new GEP.
2199 // Make sure to handle the case when they are actually different types.
2200 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
Chris Lattner13128ab2004-10-11 22:52:25 +00002201 // Otherwise it must be an array.
2202 if (!Idx0->isNullValue()) {
Chris Lattner71068a02004-07-07 04:45:13 +00002203 const Type *IdxTy = Combined->getType();
Reid Spencer1a063892006-12-04 02:46:44 +00002204 if (IdxTy != Idx0->getType()) {
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002205 const Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
2206 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
2207 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
Owen Anderson487375e2009-07-29 18:55:55 +00002208 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
Reid Spencer1a063892006-12-04 02:46:44 +00002209 } else {
2210 Combined =
Owen Anderson487375e2009-07-29 18:55:55 +00002211 ConstantExpr::get(Instruction::Add, Idx0, Combined);
Reid Spencer1a063892006-12-04 02:46:44 +00002212 }
Chris Lattner71068a02004-07-07 04:45:13 +00002213 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002214
Chris Lattner1dd054c2004-01-12 22:07:24 +00002215 NewIndices.push_back(Combined);
Chris Lattner302116a2007-01-31 04:40:28 +00002216 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
Dan Gohman21c62162009-09-11 00:04:14 +00002217 return (inBounds && cast<GEPOperator>(CE)->isInBounds()) ?
2218 ConstantExpr::getInBoundsGetElementPtr(CE->getOperand(0),
2219 &NewIndices[0],
2220 NewIndices.size()) :
2221 ConstantExpr::getGetElementPtr(CE->getOperand(0),
2222 &NewIndices[0],
2223 NewIndices.size());
Chris Lattner1dd054c2004-01-12 22:07:24 +00002224 }
2225 }
2226
2227 // Implement folding of:
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00002228 // int* getelementptr ([2 x int]* bitcast ([3 x int]* %X to [2 x int]*),
Chris Lattner1dd054c2004-01-12 22:07:24 +00002229 // long 0, long 0)
2230 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
2231 //
Chris Lattneraadc7782007-08-13 17:09:08 +00002232 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002233 if (const PointerType *SPT =
Chris Lattner1dd054c2004-01-12 22:07:24 +00002234 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
2235 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
2236 if (const ArrayType *CAT =
Chris Lattner02157b02006-06-28 21:38:54 +00002237 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
Chris Lattner1dd054c2004-01-12 22:07:24 +00002238 if (CAT->getElementType() == SAT->getElementType())
Dan Gohman21c62162009-09-11 00:04:14 +00002239 return inBounds ?
2240 ConstantExpr::getInBoundsGetElementPtr(
2241 (Constant*)CE->getOperand(0), Idxs, NumIdx) :
2242 ConstantExpr::getGetElementPtr(
Owen Anderson0d2de8c2009-06-20 00:24:58 +00002243 (Constant*)CE->getOperand(0), Idxs, NumIdx);
Chris Lattneraadc7782007-08-13 17:09:08 +00002244 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00002245 }
Dan Gohman21c62162009-09-11 00:04:14 +00002246
2247 // Check to see if any array indices are not within the corresponding
2248 // notional array bounds. If so, try to determine if they can be factored
2249 // out into preceding dimensions.
2250 bool Unknown = false;
2251 SmallVector<Constant *, 8> NewIdxs;
2252 const Type *Ty = C->getType();
2253 const Type *Prev = 0;
2254 for (unsigned i = 0; i != NumIdx;
2255 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2256 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2257 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2258 if (ATy->getNumElements() <= INT64_MAX &&
2259 ATy->getNumElements() != 0 &&
2260 CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2261 if (isa<SequentialType>(Prev)) {
2262 // It's out of range, but we can factor it into the prior
2263 // dimension.
2264 NewIdxs.resize(NumIdx);
2265 ConstantInt *Factor = ConstantInt::get(CI->getType(),
2266 ATy->getNumElements());
2267 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2268
2269 Constant *PrevIdx = Idxs[i-1];
2270 Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2271
2272 // Before adding, extend both operands to i64 to avoid
2273 // overflow trouble.
Duncan Sands9dff9be2010-02-15 16:12:20 +00002274 if (!PrevIdx->getType()->isIntegerTy(64))
Dan Gohman21c62162009-09-11 00:04:14 +00002275 PrevIdx = ConstantExpr::getSExt(PrevIdx,
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002276 Type::getInt64Ty(Div->getContext()));
Duncan Sands9dff9be2010-02-15 16:12:20 +00002277 if (!Div->getType()->isIntegerTy(64))
Dan Gohman21c62162009-09-11 00:04:14 +00002278 Div = ConstantExpr::getSExt(Div,
Chris Lattnerf5edeeb2010-02-01 20:48:08 +00002279 Type::getInt64Ty(Div->getContext()));
Dan Gohman21c62162009-09-11 00:04:14 +00002280
2281 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2282 } else {
2283 // It's out of range, but the prior dimension is a struct
2284 // so we can't do anything about it.
2285 Unknown = true;
2286 }
2287 }
2288 } else {
2289 // We don't know if it's in range or not.
2290 Unknown = true;
2291 }
2292 }
2293
2294 // If we did any factoring, start over with the adjusted indices.
2295 if (!NewIdxs.empty()) {
2296 for (unsigned i = 0; i != NumIdx; ++i)
2297 if (!NewIdxs[i]) NewIdxs[i] = Idxs[i];
2298 return inBounds ?
Nick Lewyckye0332982009-09-20 01:35:59 +00002299 ConstantExpr::getInBoundsGetElementPtr(C, NewIdxs.data(),
2300 NewIdxs.size()) :
2301 ConstantExpr::getGetElementPtr(C, NewIdxs.data(), NewIdxs.size());
Dan Gohman21c62162009-09-11 00:04:14 +00002302 }
2303
2304 // If all indices are known integers and normalized, we can do a simple
2305 // check for the "inbounds" property.
2306 if (!Unknown && !inBounds &&
2307 isa<GlobalVariable>(C) && isInBoundsIndices(Idxs, NumIdx))
Nick Lewyckye0332982009-09-20 01:35:59 +00002308 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs, NumIdx);
Dan Gohman21c62162009-09-11 00:04:14 +00002309
Chris Lattner1dd054c2004-01-12 22:07:24 +00002310 return 0;
2311}