blob: d35ace0af15e99b9f6bd2ec4318b018e0862db0f [file] [log] [blame]
Chris Lattner5a945e32004-01-12 21:13:12 +00001//===- ConstantFolding.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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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
11// (internal) ConstantFolding.h interface, which is used by the
12// 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 Lattner5a945e32004-01-12 21:13:12 +000021#include "ConstantFolding.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 Lattner3d27be12006-08-27 12:54:02 +000026#include "llvm/Support/Compiler.h"
Chris Lattner057083f2006-10-13 17:22:21 +000027#include "llvm/Support/GetElementPtrTypeIterator.h"
28#include "llvm/Support/ManagedStatic.h"
29#include "llvm/Support/MathExtras.h"
Jeff Cohen4e3aede2005-05-03 03:13:01 +000030#include <limits>
Chris Lattner9d9cbcf2003-11-17 19:05:17 +000031using namespace llvm;
Chris Lattner61607ee2001-09-09 21:01:20 +000032
Chris Lattner1dd054c2004-01-12 22:07:24 +000033//===----------------------------------------------------------------------===//
34// ConstantFold*Instruction Implementations
35//===----------------------------------------------------------------------===//
Chris Lattner1dd054c2004-01-12 22:07:24 +000036
Chris Lattner6b3f4752006-04-02 01:38:28 +000037/// CastConstantPacked - Convert the specified ConstantPacked node to the
38/// specified packed type. At this point, we know that the elements of the
39/// input packed constant are all simple integer or FP values.
40static Constant *CastConstantPacked(ConstantPacked *CP,
41 const PackedType *DstTy) {
42 unsigned SrcNumElts = CP->getType()->getNumElements();
43 unsigned DstNumElts = DstTy->getNumElements();
44 const Type *SrcEltTy = CP->getType()->getElementType();
45 const Type *DstEltTy = DstTy->getElementType();
46
47 // If both vectors have the same number of elements (thus, the elements
48 // are the same size), perform the conversion now.
49 if (SrcNumElts == DstNumElts) {
50 std::vector<Constant*> Result;
51
Reid Spencer6c38f0b2006-11-27 01:05:10 +000052 // If the src and dest elements are both integers, or both floats, we can
53 // just BitCast each element because the elements are the same size.
54 if ((SrcEltTy->isIntegral() && DstEltTy->isIntegral()) ||
55 (SrcEltTy->isFloatingPoint() && DstEltTy->isFloatingPoint())) {
Chris Lattner6b3f4752006-04-02 01:38:28 +000056 for (unsigned i = 0; i != SrcNumElts; ++i)
Reid Spencer6c38f0b2006-11-27 01:05:10 +000057 Result.push_back(
Reid Spencerbb65ebf2006-12-12 23:36:14 +000058 ConstantExpr::getBitCast(CP->getOperand(i), DstEltTy));
Chris Lattner6b3f4752006-04-02 01:38:28 +000059 return ConstantPacked::get(Result);
60 }
61
Reid Spencer6c38f0b2006-11-27 01:05:10 +000062 // If this is an int-to-fp cast ..
Chris Lattner6b3f4752006-04-02 01:38:28 +000063 if (SrcEltTy->isIntegral()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +000064 // Ensure that it is int-to-fp cast
Chris Lattner6b3f4752006-04-02 01:38:28 +000065 assert(DstEltTy->isFloatingPoint());
66 if (DstEltTy->getTypeID() == Type::DoubleTyID) {
67 for (unsigned i = 0; i != SrcNumElts; ++i) {
68 double V =
Reid Spencere0fc4df2006-10-20 07:07:24 +000069 BitsToDouble(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner6b3f4752006-04-02 01:38:28 +000070 Result.push_back(ConstantFP::get(Type::DoubleTy, V));
71 }
72 return ConstantPacked::get(Result);
73 }
74 assert(DstEltTy == Type::FloatTy && "Unknown fp type!");
75 for (unsigned i = 0; i != SrcNumElts; ++i) {
76 float V =
Reid Spencere0fc4df2006-10-20 07:07:24 +000077 BitsToFloat(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner6b3f4752006-04-02 01:38:28 +000078 Result.push_back(ConstantFP::get(Type::FloatTy, V));
79 }
80 return ConstantPacked::get(Result);
81 }
82
83 // Otherwise, this is an fp-to-int cast.
84 assert(SrcEltTy->isFloatingPoint() && DstEltTy->isIntegral());
85
86 if (SrcEltTy->getTypeID() == Type::DoubleTyID) {
87 for (unsigned i = 0; i != SrcNumElts; ++i) {
88 uint64_t V =
89 DoubleToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
Reid Spencer8d9336d2006-12-31 05:26:44 +000090 Constant *C = ConstantInt::get(Type::Int64Ty, V);
Reid Spencera16f9302006-12-05 07:18:07 +000091 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy ));
Chris Lattner6b3f4752006-04-02 01:38:28 +000092 }
93 return ConstantPacked::get(Result);
94 }
95
96 assert(SrcEltTy->getTypeID() == Type::FloatTyID);
97 for (unsigned i = 0; i != SrcNumElts; ++i) {
Reid Spencere0fc4df2006-10-20 07:07:24 +000098 uint32_t V = FloatToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
Reid Spencer8d9336d2006-12-31 05:26:44 +000099 Constant *C = ConstantInt::get(Type::Int32Ty, V);
Reid Spencera16f9302006-12-05 07:18:07 +0000100 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy));
Chris Lattner6b3f4752006-04-02 01:38:28 +0000101 }
102 return ConstantPacked::get(Result);
103 }
104
105 // Otherwise, this is a cast that changes element count and size. Handle
106 // casts which shrink the elements here.
107
108 // FIXME: We need to know endianness to do this!
109
110 return 0;
111}
112
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000113/// This function determines which opcode to use to fold two constant cast
114/// expressions together. It uses CastInst::isEliminableCastPair to determine
115/// the opcode. Consequently its just a wrapper around that function.
116/// @Determine if it is valid to fold a cast of a cast
117static unsigned
118foldConstantCastPair(
119 unsigned opc, ///< opcode of the second cast constant expression
120 const ConstantExpr*Op, ///< the first cast constant expression
121 const Type *DstTy ///< desintation type of the first cast
122) {
123 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
124 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
125 assert(CastInst::isCast(opc) && "Invalid cast opcode");
126
127 // The the types and opcodes for the two Cast constant expressions
128 const Type *SrcTy = Op->getOperand(0)->getType();
129 const Type *MidTy = Op->getType();
130 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
131 Instruction::CastOps secondOp = Instruction::CastOps(opc);
Chris Lattner6b3f4752006-04-02 01:38:28 +0000132
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000133 // Let CastInst::isEliminableCastPair do the heavy lifting.
134 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
Reid Spencer8d9336d2006-12-31 05:26:44 +0000135 Type::Int64Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000136}
137
138Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
Chris Lattner1dd054c2004-01-12 22:07:24 +0000139 const Type *DestTy) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000140 const Type *SrcTy = V->getType();
Chris Lattner1dd054c2004-01-12 22:07:24 +0000141
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000142 if (isa<UndefValue>(V))
143 return UndefValue::get(DestTy);
144
145 // If the cast operand is a constant expression, there's a few things we can
146 // do to try to simplify it.
147 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
148 if (CE->isCast()) {
Reid Spencer1a063892006-12-04 02:46:44 +0000149 // Try hard to fold cast of cast because they are often eliminable.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000150 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
151 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
Chris Lattner1dd054c2004-01-12 22:07:24 +0000152 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
153 // If all of the indexes in the GEP are null values, there is no pointer
154 // adjustment going on. We might as well cast the source pointer.
155 bool isAllNull = true;
156 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
157 if (!CE->getOperand(i)->isNullValue()) {
158 isAllNull = false;
159 break;
160 }
161 if (isAllNull)
Reid Spencer1a063892006-12-04 02:46:44 +0000162 // This is casting one pointer type to another, always BitCast
Reid Spencer27720a92006-12-05 03:30:09 +0000163 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
Chris Lattner1dd054c2004-01-12 22:07:24 +0000164 }
Chris Lattnerfd7bf722004-10-16 23:31:32 +0000165 }
Chris Lattner1dd054c2004-01-12 22:07:24 +0000166
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000167 // We actually have to do a cast now. Perform the cast according to the
168 // opcode specified.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000169 switch (opc) {
170 case Instruction::FPTrunc:
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000171 case Instruction::FPExt:
Reid Spencer8dabca42006-12-19 07:41:40 +0000172 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V))
173 return ConstantFP::get(DestTy, FPC->getValue());
174 return 0; // Can't fold.
175 case Instruction::FPToUI:
176 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V))
177 return ConstantIntegral::get(DestTy,(uint64_t) FPC->getValue());
178 return 0; // Can't fold.
179 case Instruction::FPToSI:
180 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V))
181 return ConstantIntegral::get(DestTy,(int64_t) FPC->getValue());
182 return 0; // Can't fold.
183 case Instruction::IntToPtr: //always treated as unsigned
184 if (V->isNullValue()) // Is it an integral null value?
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000185 return ConstantPointerNull::get(cast<PointerType>(DestTy));
Reid Spencer8dabca42006-12-19 07:41:40 +0000186 return 0; // Other pointer types cannot be casted
187 case Instruction::PtrToInt: // always treated as unsigned
188 if (V->isNullValue()) // is it a null pointer value?
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000189 return ConstantIntegral::get(DestTy, 0);
Reid Spencer8dabca42006-12-19 07:41:40 +0000190 return 0; // Other pointer types cannot be casted
191 case Instruction::UIToFP:
192 if (const ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
193 return ConstantFP::get(DestTy, double(CI->getZExtValue()));
194 return 0;
195 case Instruction::SIToFP:
196 if (const ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
197 return ConstantFP::get(DestTy, double(CI->getSExtValue()));
198 return 0;
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000199 case Instruction::ZExt:
Reid Spencer8dabca42006-12-19 07:41:40 +0000200 if (const ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
201 return ConstantInt::get(DestTy, CI->getZExtValue());
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000202 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000203 case Instruction::SExt:
Reid Spencer8dabca42006-12-19 07:41:40 +0000204 if (const ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
205 return ConstantInt::get(DestTy, CI->getSExtValue());
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000206 return 0;
Chris Lattner710ebaf2006-12-01 19:22:41 +0000207 case Instruction::Trunc:
Reid Spencer8dabca42006-12-19 07:41:40 +0000208 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) // Can't trunc a bool
Chris Lattner710ebaf2006-12-01 19:22:41 +0000209 return ConstantIntegral::get(DestTy, CI->getZExtValue());
210 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000211 case Instruction::BitCast:
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000212 if (SrcTy == DestTy)
213 return (Constant*)V; // no-op cast
Chris Lattner4d1da162006-12-11 18:30:27 +0000214
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000215 // Check to see if we are casting a pointer to an aggregate to a pointer to
216 // the first element. If so, return the appropriate GEP instruction.
217 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
218 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
219 std::vector<Value*> IdxList;
Reid Spencer8d9336d2006-12-31 05:26:44 +0000220 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000221 const Type *ElTy = PTy->getElementType();
222 while (ElTy != DPTy->getElementType()) {
223 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
224 if (STy->getNumElements() == 0) break;
225 ElTy = STy->getElementType(0);
Reid Spencer8d9336d2006-12-31 05:26:44 +0000226 IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000227 } else if (const SequentialType *STy =
228 dyn_cast<SequentialType>(ElTy)) {
229 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
230 ElTy = STy->getElementType();
231 IdxList.push_back(IdxList[0]);
232 } else {
Chris Lattner6b3f4752006-04-02 01:38:28 +0000233 break;
234 }
235 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000236
237 if (ElTy == DPTy->getElementType())
238 return ConstantExpr::getGetElementPtr(
239 const_cast<Constant*>(V),IdxList);
240 }
241
242 // Handle casts from one packed constant to another. We know that the src
243 // and dest type have the same size (otherwise its an illegal cast).
244 if (const PackedType *DestPTy = dyn_cast<PackedType>(DestTy)) {
245 if (const PackedType *SrcTy = dyn_cast<PackedType>(V->getType())) {
246 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
247 "Not cast between same sized vectors!");
248 // First, check for null and undef
249 if (isa<ConstantAggregateZero>(V))
250 return Constant::getNullValue(DestTy);
251 if (isa<UndefValue>(V))
252 return UndefValue::get(DestTy);
253
254 if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
255 // This is a cast from a ConstantPacked of one type to a
256 // ConstantPacked of another type. Check to see if all elements of
257 // the input are simple.
258 bool AllSimpleConstants = true;
259 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
260 if (!isa<ConstantInt>(CP->getOperand(i)) &&
261 !isa<ConstantFP>(CP->getOperand(i))) {
262 AllSimpleConstants = false;
263 break;
264 }
265 }
266
267 // If all of the elements are simple constants, we can fold this.
268 if (AllSimpleConstants)
269 return CastConstantPacked(const_cast<ConstantPacked*>(CP), DestPTy);
270 }
Chris Lattner6b3f4752006-04-02 01:38:28 +0000271 }
272 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000273
Chris Lattner4d1da162006-12-11 18:30:27 +0000274 // Finally, implement bitcast folding now. The code below doesn't handle
275 // bitcast right.
276 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
277 return ConstantPointerNull::get(cast<PointerType>(DestTy));
278
279 // Handle integral constant input.
280 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
281 // Integral -> Integral, must be changing sign.
282 if (DestTy->isIntegral())
283 return ConstantInt::get(DestTy, CI->getZExtValue());
284
285 if (DestTy->isFloatingPoint()) {
286 if (DestTy == Type::FloatTy)
287 return ConstantFP::get(DestTy, BitsToFloat(CI->getZExtValue()));
288 assert(DestTy == Type::DoubleTy && "Unknown FP type!");
289 return ConstantFP::get(DestTy, BitsToDouble(CI->getZExtValue()));
290 }
291 // Otherwise, can't fold this (packed?)
292 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000293 }
Chris Lattner4d1da162006-12-11 18:30:27 +0000294
295 // Handle ConstantFP input.
296 if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
297 // FP -> Integral.
298 if (DestTy->isIntegral()) {
Reid Spencer8d9336d2006-12-31 05:26:44 +0000299 if (DestTy == Type::Int32Ty)
Chris Lattner4d1da162006-12-11 18:30:27 +0000300 return ConstantInt::get(DestTy, FloatToBits(FP->getValue()));
Reid Spencer8d9336d2006-12-31 05:26:44 +0000301 assert(DestTy == Type::Int64Ty &&
Reid Spencerc90cf772006-12-31 21:43:30 +0000302 "Incorrect integer type for bitcast!");
Chris Lattner4d1da162006-12-11 18:30:27 +0000303 return ConstantInt::get(DestTy, DoubleToBits(FP->getValue()));
304 }
305 }
306 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000307 default:
308 assert(!"Invalid CE CastInst opcode");
309 break;
Chris Lattner6b3f4752006-04-02 01:38:28 +0000310 }
Chris Lattnerb2b7f902004-10-11 03:57:30 +0000311
Reid Spencerf5fc34a2006-12-19 03:15:47 +0000312 assert(0 && "Failed to cast constant expression");
313 return 0;
Chris Lattner1dd054c2004-01-12 22:07:24 +0000314}
315
Chris Lattner6ea4b522004-03-12 05:53:32 +0000316Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
317 const Constant *V1,
318 const Constant *V2) {
Chris Lattner78430662006-09-28 23:34:49 +0000319 if (const ConstantBool *CB = dyn_cast<ConstantBool>(Cond))
320 return const_cast<Constant*>(CB->getValue() ? V1 : V2);
Chris Lattnerfd7bf722004-10-16 23:31:32 +0000321
322 if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
323 if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
324 if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000325 if (V1 == V2) return const_cast<Constant*>(V1);
Chris Lattner6ea4b522004-03-12 05:53:32 +0000326 return 0;
327}
328
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000329Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
330 const Constant *Idx) {
Chris Lattnere52f29b2006-03-31 18:31:40 +0000331 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
332 return UndefValue::get(cast<PackedType>(Val->getType())->getElementType());
Chris Lattnere4f9d7b2006-04-07 04:44:06 +0000333 if (Val->isNullValue()) // ee(zero, x) -> zero
334 return Constant::getNullValue(
335 cast<PackedType>(Val->getType())->getElementType());
Chris Lattnere52f29b2006-03-31 18:31:40 +0000336
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000337 if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000338 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
339 return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
Chris Lattnere52f29b2006-03-31 18:31:40 +0000340 } else if (isa<UndefValue>(Idx)) {
341 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
342 return const_cast<Constant*>(CVal->getOperand(0));
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000343 }
Chris Lattnere52f29b2006-03-31 18:31:40 +0000344 }
Robert Bocchinode7f1c92006-01-10 20:03:46 +0000345 return 0;
346}
347
Robert Bocchinoca27f032006-01-17 20:07:22 +0000348Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
349 const Constant *Elt,
350 const Constant *Idx) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000351 const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
Robert Bocchinoca27f032006-01-17 20:07:22 +0000352 if (!CIdx) return 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000353 uint64_t idxVal = CIdx->getZExtValue();
Reid Spencer3054b142006-11-02 08:18:15 +0000354 if (isa<UndefValue>(Val)) {
Robert Bocchinoca27f032006-01-17 20:07:22 +0000355 // Insertion of scalar constant into packed undef
356 // Optimize away insertion of undef
357 if (isa<UndefValue>(Elt))
358 return const_cast<Constant*>(Val);
359 // Otherwise break the aggregate undef into multiple undefs and do
360 // the insertion
361 unsigned numOps =
362 cast<PackedType>(Val->getType())->getNumElements();
363 std::vector<Constant*> Ops;
364 Ops.reserve(numOps);
365 for (unsigned i = 0; i < numOps; ++i) {
366 const Constant *Op =
367 (i == idxVal) ? Elt : UndefValue::get(Elt->getType());
368 Ops.push_back(const_cast<Constant*>(Op));
369 }
370 return ConstantPacked::get(Ops);
371 }
Reid Spencer3054b142006-11-02 08:18:15 +0000372 if (isa<ConstantAggregateZero>(Val)) {
Robert Bocchinoca27f032006-01-17 20:07:22 +0000373 // Insertion of scalar constant into packed aggregate zero
374 // Optimize away insertion of zero
375 if (Elt->isNullValue())
376 return const_cast<Constant*>(Val);
377 // Otherwise break the aggregate zero into multiple zeros and do
378 // the insertion
379 unsigned numOps =
380 cast<PackedType>(Val->getType())->getNumElements();
381 std::vector<Constant*> Ops;
382 Ops.reserve(numOps);
383 for (unsigned i = 0; i < numOps; ++i) {
384 const Constant *Op =
385 (i == idxVal) ? Elt : Constant::getNullValue(Elt->getType());
386 Ops.push_back(const_cast<Constant*>(Op));
387 }
388 return ConstantPacked::get(Ops);
389 }
390 if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
391 // Insertion of scalar constant into packed constant
392 std::vector<Constant*> Ops;
393 Ops.reserve(CVal->getNumOperands());
394 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
395 const Constant *Op =
396 (i == idxVal) ? Elt : cast<Constant>(CVal->getOperand(i));
397 Ops.push_back(const_cast<Constant*>(Op));
398 }
399 return ConstantPacked::get(Ops);
400 }
401 return 0;
402}
403
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000404Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
405 const Constant *V2,
406 const Constant *Mask) {
407 // TODO:
408 return 0;
409}
410
Reid Spencer266e42b2006-12-23 06:05:41 +0000411/// EvalVectorOp - Given two packed constants and a function pointer, apply the
412/// function pointer to each element pair, producing a new ConstantPacked
413/// constant.
414static Constant *EvalVectorOp(const ConstantPacked *V1,
415 const ConstantPacked *V2,
416 Constant *(*FP)(Constant*, Constant*)) {
417 std::vector<Constant*> Res;
418 for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i)
419 Res.push_back(FP(const_cast<Constant*>(V1->getOperand(i)),
420 const_cast<Constant*>(V2->getOperand(i))));
421 return ConstantPacked::get(Res);
422}
423
424Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
425 const Constant *C1,
426 const Constant *C2) {
427 // Handle UndefValue up front
428 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
429 switch (Opcode) {
430 case Instruction::Add:
431 case Instruction::Sub:
432 case Instruction::Xor:
433 return UndefValue::get(C1->getType());
434 case Instruction::Mul:
435 case Instruction::And:
436 return Constant::getNullValue(C1->getType());
437 case Instruction::UDiv:
438 case Instruction::SDiv:
439 case Instruction::FDiv:
440 case Instruction::URem:
441 case Instruction::SRem:
442 case Instruction::FRem:
443 if (!isa<UndefValue>(C2)) // undef / X -> 0
444 return Constant::getNullValue(C1->getType());
445 return const_cast<Constant*>(C2); // X / undef -> undef
446 case Instruction::Or: // X | undef -> -1
Chris Lattner26f13eb2007-01-04 01:56:39 +0000447 if (const PackedType *PTy = dyn_cast<PackedType>(C1->getType()))
448 return ConstantPacked::getAllOnesValue(PTy);
Reid Spencer266e42b2006-12-23 06:05:41 +0000449 return ConstantInt::getAllOnesValue(C1->getType());
450 case Instruction::LShr:
451 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
452 return const_cast<Constant*>(C1); // undef lshr undef -> undef
453 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
454 // undef lshr X -> 0
455 case Instruction::AShr:
456 if (!isa<UndefValue>(C2))
457 return const_cast<Constant*>(C1); // undef ashr X --> undef
458 else if (isa<UndefValue>(C1))
459 return const_cast<Constant*>(C1); // undef ashr undef -> undef
460 else
461 return const_cast<Constant*>(C1); // X ashr undef --> X
462 case Instruction::Shl:
463 // undef << X -> 0 or X << undef -> 0
464 return Constant::getNullValue(C1->getType());
465 }
466 }
467
468 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
469 if (isa<ConstantExpr>(C2)) {
470 // There are many possible foldings we could do here. We should probably
471 // at least fold add of a pointer with an integer into the appropriate
472 // getelementptr. This will improve alias analysis a bit.
473 } else {
474 // Just implement a couple of simple identities.
475 switch (Opcode) {
476 case Instruction::Add:
477 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X + 0 == X
478 break;
479 case Instruction::Sub:
480 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X - 0 == X
481 break;
482 case Instruction::Mul:
483 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X * 0 == 0
484 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
485 if (CI->getZExtValue() == 1)
486 return const_cast<Constant*>(C1); // X * 1 == X
487 break;
488 case Instruction::UDiv:
489 case Instruction::SDiv:
490 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
491 if (CI->getZExtValue() == 1)
492 return const_cast<Constant*>(C1); // X / 1 == X
493 break;
494 case Instruction::URem:
495 case Instruction::SRem:
496 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
497 if (CI->getZExtValue() == 1)
498 return Constant::getNullValue(CI->getType()); // X % 1 == 0
499 break;
500 case Instruction::And:
Chris Lattner26f13eb2007-01-04 01:56:39 +0000501 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
502 if (CI->isAllOnesValue())
503 return const_cast<Constant*>(C1); // X & -1 == X
Reid Spencer266e42b2006-12-23 06:05:41 +0000504 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X & 0 == 0
505 if (CE1->isCast() && isa<GlobalValue>(CE1->getOperand(0))) {
506 GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
507
508 // Functions are at least 4-byte aligned. If and'ing the address of a
509 // function with a constant < 4, fold it to zero.
510 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
511 if (CI->getZExtValue() < 4 && isa<Function>(CPR))
512 return Constant::getNullValue(CI->getType());
513 }
514 break;
515 case Instruction::Or:
516 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X | 0 == X
Chris Lattner26f13eb2007-01-04 01:56:39 +0000517 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
518 if (CI->isAllOnesValue())
519 return const_cast<Constant*>(C2); // X | -1 == -1
Reid Spencer266e42b2006-12-23 06:05:41 +0000520 break;
521 case Instruction::Xor:
522 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X ^ 0 == X
523 break;
524 }
525 }
526 } else if (isa<ConstantExpr>(C2)) {
527 // If C2 is a constant expr and C1 isn't, flop them around and fold the
528 // other way if possible.
529 switch (Opcode) {
530 case Instruction::Add:
531 case Instruction::Mul:
532 case Instruction::And:
533 case Instruction::Or:
534 case Instruction::Xor:
535 // No change of opcode required.
536 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
537
538 case Instruction::Shl:
539 case Instruction::LShr:
540 case Instruction::AShr:
541 case Instruction::Sub:
542 case Instruction::SDiv:
543 case Instruction::UDiv:
544 case Instruction::FDiv:
545 case Instruction::URem:
546 case Instruction::SRem:
547 case Instruction::FRem:
548 default: // These instructions cannot be flopped around.
549 return 0;
550 }
551 }
552
553 // At this point we know neither constant is an UndefValue nor a ConstantExpr
Chris Lattner26f13eb2007-01-04 01:56:39 +0000554 // so look at directly computing the value.
Reid Spencer266e42b2006-12-23 06:05:41 +0000555 if (const ConstantBool *CB1 = dyn_cast<ConstantBool>(C1)) {
556 if (const ConstantBool *CB2 = dyn_cast<ConstantBool>(C2)) {
557 switch (Opcode) {
558 default:
559 break;
560 case Instruction::And:
561 return ConstantBool::get(CB1->getValue() & CB2->getValue());
562 case Instruction::Or:
563 return ConstantBool::get(CB1->getValue() | CB2->getValue());
564 case Instruction::Xor:
565 return ConstantBool::get(CB1->getValue() ^ CB2->getValue());
566 }
567 }
568 } else if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
569 if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
570 uint64_t C1Val = CI1->getZExtValue();
571 uint64_t C2Val = CI2->getZExtValue();
572 switch (Opcode) {
573 default:
574 break;
575 case Instruction::Add:
576 return ConstantInt::get(C1->getType(), C1Val + C2Val);
577 case Instruction::Sub:
578 return ConstantInt::get(C1->getType(), C1Val - C2Val);
579 case Instruction::Mul:
580 return ConstantInt::get(C1->getType(), C1Val * C2Val);
581 case Instruction::UDiv:
582 if (CI2->isNullValue()) // X / 0 -> can't fold
583 return 0;
584 return ConstantInt::get(C1->getType(), C1Val / C2Val);
585 case Instruction::SDiv:
586 if (CI2->isNullValue()) return 0; // X / 0 -> can't fold
587 if (CI2->isAllOnesValue() &&
588 (((CI1->getType()->getPrimitiveSizeInBits() == 64) &&
589 (CI1->getSExtValue() == INT64_MIN)) ||
590 (CI1->getSExtValue() == -CI1->getSExtValue())))
591 return 0; // MIN_INT / -1 -> overflow
592 return ConstantInt::get(C1->getType(),
593 CI1->getSExtValue() / CI2->getSExtValue());
594 case Instruction::URem:
595 if (C2->isNullValue()) return 0; // X / 0 -> can't fold
596 return ConstantInt::get(C1->getType(), C1Val % C2Val);
597 case Instruction::SRem:
598 if (CI2->isNullValue()) return 0; // X % 0 -> can't fold
599 if (CI2->isAllOnesValue() &&
600 (((CI1->getType()->getPrimitiveSizeInBits() == 64) &&
601 (CI1->getSExtValue() == INT64_MIN)) ||
602 (CI1->getSExtValue() == -CI1->getSExtValue())))
603 return 0; // MIN_INT % -1 -> overflow
604 return ConstantInt::get(C1->getType(),
605 CI1->getSExtValue() % CI2->getSExtValue());
606 case Instruction::And:
607 return ConstantInt::get(C1->getType(), C1Val & C2Val);
608 case Instruction::Or:
609 return ConstantInt::get(C1->getType(), C1Val | C2Val);
610 case Instruction::Xor:
611 return ConstantInt::get(C1->getType(), C1Val ^ C2Val);
612 case Instruction::Shl:
Chris Lattner26f13eb2007-01-04 01:56:39 +0000613 if (C2Val >= CI1->getType()->getPrimitiveSizeInBits())
614 C2Val = CI1->getType()->getPrimitiveSizeInBits() - 1;
Reid Spencer266e42b2006-12-23 06:05:41 +0000615 return ConstantInt::get(C1->getType(), C1Val << C2Val);
616 case Instruction::LShr:
Chris Lattner26f13eb2007-01-04 01:56:39 +0000617 if (C2Val >= CI1->getType()->getPrimitiveSizeInBits())
618 C2Val = CI1->getType()->getPrimitiveSizeInBits() - 1;
Reid Spencer266e42b2006-12-23 06:05:41 +0000619 return ConstantInt::get(C1->getType(), C1Val >> C2Val);
620 case Instruction::AShr:
Chris Lattner26f13eb2007-01-04 01:56:39 +0000621 if (C2Val >= CI1->getType()->getPrimitiveSizeInBits())
622 C2Val = CI1->getType()->getPrimitiveSizeInBits() - 1;
Reid Spencer266e42b2006-12-23 06:05:41 +0000623 return ConstantInt::get(C1->getType(),
624 CI1->getSExtValue() >> C2Val);
625 }
626 }
627 } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
628 if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
629 double C1Val = CFP1->getValue();
630 double C2Val = CFP2->getValue();
631 switch (Opcode) {
632 default:
633 break;
634 case Instruction::Add:
635 return ConstantFP::get(CFP1->getType(), C1Val + C2Val);
636 case Instruction::Sub:
637 return ConstantFP::get(CFP1->getType(), C1Val - C2Val);
638 case Instruction::Mul:
639 return ConstantFP::get(CFP1->getType(), C1Val * C2Val);
640 case Instruction::FDiv:
641 if (CFP2->isExactlyValue(0.0))
642 return ConstantFP::get(CFP1->getType(),
643 std::numeric_limits<double>::infinity());
644 if (CFP2->isExactlyValue(-0.0))
645 return ConstantFP::get(CFP1->getType(),
646 -std::numeric_limits<double>::infinity());
647 return ConstantFP::get(CFP1->getType(), C1Val / C2Val);
648 case Instruction::FRem:
649 if (CFP2->isNullValue())
650 return 0;
651 return ConstantFP::get(CFP1->getType(), std::fmod(C1Val, C2Val));
652 }
653 }
654 } else if (const ConstantPacked *CP1 = dyn_cast<ConstantPacked>(C1)) {
655 if (const ConstantPacked *CP2 = dyn_cast<ConstantPacked>(C2)) {
656 switch (Opcode) {
657 default:
658 break;
659 case Instruction::Add:
660 return EvalVectorOp(CP1, CP2, ConstantExpr::getAdd);
661 case Instruction::Sub:
662 return EvalVectorOp(CP1, CP2, ConstantExpr::getSub);
663 case Instruction::Mul:
664 return EvalVectorOp(CP1, CP2, ConstantExpr::getMul);
665 case Instruction::UDiv:
666 return EvalVectorOp(CP1, CP2, ConstantExpr::getUDiv);
667 case Instruction::SDiv:
668 return EvalVectorOp(CP1, CP2, ConstantExpr::getSDiv);
669 case Instruction::FDiv:
670 return EvalVectorOp(CP1, CP2, ConstantExpr::getFDiv);
671 case Instruction::URem:
672 return EvalVectorOp(CP1, CP2, ConstantExpr::getURem);
673 case Instruction::SRem:
674 return EvalVectorOp(CP1, CP2, ConstantExpr::getSRem);
675 case Instruction::FRem:
676 return EvalVectorOp(CP1, CP2, ConstantExpr::getFRem);
677 case Instruction::And:
678 return EvalVectorOp(CP1, CP2, ConstantExpr::getAnd);
679 case Instruction::Or:
680 return EvalVectorOp(CP1, CP2, ConstantExpr::getOr);
681 case Instruction::Xor:
682 return EvalVectorOp(CP1, CP2, ConstantExpr::getXor);
683 }
684 }
685 }
686
687 // We don't know how to fold this
688 return 0;
689}
Chris Lattnerbbe0a422006-04-08 01:18:18 +0000690
Chris Lattner60c47262005-01-28 19:09:51 +0000691/// isZeroSizedType - This type is zero sized if its an array or structure of
692/// zero sized types. The only leaf zero sized type is an empty structure.
693static bool isMaybeZeroSizedType(const Type *Ty) {
694 if (isa<OpaqueType>(Ty)) return true; // Can't say.
695 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
696
697 // If all of elements have zero size, this does too.
698 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerfeaf92f2005-01-28 23:17:27 +0000699 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
Chris Lattner60c47262005-01-28 19:09:51 +0000700 return true;
701
702 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
703 return isMaybeZeroSizedType(ATy->getElementType());
704 }
705 return false;
706}
Chris Lattner6ea4b522004-03-12 05:53:32 +0000707
Chris Lattner061da2f2004-01-13 05:51:55 +0000708/// IdxCompare - Compare the two constants as though they were getelementptr
709/// indices. This allows coersion of the types to be the same thing.
710///
711/// If the two constants are the "same" (after coersion), return 0. If the
712/// first is less than the second, return -1, if the second is less than the
713/// first, return 1. If the constants are not integral, return -2.
714///
Chris Lattner60c47262005-01-28 19:09:51 +0000715static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
Chris Lattner061da2f2004-01-13 05:51:55 +0000716 if (C1 == C2) return 0;
717
Reid Spencerc90cf772006-12-31 21:43:30 +0000718 // Ok, we found a different index. If they are not ConstantInt, we can't do
719 // anything with them.
Chris Lattner061da2f2004-01-13 05:51:55 +0000720 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
721 return -2; // don't know!
Misha Brukmanb1c93172005-04-21 23:48:37 +0000722
Chris Lattner69193f92004-04-05 01:30:19 +0000723 // Ok, we have two differing integer indices. Sign extend them to be the same
724 // type. Long is always big enough, so we use it.
Reid Spencer8d9336d2006-12-31 05:26:44 +0000725 if (C1->getType() != Type::Int64Ty)
726 C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000727
Reid Spencer8d9336d2006-12-31 05:26:44 +0000728 if (C2->getType() != Type::Int64Ty)
Reid Spencerc90cf772006-12-31 21:43:30 +0000729 C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
Reid Spencer8d9336d2006-12-31 05:26:44 +0000730
731 if (C1 == C2) return 0; // They are equal
Chris Lattner061da2f2004-01-13 05:51:55 +0000732
Chris Lattner60c47262005-01-28 19:09:51 +0000733 // If the type being indexed over is really just a zero sized type, there is
734 // no pointer difference being made here.
735 if (isMaybeZeroSizedType(ElTy))
736 return -2; // dunno.
737
Chris Lattner061da2f2004-01-13 05:51:55 +0000738 // If they are really different, now that they are the same type, then we
739 // found a difference!
Reid Spencere0fc4df2006-10-20 07:07:24 +0000740 if (cast<ConstantInt>(C1)->getSExtValue() <
741 cast<ConstantInt>(C2)->getSExtValue())
Chris Lattner061da2f2004-01-13 05:51:55 +0000742 return -1;
743 else
744 return 1;
745}
746
Reid Spencer266e42b2006-12-23 06:05:41 +0000747/// evaluatFCmpeRelation - This function determines if there is anything we can
748/// decide about the two constants provided. This doesn't need to handle simple
749/// things like ConstantFP comparisons, but should instead handle ConstantExprs.
750/// If we can determine that the two constants have a particular relation to
751/// each other, we should return the corresponding FCmpInst predicate,
Reid Spencer9d36acf2006-12-24 18:52:08 +0000752/// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
753/// ConstantFoldCompareInstruction.
Reid Spencer266e42b2006-12-23 06:05:41 +0000754///
755/// To simplify this code we canonicalize the relation so that the first
Reid Spencer9d36acf2006-12-24 18:52:08 +0000756/// operand is always the most "complex" of the two. We consider ConstantFP
757/// to be the simplest, and ConstantExprs to be the most complex.
758static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1,
759 const Constant *V2) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000760 assert(V1->getType() == V2->getType() &&
Reid Spencer9d36acf2006-12-24 18:52:08 +0000761 "Cannot compare values of different types!");
762 // Handle degenerate case quickly
Reid Spencer266e42b2006-12-23 06:05:41 +0000763 if (V1 == V2) return FCmpInst::FCMP_OEQ;
764
Reid Spencer9d36acf2006-12-24 18:52:08 +0000765 if (!isa<ConstantExpr>(V1)) {
766 if (!isa<ConstantExpr>(V2)) {
767 // We distilled thisUse the standard constant folder for a few cases
768 ConstantBool *R = 0;
769 Constant *C1 = const_cast<Constant*>(V1);
770 Constant *C2 = const_cast<Constant*>(V2);
771 R = dyn_cast<ConstantBool>(
772 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
Reid Spencer266e42b2006-12-23 06:05:41 +0000773 if (R && R->getValue())
774 return FCmpInst::FCMP_OEQ;
775 R = dyn_cast<ConstantBool>(
Reid Spencer9d36acf2006-12-24 18:52:08 +0000776 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
Reid Spencer266e42b2006-12-23 06:05:41 +0000777 if (R && R->getValue())
778 return FCmpInst::FCMP_OLT;
779 R = dyn_cast<ConstantBool>(
Reid Spencer9d36acf2006-12-24 18:52:08 +0000780 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
781 if (R && R->getValue())
782 return FCmpInst::FCMP_OGT;
783
784 // Nothing more we can do
Reid Spencer266e42b2006-12-23 06:05:41 +0000785 return FCmpInst::BAD_FCMP_PREDICATE;
786 }
787
Reid Spencer9d36acf2006-12-24 18:52:08 +0000788 // If the first operand is simple and second is ConstantExpr, swap operands.
789 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
790 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
791 return FCmpInst::getSwappedPredicate(SwappedRelation);
792 } else {
793 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
794 // constantexpr or a simple constant.
795 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
796 switch (CE1->getOpcode()) {
797 case Instruction::FPTrunc:
798 case Instruction::FPExt:
799 case Instruction::UIToFP:
800 case Instruction::SIToFP:
801 // We might be able to do something with these but we don't right now.
802 break;
803 default:
804 break;
805 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000806 }
Reid Spencer266e42b2006-12-23 06:05:41 +0000807 // There are MANY other foldings that we could perform here. They will
808 // probably be added on demand, as they seem needed.
809 return FCmpInst::BAD_FCMP_PREDICATE;
810}
811
812/// evaluateICmpRelation - This function determines if there is anything we can
Chris Lattner061da2f2004-01-13 05:51:55 +0000813/// decide about the two constants provided. This doesn't need to handle simple
Reid Spenceraccd7c72004-07-17 23:47:01 +0000814/// things like integer comparisons, but should instead handle ConstantExprs
Chris Lattner8410beb2006-12-11 02:16:58 +0000815/// and GlobalValues. If we can determine that the two constants have a
Reid Spencer266e42b2006-12-23 06:05:41 +0000816/// particular relation to each other, we should return the corresponding ICmp
817/// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
Chris Lattner061da2f2004-01-13 05:51:55 +0000818///
819/// To simplify this code we canonicalize the relation so that the first
820/// operand is always the most "complex" of the two. We consider simple
821/// constants (like ConstantInt) to be the simplest, followed by
Reid Spenceraccd7c72004-07-17 23:47:01 +0000822/// GlobalValues, followed by ConstantExpr's (the most complex).
Chris Lattner061da2f2004-01-13 05:51:55 +0000823///
Reid Spencer9d36acf2006-12-24 18:52:08 +0000824static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1,
825 const Constant *V2,
Reid Spencer266e42b2006-12-23 06:05:41 +0000826 bool isSigned) {
Chris Lattner061da2f2004-01-13 05:51:55 +0000827 assert(V1->getType() == V2->getType() &&
828 "Cannot compare different types of values!");
Reid Spencer266e42b2006-12-23 06:05:41 +0000829 if (V1 == V2) return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +0000830
Reid Spenceraccd7c72004-07-17 23:47:01 +0000831 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000832 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
833 // We distilled this down to a simple case, use the standard constant
834 // folder.
Reid Spencer9d36acf2006-12-24 18:52:08 +0000835 ConstantBool *R = 0;
836 Constant *C1 = const_cast<Constant*>(V1);
837 Constant *C2 = const_cast<Constant*>(V2);
Reid Spencer266e42b2006-12-23 06:05:41 +0000838 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
Reid Spencer9d36acf2006-12-24 18:52:08 +0000839 R = dyn_cast<ConstantBool>(ConstantExpr::getICmp(pred, C1, C2));
Reid Spencer266e42b2006-12-23 06:05:41 +0000840 if (R && R->getValue())
841 return pred;
842 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Reid Spencer9d36acf2006-12-24 18:52:08 +0000843 R = dyn_cast<ConstantBool>(ConstantExpr::getICmp(pred, C1, C2));
Reid Spencer266e42b2006-12-23 06:05:41 +0000844 if (R && R->getValue())
845 return pred;
846 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Reid Spencer9d36acf2006-12-24 18:52:08 +0000847 R = dyn_cast<ConstantBool>(ConstantExpr::getICmp(pred, C1, C2));
Reid Spencer266e42b2006-12-23 06:05:41 +0000848 if (R && R->getValue())
849 return pred;
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000850
851 // If we couldn't figure it out, bail.
Reid Spencer266e42b2006-12-23 06:05:41 +0000852 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000853 }
854
Chris Lattner061da2f2004-01-13 05:51:55 +0000855 // If the first operand is simple, swap operands.
Reid Spencer266e42b2006-12-23 06:05:41 +0000856 ICmpInst::Predicate SwappedRelation =
857 evaluateICmpRelation(V2, V1, isSigned);
858 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
859 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner061da2f2004-01-13 05:51:55 +0000860
Chris Lattner0f7e9f52006-01-05 07:19:51 +0000861 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
Chris Lattner125ed542004-02-01 01:23:19 +0000862 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
Reid Spencer266e42b2006-12-23 06:05:41 +0000863 ICmpInst::Predicate SwappedRelation =
864 evaluateICmpRelation(V2, V1, isSigned);
865 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
866 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner0f7e9f52006-01-05 07:19:51 +0000867 else
Reid Spencer266e42b2006-12-23 06:05:41 +0000868 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner125ed542004-02-01 01:23:19 +0000869 }
Chris Lattner061da2f2004-01-13 05:51:55 +0000870
Reid Spenceraccd7c72004-07-17 23:47:01 +0000871 // Now we know that the RHS is a GlobalValue or simple constant,
Chris Lattner061da2f2004-01-13 05:51:55 +0000872 // which (since the types must match) means that it's a ConstantPointerNull.
Reid Spenceraccd7c72004-07-17 23:47:01 +0000873 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
Reid Spencer876f7222006-12-06 00:25:09 +0000874 if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
Reid Spencer266e42b2006-12-23 06:05:41 +0000875 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +0000876 } else {
Reid Spencer876f7222006-12-06 00:25:09 +0000877 // GlobalVals can never be null.
Chris Lattner061da2f2004-01-13 05:51:55 +0000878 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
Reid Spencer876f7222006-12-06 00:25:09 +0000879 if (!CPR1->hasExternalWeakLinkage())
Reid Spencer266e42b2006-12-23 06:05:41 +0000880 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +0000881 }
Chris Lattner061da2f2004-01-13 05:51:55 +0000882 } else {
883 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
884 // constantexpr, a CPR, or a simple constant.
Reid Spencer9d36acf2006-12-24 18:52:08 +0000885 const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
886 const Constant *CE1Op0 = CE1->getOperand(0);
Chris Lattner061da2f2004-01-13 05:51:55 +0000887
888 switch (CE1->getOpcode()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000889 case Instruction::Trunc:
890 case Instruction::FPTrunc:
891 case Instruction::FPExt:
892 case Instruction::FPToUI:
893 case Instruction::FPToSI:
Reid Spencer266e42b2006-12-23 06:05:41 +0000894 break; // We can't evaluate floating point casts or truncations.
895
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000896 case Instruction::UIToFP:
897 case Instruction::SIToFP:
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000898 case Instruction::IntToPtr:
899 case Instruction::BitCast:
Reid Spencer266e42b2006-12-23 06:05:41 +0000900 case Instruction::ZExt:
901 case Instruction::SExt:
902 case Instruction::PtrToInt:
Chris Lattner061da2f2004-01-13 05:51:55 +0000903 // If the cast is not actually changing bits, and the second operand is a
904 // null pointer, do the comparison with the pre-casted value.
905 if (V2->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +0000906 (isa<PointerType>(CE1->getType()) || CE1->getType()->isIntegral())) {
Reid Spencerccf78ac2006-12-23 10:21:26 +0000907 bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
Reid Spencer266e42b2006-12-23 06:05:41 +0000908 (CE1->getOpcode() == Instruction::SExt ? true :
909 (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
910 return evaluateICmpRelation(
Reid Spencerccf78ac2006-12-23 10:21:26 +0000911 CE1Op0, Constant::getNullValue(CE1Op0->getType()), sgnd);
Reid Spencer266e42b2006-12-23 06:05:41 +0000912 }
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000913
914 // If the dest type is a pointer type, and the RHS is a constantexpr cast
915 // from the same type as the src of the LHS, evaluate the inputs. This is
Reid Spencer266e42b2006-12-23 06:05:41 +0000916 // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000917 // which happens a lot in compilers with tagged integers.
Reid Spencer9d36acf2006-12-24 18:52:08 +0000918 if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
Reid Spencer266e42b2006-12-23 06:05:41 +0000919 if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000920 CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
921 CE1->getOperand(0)->getType()->isIntegral()) {
Reid Spencerccf78ac2006-12-23 10:21:26 +0000922 bool sgnd = CE1->getOpcode() == Instruction::ZExt ? false :
Reid Spencer266e42b2006-12-23 06:05:41 +0000923 (CE1->getOpcode() == Instruction::SExt ? true :
924 (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
925 return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
Reid Spencerccf78ac2006-12-23 10:21:26 +0000926 sgnd);
Chris Lattnerfed8ceb2006-01-05 07:49:30 +0000927 }
Chris Lattner192e3262004-04-11 01:29:30 +0000928 break;
Chris Lattner061da2f2004-01-13 05:51:55 +0000929
930 case Instruction::GetElementPtr:
931 // Ok, since this is a getelementptr, we know that the constant has a
932 // pointer type. Check the various cases.
933 if (isa<ConstantPointerNull>(V2)) {
934 // If we are comparing a GEP to a null pointer, check to see if the base
935 // of the GEP equals the null pointer.
Reid Spencer9d36acf2006-12-24 18:52:08 +0000936 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
Reid Spencer876f7222006-12-06 00:25:09 +0000937 if (GV->hasExternalWeakLinkage())
938 // Weak linkage GVals could be zero or not. We're comparing that
939 // to null pointer so its greater-or-equal
Reid Spencer266e42b2006-12-23 06:05:41 +0000940 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
Reid Spencer876f7222006-12-06 00:25:09 +0000941 else
942 // If its not weak linkage, the GVal must have a non-zero address
943 // so the result is greater-than
Reid Spencer266e42b2006-12-23 06:05:41 +0000944 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +0000945 } else if (isa<ConstantPointerNull>(CE1Op0)) {
946 // If we are indexing from a null pointer, check to see if we have any
947 // non-zero indices.
948 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
949 if (!CE1->getOperand(i)->isNullValue())
950 // Offsetting from null, must not be equal.
Reid Spencer266e42b2006-12-23 06:05:41 +0000951 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +0000952 // Only zero indexes from null, must still be zero.
Reid Spencer266e42b2006-12-23 06:05:41 +0000953 return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +0000954 }
955 // Otherwise, we can't really say if the first operand is null or not.
Reid Spenceraccd7c72004-07-17 23:47:01 +0000956 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattner061da2f2004-01-13 05:51:55 +0000957 if (isa<ConstantPointerNull>(CE1Op0)) {
Reid Spencer876f7222006-12-06 00:25:09 +0000958 if (CPR2->hasExternalWeakLinkage())
959 // Weak linkage GVals could be zero or not. We're comparing it to
960 // a null pointer, so its less-or-equal
Reid Spencer266e42b2006-12-23 06:05:41 +0000961 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
Reid Spencer876f7222006-12-06 00:25:09 +0000962 else
963 // If its not weak linkage, the GVal must have a non-zero address
964 // so the result is less-than
Reid Spencer266e42b2006-12-23 06:05:41 +0000965 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Reid Spenceraccd7c72004-07-17 23:47:01 +0000966 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
Chris Lattner061da2f2004-01-13 05:51:55 +0000967 if (CPR1 == CPR2) {
968 // If this is a getelementptr of the same global, then it must be
969 // different. Because the types must match, the getelementptr could
970 // only have at most one index, and because we fold getelementptr's
971 // with a single zero index, it must be nonzero.
972 assert(CE1->getNumOperands() == 2 &&
973 !CE1->getOperand(1)->isNullValue() &&
974 "Suprising getelementptr!");
Reid Spencer266e42b2006-12-23 06:05:41 +0000975 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner061da2f2004-01-13 05:51:55 +0000976 } else {
977 // If they are different globals, we don't know what the value is,
978 // but they can't be equal.
Reid Spencer266e42b2006-12-23 06:05:41 +0000979 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +0000980 }
981 }
982 } else {
983 const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
984 const Constant *CE2Op0 = CE2->getOperand(0);
985
986 // There are MANY other foldings that we could perform here. They will
987 // probably be added on demand, as they seem needed.
988 switch (CE2->getOpcode()) {
989 default: break;
990 case Instruction::GetElementPtr:
991 // By far the most common case to handle is when the base pointers are
992 // obviously to the same or different globals.
Reid Spenceraccd7c72004-07-17 23:47:01 +0000993 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
Chris Lattner061da2f2004-01-13 05:51:55 +0000994 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
Reid Spencer266e42b2006-12-23 06:05:41 +0000995 return ICmpInst::ICMP_NE;
Chris Lattner061da2f2004-01-13 05:51:55 +0000996 // Ok, we know that both getelementptr instructions are based on the
997 // same global. From this, we can precisely determine the relative
998 // ordering of the resultant pointers.
999 unsigned i = 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001000
Chris Lattner061da2f2004-01-13 05:51:55 +00001001 // Compare all of the operands the GEP's have in common.
Chris Lattner60c47262005-01-28 19:09:51 +00001002 gep_type_iterator GTI = gep_type_begin(CE1);
1003 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1004 ++i, ++GTI)
1005 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1006 GTI.getIndexedType())) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001007 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1008 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1009 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001010 }
1011
1012 // Ok, we ran out of things they have in common. If any leftovers
1013 // are non-zero then we have a difference, otherwise we are equal.
1014 for (; i < CE1->getNumOperands(); ++i)
1015 if (!CE1->getOperand(i)->isNullValue())
Chris Lattner60c47262005-01-28 19:09:51 +00001016 if (isa<ConstantIntegral>(CE1->getOperand(i)))
Reid Spencer266e42b2006-12-23 06:05:41 +00001017 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner60c47262005-01-28 19:09:51 +00001018 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001019 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001020
Chris Lattner061da2f2004-01-13 05:51:55 +00001021 for (; i < CE2->getNumOperands(); ++i)
1022 if (!CE2->getOperand(i)->isNullValue())
Chris Lattner60c47262005-01-28 19:09:51 +00001023 if (isa<ConstantIntegral>(CE2->getOperand(i)))
Reid Spencer266e42b2006-12-23 06:05:41 +00001024 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Chris Lattner60c47262005-01-28 19:09:51 +00001025 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001026 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1027 return ICmpInst::ICMP_EQ;
Chris Lattner061da2f2004-01-13 05:51:55 +00001028 }
1029 }
1030 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001031 default:
1032 break;
1033 }
1034 }
1035
Reid Spencer266e42b2006-12-23 06:05:41 +00001036 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner061da2f2004-01-13 05:51:55 +00001037}
1038
Reid Spencer9d36acf2006-12-24 18:52:08 +00001039Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1040 const Constant *C1,
1041 const Constant *C2) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001042
1043 // Handle some degenerate cases first
1044 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1045 return UndefValue::get(Type::BoolTy);
1046
1047 // icmp eq/ne(null,GV) -> false/true
1048 if (C1->isNullValue()) {
1049 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1050 if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
Reid Spencer9d36acf2006-12-24 18:52:08 +00001051 if (pred == ICmpInst::ICMP_EQ)
Reid Spencer6f05d732006-12-01 03:56:30 +00001052 return ConstantBool::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001053 else if (pred == ICmpInst::ICMP_NE)
Reid Spencer266e42b2006-12-23 06:05:41 +00001054 return ConstantBool::getTrue();
1055 // icmp eq/ne(GV,null) -> false/true
1056 } else if (C2->isNullValue()) {
1057 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1058 if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
Reid Spencer9d36acf2006-12-24 18:52:08 +00001059 if (pred == ICmpInst::ICMP_EQ)
Reid Spencer6f05d732006-12-01 03:56:30 +00001060 return ConstantBool::getFalse();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001061 else if (pred == ICmpInst::ICMP_NE)
Reid Spencer6f05d732006-12-01 03:56:30 +00001062 return ConstantBool::getTrue();
Chris Lattner1dd054c2004-01-12 22:07:24 +00001063 }
1064
Reid Spencer266e42b2006-12-23 06:05:41 +00001065 if (isa<ConstantBool>(C1) && isa<ConstantBool>(C2)) {
1066 bool C1Val = cast<ConstantBool>(C1)->getValue();
1067 bool C2Val = cast<ConstantBool>(C2)->getValue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001068 switch (pred) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001069 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1070 case ICmpInst::ICMP_EQ: return ConstantBool::get(C1Val == C2Val);
1071 case ICmpInst::ICMP_NE: return ConstantBool::get(C1Val != C2Val);
1072 case ICmpInst::ICMP_ULT:return ConstantBool::get(C1Val < C2Val);
1073 case ICmpInst::ICMP_UGT:return ConstantBool::get(C1Val > C2Val);
1074 case ICmpInst::ICMP_ULE:return ConstantBool::get(C1Val <= C2Val);
1075 case ICmpInst::ICMP_UGE:return ConstantBool::get(C1Val >= C2Val);
1076 case ICmpInst::ICMP_SLT:return ConstantBool::get(C1Val < C2Val);
1077 case ICmpInst::ICMP_SGT:return ConstantBool::get(C1Val > C2Val);
1078 case ICmpInst::ICMP_SLE:return ConstantBool::get(C1Val <= C2Val);
1079 case ICmpInst::ICMP_SGE:return ConstantBool::get(C1Val >= C2Val);
Chris Lattner061da2f2004-01-13 05:51:55 +00001080 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001081 } else if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
Reid Spencer9d36acf2006-12-24 18:52:08 +00001082 if (ICmpInst::isSignedPredicate(ICmpInst::Predicate(pred))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001083 int64_t V1 = cast<ConstantInt>(C1)->getSExtValue();
1084 int64_t V2 = cast<ConstantInt>(C2)->getSExtValue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001085 switch (pred) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001086 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1087 case ICmpInst::ICMP_SLT:return ConstantBool::get(V1 < V2);
1088 case ICmpInst::ICMP_SGT:return ConstantBool::get(V1 > V2);
1089 case ICmpInst::ICMP_SLE:return ConstantBool::get(V1 <= V2);
1090 case ICmpInst::ICMP_SGE:return ConstantBool::get(V1 >= V2);
1091 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001092 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00001093 uint64_t V1 = cast<ConstantInt>(C1)->getZExtValue();
1094 uint64_t V2 = cast<ConstantInt>(C2)->getZExtValue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001095 switch (pred) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001096 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1097 case ICmpInst::ICMP_EQ: return ConstantBool::get(V1 == V2);
1098 case ICmpInst::ICMP_NE: return ConstantBool::get(V1 != V2);
1099 case ICmpInst::ICMP_ULT:return ConstantBool::get(V1 < V2);
1100 case ICmpInst::ICMP_UGT:return ConstantBool::get(V1 > V2);
1101 case ICmpInst::ICMP_ULE:return ConstantBool::get(V1 <= V2);
1102 case ICmpInst::ICMP_UGE:return ConstantBool::get(V1 >= V2);
Chris Lattner061da2f2004-01-13 05:51:55 +00001103 }
1104 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001105 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1106 double C1Val = cast<ConstantFP>(C1)->getValue();
1107 double C2Val = cast<ConstantFP>(C2)->getValue();
Reid Spencer9d36acf2006-12-24 18:52:08 +00001108 switch (pred) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001109 default: assert(0 && "Invalid FCmp Predicate"); return 0;
1110 case FCmpInst::FCMP_FALSE: return ConstantBool::getFalse();
1111 case FCmpInst::FCMP_TRUE: return ConstantBool::getTrue();
1112 case FCmpInst::FCMP_UNO:
1113 case FCmpInst::FCMP_ORD: break; // Can't fold these
1114 case FCmpInst::FCMP_UEQ:
1115 case FCmpInst::FCMP_OEQ: return ConstantBool::get(C1Val == C2Val);
1116 case FCmpInst::FCMP_ONE:
1117 case FCmpInst::FCMP_UNE: return ConstantBool::get(C1Val != C2Val);
1118 case FCmpInst::FCMP_OLT:
1119 case FCmpInst::FCMP_ULT: return ConstantBool::get(C1Val < C2Val);
1120 case FCmpInst::FCMP_UGT:
1121 case FCmpInst::FCMP_OGT: return ConstantBool::get(C1Val > C2Val);
1122 case FCmpInst::FCMP_OLE:
1123 case FCmpInst::FCMP_ULE: return ConstantBool::get(C1Val <= C2Val);
1124 case FCmpInst::FCMP_UGE:
1125 case FCmpInst::FCMP_OGE: return ConstantBool::get(C1Val >= C2Val);
1126 }
Reid Spencer9d36acf2006-12-24 18:52:08 +00001127 } else if (const ConstantPacked *CP1 = dyn_cast<ConstantPacked>(C1)) {
1128 if (const ConstantPacked *CP2 = dyn_cast<ConstantPacked>(C2)) {
1129 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001130 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1131 Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1132 const_cast<Constant*>(CP1->getOperand(i)),
1133 const_cast<Constant*>(CP2->getOperand(i)));
1134 if (ConstantBool *CB = dyn_cast<ConstantBool>(C))
1135 return CB;
1136 }
1137 // Otherwise, could not decide from any element pairs.
1138 return 0;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001139 } else if (pred == ICmpInst::ICMP_EQ) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001140 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1141 Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1142 const_cast<Constant*>(CP1->getOperand(i)),
1143 const_cast<Constant*>(CP2->getOperand(i)));
1144 if (ConstantBool *CB = dyn_cast<ConstantBool>(C))
1145 return CB;
1146 }
1147 // Otherwise, could not decide from any element pairs.
1148 return 0;
1149 }
1150 }
1151 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001152
Reid Spencer9d36acf2006-12-24 18:52:08 +00001153 if (C1->getType()->isFloatingPoint()) {
1154 switch (evaluateFCmpRelation(C1, C2)) {
1155 default: assert(0 && "Unknown relation!");
1156 case FCmpInst::FCMP_UNO:
1157 case FCmpInst::FCMP_ORD:
1158 case FCmpInst::FCMP_UEQ:
1159 case FCmpInst::FCMP_UNE:
1160 case FCmpInst::FCMP_ULT:
1161 case FCmpInst::FCMP_UGT:
1162 case FCmpInst::FCMP_ULE:
1163 case FCmpInst::FCMP_UGE:
1164 case FCmpInst::FCMP_TRUE:
1165 case FCmpInst::FCMP_FALSE:
1166 case FCmpInst::BAD_FCMP_PREDICATE:
1167 break; // Couldn't determine anything about these constants.
1168 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1169 return ConstantBool::get(
1170 pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1171 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1172 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1173 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1174 return ConstantBool::get(
1175 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1176 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1177 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1178 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1179 return ConstantBool::get(
1180 pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1181 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1182 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1183 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1184 // We can only partially decide this relation.
1185 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1186 return ConstantBool::getFalse();
1187 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1188 return ConstantBool::getTrue();
Chris Lattner061da2f2004-01-13 05:51:55 +00001189 break;
Reid Spencer9d36acf2006-12-24 18:52:08 +00001190 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1191 // We can only partially decide this relation.
1192 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1193 return ConstantBool::getFalse();
1194 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1195 return ConstantBool::getTrue();
1196 break;
1197 case ICmpInst::ICMP_NE: // We know that C1 != C2
1198 // We can only partially decide this relation.
1199 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1200 return ConstantBool::getFalse();
1201 if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1202 return ConstantBool::getTrue();
1203 break;
1204 }
1205 } else {
1206 // Evaluate the relation between the two constants, per the predicate.
1207 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1208 default: assert(0 && "Unknown relational!");
1209 case ICmpInst::BAD_ICMP_PREDICATE:
1210 break; // Couldn't determine anything about these constants.
1211 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1212 // If we know the constants are equal, we can decide the result of this
1213 // computation precisely.
1214 return ConstantBool::get(pred == ICmpInst::ICMP_EQ ||
1215 pred == ICmpInst::ICMP_ULE ||
1216 pred == ICmpInst::ICMP_SLE ||
1217 pred == ICmpInst::ICMP_UGE ||
1218 pred == ICmpInst::ICMP_SGE);
1219 case ICmpInst::ICMP_ULT:
1220 // If we know that C1 < C2, we can decide the result of this computation
1221 // precisely.
1222 return ConstantBool::get(pred == ICmpInst::ICMP_ULT ||
1223 pred == ICmpInst::ICMP_NE ||
1224 pred == ICmpInst::ICMP_ULE);
1225 case ICmpInst::ICMP_SLT:
1226 // If we know that C1 < C2, we can decide the result of this computation
1227 // precisely.
1228 return ConstantBool::get(pred == ICmpInst::ICMP_SLT ||
1229 pred == ICmpInst::ICMP_NE ||
1230 pred == ICmpInst::ICMP_SLE);
1231 case ICmpInst::ICMP_UGT:
1232 // If we know that C1 > C2, we can decide the result of this computation
1233 // precisely.
1234 return ConstantBool::get(pred == ICmpInst::ICMP_UGT ||
1235 pred == ICmpInst::ICMP_NE ||
1236 pred == ICmpInst::ICMP_UGE);
1237 case ICmpInst::ICMP_SGT:
1238 // If we know that C1 > C2, we can decide the result of this computation
1239 // precisely.
1240 return ConstantBool::get(pred == ICmpInst::ICMP_SGT ||
1241 pred == ICmpInst::ICMP_NE ||
1242 pred == ICmpInst::ICMP_SGE);
1243 case ICmpInst::ICMP_ULE:
1244 // If we know that C1 <= C2, we can only partially decide this relation.
1245 if (pred == ICmpInst::ICMP_UGT) return ConstantBool::getFalse();
1246 if (pred == ICmpInst::ICMP_ULT) return ConstantBool::getTrue();
1247 break;
1248 case ICmpInst::ICMP_SLE:
1249 // If we know that C1 <= C2, we can only partially decide this relation.
1250 if (pred == ICmpInst::ICMP_SGT) return ConstantBool::getFalse();
1251 if (pred == ICmpInst::ICMP_SLT) return ConstantBool::getTrue();
1252 break;
1253
1254 case ICmpInst::ICMP_UGE:
1255 // If we know that C1 >= C2, we can only partially decide this relation.
1256 if (pred == ICmpInst::ICMP_ULT) return ConstantBool::getFalse();
1257 if (pred == ICmpInst::ICMP_UGT) return ConstantBool::getTrue();
1258 break;
1259 case ICmpInst::ICMP_SGE:
1260 // If we know that C1 >= C2, we can only partially decide this relation.
1261 if (pred == ICmpInst::ICMP_SLT) return ConstantBool::getFalse();
1262 if (pred == ICmpInst::ICMP_SGT) return ConstantBool::getTrue();
1263 break;
1264
1265 case ICmpInst::ICMP_NE:
1266 // If we know that C1 != C2, we can only partially decide this relation.
1267 if (pred == ICmpInst::ICMP_EQ) return ConstantBool::getFalse();
1268 if (pred == ICmpInst::ICMP_NE) return ConstantBool::getTrue();
1269 break;
1270 }
1271
1272 if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1273 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1274 // other way if possible.
1275 switch (pred) {
1276 case ICmpInst::ICMP_EQ:
1277 case ICmpInst::ICMP_NE:
1278 // No change of predicate required.
1279 return ConstantFoldCompareInstruction(pred, C2, C1);
1280
1281 case ICmpInst::ICMP_ULT:
1282 case ICmpInst::ICMP_SLT:
1283 case ICmpInst::ICMP_UGT:
1284 case ICmpInst::ICMP_SGT:
1285 case ICmpInst::ICMP_ULE:
1286 case ICmpInst::ICMP_SLE:
1287 case ICmpInst::ICMP_UGE:
1288 case ICmpInst::ICMP_SGE:
1289 // Change the predicate as necessary to swap the operands.
1290 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1291 return ConstantFoldCompareInstruction(pred, C2, C1);
1292
1293 default: // These predicates cannot be flopped around.
1294 break;
1295 }
Chris Lattner061da2f2004-01-13 05:51:55 +00001296 }
1297 }
1298 return 0;
Chris Lattner1dd054c2004-01-12 22:07:24 +00001299}
1300
1301Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
Chris Lattner13128ab2004-10-11 22:52:25 +00001302 const std::vector<Value*> &IdxList) {
Chris Lattner1dd054c2004-01-12 22:07:24 +00001303 if (IdxList.size() == 0 ||
Chris Lattner13128ab2004-10-11 22:52:25 +00001304 (IdxList.size() == 1 && cast<Constant>(IdxList[0])->isNullValue()))
Chris Lattner1dd054c2004-01-12 22:07:24 +00001305 return const_cast<Constant*>(C);
1306
Chris Lattnerf6013752004-10-17 21:54:55 +00001307 if (isa<UndefValue>(C)) {
1308 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1309 true);
1310 assert(Ty != 0 && "Invalid indices for GEP!");
1311 return UndefValue::get(PointerType::get(Ty));
1312 }
1313
1314 Constant *Idx0 = cast<Constant>(IdxList[0]);
Chris Lattner04b60fe2004-02-16 20:46:13 +00001315 if (C->isNullValue()) {
1316 bool isNull = true;
1317 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
Chris Lattner13128ab2004-10-11 22:52:25 +00001318 if (!cast<Constant>(IdxList[i])->isNullValue()) {
Chris Lattner04b60fe2004-02-16 20:46:13 +00001319 isNull = false;
1320 break;
1321 }
1322 if (isNull) {
Chris Lattner13128ab2004-10-11 22:52:25 +00001323 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
Chris Lattner04b60fe2004-02-16 20:46:13 +00001324 true);
1325 assert(Ty != 0 && "Invalid indices for GEP!");
1326 return ConstantPointerNull::get(PointerType::get(Ty));
1327 }
Chris Lattner4bbd4092004-07-15 01:16:59 +00001328
1329 if (IdxList.size() == 1) {
1330 const Type *ElTy = cast<PointerType>(C->getType())->getElementType();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001331 if (uint32_t ElSize = ElTy->getPrimitiveSize()) {
Chris Lattner4bbd4092004-07-15 01:16:59 +00001332 // gep null, C is equal to C*sizeof(nullty). If nullty is a known llvm
1333 // type, we can statically fold this.
Reid Spencer8d9336d2006-12-31 05:26:44 +00001334 Constant *R = ConstantInt::get(Type::Int32Ty, ElSize);
Reid Spencer1a063892006-12-04 02:46:44 +00001335 // We know R is unsigned, Idx0 is signed because it must be an index
1336 // through a sequential type (gep pointer operand) which is always
1337 // signed.
Reid Spencer27720a92006-12-05 03:30:09 +00001338 R = ConstantExpr::getSExtOrBitCast(R, Idx0->getType());
Reid Spencer1a063892006-12-04 02:46:44 +00001339 R = ConstantExpr::getMul(R, Idx0); // signed multiply
1340 // R is a signed integer, C is the GEP pointer so -> IntToPtr
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001341 return ConstantExpr::getIntToPtr(R, C->getType());
Chris Lattner4bbd4092004-07-15 01:16:59 +00001342 }
1343 }
Chris Lattner04b60fe2004-02-16 20:46:13 +00001344 }
Chris Lattner1dd054c2004-01-12 22:07:24 +00001345
1346 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1347 // Combine Indices - If the source pointer to this getelementptr instruction
1348 // is a getelementptr instruction, combine the indices of the two
1349 // getelementptr instructions into a single instruction.
1350 //
1351 if (CE->getOpcode() == Instruction::GetElementPtr) {
1352 const Type *LastTy = 0;
1353 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1354 I != E; ++I)
1355 LastTy = *I;
1356
Chris Lattner13128ab2004-10-11 22:52:25 +00001357 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1358 std::vector<Value*> NewIndices;
Chris Lattner1dd054c2004-01-12 22:07:24 +00001359 NewIndices.reserve(IdxList.size() + CE->getNumOperands());
1360 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
Chris Lattner13128ab2004-10-11 22:52:25 +00001361 NewIndices.push_back(CE->getOperand(i));
Chris Lattner1dd054c2004-01-12 22:07:24 +00001362
1363 // Add the last index of the source with the first index of the new GEP.
1364 // Make sure to handle the case when they are actually different types.
1365 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
Chris Lattner13128ab2004-10-11 22:52:25 +00001366 // Otherwise it must be an array.
1367 if (!Idx0->isNullValue()) {
Chris Lattner71068a02004-07-07 04:45:13 +00001368 const Type *IdxTy = Combined->getType();
Reid Spencer1a063892006-12-04 02:46:44 +00001369 if (IdxTy != Idx0->getType()) {
Reid Spencer8d9336d2006-12-31 05:26:44 +00001370 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
Reid Spencer27720a92006-12-05 03:30:09 +00001371 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
Reid Spencer8d9336d2006-12-31 05:26:44 +00001372 Type::Int64Ty);
Reid Spencer1a063892006-12-04 02:46:44 +00001373 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1374 } else {
1375 Combined =
1376 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1377 }
Chris Lattner71068a02004-07-07 04:45:13 +00001378 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001379
Chris Lattner1dd054c2004-01-12 22:07:24 +00001380 NewIndices.push_back(Combined);
1381 NewIndices.insert(NewIndices.end(), IdxList.begin()+1, IdxList.end());
1382 return ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices);
1383 }
1384 }
1385
1386 // Implement folding of:
1387 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1388 // long 0, long 0)
1389 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1390 //
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001391 if (CE->isCast() && IdxList.size() > 1 && Idx0->isNullValue())
Misha Brukmanb1c93172005-04-21 23:48:37 +00001392 if (const PointerType *SPT =
Chris Lattner1dd054c2004-01-12 22:07:24 +00001393 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1394 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1395 if (const ArrayType *CAT =
Chris Lattner02157b02006-06-28 21:38:54 +00001396 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
Chris Lattner1dd054c2004-01-12 22:07:24 +00001397 if (CAT->getElementType() == SAT->getElementType())
1398 return ConstantExpr::getGetElementPtr(
1399 (Constant*)CE->getOperand(0), IdxList);
1400 }
1401 return 0;
1402}
1403