blob: 762a24a26330165ccee1d95cd5adbcc62b585c4b [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
15// template-based folder for simple primitive constants like ConstantInt, and
16// the special case hackery that we use to symbolically evaluate expressions
17// that use ConstantExprs.
18//
Chris Lattner2f7c9632001-06-06 20:29:01 +000019//===----------------------------------------------------------------------===//
20
Chris Lattner33e93b82007-02-27 03:05:06 +000021#include "ConstantFold.h"
Chris Lattner6ff6cea2004-01-12 21:02:29 +000022#include "llvm/Constants.h"
Chris Lattnera9eddae2004-02-22 06:25:38 +000023#include "llvm/Instructions.h"
Chris Lattner1f0049c2003-04-17 19:24:18 +000024#include "llvm/DerivedTypes.h"
Chris Lattnerea0789c2004-03-08 06:17:35 +000025#include "llvm/Function.h"
Chris Lattner52fe8692007-09-10 23:42:42 +000026#include "llvm/GlobalAlias.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"
Chris Lattner057083f2006-10-13 17:22:21 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
30#include "llvm/Support/ManagedStatic.h"
31#include "llvm/Support/MathExtras.h"
Jeff Cohen4e3aede2005-05-03 03:13:01 +000032#include <limits>
Chris Lattner9d9cbcf2003-11-17 19:05:17 +000033using namespace llvm;
Chris Lattner61607ee2001-09-09 21:01:20 +000034
Chris Lattner1dd054c2004-01-12 22:07:24 +000035//===----------------------------------------------------------------------===//
36// ConstantFold*Instruction Implementations
37//===----------------------------------------------------------------------===//
Chris Lattner1dd054c2004-01-12 22:07:24 +000038
Chris Lattner5c6399e2007-12-11 06:07:39 +000039/// BitCastConstantVector - Convert the specified ConstantVector node to the
Reid Spencer09575ba2007-02-15 03:39:18 +000040/// specified vector type. At this point, we know that the elements of the
Dan Gohman06c60b62007-07-16 14:29:03 +000041/// input vector constant are all simple integer or FP values.
Chris Lattner5c6399e2007-12-11 06:07:39 +000042static Constant *BitCastConstantVector(ConstantVector *CV,
43 const VectorType *DstTy) {
44 // If this cast changes element count then we can't handle it here:
45 // doing so requires endianness information. This should be handled by
46 // Analysis/ConstantFolding.cpp
47 unsigned NumElts = DstTy->getNumElements();
48 if (NumElts != CV->getNumOperands())
49 return 0;
Chris Lattner6b3f4752006-04-02 01:38:28 +000050
Chris Lattner5c6399e2007-12-11 06:07:39 +000051 // Check to verify that all elements of the input are simple.
52 for (unsigned i = 0; i != NumElts; ++i) {
53 if (!isa<ConstantInt>(CV->getOperand(i)) &&
54 !isa<ConstantFP>(CV->getOperand(i)))
55 return 0;
Chris Lattner6b3f4752006-04-02 01:38:28 +000056 }
Chris Lattner5c6399e2007-12-11 06:07:39 +000057
58 // Bitcast each element now.
59 std::vector<Constant*> Result;
60 const Type *DstEltTy = DstTy->getElementType();
61 for (unsigned i = 0; i != NumElts; ++i)
62 Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i), DstEltTy));
63 return ConstantVector::get(Result);
Chris Lattner6b3f4752006-04-02 01:38:28 +000064}
65
Reid Spencer6c38f0b2006-11-27 01:05:10 +000066/// This function determines which opcode to use to fold two constant cast
67/// expressions together. It uses CastInst::isEliminableCastPair to determine
68/// the opcode. Consequently its just a wrapper around that function.
Reid Spencer05d55b32007-08-05 19:27:01 +000069/// @brief Determine if it is valid to fold a cast of a cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +000070static unsigned
71foldConstantCastPair(
72 unsigned opc, ///< opcode of the second cast constant expression
73 const ConstantExpr*Op, ///< the first cast constant expression
74 const Type *DstTy ///< desintation type of the first cast
75) {
76 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
77 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
78 assert(CastInst::isCast(opc) && "Invalid cast opcode");
79
80 // The the types and opcodes for the two Cast constant expressions
81 const Type *SrcTy = Op->getOperand(0)->getType();
82 const Type *MidTy = Op->getType();
83 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
84 Instruction::CastOps secondOp = Instruction::CastOps(opc);
Chris Lattner6b3f4752006-04-02 01:38:28 +000085
Reid Spencer6c38f0b2006-11-27 01:05:10 +000086 // Let CastInst::isEliminableCastPair do the heavy lifting.
87 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
Reid Spencer8d9336d2006-12-31 05:26:44 +000088 Type::Int64Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +000089}
90
Chris Lattnere8ea0372007-12-11 05:55:02 +000091static Constant *FoldBitCast(Constant *V, const Type *DestTy) {
92 const Type *SrcTy = V->getType();
93 if (SrcTy == DestTy)
94 return V; // no-op cast
95
96 // Check to see if we are casting a pointer to an aggregate to a pointer to
97 // the first element. If so, return the appropriate GEP instruction.
98 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
99 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
100 SmallVector<Value*, 8> IdxList;
101 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
102 const Type *ElTy = PTy->getElementType();
103 while (ElTy != DPTy->getElementType()) {
104 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
105 if (STy->getNumElements() == 0) break;
106 ElTy = STy->getElementType(0);
107 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
108 } else if (const SequentialType *STy = dyn_cast<SequentialType>(ElTy)) {
109 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
110 ElTy = STy->getElementType();
111 IdxList.push_back(IdxList[0]);
112 } else {
113 break;
114 }
115 }
116
117 if (ElTy == DPTy->getElementType())
118 return ConstantExpr::getGetElementPtr(V, &IdxList[0], IdxList.size());
119 }
120
121 // Handle casts from one vector constant to another. We know that the src
122 // and dest type have the same size (otherwise its an illegal cast).
123 if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
124 if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
125 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
126 "Not cast between same sized vectors!");
127 // First, check for null. Undef is already handled.
128 if (isa<ConstantAggregateZero>(V))
129 return Constant::getNullValue(DestTy);
130
Chris Lattner5c6399e2007-12-11 06:07:39 +0000131 if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
132 return BitCastConstantVector(CV, DestPTy);
Chris Lattnere8ea0372007-12-11 05:55:02 +0000133 }
134 }
135
136 // Finally, implement bitcast folding now. The code below doesn't handle
137 // bitcast right.
138 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
139 return ConstantPointerNull::get(cast<PointerType>(DestTy));
140
141 // Handle integral constant input.
142 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
143 if (DestTy->isInteger())
144 // Integral -> Integral. This is a no-op because the bit widths must
145 // be the same. Consequently, we just fold to V.
146 return V;
147
148 if (DestTy->isFloatingPoint()) {
149 assert((DestTy == Type::DoubleTy || DestTy == Type::FloatTy) &&
150 "Unknown FP type!");
151 return ConstantFP::get(DestTy, APFloat(CI->getValue()));
152 }
153 // Otherwise, can't fold this (vector?)
154 return 0;
155 }
156
157 // Handle ConstantFP input.
158 if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
159 // FP -> Integral.
160 if (DestTy == Type::Int32Ty) {
161 return ConstantInt::get(FP->getValueAPF().convertToAPInt());
162 } else {
163 assert(DestTy == Type::Int64Ty && "only support f32/f64 for now!");
164 return ConstantInt::get(FP->getValueAPF().convertToAPInt());
165 }
166 }
167 return 0;
168}
169
170
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000171Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
Chris Lattner1dd054c2004-01-12 22:07:24 +0000172 const Type *DestTy) {
Chris Lattner363485d2007-07-20 22:09:02 +0000173 if (isa<UndefValue>(V)) {
174 // zext(undef) = 0, because the top bits will be zero.
175 // sext(undef) = 0, because the top bits will all be the same.
Chris Lattnerb4c6cc92008-02-19 06:22:12 +0000176 // [us]itofp(undef) = 0, because the result value is bounded.
177 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
178 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
Chris Lattner363485d2007-07-20 22:09:02 +0000179 return Constant::getNullValue(DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000180 return UndefValue::get(DestTy);
Chris Lattner363485d2007-07-20 22:09:02 +0000181 }
Dale Johannesen19db0932007-10-14 01:56:47 +0000182 // No compile-time operations on this type yet.
183 if (V->getType() == Type::PPC_FP128Ty || DestTy == Type::PPC_FP128Ty)
184 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000185
186 // If the cast operand is a constant expression, there's a few things we can
187 // do to try to simplify it.
188 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
189 if (CE->isCast()) {
Reid Spencer1a063892006-12-04 02:46:44 +0000190 // Try hard to fold cast of cast because they are often eliminable.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000191 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
192 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
Chris Lattner1dd054c2004-01-12 22:07:24 +0000193 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
194 // If all of the indexes in the GEP are null values, there is no pointer
195 // adjustment going on. We might as well cast the source pointer.
196 bool isAllNull = true;
197 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
198 if (!CE->getOperand(i)->isNullValue()) {
199 isAllNull = false;
200 break;
201 }
202 if (isAllNull)
Reid Spencer1a063892006-12-04 02:46:44 +0000203 // This is casting one pointer type to another, always BitCast
Reid Spencer27720a92006-12-05 03:30:09 +0000204 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
Chris Lattner1dd054c2004-01-12 22:07:24 +0000205 }
Chris Lattnerfd7bf722004-10-16 23:31:32 +0000206 }
Chris Lattner1dd054c2004-01-12 22:07:24 +0000207
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000208 // We actually have to do a cast now. Perform the cast according to the
209 // opcode specified.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000210 switch (opc) {
211 case Instruction::FPTrunc:
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000212 case Instruction::FPExt:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000213 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
Dale Johannesenf4bad972007-09-19 14:22:58 +0000214 APFloat Val = FPC->getValueAPF();
215 Val.convert(DestTy == Type::FloatTy ? APFloat::IEEEsingle :
216 DestTy == Type::DoubleTy ? APFloat::IEEEdouble :
217 DestTy == Type::X86_FP80Ty ? APFloat::x87DoubleExtended :
218 DestTy == Type::FP128Ty ? APFloat::IEEEquad :
219 APFloat::Bogus,
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000220 APFloat::rmNearestTiesToEven);
221 return ConstantFP::get(DestTy, Val);
222 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000223 return 0; // Can't fold.
224 case Instruction::FPToUI:
Reid Spencer8dabca42006-12-19 07:41:40 +0000225 case Instruction::FPToSI:
Reid Spencer81658a82007-02-27 06:23:51 +0000226 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
Chris Lattner2b827fd2007-10-15 05:34:10 +0000227 const APFloat &V = FPC->getValueAPF();
Dale Johannesenf4bad972007-09-19 14:22:58 +0000228 uint64_t x[2];
Reid Spencer81658a82007-02-27 06:23:51 +0000229 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
Dale Johannesen17663f42007-09-25 23:32:20 +0000230 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
231 APFloat::rmTowardZero);
Dale Johannesenf4bad972007-09-19 14:22:58 +0000232 APInt Val(DestBitWidth, 2, x);
Reid Spencera1276332007-03-01 19:31:12 +0000233 return ConstantInt::get(Val);
Reid Spencer81658a82007-02-27 06:23:51 +0000234 }
Nate Begemand4d45c22007-11-17 03:58:34 +0000235 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
236 std::vector<Constant*> res;
237 const VectorType *DestVecTy = cast<VectorType>(DestTy);
238 const Type *DstEltTy = DestVecTy->getElementType();
239 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
240 res.push_back(ConstantFoldCastInstruction(opc, V->getOperand(i),
241 DstEltTy));
242 return ConstantVector::get(DestVecTy, res);
243 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000244 return 0; // Can't fold.
245 case Instruction::IntToPtr: //always treated as unsigned
246 if (V->isNullValue()) // Is it an integral null value?
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000247 return ConstantPointerNull::get(cast<PointerType>(DestTy));
Reid Spencer8dabca42006-12-19 07:41:40 +0000248 return 0; // Other pointer types cannot be casted
249 case Instruction::PtrToInt: // always treated as unsigned
250 if (V->isNullValue()) // is it a null pointer value?
Zhou Sheng75b871f2007-01-11 12:24:14 +0000251 return ConstantInt::get(DestTy, 0);
Reid Spencer8dabca42006-12-19 07:41:40 +0000252 return 0; // Other pointer types cannot be casted
253 case Instruction::UIToFP:
Reid Spencer8dabca42006-12-19 07:41:40 +0000254 case Instruction::SIToFP:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000255 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Dale Johannesen91506522007-09-30 18:19:03 +0000256 APInt api = CI->getValue();
257 const uint64_t zero[] = {0, 0};
Dale Johannesen91506522007-09-30 18:19:03 +0000258 APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
259 2, zero));
Dan Gohman06c45d52008-02-29 01:42:52 +0000260 (void)apf.convertFromAPInt(api,
261 opc==Instruction::SIToFP,
262 APFloat::rmNearestTiesToEven);
Dale Johannesen91506522007-09-30 18:19:03 +0000263 return ConstantFP::get(DestTy, apf);
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000264 }
Nate Begemand4d45c22007-11-17 03:58:34 +0000265 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
266 std::vector<Constant*> res;
267 const VectorType *DestVecTy = cast<VectorType>(DestTy);
268 const Type *DstEltTy = DestVecTy->getElementType();
269 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
270 res.push_back(ConstantFoldCastInstruction(opc, V->getOperand(i),
271 DstEltTy));
272 return ConstantVector::get(DestVecTy, res);
273 }
Reid Spencer8dabca42006-12-19 07:41:40 +0000274 return 0;
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000275 case Instruction::ZExt:
Reid Spencer81658a82007-02-27 06:23:51 +0000276 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
277 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
278 APInt Result(CI->getValue());
279 Result.zext(BitWidth);
Reid Spencera1276332007-03-01 19:31:12 +0000280 return ConstantInt::get(Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000281 }
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000282 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000283 case Instruction::SExt:
Reid Spencer81658a82007-02-27 06:23:51 +0000284 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
285 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
286 APInt Result(CI->getValue());
287 Result.sext(BitWidth);
Reid Spencera1276332007-03-01 19:31:12 +0000288 return ConstantInt::get(Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000289 }
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000290 return 0;
Chris Lattner710ebaf2006-12-01 19:22:41 +0000291 case Instruction::Trunc:
Reid Spencer81658a82007-02-27 06:23:51 +0000292 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
293 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
294 APInt Result(CI->getValue());
295 Result.trunc(BitWidth);
Reid Spencera1276332007-03-01 19:31:12 +0000296 return ConstantInt::get(Result);
Reid Spencer81658a82007-02-27 06:23:51 +0000297 }
Chris Lattner710ebaf2006-12-01 19:22:41 +0000298 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000299 case Instruction::BitCast:
Chris Lattnere8ea0372007-12-11 05:55:02 +0000300 return FoldBitCast(const_cast<Constant*>(V), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000301 default:
302 assert(!"Invalid CE CastInst opcode");
303 break;
Chris Lattner6b3f4752006-04-02 01:38:28 +0000304 }
Chris Lattnerb2b7f902004-10-11 03:57:30 +0000305
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000306 assert(0 && "Failed to cast constant expression");
307 return 0;
Chris Lattner1dd054c2004-01-12 22:07:24 +0000308}
309
Chris Lattner6ea4b522004-03-12 05:53:32 +0000310Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
311 const Constant *V1,
312 const Constant *V2) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000313 if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
Reid Spencercddc9df2007-01-12 04:24:46 +0000314 return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
Chris Lattnerfd7bf722004-10-16 23:31:32 +0000315
316 if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
317 if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
318 if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000319 if (V1 == V2) return const_cast<Constant*>(V1);
Chris Lattner6ea4b522004-03-12 05:53:32 +0000320 return 0;
321}
322
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000323Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
324 const Constant *Idx) {
Chris Lattnere52f29b2006-03-31 18:31:40 +0000325 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
Reid Spencerd84d35b2007-02-15 02:26:10 +0000326 return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
Chris Lattnere4f9d7b2006-04-07 04:44:06 +0000327 if (Val->isNullValue()) // ee(zero, x) -> zero
328 return Constant::getNullValue(
Reid Spencerd84d35b2007-02-15 02:26:10 +0000329 cast<VectorType>(Val->getType())->getElementType());
Chris Lattnere52f29b2006-03-31 18:31:40 +0000330
Reid Spencerd84d35b2007-02-15 02:26:10 +0000331 if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000332 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
333 return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
Chris Lattnere52f29b2006-03-31 18:31:40 +0000334 } else if (isa<UndefValue>(Idx)) {
335 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
336 return const_cast<Constant*>(CVal->getOperand(0));
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000337 }
Chris Lattnere52f29b2006-03-31 18:31:40 +0000338 }
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000339 return 0;
340}
341
Robert Bocchinoca27f032006-01-17 20:07:22 +0000342Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
343 const Constant *Elt,
344 const Constant *Idx) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000345 const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000346 if (!CIdx) return 0;
Reid Spencer81658a82007-02-27 06:23:51 +0000347 APInt idxVal = CIdx->getValue();
Reid Spencer3054b142006-11-02 08:18:15 +0000348 if (isa<UndefValue>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000349 // Insertion of scalar constant into vector undef
Robert Bocchinoca27f032006-01-17 20:07:22 +0000350 // Optimize away insertion of undef
351 if (isa<UndefValue>(Elt))
352 return const_cast<Constant*>(Val);
353 // Otherwise break the aggregate undef into multiple undefs and do
354 // the insertion
355 unsigned numOps =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000356 cast<VectorType>(Val->getType())->getNumElements();
Robert Bocchinoca27f032006-01-17 20:07:22 +0000357 std::vector<Constant*> Ops;
358 Ops.reserve(numOps);
359 for (unsigned i = 0; i < numOps; ++i) {
360 const Constant *Op =
Reid Spencer81658a82007-02-27 06:23:51 +0000361 (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
Robert Bocchinoca27f032006-01-17 20:07:22 +0000362 Ops.push_back(const_cast<Constant*>(Op));
363 }
Reid Spencerd84d35b2007-02-15 02:26:10 +0000364 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000365 }
Reid Spencer3054b142006-11-02 08:18:15 +0000366 if (isa<ConstantAggregateZero>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000367 // Insertion of scalar constant into vector aggregate zero
Robert Bocchinoca27f032006-01-17 20:07:22 +0000368 // Optimize away insertion of zero
369 if (Elt->isNullValue())
370 return const_cast<Constant*>(Val);
371 // Otherwise break the aggregate zero into multiple zeros and do
372 // the insertion
373 unsigned numOps =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000374 cast<VectorType>(Val->getType())->getNumElements();
Robert Bocchinoca27f032006-01-17 20:07:22 +0000375 std::vector<Constant*> Ops;
376 Ops.reserve(numOps);
377 for (unsigned i = 0; i < numOps; ++i) {
378 const Constant *Op =
Reid Spencer81658a82007-02-27 06:23:51 +0000379 (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
Robert Bocchinoca27f032006-01-17 20:07:22 +0000380 Ops.push_back(const_cast<Constant*>(Op));
381 }
Reid Spencerd84d35b2007-02-15 02:26:10 +0000382 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000383 }
Reid Spencerd84d35b2007-02-15 02:26:10 +0000384 if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
Dan Gohman06c60b62007-07-16 14:29:03 +0000385 // Insertion of scalar constant into vector constant
Robert Bocchinoca27f032006-01-17 20:07:22 +0000386 std::vector<Constant*> Ops;
387 Ops.reserve(CVal->getNumOperands());
388 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
389 const Constant *Op =
Reid Spencer81658a82007-02-27 06:23:51 +0000390 (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
Robert Bocchinoca27f032006-01-17 20:07:22 +0000391 Ops.push_back(const_cast<Constant*>(Op));
392 }
Reid Spencerd84d35b2007-02-15 02:26:10 +0000393 return ConstantVector::get(Ops);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000394 }
395 return 0;
396}
397
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000398/// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
399/// return the specified element value. Otherwise return null.
400static Constant *GetVectorElement(const Constant *C, unsigned EltNo) {
401 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C))
402 return const_cast<Constant*>(CV->getOperand(EltNo));
403
404 const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
405 if (isa<ConstantAggregateZero>(C))
406 return Constant::getNullValue(EltTy);
407 if (isa<UndefValue>(C))
408 return UndefValue::get(EltTy);
409 return 0;
410}
411
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000412Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
413 const Constant *V2,
414 const Constant *Mask) {
Chris Lattner8e6a8f92007-12-11 07:49:37 +0000415 // Undefined shuffle mask -> undefined value.
416 if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
417
418 unsigned NumElts = cast<VectorType>(V1->getType())->getNumElements();
419 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
420
421 // Loop over the shuffle mask, evaluating each element.
422 SmallVector<Constant*, 32> Result;
423 for (unsigned i = 0; i != NumElts; ++i) {
424 Constant *InElt = GetVectorElement(Mask, i);
425 if (InElt == 0) return 0;
426
427 if (isa<UndefValue>(InElt))
428 InElt = UndefValue::get(EltTy);
429 else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
430 unsigned Elt = CI->getZExtValue();
431 if (Elt >= NumElts*2)
432 InElt = UndefValue::get(EltTy);
433 else if (Elt >= NumElts)
434 InElt = GetVectorElement(V2, Elt-NumElts);
435 else
436 InElt = GetVectorElement(V1, Elt);
437 if (InElt == 0) return 0;
438 } else {
439 // Unknown value.
440 return 0;
441 }
442 Result.push_back(InElt);
443 }
444
445 return ConstantVector::get(&Result[0], Result.size());
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000446}
447
Dan Gohman06c60b62007-07-16 14:29:03 +0000448/// EvalVectorOp - Given two vector constants and a function pointer, apply the
Reid Spencerd84d35b2007-02-15 02:26:10 +0000449/// function pointer to each element pair, producing a new ConstantVector
Dan Gohman9f396602007-10-30 19:00:49 +0000450/// constant. Either or both of V1 and V2 may be NULL, meaning a
451/// ConstantAggregateZero operand.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000452static Constant *EvalVectorOp(const ConstantVector *V1,
453 const ConstantVector *V2,
Dan Gohman9f396602007-10-30 19:00:49 +0000454 const VectorType *VTy,
Reid Spencer266e42b2006-12-23 06:05:41 +0000455 Constant *(*FP)(Constant*, Constant*)) {
456 std::vector<Constant*> Res;
Dan Gohman9f396602007-10-30 19:00:49 +0000457 const Type *EltTy = VTy->getElementType();
458 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
459 const Constant *C1 = V1 ? V1->getOperand(i) : Constant::getNullValue(EltTy);
460 const Constant *C2 = V2 ? V2->getOperand(i) : Constant::getNullValue(EltTy);
461 Res.push_back(FP(const_cast<Constant*>(C1),
462 const_cast<Constant*>(C2)));
463 }
Reid Spencerd84d35b2007-02-15 02:26:10 +0000464 return ConstantVector::get(Res);
Reid Spencer266e42b2006-12-23 06:05:41 +0000465}
466
467Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
468 const Constant *C1,
469 const Constant *C2) {
Dale Johannesene5facd52007-10-16 23:38:29 +0000470 // No compile-time operations on this type yet.
471 if (C1->getType() == Type::PPC_FP128Ty)
472 return 0;
473
Reid Spencer266e42b2006-12-23 06:05:41 +0000474 // Handle UndefValue up front
475 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
476 switch (Opcode) {
477 case Instruction::Add:
478 case Instruction::Sub:
479 case Instruction::Xor:
480 return UndefValue::get(C1->getType());
481 case Instruction::Mul:
482 case Instruction::And:
483 return Constant::getNullValue(C1->getType());
484 case Instruction::UDiv:
485 case Instruction::SDiv:
486 case Instruction::FDiv:
487 case Instruction::URem:
488 case Instruction::SRem:
489 case Instruction::FRem:
490 if (!isa<UndefValue>(C2)) // undef / X -> 0
491 return Constant::getNullValue(C1->getType());
492 return const_cast<Constant*>(C2); // X / undef -> undef
493 case Instruction::Or: // X | undef -> -1
Reid Spencerd84d35b2007-02-15 02:26:10 +0000494 if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
495 return ConstantVector::getAllOnesValue(PTy);
Reid Spencer266e42b2006-12-23 06:05:41 +0000496 return ConstantInt::getAllOnesValue(C1->getType());
497 case Instruction::LShr:
498 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
499 return const_cast<Constant*>(C1); // undef lshr undef -> undef
500 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
501 // undef lshr X -> 0
502 case Instruction::AShr:
503 if (!isa<UndefValue>(C2))
504 return const_cast<Constant*>(C1); // undef ashr X --> undef
505 else if (isa<UndefValue>(C1))
506 return const_cast<Constant*>(C1); // undef ashr undef -> undef
507 else
508 return const_cast<Constant*>(C1); // X ashr undef --> X
509 case Instruction::Shl:
510 // undef << X -> 0 or X << undef -> 0
511 return Constant::getNullValue(C1->getType());
512 }
513 }
514
515 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
516 if (isa<ConstantExpr>(C2)) {
517 // There are many possible foldings we could do here. We should probably
518 // at least fold add of a pointer with an integer into the appropriate
519 // getelementptr. This will improve alias analysis a bit.
520 } else {
521 // Just implement a couple of simple identities.
522 switch (Opcode) {
523 case Instruction::Add:
524 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X + 0 == X
525 break;
526 case Instruction::Sub:
527 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X - 0 == X
528 break;
529 case Instruction::Mul:
530 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X * 0 == 0
531 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
Reid Spencer81658a82007-02-27 06:23:51 +0000532 if (CI->equalsInt(1))
Reid Spencer266e42b2006-12-23 06:05:41 +0000533 return const_cast<Constant*>(C1); // X * 1 == X
534 break;
535 case Instruction::UDiv:
536 case Instruction::SDiv:
537 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
Reid Spencer81658a82007-02-27 06:23:51 +0000538 if (CI->equalsInt(1))
Reid Spencer266e42b2006-12-23 06:05:41 +0000539 return const_cast<Constant*>(C1); // X / 1 == X
540 break;
541 case Instruction::URem:
542 case Instruction::SRem:
543 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
Reid Spencer81658a82007-02-27 06:23:51 +0000544 if (CI->equalsInt(1))
Reid Spencer266e42b2006-12-23 06:05:41 +0000545 return Constant::getNullValue(CI->getType()); // X % 1 == 0
546 break;
547 case Instruction::And:
Chris Lattner6d94bb72007-03-25 05:47:04 +0000548 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2)) {
549 if (CI->isZero()) return const_cast<Constant*>(C2); // X & 0 == 0
Chris Lattner26f13eb2007-01-04 01:56:39 +0000550 if (CI->isAllOnesValue())
551 return const_cast<Constant*>(C1); // X & -1 == X
Chris Lattner6d94bb72007-03-25 05:47:04 +0000552
553 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
554 if (CE1->getOpcode() == Instruction::ZExt) {
555 APInt PossiblySetBits
556 = cast<IntegerType>(CE1->getOperand(0)->getType())->getMask();
557 PossiblySetBits.zext(C1->getType()->getPrimitiveSizeInBits());
558 if ((PossiblySetBits & CI->getValue()) == PossiblySetBits)
559 return const_cast<Constant*>(C1);
560 }
561 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000562 if (CE1->isCast() && isa<GlobalValue>(CE1->getOperand(0))) {
563 GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
564
565 // Functions are at least 4-byte aligned. If and'ing the address of a
566 // function with a constant < 4, fold it to zero.
567 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
Reid Spencer81658a82007-02-27 06:23:51 +0000568 if (CI->getValue().ult(APInt(CI->getType()->getBitWidth(),4)) &&
569 isa<Function>(CPR))
Reid Spencer266e42b2006-12-23 06:05:41 +0000570 return Constant::getNullValue(CI->getType());
571 }
572 break;
573 case Instruction::Or:
574 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X | 0 == X
Chris Lattner26f13eb2007-01-04 01:56:39 +0000575 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
576 if (CI->isAllOnesValue())
577 return const_cast<Constant*>(C2); // X | -1 == -1
Reid Spencer266e42b2006-12-23 06:05:41 +0000578 break;
579 case Instruction::Xor:
580 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X ^ 0 == X
581 break;
Chris Lattner6d94bb72007-03-25 05:47:04 +0000582 case Instruction::AShr:
Reid Spencere20090b2007-03-26 20:09:02 +0000583 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
Chris Lattner6d94bb72007-03-25 05:47:04 +0000584 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
585 return ConstantExpr::getLShr(const_cast<Constant*>(C1),
586 const_cast<Constant*>(C2));
587 break;
Reid Spencer266e42b2006-12-23 06:05:41 +0000588 }
589 }
590 } else if (isa<ConstantExpr>(C2)) {
591 // If C2 is a constant expr and C1 isn't, flop them around and fold the
592 // other way if possible.
593 switch (Opcode) {
594 case Instruction::Add:
595 case Instruction::Mul:
596 case Instruction::And:
597 case Instruction::Or:
598 case Instruction::Xor:
599 // No change of opcode required.
600 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
601
602 case Instruction::Shl:
603 case Instruction::LShr:
604 case Instruction::AShr:
605 case Instruction::Sub:
606 case Instruction::SDiv:
607 case Instruction::UDiv:
608 case Instruction::FDiv:
609 case Instruction::URem:
610 case Instruction::SRem:
611 case Instruction::FRem:
612 default: // These instructions cannot be flopped around.
613 return 0;
614 }
615 }
616
617 // At this point we know neither constant is an UndefValue nor a ConstantExpr
Chris Lattner26f13eb2007-01-04 01:56:39 +0000618 // so look at directly computing the value.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000619 if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
620 if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
Reid Spencer81658a82007-02-27 06:23:51 +0000621 using namespace APIntOps;
622 APInt C1V = CI1->getValue();
623 APInt C2V = CI2->getValue();
Chris Lattner344da522007-01-12 18:42:52 +0000624 switch (Opcode) {
625 default:
626 break;
627 case Instruction::Add:
Reid Spencera1276332007-03-01 19:31:12 +0000628 return ConstantInt::get(C1V + C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000629 case Instruction::Sub:
Reid Spencera1276332007-03-01 19:31:12 +0000630 return ConstantInt::get(C1V - C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000631 case Instruction::Mul:
Reid Spencera1276332007-03-01 19:31:12 +0000632 return ConstantInt::get(C1V * C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000633 case Instruction::UDiv:
Reid Spencer81658a82007-02-27 06:23:51 +0000634 if (CI2->isNullValue())
635 return 0; // X / 0 -> can't fold
Reid Spencera1276332007-03-01 19:31:12 +0000636 return ConstantInt::get(C1V.udiv(C2V));
Chris Lattner344da522007-01-12 18:42:52 +0000637 case Instruction::SDiv:
Reid Spencer81658a82007-02-27 06:23:51 +0000638 if (CI2->isNullValue())
639 return 0; // X / 0 -> can't fold
Reid Spencer81658a82007-02-27 06:23:51 +0000640 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
641 return 0; // MIN_INT / -1 -> overflow
Reid Spencera1276332007-03-01 19:31:12 +0000642 return ConstantInt::get(C1V.sdiv(C2V));
Reid Spencer81658a82007-02-27 06:23:51 +0000643 case Instruction::URem:
644 if (C2->isNullValue())
645 return 0; // X / 0 -> can't fold
Reid Spencera1276332007-03-01 19:31:12 +0000646 return ConstantInt::get(C1V.urem(C2V));
Chris Lattner344da522007-01-12 18:42:52 +0000647 case Instruction::SRem:
Reid Spencer81658a82007-02-27 06:23:51 +0000648 if (CI2->isNullValue())
649 return 0; // X % 0 -> can't fold
650 if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
651 return 0; // MIN_INT % -1 -> overflow
Reid Spencera1276332007-03-01 19:31:12 +0000652 return ConstantInt::get(C1V.srem(C2V));
Chris Lattner344da522007-01-12 18:42:52 +0000653 case Instruction::And:
Reid Spencera1276332007-03-01 19:31:12 +0000654 return ConstantInt::get(C1V & C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000655 case Instruction::Or:
Reid Spencera1276332007-03-01 19:31:12 +0000656 return ConstantInt::get(C1V | C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000657 case Instruction::Xor:
Reid Spencera1276332007-03-01 19:31:12 +0000658 return ConstantInt::get(C1V ^ C2V);
Chris Lattner344da522007-01-12 18:42:52 +0000659 case Instruction::Shl:
Anton Korobeynikov579f0712008-02-20 11:08:44 +0000660 if (uint32_t shiftAmt = C2V.getZExtValue()) {
Reid Spencerac419b52007-02-27 19:29:54 +0000661 if (shiftAmt < C1V.getBitWidth())
Reid Spencera1276332007-03-01 19:31:12 +0000662 return ConstantInt::get(C1V.shl(shiftAmt));
Reid Spencer81658a82007-02-27 06:23:51 +0000663 else
664 return UndefValue::get(C1->getType()); // too big shift is undef
Anton Korobeynikov579f0712008-02-20 11:08:44 +0000665 }
Reid Spencer81658a82007-02-27 06:23:51 +0000666 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
Chris Lattner344da522007-01-12 18:42:52 +0000667 case Instruction::LShr:
Anton Korobeynikov579f0712008-02-20 11:08:44 +0000668 if (uint32_t shiftAmt = C2V.getZExtValue()) {
Reid Spencerac419b52007-02-27 19:29:54 +0000669 if (shiftAmt < C1V.getBitWidth())
Reid Spencera1276332007-03-01 19:31:12 +0000670 return ConstantInt::get(C1V.lshr(shiftAmt));
Reid Spencer81658a82007-02-27 06:23:51 +0000671 else
672 return UndefValue::get(C1->getType()); // too big shift is undef
Anton Korobeynikov579f0712008-02-20 11:08:44 +0000673 }
Reid Spencer81658a82007-02-27 06:23:51 +0000674 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
Chris Lattner344da522007-01-12 18:42:52 +0000675 case Instruction::AShr:
Anton Korobeynikov579f0712008-02-20 11:08:44 +0000676 if (uint32_t shiftAmt = C2V.getZExtValue()) {
Reid Spencerac419b52007-02-27 19:29:54 +0000677 if (shiftAmt < C1V.getBitWidth())
Reid Spencera1276332007-03-01 19:31:12 +0000678 return ConstantInt::get(C1V.ashr(shiftAmt));
Reid Spencer81658a82007-02-27 06:23:51 +0000679 else
680 return UndefValue::get(C1->getType()); // too big shift is undef
Anton Korobeynikov579f0712008-02-20 11:08:44 +0000681 }
Reid Spencer81658a82007-02-27 06:23:51 +0000682 return const_cast<ConstantInt*>(CI1); // Zero shift is identity
Reid Spencer266e42b2006-12-23 06:05:41 +0000683 }
684 }
685 } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
686 if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000687 APFloat C1V = CFP1->getValueAPF();
688 APFloat C2V = CFP2->getValueAPF();
689 APFloat C3V = C1V; // copy for modification
690 bool isDouble = CFP1->getType()==Type::DoubleTy;
Reid Spencer266e42b2006-12-23 06:05:41 +0000691 switch (Opcode) {
692 default:
693 break;
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000694 case Instruction::Add:
695 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
696 return ConstantFP::get(CFP1->getType(), C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +0000697 case Instruction::Sub:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000698 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
699 return ConstantFP::get(CFP1->getType(), C3V);
700 case Instruction::Mul:
701 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
702 return ConstantFP::get(CFP1->getType(), C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +0000703 case Instruction::FDiv:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000704 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
705 return ConstantFP::get(CFP1->getType(), C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +0000706 case Instruction::FRem:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000707 if (C2V.isZero())
Reid Spencerd96dc902007-03-23 05:33:23 +0000708 // IEEE 754, Section 7.1, #5
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000709 return ConstantFP::get(CFP1->getType(), isDouble ?
710 APFloat(std::numeric_limits<double>::quiet_NaN()) :
711 APFloat(std::numeric_limits<float>::quiet_NaN()));
712 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
713 return ConstantFP::get(CFP1->getType(), C3V);
Reid Spencer266e42b2006-12-23 06:05:41 +0000714 }
715 }
Dan Gohman9f396602007-10-30 19:00:49 +0000716 } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
717 const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
718 const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
Dan Gohmanb43e0202007-10-31 21:36:31 +0000719 if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
720 (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000721 switch (Opcode) {
722 default:
723 break;
724 case Instruction::Add:
Dan Gohman9f396602007-10-30 19:00:49 +0000725 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAdd);
Reid Spencer266e42b2006-12-23 06:05:41 +0000726 case Instruction::Sub:
Dan Gohman9f396602007-10-30 19:00:49 +0000727 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSub);
Reid Spencer266e42b2006-12-23 06:05:41 +0000728 case Instruction::Mul:
Dan Gohman9f396602007-10-30 19:00:49 +0000729 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getMul);
Reid Spencer266e42b2006-12-23 06:05:41 +0000730 case Instruction::UDiv:
Dan Gohman9f396602007-10-30 19:00:49 +0000731 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getUDiv);
Reid Spencer266e42b2006-12-23 06:05:41 +0000732 case Instruction::SDiv:
Dan Gohman9f396602007-10-30 19:00:49 +0000733 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSDiv);
Reid Spencer266e42b2006-12-23 06:05:41 +0000734 case Instruction::FDiv:
Dan Gohman9f396602007-10-30 19:00:49 +0000735 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFDiv);
Reid Spencer266e42b2006-12-23 06:05:41 +0000736 case Instruction::URem:
Dan Gohman9f396602007-10-30 19:00:49 +0000737 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getURem);
Reid Spencer266e42b2006-12-23 06:05:41 +0000738 case Instruction::SRem:
Dan Gohman9f396602007-10-30 19:00:49 +0000739 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSRem);
Reid Spencer266e42b2006-12-23 06:05:41 +0000740 case Instruction::FRem:
Dan Gohman9f396602007-10-30 19:00:49 +0000741 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFRem);
Reid Spencer266e42b2006-12-23 06:05:41 +0000742 case Instruction::And:
Dan Gohman9f396602007-10-30 19:00:49 +0000743 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAnd);
Reid Spencer266e42b2006-12-23 06:05:41 +0000744 case Instruction::Or:
Dan Gohman9f396602007-10-30 19:00:49 +0000745 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getOr);
Reid Spencer266e42b2006-12-23 06:05:41 +0000746 case Instruction::Xor:
Dan Gohman9f396602007-10-30 19:00:49 +0000747 return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getXor);
Dan Gohmanb43e0202007-10-31 21:36:31 +0000748 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000749 }
750 }
751
752 // We don't know how to fold this
753 return 0;
754}
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000755
Chris Lattner60c47262005-01-28 19:09:51 +0000756/// isZeroSizedType - This type is zero sized if its an array or structure of
757/// zero sized types. The only leaf zero sized type is an empty structure.
758static bool isMaybeZeroSizedType(const Type *Ty) {
759 if (isa<OpaqueType>(Ty)) return true; // Can't say.
760 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
761
762 // If all of elements have zero size, this does too.
763 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerfeaf92f2005-01-28 23:17:27 +0000764 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
Chris Lattner60c47262005-01-28 19:09:51 +0000765 return true;
766
767 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
768 return isMaybeZeroSizedType(ATy->getElementType());
769 }
770 return false;
771}
Chris Lattner6ea4b522004-03-12 05:53:32 +0000772
Chris Lattner061da2f2004-01-13 05:51:55 +0000773/// IdxCompare - Compare the two constants as though they were getelementptr
774/// indices. This allows coersion of the types to be the same thing.
775///
776/// If the two constants are the "same" (after coersion), return 0. If the
777/// first is less than the second, return -1, if the second is less than the
778/// first, return 1. If the constants are not integral, return -2.
779///
Chris Lattner60c47262005-01-28 19:09:51 +0000780static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
Chris Lattner061da2f2004-01-13 05:51:55 +0000781 if (C1 == C2) return 0;
782
Reid Spencerc90cf772006-12-31 21:43:30 +0000783 // Ok, we found a different index. If they are not ConstantInt, we can't do
784 // anything with them.
Chris Lattner061da2f2004-01-13 05:51:55 +0000785 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
786 return -2; // don't know!
Misha Brukmanb1c93172005-04-21 23:48:37 +0000787
Chris Lattner69193f92004-04-05 01:30:19 +0000788 // Ok, we have two differing integer indices. Sign extend them to be the same
789 // type. Long is always big enough, so we use it.
Reid Spencer8d9336d2006-12-31 05:26:44 +0000790 if (C1->getType() != Type::Int64Ty)
791 C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000792
Reid Spencer8d9336d2006-12-31 05:26:44 +0000793 if (C2->getType() != Type::Int64Ty)
Reid Spencerc90cf772006-12-31 21:43:30 +0000794 C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
Reid Spencer8d9336d2006-12-31 05:26:44 +0000795
796 if (C1 == C2) return 0; // They are equal
Chris Lattner061da2f2004-01-13 05:51:55 +0000797
Chris Lattner60c47262005-01-28 19:09:51 +0000798 // If the type being indexed over is really just a zero sized type, there is
799 // no pointer difference being made here.
800 if (isMaybeZeroSizedType(ElTy))
801 return -2; // dunno.
802
Chris Lattner061da2f2004-01-13 05:51:55 +0000803 // If they are really different, now that they are the same type, then we
804 // found a difference!
Reid Spencere0fc4df2006-10-20 07:07:24 +0000805 if (cast<ConstantInt>(C1)->getSExtValue() <
806 cast<ConstantInt>(C2)->getSExtValue())
Chris Lattner061da2f2004-01-13 05:51:55 +0000807 return -1;
808 else
809 return 1;
810}
811
Chris Lattner858f4e92007-01-04 02:13:20 +0000812/// evaluateFCmpRelation - This function determines if there is anything we can
Reid Spencer266e42b2006-12-23 06:05:41 +0000813/// decide about the two constants provided. This doesn't need to handle simple
814/// things like ConstantFP comparisons, but should instead handle ConstantExprs.
815/// If we can determine that the two constants have a particular relation to
816/// each other, we should return the corresponding FCmpInst predicate,
Reid Spencer9d36acf2006-12-24 18:52:08 +0000817/// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
818/// ConstantFoldCompareInstruction.
Reid Spencer266e42b2006-12-23 06:05:41 +0000819///
820/// To simplify this code we canonicalize the relation so that the first
Reid Spencer9d36acf2006-12-24 18:52:08 +0000821/// operand is always the most "complex" of the two. We consider ConstantFP
822/// to be the simplest, and ConstantExprs to be the most complex.
823static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1,
824 const Constant *V2) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000825 assert(V1->getType() == V2->getType() &&
Reid Spencer9d36acf2006-12-24 18:52:08 +0000826 "Cannot compare values of different types!");
Dale Johannesen19db0932007-10-14 01:56:47 +0000827
828 // No compile-time operations on this type yet.
829 if (V1->getType() == Type::PPC_FP128Ty)
830 return FCmpInst::BAD_FCMP_PREDICATE;
831
Reid Spencer9d36acf2006-12-24 18:52:08 +0000832 // Handle degenerate case quickly
Reid Spencer266e42b2006-12-23 06:05:41 +0000833 if (V1 == V2) return FCmpInst::FCMP_OEQ;
834
Reid Spencer9d36acf2006-12-24 18:52:08 +0000835 if (!isa<ConstantExpr>(V1)) {
836 if (!isa<ConstantExpr>(V2)) {
837 // We distilled thisUse the standard constant folder for a few cases
Zhou Sheng75b871f2007-01-11 12:24:14 +0000838 ConstantInt *R = 0;
Reid Spencer9d36acf2006-12-24 18:52:08 +0000839 Constant *C1 = const_cast<Constant*>(V1);
840 Constant *C2 = const_cast<Constant*>(V2);
Zhou Sheng75b871f2007-01-11 12:24:14 +0000841 R = dyn_cast<ConstantInt>(
Reid Spencer9d36acf2006-12-24 18:52:08 +0000842 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
Reid Spencer2e54a152007-03-02 00:28:52 +0000843 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +0000844 return FCmpInst::FCMP_OEQ;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000845 R = dyn_cast<ConstantInt>(
Reid Spencer9d36acf2006-12-24 18:52:08 +0000846 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
Reid Spencer2e54a152007-03-02 00:28:52 +0000847 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +0000848 return FCmpInst::FCMP_OLT;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000849 R = dyn_cast<ConstantInt>(
Reid Spencer9d36acf2006-12-24 18:52:08 +0000850 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
Reid Spencer2e54a152007-03-02 00:28:52 +0000851 if (R && !R->isZero())
Reid Spencer9d36acf2006-12-24 18:52:08 +0000852 return FCmpInst::FCMP_OGT;
853
854 // Nothing more we can do
Reid Spencer266e42b2006-12-23 06:05:41 +0000855 return FCmpInst::BAD_FCMP_PREDICATE;
856 }
857
Reid Spencer9d36acf2006-12-24 18:52:08 +0000858 // If the first operand is simple and second is ConstantExpr, swap operands.
859 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
860 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
861 return FCmpInst::getSwappedPredicate(SwappedRelation);
862 } else {
863 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
864 // constantexpr or a simple constant.
865 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
866 switch (CE1->getOpcode()) {
867 case Instruction::FPTrunc:
868 case Instruction::FPExt:
869 case Instruction::UIToFP:
870 case Instruction::SIToFP:
871 // We might be able to do something with these but we don't right now.
872 break;
873 default:
874 break;
875 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000876 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000877 // There are MANY other foldings that we could perform here. They will
878 // probably be added on demand, as they seem needed.
879 return FCmpInst::BAD_FCMP_PREDICATE;
880}
881
882/// evaluateICmpRelation - This function determines if there is anything we can
Chris Lattner061da2f2004-01-13 05:51:55 +0000883/// decide about the two constants provided. This doesn't need to handle simple
Reid Spenceraccd7c72004-07-17 23:47:01 +0000884/// things like integer comparisons, but should instead handle ConstantExprs
Chris Lattner8410beb2006-12-11 02:16:58 +0000885/// and GlobalValues. If we can determine that the two constants have a
Reid Spencer266e42b2006-12-23 06:05:41 +0000886/// particular relation to each other, we should return the corresponding ICmp
887/// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
Chris Lattner061da2f2004-01-13 05:51:55 +0000888///
889/// To simplify this code we canonicalize the relation so that the first
890/// operand is always the most "complex" of the two. We consider simple
891/// constants (like ConstantInt) to be the simplest, followed by
Reid Spenceraccd7c72004-07-17 23:47:01 +0000892/// GlobalValues, followed by ConstantExpr's (the most complex).
Chris Lattner061da2f2004-01-13 05:51:55 +0000893///
Reid Spencer9d36acf2006-12-24 18:52:08 +0000894static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1,
895 const Constant *V2,
Reid Spencer266e42b2006-12-23 06:05:41 +0000896 bool isSigned) {
Chris Lattner061da2f2004-01-13 05:51:55 +0000897 assert(V1->getType() == V2->getType() &&
898 "Cannot compare different types of values!");
Reid Spencer266e42b2006-12-23 06:05:41 +0000899 if (V1 == V2) return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +0000900
Reid Spenceraccd7c72004-07-17 23:47:01 +0000901 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000902 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
903 // We distilled this down to a simple case, use the standard constant
904 // folder.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000905 ConstantInt *R = 0;
Reid Spencer9d36acf2006-12-24 18:52:08 +0000906 Constant *C1 = const_cast<Constant*>(V1);
907 Constant *C2 = const_cast<Constant*>(V2);
Reid Spencer266e42b2006-12-23 06:05:41 +0000908 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000909 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
Reid Spencer2e54a152007-03-02 00:28:52 +0000910 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +0000911 return pred;
912 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000913 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
Reid Spencer2e54a152007-03-02 00:28:52 +0000914 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +0000915 return pred;
916 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Zhou Sheng75b871f2007-01-11 12:24:14 +0000917 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
Reid Spencer2e54a152007-03-02 00:28:52 +0000918 if (R && !R->isZero())
Reid Spencer266e42b2006-12-23 06:05:41 +0000919 return pred;
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000920
921 // If we couldn't figure it out, bail.
Reid Spencer266e42b2006-12-23 06:05:41 +0000922 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000923 }
924
Chris Lattner061da2f2004-01-13 05:51:55 +0000925 // If the first operand is simple, swap operands.
Reid Spencer266e42b2006-12-23 06:05:41 +0000926 ICmpInst::Predicate SwappedRelation =
927 evaluateICmpRelation(V2, V1, isSigned);
928 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
929 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner061da2f2004-01-13 05:51:55 +0000930
Chris Lattner0f7e9f52006-01-05 07:19:51 +0000931 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
Chris Lattner125ed542004-02-01 01:23:19 +0000932 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
Reid Spencer266e42b2006-12-23 06:05:41 +0000933 ICmpInst::Predicate SwappedRelation =
934 evaluateICmpRelation(V2, V1, isSigned);
935 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
936 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner0f7e9f52006-01-05 07:19:51 +0000937 else
Reid Spencer266e42b2006-12-23 06:05:41 +0000938 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner125ed542004-02-01 01:23:19 +0000939 }
Chris Lattner061da2f2004-01-13 05:51:55 +0000940
Reid Spenceraccd7c72004-07-17 23:47:01 +0000941 // Now we know that the RHS is a GlobalValue or simple constant,
Chris Lattner061da2f2004-01-13 05:51:55 +0000942 // which (since the types must match) means that it's a ConstantPointerNull.
Reid Spenceraccd7c72004-07-17 23:47:01 +0000943 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattner52fe8692007-09-10 23:42:42 +0000944 // Don't try to decide equality of aliases.
945 if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
946 if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
947 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +0000948 } else {
949 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
Chris Lattner52fe8692007-09-10 23:42:42 +0000950 // GlobalVals can never be null. Don't try to evaluate aliases.
951 if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
Reid Spencer266e42b2006-12-23 06:05:41 +0000952 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +0000953 }
Chris Lattner061da2f2004-01-13 05:51:55 +0000954 } else {
955 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
956 // constantexpr, a CPR, or a simple constant.
Reid Spencer9d36acf2006-12-24 18:52:08 +0000957 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
958 const Constant *CE1Op0 = CE1->getOperand(0);
Chris Lattner061da2f2004-01-13 05:51:55 +0000959
960 switch (CE1->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000961 case Instruction::Trunc:
962 case Instruction::FPTrunc:
963 case Instruction::FPExt:
964 case Instruction::FPToUI:
965 case Instruction::FPToSI:
Reid Spencer266e42b2006-12-23 06:05:41 +0000966 break; // We can't evaluate floating point casts or truncations.
967
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000968 case Instruction::UIToFP:
969 case Instruction::SIToFP:
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000970 case Instruction::BitCast:
Reid Spencer266e42b2006-12-23 06:05:41 +0000971 case Instruction::ZExt:
972 case Instruction::SExt:
Chris Lattner061da2f2004-01-13 05:51:55 +0000973 // If the cast is not actually changing bits, and the second operand is a
974 // null pointer, do the comparison with the pre-casted value.
975 if (V2->isNullValue() &&
Chris Lattner03c49532007-01-15 02:27:26 +0000976 (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
Chris Lattnerd2265b42007-12-10 22:53:04 +0000977 bool sgnd = isSigned;
978 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
979 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
980 return evaluateICmpRelation(CE1Op0,
981 Constant::getNullValue(CE1Op0->getType()),
982 sgnd);
Reid Spencer266e42b2006-12-23 06:05:41 +0000983 }
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000984
985 // If the dest type is a pointer type, and the RHS is a constantexpr cast
986 // from the same type as the src of the LHS, evaluate the inputs. This is
Reid Spencer266e42b2006-12-23 06:05:41 +0000987 // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000988 // which happens a lot in compilers with tagged integers.
Reid Spencer9d36acf2006-12-24 18:52:08 +0000989 if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
Reid Spencer266e42b2006-12-23 06:05:41 +0000990 if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000991 CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
Chris Lattner03c49532007-01-15 02:27:26 +0000992 CE1->getOperand(0)->getType()->isInteger()) {
Chris Lattnerd2265b42007-12-10 22:53:04 +0000993 bool sgnd = isSigned;
994 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
995 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
Reid Spencer266e42b2006-12-23 06:05:41 +0000996 return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
Chris Lattnerd2265b42007-12-10 22:53:04 +0000997 sgnd);
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000998 }
Chris Lattner192e3262004-04-11 01:29:30 +0000999 break;
Chris Lattner061da2f2004-01-13 05:51:55 +00001000
1001 case Instruction::GetElementPtr:
1002 // Ok, since this is a getelementptr, we know that the constant has a
1003 // pointer type. Check the various cases.
1004 if (isa<ConstantPointerNull>(V2)) {
1005 // If we are comparing a GEP to a null pointer, check to see if the base
1006 // of the GEP equals the null pointer.
Reid Spencer9d36acf2006-12-24 18:52:08 +00001007 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
Reid Spencer876f7222006-12-06 00:25:09 +00001008 if (GV->hasExternalWeakLinkage())
1009 // Weak linkage GVals could be zero or not. We're comparing that
1010 // to null pointer so its greater-or-equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001011 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
Reid Spencer876f7222006-12-06 00:25:09 +00001012 else
1013 // If its not weak linkage, the GVal must have a non-zero address
1014 // so the result is greater-than
Reid Spencer266e42b2006-12-23 06:05:41 +00001015 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001016 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1017 // If we are indexing from a null pointer, check to see if we have any
1018 // non-zero indices.
1019 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1020 if (!CE1->getOperand(i)->isNullValue())
1021 // Offsetting from null, must not be equal.
Reid Spencer266e42b2006-12-23 06:05:41 +00001022 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001023 // Only zero indexes from null, must still be zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00001024 return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001025 }
1026 // Otherwise, we can't really say if the first operand is null or not.
Reid Spenceraccd7c72004-07-17 23:47:01 +00001027 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001028 if (isa<ConstantPointerNull>(CE1Op0)) {
Reid Spencer876f7222006-12-06 00:25:09 +00001029 if (CPR2->hasExternalWeakLinkage())
1030 // Weak linkage GVals could be zero or not. We're comparing it to
1031 // a null pointer, so its less-or-equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001032 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
Reid Spencer876f7222006-12-06 00:25:09 +00001033 else
1034 // If its not weak linkage, the GVal must have a non-zero address
1035 // so the result is less-than
Reid Spencer266e42b2006-12-23 06:05:41 +00001036 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Reid Spenceraccd7c72004-07-17 23:47:01 +00001037 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001038 if (CPR1 == CPR2) {
1039 // If this is a getelementptr of the same global, then it must be
1040 // different. Because the types must match, the getelementptr could
1041 // only have at most one index, and because we fold getelementptr's
1042 // with a single zero index, it must be nonzero.
1043 assert(CE1->getNumOperands() == 2 &&
1044 !CE1->getOperand(1)->isNullValue() &&
1045 "Suprising getelementptr!");
Reid Spencer266e42b2006-12-23 06:05:41 +00001046 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +00001047 } else {
1048 // If they are different globals, we don't know what the value is,
1049 // but they can't be equal.
Reid Spencer266e42b2006-12-23 06:05:41 +00001050 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001051 }
1052 }
1053 } else {
1054 const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1055 const Constant *CE2Op0 = CE2->getOperand(0);
1056
1057 // There are MANY other foldings that we could perform here. They will
1058 // probably be added on demand, as they seem needed.
1059 switch (CE2->getOpcode()) {
1060 default: break;
1061 case Instruction::GetElementPtr:
1062 // By far the most common case to handle is when the base pointers are
1063 // obviously to the same or different globals.
Reid Spenceraccd7c72004-07-17 23:47:01 +00001064 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
Chris Lattner061da2f2004-01-13 05:51:55 +00001065 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
Reid Spencer266e42b2006-12-23 06:05:41 +00001066 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001067 // Ok, we know that both getelementptr instructions are based on the
1068 // same global. From this, we can precisely determine the relative
1069 // ordering of the resultant pointers.
1070 unsigned i = 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001071
Chris Lattner061da2f2004-01-13 05:51:55 +00001072 // Compare all of the operands the GEP's have in common.
Chris Lattner60c47262005-01-28 19:09:51 +00001073 gep_type_iterator GTI = gep_type_begin(CE1);
1074 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1075 ++i, ++GTI)
1076 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1077 GTI.getIndexedType())) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001078 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1079 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1080 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001081 }
1082
1083 // Ok, we ran out of things they have in common. If any leftovers
1084 // are non-zero then we have a difference, otherwise we are equal.
1085 for (; i < CE1->getNumOperands(); ++i)
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001086 if (!CE1->getOperand(i)->isNullValue()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001087 if (isa<ConstantInt>(CE1->getOperand(i)))
Reid Spencer266e42b2006-12-23 06:05:41 +00001088 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner60c47262005-01-28 19:09:51 +00001089 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001090 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001091 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001092
Chris Lattner061da2f2004-01-13 05:51:55 +00001093 for (; i < CE2->getNumOperands(); ++i)
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001094 if (!CE2->getOperand(i)->isNullValue()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001095 if (isa<ConstantInt>(CE2->getOperand(i)))
Reid Spencer266e42b2006-12-23 06:05:41 +00001096 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Chris Lattner60c47262005-01-28 19:09:51 +00001097 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001098 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001099 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001100 return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001101 }
1102 }
1103 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001104 default:
1105 break;
1106 }
1107 }
1108
Reid Spencer266e42b2006-12-23 06:05:41 +00001109 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001110}
1111
Reid Spencer9d36acf2006-12-24 18:52:08 +00001112Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1113 const Constant *C1,
1114 const Constant *C2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001115
1116 // Handle some degenerate cases first
1117 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
Reid Spencer542964f2007-01-11 18:21:29 +00001118 return UndefValue::get(Type::Int1Ty);
Reid Spencer266e42b2006-12-23 06:05:41 +00001119
Dale Johannesen19db0932007-10-14 01:56:47 +00001120 // No compile-time operations on this type yet.
1121 if (C1->getType() == Type::PPC_FP128Ty)
1122 return 0;
1123
Reid Spencer266e42b2006-12-23 06:05:41 +00001124 // icmp eq/ne(null,GV) -> false/true
1125 if (C1->isNullValue()) {
1126 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
Duncan Sandsa38e5272007-09-19 10:16:17 +00001127 // Don't try to evaluate aliases. External weak GV can be null.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001128 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
Reid Spencer9d36acf2006-12-24 18:52:08 +00001129 if (pred == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001130 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001131 else if (pred == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001132 return ConstantInt::getTrue();
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001133 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001134 // icmp eq/ne(GV,null) -> false/true
1135 } else if (C2->isNullValue()) {
1136 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
Duncan Sandsa38e5272007-09-19 10:16:17 +00001137 // Don't try to evaluate aliases. External weak GV can be null.
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001138 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
Reid Spencer9d36acf2006-12-24 18:52:08 +00001139 if (pred == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001140 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001141 else if (pred == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001142 return ConstantInt::getTrue();
Anton Korobeynikov579f0712008-02-20 11:08:44 +00001143 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00001144 }
1145
Chris Lattner344da522007-01-12 18:42:52 +00001146 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
Reid Spencer81658a82007-02-27 06:23:51 +00001147 APInt V1 = cast<ConstantInt>(C1)->getValue();
1148 APInt V2 = cast<ConstantInt>(C2)->getValue();
1149 switch (pred) {
1150 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1151 case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1152 case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1153 case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1.slt(V2));
1154 case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1.sgt(V2));
1155 case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1.sle(V2));
1156 case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1.sge(V2));
1157 case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1.ult(V2));
1158 case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1.ugt(V2));
1159 case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1.ule(V2));
1160 case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1.uge(V2));
Chris Lattner061da2f2004-01-13 05:51:55 +00001161 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001162 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001163 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1164 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1165 APFloat::cmpResult R = C1V.compare(C2V);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001166 switch (pred) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001167 default: assert(0 && "Invalid FCmp Predicate"); return 0;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001168 case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1169 case FCmpInst::FCMP_TRUE: return ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00001170 case FCmpInst::FCMP_UNO:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001171 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered);
Reid Spencer74bd0362007-01-11 00:25:45 +00001172 case FCmpInst::FCMP_ORD:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001173 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpUnordered);
Reid Spencer266e42b2006-12-23 06:05:41 +00001174 case FCmpInst::FCMP_UEQ:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001175 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1176 R==APFloat::cmpEqual);
Reid Spencercddc9df2007-01-12 04:24:46 +00001177 case FCmpInst::FCMP_OEQ:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001178 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpEqual);
Reid Spencer74bd0362007-01-11 00:25:45 +00001179 case FCmpInst::FCMP_UNE:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001180 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpEqual);
Reid Spencercddc9df2007-01-12 04:24:46 +00001181 case FCmpInst::FCMP_ONE:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001182 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1183 R==APFloat::cmpGreaterThan);
Reid Spencer74bd0362007-01-11 00:25:45 +00001184 case FCmpInst::FCMP_ULT:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001185 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1186 R==APFloat::cmpLessThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001187 case FCmpInst::FCMP_OLT:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001188 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan);
Reid Spencer266e42b2006-12-23 06:05:41 +00001189 case FCmpInst::FCMP_UGT:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001190 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1191 R==APFloat::cmpGreaterThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001192 case FCmpInst::FCMP_OGT:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001193 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan);
Reid Spencer74bd0362007-01-11 00:25:45 +00001194 case FCmpInst::FCMP_ULE:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001195 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpGreaterThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001196 case FCmpInst::FCMP_OLE:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001197 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1198 R==APFloat::cmpEqual);
Reid Spencer266e42b2006-12-23 06:05:41 +00001199 case FCmpInst::FCMP_UGE:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001200 return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpLessThan);
Reid Spencercddc9df2007-01-12 04:24:46 +00001201 case FCmpInst::FCMP_OGE:
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001202 return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan ||
1203 R==APFloat::cmpEqual);
Reid Spencer266e42b2006-12-23 06:05:41 +00001204 }
Reid Spencerd84d35b2007-02-15 02:26:10 +00001205 } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
1206 if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
Reid Spencer9d36acf2006-12-24 18:52:08 +00001207 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001208 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1209 Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1210 const_cast<Constant*>(CP1->getOperand(i)),
1211 const_cast<Constant*>(CP2->getOperand(i)));
Zhou Sheng75b871f2007-01-11 12:24:14 +00001212 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
Reid Spencer266e42b2006-12-23 06:05:41 +00001213 return CB;
1214 }
1215 // Otherwise, could not decide from any element pairs.
1216 return 0;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001217 } else if (pred == ICmpInst::ICMP_EQ) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001218 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1219 Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1220 const_cast<Constant*>(CP1->getOperand(i)),
1221 const_cast<Constant*>(CP2->getOperand(i)));
Zhou Sheng75b871f2007-01-11 12:24:14 +00001222 if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
Reid Spencer266e42b2006-12-23 06:05:41 +00001223 return CB;
1224 }
1225 // Otherwise, could not decide from any element pairs.
1226 return 0;
1227 }
1228 }
1229 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001230
Reid Spencer9d36acf2006-12-24 18:52:08 +00001231 if (C1->getType()->isFloatingPoint()) {
1232 switch (evaluateFCmpRelation(C1, C2)) {
1233 default: assert(0 && "Unknown relation!");
1234 case FCmpInst::FCMP_UNO:
1235 case FCmpInst::FCMP_ORD:
1236 case FCmpInst::FCMP_UEQ:
1237 case FCmpInst::FCMP_UNE:
1238 case FCmpInst::FCMP_ULT:
1239 case FCmpInst::FCMP_UGT:
1240 case FCmpInst::FCMP_ULE:
1241 case FCmpInst::FCMP_UGE:
1242 case FCmpInst::FCMP_TRUE:
1243 case FCmpInst::FCMP_FALSE:
1244 case FCmpInst::BAD_FCMP_PREDICATE:
1245 break; // Couldn't determine anything about these constants.
1246 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
Reid Spencercddc9df2007-01-12 04:24:46 +00001247 return ConstantInt::get(Type::Int1Ty,
Reid Spencer9d36acf2006-12-24 18:52:08 +00001248 pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1249 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1250 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1251 case FCmpInst::FCMP_OLT: // We know that C1 < C2
Reid Spencercddc9df2007-01-12 04:24:46 +00001252 return ConstantInt::get(Type::Int1Ty,
Reid Spencer9d36acf2006-12-24 18:52:08 +00001253 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1254 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1255 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1256 case FCmpInst::FCMP_OGT: // We know that C1 > C2
Reid Spencercddc9df2007-01-12 04:24:46 +00001257 return ConstantInt::get(Type::Int1Ty,
Reid Spencer9d36acf2006-12-24 18:52:08 +00001258 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1259 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1260 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1261 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1262 // We can only partially decide this relation.
1263 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001264 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001265 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001266 return ConstantInt::getTrue();
Chris Lattner061da2f2004-01-13 05:51:55 +00001267 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001268 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1269 // We can only partially decide this relation.
1270 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001271 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001272 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001273 return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001274 break;
1275 case ICmpInst::ICMP_NE: // We know that C1 != C2
1276 // We can only partially decide this relation.
1277 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001278 return ConstantInt::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001279 if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001280 return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001281 break;
1282 }
1283 } else {
1284 // Evaluate the relation between the two constants, per the predicate.
1285 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1286 default: assert(0 && "Unknown relational!");
1287 case ICmpInst::BAD_ICMP_PREDICATE:
1288 break; // Couldn't determine anything about these constants.
1289 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1290 // If we know the constants are equal, we can decide the result of this
1291 // computation precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001292 return ConstantInt::get(Type::Int1Ty,
1293 pred == ICmpInst::ICMP_EQ ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001294 pred == ICmpInst::ICMP_ULE ||
1295 pred == ICmpInst::ICMP_SLE ||
1296 pred == ICmpInst::ICMP_UGE ||
1297 pred == ICmpInst::ICMP_SGE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001298 case ICmpInst::ICMP_ULT:
1299 // If we know that C1 < C2, we can decide the result of this computation
1300 // precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001301 return ConstantInt::get(Type::Int1Ty,
1302 pred == ICmpInst::ICMP_ULT ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001303 pred == ICmpInst::ICMP_NE ||
1304 pred == ICmpInst::ICMP_ULE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001305 case ICmpInst::ICMP_SLT:
1306 // If we know that C1 < C2, we can decide the result of this computation
1307 // precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001308 return ConstantInt::get(Type::Int1Ty,
1309 pred == ICmpInst::ICMP_SLT ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001310 pred == ICmpInst::ICMP_NE ||
1311 pred == ICmpInst::ICMP_SLE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001312 case ICmpInst::ICMP_UGT:
1313 // If we know that C1 > C2, we can decide the result of this computation
1314 // precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001315 return ConstantInt::get(Type::Int1Ty,
1316 pred == ICmpInst::ICMP_UGT ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001317 pred == ICmpInst::ICMP_NE ||
1318 pred == ICmpInst::ICMP_UGE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001319 case ICmpInst::ICMP_SGT:
1320 // If we know that C1 > C2, we can decide the result of this computation
1321 // precisely.
Reid Spencercddc9df2007-01-12 04:24:46 +00001322 return ConstantInt::get(Type::Int1Ty,
1323 pred == ICmpInst::ICMP_SGT ||
Zhou Sheng75b871f2007-01-11 12:24:14 +00001324 pred == ICmpInst::ICMP_NE ||
1325 pred == ICmpInst::ICMP_SGE);
Reid Spencer9d36acf2006-12-24 18:52:08 +00001326 case ICmpInst::ICMP_ULE:
1327 // If we know that C1 <= C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001328 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getFalse();
1329 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001330 break;
1331 case ICmpInst::ICMP_SLE:
1332 // If we know that C1 <= C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001333 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getFalse();
1334 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001335 break;
1336
1337 case ICmpInst::ICMP_UGE:
1338 // If we know that C1 >= C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001339 if (pred == ICmpInst::ICMP_ULT) return ConstantInt::getFalse();
1340 if (pred == ICmpInst::ICMP_UGT) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001341 break;
1342 case ICmpInst::ICMP_SGE:
1343 // If we know that C1 >= C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001344 if (pred == ICmpInst::ICMP_SLT) return ConstantInt::getFalse();
1345 if (pred == ICmpInst::ICMP_SGT) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001346 break;
1347
1348 case ICmpInst::ICMP_NE:
1349 // If we know that C1 != C2, we can only partially decide this relation.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001350 if (pred == ICmpInst::ICMP_EQ) return ConstantInt::getFalse();
1351 if (pred == ICmpInst::ICMP_NE) return ConstantInt::getTrue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001352 break;
1353 }
1354
1355 if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1356 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1357 // other way if possible.
1358 switch (pred) {
1359 case ICmpInst::ICMP_EQ:
1360 case ICmpInst::ICMP_NE:
1361 // No change of predicate required.
1362 return ConstantFoldCompareInstruction(pred, C2, C1);
1363
1364 case ICmpInst::ICMP_ULT:
1365 case ICmpInst::ICMP_SLT:
1366 case ICmpInst::ICMP_UGT:
1367 case ICmpInst::ICMP_SGT:
1368 case ICmpInst::ICMP_ULE:
1369 case ICmpInst::ICMP_SLE:
1370 case ICmpInst::ICMP_UGE:
1371 case ICmpInst::ICMP_SGE:
1372 // Change the predicate as necessary to swap the operands.
1373 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1374 return ConstantFoldCompareInstruction(pred, C2, C1);
1375
1376 default: // These predicates cannot be flopped around.
1377 break;
1378 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001379 }
1380 }
1381 return 0;
Chris Lattner1dd054c2004-01-12 22:07:24 +00001382}
1383
1384Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
David Greenec656cbb2007-09-04 15:46:09 +00001385 Constant* const *Idxs,
Chris Lattner302116a2007-01-31 04:40:28 +00001386 unsigned NumIdx) {
1387 if (NumIdx == 0 ||
1388 (NumIdx == 1 && Idxs[0]->isNullValue()))
Chris Lattner1dd054c2004-01-12 22:07:24 +00001389 return const_cast<Constant*>(C);
1390
Chris Lattnerf6013752004-10-17 21:54:55 +00001391 if (isa<UndefValue>(C)) {
Christopher Lambedf07882007-12-17 01:12:55 +00001392 const PointerType *Ptr = cast<PointerType>(C->getType());
1393 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
David Greenec656cbb2007-09-04 15:46:09 +00001394 (Value **)Idxs,
1395 (Value **)Idxs+NumIdx,
Chris Lattnerf6013752004-10-17 21:54:55 +00001396 true);
1397 assert(Ty != 0 && "Invalid indices for GEP!");
Christopher Lambedf07882007-12-17 01:12:55 +00001398 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
Chris Lattnerf6013752004-10-17 21:54:55 +00001399 }
1400
Chris Lattner302116a2007-01-31 04:40:28 +00001401 Constant *Idx0 = Idxs[0];
Chris Lattner04b60fe2004-02-16 20:46:13 +00001402 if (C->isNullValue()) {
1403 bool isNull = true;
Chris Lattner302116a2007-01-31 04:40:28 +00001404 for (unsigned i = 0, e = NumIdx; i != e; ++i)
1405 if (!Idxs[i]->isNullValue()) {
Chris Lattner04b60fe2004-02-16 20:46:13 +00001406 isNull = false;
1407 break;
1408 }
1409 if (isNull) {
Christopher Lambedf07882007-12-17 01:12:55 +00001410 const PointerType *Ptr = cast<PointerType>(C->getType());
1411 const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
David Greenec656cbb2007-09-04 15:46:09 +00001412 (Value**)Idxs,
1413 (Value**)Idxs+NumIdx,
Chris Lattner04b60fe2004-02-16 20:46:13 +00001414 true);
1415 assert(Ty != 0 && "Invalid indices for GEP!");
Christopher Lambedf07882007-12-17 01:12:55 +00001416 return
1417 ConstantPointerNull::get(PointerType::get(Ty,Ptr->getAddressSpace()));
Chris Lattner04b60fe2004-02-16 20:46:13 +00001418 }
1419 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00001420
1421 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1422 // Combine Indices - If the source pointer to this getelementptr instruction
1423 // is a getelementptr instruction, combine the indices of the two
1424 // getelementptr instructions into a single instruction.
1425 //
1426 if (CE->getOpcode() == Instruction::GetElementPtr) {
1427 const Type *LastTy = 0;
1428 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1429 I != E; ++I)
1430 LastTy = *I;
1431
Chris Lattner13128ab2004-10-11 22:52:25 +00001432 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
Chris Lattner302116a2007-01-31 04:40:28 +00001433 SmallVector<Value*, 16> NewIndices;
1434 NewIndices.reserve(NumIdx + CE->getNumOperands());
Chris Lattner1dd054c2004-01-12 22:07:24 +00001435 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
Chris Lattner13128ab2004-10-11 22:52:25 +00001436 NewIndices.push_back(CE->getOperand(i));
Chris Lattner1dd054c2004-01-12 22:07:24 +00001437
1438 // Add the last index of the source with the first index of the new GEP.
1439 // Make sure to handle the case when they are actually different types.
1440 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
Chris Lattner13128ab2004-10-11 22:52:25 +00001441 // Otherwise it must be an array.
1442 if (!Idx0->isNullValue()) {
Chris Lattner71068a02004-07-07 04:45:13 +00001443 const Type *IdxTy = Combined->getType();
Reid Spencer1a063892006-12-04 02:46:44 +00001444 if (IdxTy != Idx0->getType()) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001445 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
Reid Spencer27720a92006-12-05 03:30:09 +00001446 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
Reid Spencer8d9336d2006-12-31 05:26:44 +00001447 Type::Int64Ty);
Reid Spencer1a063892006-12-04 02:46:44 +00001448 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1449 } else {
1450 Combined =
1451 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1452 }
Chris Lattner71068a02004-07-07 04:45:13 +00001453 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001454
Chris Lattner1dd054c2004-01-12 22:07:24 +00001455 NewIndices.push_back(Combined);
Chris Lattner302116a2007-01-31 04:40:28 +00001456 NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1457 return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1458 NewIndices.size());
Chris Lattner1dd054c2004-01-12 22:07:24 +00001459 }
1460 }
1461
1462 // Implement folding of:
1463 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1464 // long 0, long 0)
1465 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1466 //
Chris Lattneraadc7782007-08-13 17:09:08 +00001467 if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001468 if (const PointerType *SPT =
Chris Lattner1dd054c2004-01-12 22:07:24 +00001469 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1470 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1471 if (const ArrayType *CAT =
Chris Lattner02157b02006-06-28 21:38:54 +00001472 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
Chris Lattner1dd054c2004-01-12 22:07:24 +00001473 if (CAT->getElementType() == SAT->getElementType())
1474 return ConstantExpr::getGetElementPtr(
Chris Lattner302116a2007-01-31 04:40:28 +00001475 (Constant*)CE->getOperand(0), Idxs, NumIdx);
Chris Lattneraadc7782007-08-13 17:09:08 +00001476 }
1477
1478 // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
1479 // Into: inttoptr (i64 0 to i8*)
1480 // This happens with pointers to member functions in C++.
1481 if (CE->getOpcode() == Instruction::IntToPtr && NumIdx == 1 &&
1482 isa<ConstantInt>(CE->getOperand(0)) && isa<ConstantInt>(Idxs[0]) &&
1483 cast<PointerType>(CE->getType())->getElementType() == Type::Int8Ty) {
1484 Constant *Base = CE->getOperand(0);
1485 Constant *Offset = Idxs[0];
1486
1487 // Convert the smaller integer to the larger type.
1488 if (Offset->getType()->getPrimitiveSizeInBits() <
1489 Base->getType()->getPrimitiveSizeInBits())
1490 Offset = ConstantExpr::getSExt(Offset, Base->getType());
1491 else if (Base->getType()->getPrimitiveSizeInBits() <
1492 Offset->getType()->getPrimitiveSizeInBits())
1493 Base = ConstantExpr::getZExt(Base, Base->getType());
1494
1495 Base = ConstantExpr::getAdd(Base, Offset);
1496 return ConstantExpr::getIntToPtr(Base, CE->getType());
1497 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00001498 }
1499 return 0;
1500}
1501