blob: a7438fcde81958039d58d72c74017d955e850cb6 [file] [log] [blame]
Chris Lattnercbfd4062004-01-12 21:13:12 +00001//===- ConstantFolding.cpp - LLVM constant folder -------------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chris Lattnercbfd4062004-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 Lattner00950542001-06-06 20:29:01 +000013//
Chris Lattnereab20b52004-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 Lattner00950542001-06-06 20:29:01 +000019//===----------------------------------------------------------------------===//
20
Chris Lattnercbfd4062004-01-12 21:13:12 +000021#include "ConstantFolding.h"
Chris Lattner8b0f0cb2004-01-12 21:02:29 +000022#include "llvm/Constants.h"
Chris Lattnerb228f9c2004-02-22 06:25:38 +000023#include "llvm/Instructions.h"
Chris Lattner27287de2003-04-17 19:24:18 +000024#include "llvm/DerivedTypes.h"
Chris Lattner802b5ab2004-03-08 06:17:35 +000025#include "llvm/Function.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000026#include "llvm/Support/Compiler.h"
Chris Lattner0eff5ad2006-10-13 17:22:21 +000027#include "llvm/Support/GetElementPtrTypeIterator.h"
28#include "llvm/Support/ManagedStatic.h"
29#include "llvm/Support/MathExtras.h"
Jeff Cohena97e8db2005-05-03 03:13:01 +000030#include <limits>
Chris Lattner0dc39692003-11-17 19:05:17 +000031using namespace llvm;
Chris Lattner14712a62001-09-09 21:01:20 +000032
Chris Lattnereab20b52004-01-12 22:07:24 +000033//===----------------------------------------------------------------------===//
34// ConstantFold*Instruction Implementations
35//===----------------------------------------------------------------------===//
Chris Lattnereab20b52004-01-12 22:07:24 +000036
Chris Lattner4460f402006-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 Spencer3da59db2006-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 Lattner4460f402006-04-02 01:38:28 +000056 for (unsigned i = 0; i != SrcNumElts; ++i)
Reid Spencer3da59db2006-11-27 01:05:10 +000057 Result.push_back(
Reid Spencerd977d862006-12-12 23:36:14 +000058 ConstantExpr::getBitCast(CP->getOperand(i), DstEltTy));
Chris Lattner4460f402006-04-02 01:38:28 +000059 return ConstantPacked::get(Result);
60 }
61
Reid Spencer3da59db2006-11-27 01:05:10 +000062 // If this is an int-to-fp cast ..
Chris Lattner4460f402006-04-02 01:38:28 +000063 if (SrcEltTy->isIntegral()) {
Reid Spencer3da59db2006-11-27 01:05:10 +000064 // Ensure that it is int-to-fp cast
Chris Lattner4460f402006-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 Spencerb83eb642006-10-20 07:07:24 +000069 BitsToDouble(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner4460f402006-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 Spencerb83eb642006-10-20 07:07:24 +000077 BitsToFloat(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner4460f402006-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 Spencerb83eb642006-10-20 07:07:24 +000090 Constant *C = ConstantInt::get(Type::ULongTy, V);
Reid Spencer6f40b832006-12-05 07:18:07 +000091 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy ));
Chris Lattner4460f402006-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 Spencerb83eb642006-10-20 07:07:24 +000098 uint32_t V = FloatToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
99 Constant *C = ConstantInt::get(Type::UIntTy, V);
Reid Spencer6f40b832006-12-05 07:18:07 +0000100 Result.push_back(ConstantExpr::getBitCast(C, DstEltTy));
Chris Lattner4460f402006-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 Spencer3da59db2006-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 Lattner4460f402006-04-02 01:38:28 +0000132
Reid Spencer3da59db2006-11-27 01:05:10 +0000133 // Let CastInst::isEliminableCastPair do the heavy lifting.
134 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
135 Type::ULongTy);
136}
137
138Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
Chris Lattnereab20b52004-01-12 22:07:24 +0000139 const Type *DestTy) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000140 const Type *SrcTy = V->getType();
Chris Lattnereab20b52004-01-12 22:07:24 +0000141
Reid Spencer3da59db2006-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 Spencer575d95c2006-12-04 02:46:44 +0000149 // Try hard to fold cast of cast because they are often eliminable.
Reid Spencer3da59db2006-11-27 01:05:10 +0000150 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
151 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
Chris Lattnereab20b52004-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 Spencer575d95c2006-12-04 02:46:44 +0000162 // This is casting one pointer type to another, always BitCast
Reid Spencer57c69932006-12-05 03:30:09 +0000163 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
Chris Lattnereab20b52004-01-12 22:07:24 +0000164 }
Chris Lattner71d37782004-10-16 23:31:32 +0000165 }
Chris Lattnereab20b52004-01-12 22:07:24 +0000166
Reid Spencer390437f2006-12-19 03:15:47 +0000167 // We actually have to do a cast now. Perform the cast according to the
168 // opcode specified.
Reid Spencer3da59db2006-11-27 01:05:10 +0000169 switch (opc) {
170 case Instruction::FPTrunc:
Reid Spencer3da59db2006-11-27 01:05:10 +0000171 case Instruction::FPExt:
Reid Spencer85e36e42006-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 Spencer390437f2006-12-19 03:15:47 +0000185 return ConstantPointerNull::get(cast<PointerType>(DestTy));
Reid Spencer85e36e42006-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 Spencer390437f2006-12-19 03:15:47 +0000189 return ConstantIntegral::get(DestTy, 0);
Reid Spencer85e36e42006-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 Spencer390437f2006-12-19 03:15:47 +0000199 case Instruction::ZExt:
Reid Spencer85e36e42006-12-19 07:41:40 +0000200 if (const ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
201 return ConstantInt::get(DestTy, CI->getZExtValue());
Reid Spencer390437f2006-12-19 03:15:47 +0000202 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +0000203 case Instruction::SExt:
Reid Spencer85e36e42006-12-19 07:41:40 +0000204 if (const ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
205 return ConstantInt::get(DestTy, CI->getSExtValue());
Reid Spencer390437f2006-12-19 03:15:47 +0000206 return 0;
Chris Lattner5be66252006-12-01 19:22:41 +0000207 case Instruction::Trunc:
Reid Spencer85e36e42006-12-19 07:41:40 +0000208 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) // Can't trunc a bool
Chris Lattner5be66252006-12-01 19:22:41 +0000209 return ConstantIntegral::get(DestTy, CI->getZExtValue());
210 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +0000211 case Instruction::BitCast:
Reid Spencer390437f2006-12-19 03:15:47 +0000212 if (SrcTy == DestTy)
213 return (Constant*)V; // no-op cast
Chris Lattner14f440a2006-12-11 18:30:27 +0000214
Reid Spencer3da59db2006-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;
220 IdxList.push_back(Constant::getNullValue(Type::IntTy));
221 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);
226 IdxList.push_back(Constant::getNullValue(Type::UIntTy));
227 } 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 Lattner4460f402006-04-02 01:38:28 +0000233 break;
234 }
235 }
Reid Spencer3da59db2006-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 Lattner4460f402006-04-02 01:38:28 +0000271 }
272 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000273
Chris Lattner14f440a2006-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 Spencer3da59db2006-11-27 01:05:10 +0000293 }
Chris Lattner14f440a2006-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 Spencer8c4fed52006-12-11 21:27:28 +0000299 if (DestTy == Type::IntTy || DestTy == Type::UIntTy)
Chris Lattner14f440a2006-12-11 18:30:27 +0000300 return ConstantInt::get(DestTy, FloatToBits(FP->getValue()));
Reid Spencer8c4fed52006-12-11 21:27:28 +0000301 assert((DestTy == Type::LongTy || DestTy == Type::ULongTy)
302 && "Incorrect integer type for bitcast!");
Chris Lattner14f440a2006-12-11 18:30:27 +0000303 return ConstantInt::get(DestTy, DoubleToBits(FP->getValue()));
304 }
305 }
306 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +0000307 default:
308 assert(!"Invalid CE CastInst opcode");
309 break;
Chris Lattner4460f402006-04-02 01:38:28 +0000310 }
Chris Lattnerf8d10972004-10-11 03:57:30 +0000311
Reid Spencer390437f2006-12-19 03:15:47 +0000312 assert(0 && "Failed to cast constant expression");
313 return 0;
Chris Lattnereab20b52004-01-12 22:07:24 +0000314}
315
Chris Lattnere9714862004-03-12 05:53:32 +0000316Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
317 const Constant *V1,
318 const Constant *V2) {
Chris Lattner850ba992006-09-28 23:34:49 +0000319 if (const ConstantBool *CB = dyn_cast<ConstantBool>(Cond))
320 return const_cast<Constant*>(CB->getValue() ? V1 : V2);
Chris Lattner71d37782004-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 Lattner2f690c82006-01-05 07:49:30 +0000325 if (V1 == V2) return const_cast<Constant*>(V1);
Chris Lattnere9714862004-03-12 05:53:32 +0000326 return 0;
327}
328
Robert Bocchinobb90a7a2006-01-10 20:03:46 +0000329Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
330 const Constant *Idx) {
Chris Lattner6fa4cdf2006-03-31 18:31:40 +0000331 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
332 return UndefValue::get(cast<PackedType>(Val->getType())->getElementType());
Chris Lattnerf38d4712006-04-07 04:44:06 +0000333 if (Val->isNullValue()) // ee(zero, x) -> zero
334 return Constant::getNullValue(
335 cast<PackedType>(Val->getType())->getElementType());
Chris Lattner6fa4cdf2006-03-31 18:31:40 +0000336
Robert Bocchinobb90a7a2006-01-10 20:03:46 +0000337 if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000338 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
339 return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
Chris Lattner6fa4cdf2006-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 Bocchinobb90a7a2006-01-10 20:03:46 +0000343 }
Chris Lattner6fa4cdf2006-03-31 18:31:40 +0000344 }
Robert Bocchinobb90a7a2006-01-10 20:03:46 +0000345 return 0;
346}
347
Robert Bocchinoc152f9c2006-01-17 20:07:22 +0000348Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
349 const Constant *Elt,
350 const Constant *Idx) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000351 const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
Robert Bocchinoc152f9c2006-01-17 20:07:22 +0000352 if (!CIdx) return 0;
Reid Spencerb83eb642006-10-20 07:07:24 +0000353 uint64_t idxVal = CIdx->getZExtValue();
Reid Spencer4ab09d42006-11-02 08:18:15 +0000354 if (isa<UndefValue>(Val)) {
Robert Bocchinoc152f9c2006-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 Spencer4ab09d42006-11-02 08:18:15 +0000372 if (isa<ConstantAggregateZero>(Val)) {
Robert Bocchinoc152f9c2006-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 Lattner00f10232006-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 Spencere4d87aa2006-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
447 return ConstantInt::getAllOnesValue(C1->getType());
448 case Instruction::LShr:
449 if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
450 return const_cast<Constant*>(C1); // undef lshr undef -> undef
451 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
452 // undef lshr X -> 0
453 case Instruction::AShr:
454 if (!isa<UndefValue>(C2))
455 return const_cast<Constant*>(C1); // undef ashr X --> undef
456 else if (isa<UndefValue>(C1))
457 return const_cast<Constant*>(C1); // undef ashr undef -> undef
458 else
459 return const_cast<Constant*>(C1); // X ashr undef --> X
460 case Instruction::Shl:
461 // undef << X -> 0 or X << undef -> 0
462 return Constant::getNullValue(C1->getType());
463 }
464 }
465
466 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
467 if (isa<ConstantExpr>(C2)) {
468 // There are many possible foldings we could do here. We should probably
469 // at least fold add of a pointer with an integer into the appropriate
470 // getelementptr. This will improve alias analysis a bit.
471 } else {
472 // Just implement a couple of simple identities.
473 switch (Opcode) {
474 case Instruction::Add:
475 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X + 0 == X
476 break;
477 case Instruction::Sub:
478 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X - 0 == X
479 break;
480 case Instruction::Mul:
481 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X * 0 == 0
482 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
483 if (CI->getZExtValue() == 1)
484 return const_cast<Constant*>(C1); // X * 1 == X
485 break;
486 case Instruction::UDiv:
487 case Instruction::SDiv:
488 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
489 if (CI->getZExtValue() == 1)
490 return const_cast<Constant*>(C1); // X / 1 == X
491 break;
492 case Instruction::URem:
493 case Instruction::SRem:
494 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
495 if (CI->getZExtValue() == 1)
496 return Constant::getNullValue(CI->getType()); // X % 1 == 0
497 break;
498 case Instruction::And:
499 if (cast<ConstantIntegral>(C2)->isAllOnesValue())
500 return const_cast<Constant*>(C1); // X & -1 == X
501 if (C2->isNullValue()) return const_cast<Constant*>(C2); // X & 0 == 0
502 if (CE1->isCast() && isa<GlobalValue>(CE1->getOperand(0))) {
503 GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
504
505 // Functions are at least 4-byte aligned. If and'ing the address of a
506 // function with a constant < 4, fold it to zero.
507 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C2))
508 if (CI->getZExtValue() < 4 && isa<Function>(CPR))
509 return Constant::getNullValue(CI->getType());
510 }
511 break;
512 case Instruction::Or:
513 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X | 0 == X
514 if (cast<ConstantIntegral>(C2)->isAllOnesValue())
515 return const_cast<Constant*>(C2); // X | -1 == -1
516 break;
517 case Instruction::Xor:
518 if (C2->isNullValue()) return const_cast<Constant*>(C1); // X ^ 0 == X
519 break;
520 }
521 }
522 } else if (isa<ConstantExpr>(C2)) {
523 // If C2 is a constant expr and C1 isn't, flop them around and fold the
524 // other way if possible.
525 switch (Opcode) {
526 case Instruction::Add:
527 case Instruction::Mul:
528 case Instruction::And:
529 case Instruction::Or:
530 case Instruction::Xor:
531 // No change of opcode required.
532 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
533
534 case Instruction::Shl:
535 case Instruction::LShr:
536 case Instruction::AShr:
537 case Instruction::Sub:
538 case Instruction::SDiv:
539 case Instruction::UDiv:
540 case Instruction::FDiv:
541 case Instruction::URem:
542 case Instruction::SRem:
543 case Instruction::FRem:
544 default: // These instructions cannot be flopped around.
545 return 0;
546 }
547 }
548
549 // At this point we know neither constant is an UndefValue nor a ConstantExpr
550 // so look at directly computing the
551 if (const ConstantBool *CB1 = dyn_cast<ConstantBool>(C1)) {
552 if (const ConstantBool *CB2 = dyn_cast<ConstantBool>(C2)) {
553 switch (Opcode) {
554 default:
555 break;
556 case Instruction::And:
557 return ConstantBool::get(CB1->getValue() & CB2->getValue());
558 case Instruction::Or:
559 return ConstantBool::get(CB1->getValue() | CB2->getValue());
560 case Instruction::Xor:
561 return ConstantBool::get(CB1->getValue() ^ CB2->getValue());
562 }
563 }
564 } else if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
565 if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
566 uint64_t C1Val = CI1->getZExtValue();
567 uint64_t C2Val = CI2->getZExtValue();
568 switch (Opcode) {
569 default:
570 break;
571 case Instruction::Add:
572 return ConstantInt::get(C1->getType(), C1Val + C2Val);
573 case Instruction::Sub:
574 return ConstantInt::get(C1->getType(), C1Val - C2Val);
575 case Instruction::Mul:
576 return ConstantInt::get(C1->getType(), C1Val * C2Val);
577 case Instruction::UDiv:
578 if (CI2->isNullValue()) // X / 0 -> can't fold
579 return 0;
580 return ConstantInt::get(C1->getType(), C1Val / C2Val);
581 case Instruction::SDiv:
582 if (CI2->isNullValue()) return 0; // X / 0 -> can't fold
583 if (CI2->isAllOnesValue() &&
584 (((CI1->getType()->getPrimitiveSizeInBits() == 64) &&
585 (CI1->getSExtValue() == INT64_MIN)) ||
586 (CI1->getSExtValue() == -CI1->getSExtValue())))
587 return 0; // MIN_INT / -1 -> overflow
588 return ConstantInt::get(C1->getType(),
589 CI1->getSExtValue() / CI2->getSExtValue());
590 case Instruction::URem:
591 if (C2->isNullValue()) return 0; // X / 0 -> can't fold
592 return ConstantInt::get(C1->getType(), C1Val % C2Val);
593 case Instruction::SRem:
594 if (CI2->isNullValue()) return 0; // X % 0 -> can't fold
595 if (CI2->isAllOnesValue() &&
596 (((CI1->getType()->getPrimitiveSizeInBits() == 64) &&
597 (CI1->getSExtValue() == INT64_MIN)) ||
598 (CI1->getSExtValue() == -CI1->getSExtValue())))
599 return 0; // MIN_INT % -1 -> overflow
600 return ConstantInt::get(C1->getType(),
601 CI1->getSExtValue() % CI2->getSExtValue());
602 case Instruction::And:
603 return ConstantInt::get(C1->getType(), C1Val & C2Val);
604 case Instruction::Or:
605 return ConstantInt::get(C1->getType(), C1Val | C2Val);
606 case Instruction::Xor:
607 return ConstantInt::get(C1->getType(), C1Val ^ C2Val);
608 case Instruction::Shl:
609 return ConstantInt::get(C1->getType(), C1Val << C2Val);
610 case Instruction::LShr:
611 return ConstantInt::get(C1->getType(), C1Val >> C2Val);
612 case Instruction::AShr:
613 return ConstantInt::get(C1->getType(),
614 CI1->getSExtValue() >> C2Val);
615 }
616 }
617 } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
618 if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
619 double C1Val = CFP1->getValue();
620 double C2Val = CFP2->getValue();
621 switch (Opcode) {
622 default:
623 break;
624 case Instruction::Add:
625 return ConstantFP::get(CFP1->getType(), C1Val + C2Val);
626 case Instruction::Sub:
627 return ConstantFP::get(CFP1->getType(), C1Val - C2Val);
628 case Instruction::Mul:
629 return ConstantFP::get(CFP1->getType(), C1Val * C2Val);
630 case Instruction::FDiv:
631 if (CFP2->isExactlyValue(0.0))
632 return ConstantFP::get(CFP1->getType(),
633 std::numeric_limits<double>::infinity());
634 if (CFP2->isExactlyValue(-0.0))
635 return ConstantFP::get(CFP1->getType(),
636 -std::numeric_limits<double>::infinity());
637 return ConstantFP::get(CFP1->getType(), C1Val / C2Val);
638 case Instruction::FRem:
639 if (CFP2->isNullValue())
640 return 0;
641 return ConstantFP::get(CFP1->getType(), std::fmod(C1Val, C2Val));
642 }
643 }
644 } else if (const ConstantPacked *CP1 = dyn_cast<ConstantPacked>(C1)) {
645 if (const ConstantPacked *CP2 = dyn_cast<ConstantPacked>(C2)) {
646 switch (Opcode) {
647 default:
648 break;
649 case Instruction::Add:
650 return EvalVectorOp(CP1, CP2, ConstantExpr::getAdd);
651 case Instruction::Sub:
652 return EvalVectorOp(CP1, CP2, ConstantExpr::getSub);
653 case Instruction::Mul:
654 return EvalVectorOp(CP1, CP2, ConstantExpr::getMul);
655 case Instruction::UDiv:
656 return EvalVectorOp(CP1, CP2, ConstantExpr::getUDiv);
657 case Instruction::SDiv:
658 return EvalVectorOp(CP1, CP2, ConstantExpr::getSDiv);
659 case Instruction::FDiv:
660 return EvalVectorOp(CP1, CP2, ConstantExpr::getFDiv);
661 case Instruction::URem:
662 return EvalVectorOp(CP1, CP2, ConstantExpr::getURem);
663 case Instruction::SRem:
664 return EvalVectorOp(CP1, CP2, ConstantExpr::getSRem);
665 case Instruction::FRem:
666 return EvalVectorOp(CP1, CP2, ConstantExpr::getFRem);
667 case Instruction::And:
668 return EvalVectorOp(CP1, CP2, ConstantExpr::getAnd);
669 case Instruction::Or:
670 return EvalVectorOp(CP1, CP2, ConstantExpr::getOr);
671 case Instruction::Xor:
672 return EvalVectorOp(CP1, CP2, ConstantExpr::getXor);
673 }
674 }
675 }
676
677 // We don't know how to fold this
678 return 0;
679}
Chris Lattner00f10232006-04-08 01:18:18 +0000680
Chris Lattnerce04a6d2005-01-28 19:09:51 +0000681/// isZeroSizedType - This type is zero sized if its an array or structure of
682/// zero sized types. The only leaf zero sized type is an empty structure.
683static bool isMaybeZeroSizedType(const Type *Ty) {
684 if (isa<OpaqueType>(Ty)) return true; // Can't say.
685 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
686
687 // If all of elements have zero size, this does too.
688 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerf4aa3352005-01-28 23:17:27 +0000689 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
Chris Lattnerce04a6d2005-01-28 19:09:51 +0000690 return true;
691
692 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
693 return isMaybeZeroSizedType(ATy->getElementType());
694 }
695 return false;
696}
Chris Lattnere9714862004-03-12 05:53:32 +0000697
Chris Lattner504e8fb2004-01-13 05:51:55 +0000698/// IdxCompare - Compare the two constants as though they were getelementptr
699/// indices. This allows coersion of the types to be the same thing.
700///
701/// If the two constants are the "same" (after coersion), return 0. If the
702/// first is less than the second, return -1, if the second is less than the
703/// first, return 1. If the constants are not integral, return -2.
704///
Chris Lattnerce04a6d2005-01-28 19:09:51 +0000705static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
Chris Lattner504e8fb2004-01-13 05:51:55 +0000706 if (C1 == C2) return 0;
707
Reid Spencer3da59db2006-11-27 01:05:10 +0000708 // Ok, we found a different index. Are either of the operands ConstantExprs?
709 // If so, we can't do anything with them.
Chris Lattner504e8fb2004-01-13 05:51:55 +0000710 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
711 return -2; // don't know!
Misha Brukmanfd939082005-04-21 23:48:37 +0000712
Chris Lattner28977af2004-04-05 01:30:19 +0000713 // Ok, we have two differing integer indices. Sign extend them to be the same
714 // type. Long is always big enough, so we use it.
Reid Spencer3da59db2006-11-27 01:05:10 +0000715 if (C1->getType() != Type::LongTy && C1->getType() != Type::ULongTy)
Reid Spencerd977d862006-12-12 23:36:14 +0000716 C1 = ConstantExpr::getSExt(C1, Type::LongTy);
Reid Spencer3da59db2006-11-27 01:05:10 +0000717 else
718 C1 = ConstantExpr::getBitCast(C1, Type::LongTy);
719 if (C2->getType() != Type::LongTy && C1->getType() != Type::ULongTy)
Reid Spencerd977d862006-12-12 23:36:14 +0000720 C2 = ConstantExpr::getSExt(C2, Type::LongTy);
Reid Spencer3da59db2006-11-27 01:05:10 +0000721 else
722 C2 = ConstantExpr::getBitCast(C2, Type::LongTy);
723
Chris Lattner504e8fb2004-01-13 05:51:55 +0000724 if (C1 == C2) return 0; // Are they just differing types?
725
Chris Lattnerce04a6d2005-01-28 19:09:51 +0000726 // If the type being indexed over is really just a zero sized type, there is
727 // no pointer difference being made here.
728 if (isMaybeZeroSizedType(ElTy))
729 return -2; // dunno.
730
Chris Lattner504e8fb2004-01-13 05:51:55 +0000731 // If they are really different, now that they are the same type, then we
732 // found a difference!
Reid Spencerb83eb642006-10-20 07:07:24 +0000733 if (cast<ConstantInt>(C1)->getSExtValue() <
734 cast<ConstantInt>(C2)->getSExtValue())
Chris Lattner504e8fb2004-01-13 05:51:55 +0000735 return -1;
736 else
737 return 1;
738}
739
Reid Spencere4d87aa2006-12-23 06:05:41 +0000740/// evaluatFCmpeRelation - This function determines if there is anything we can
741/// decide about the two constants provided. This doesn't need to handle simple
742/// things like ConstantFP comparisons, but should instead handle ConstantExprs.
743/// If we can determine that the two constants have a particular relation to
744/// each other, we should return the corresponding FCmpInst predicate,
745/// otherwise return FCmpInst::BAD_FCMP_PREDICATE.
746///
747/// To simplify this code we canonicalize the relation so that the first
748/// operand is always the most "complex" of the two. We consider simple
749/// constants (like ConstantFP) to be the simplest, followed by
750/// GlobalValues, followed by ConstantExpr's (the most complex).
751static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
752 assert(V1->getType() == V2->getType() &&
753 "Cannot compare different types of values!");
754 if (V1 == V2) return FCmpInst::FCMP_OEQ;
755
756 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
757 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
758 // We distilled this down to a simple case, use the standard constant
759 // folder.
760 ConstantBool *R = dyn_cast<ConstantBool>(
761 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
762 if (R && R->getValue())
763 return FCmpInst::FCMP_OEQ;
764 R = dyn_cast<ConstantBool>(
765 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
766 if (R && R->getValue())
767 return FCmpInst::FCMP_OLT;
768 R = dyn_cast<ConstantBool>(
769 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
770 if (R && R->getValue()) return FCmpInst::FCMP_OGT;
771
772 // If we couldn't figure it out, bail.
773 return FCmpInst::BAD_FCMP_PREDICATE;
774 }
775
776 // If the first operand is simple, swap operands.
777 FCmpInst::Predicate SwappedPredicate = evaluateFCmpRelation(V2, V1);
778 if (SwappedPredicate != FCmpInst::BAD_FCMP_PREDICATE)
779 return FCmpInst::getSwappedPredicate(SwappedPredicate);
780
781 return FCmpInst::BAD_FCMP_PREDICATE;
782 }
783
784 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
785 // constantexpr, a CPR, or a simple constant.
786 // ConstantExpr *CE1 = cast<ConstantExpr>(V1);
787 // Constant *CE1Op0 = CE1->getOperand(0);
788
789 // There are MANY other foldings that we could perform here. They will
790 // probably be added on demand, as they seem needed.
791 return FCmpInst::BAD_FCMP_PREDICATE;
792}
793
794/// evaluateICmpRelation - This function determines if there is anything we can
Chris Lattner504e8fb2004-01-13 05:51:55 +0000795/// decide about the two constants provided. This doesn't need to handle simple
Reid Spencer79703962004-07-17 23:47:01 +0000796/// things like integer comparisons, but should instead handle ConstantExprs
Chris Lattner36c24512006-12-11 02:16:58 +0000797/// and GlobalValues. If we can determine that the two constants have a
Reid Spencere4d87aa2006-12-23 06:05:41 +0000798/// particular relation to each other, we should return the corresponding ICmp
799/// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
Chris Lattner504e8fb2004-01-13 05:51:55 +0000800///
801/// To simplify this code we canonicalize the relation so that the first
802/// operand is always the most "complex" of the two. We consider simple
803/// constants (like ConstantInt) to be the simplest, followed by
Reid Spencer79703962004-07-17 23:47:01 +0000804/// GlobalValues, followed by ConstantExpr's (the most complex).
Chris Lattner504e8fb2004-01-13 05:51:55 +0000805///
Reid Spencere4d87aa2006-12-23 06:05:41 +0000806static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
807 bool isSigned) {
Chris Lattner504e8fb2004-01-13 05:51:55 +0000808 assert(V1->getType() == V2->getType() &&
809 "Cannot compare different types of values!");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000810 if (V1 == V2) return ICmpInst::ICMP_EQ;
Chris Lattner504e8fb2004-01-13 05:51:55 +0000811
Reid Spencer79703962004-07-17 23:47:01 +0000812 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
Chris Lattner2f690c82006-01-05 07:49:30 +0000813 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
814 // We distilled this down to a simple case, use the standard constant
815 // folder.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000816 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
817 ConstantBool *R =
818 dyn_cast<ConstantBool>(ConstantExpr::getICmp(pred, V1, V2));
819 if (R && R->getValue())
820 return pred;
821 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
822 R = dyn_cast<ConstantBool>(ConstantExpr::getICmp(pred, V1, V2));
823 if (R && R->getValue())
824 return pred;
825 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
826 R = dyn_cast<ConstantBool>(ConstantExpr::getICmp(pred, V1, V2));
827 if (R && R->getValue())
828 return pred;
Chris Lattner2f690c82006-01-05 07:49:30 +0000829
830 // If we couldn't figure it out, bail.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000831 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner2f690c82006-01-05 07:49:30 +0000832 }
833
Chris Lattner504e8fb2004-01-13 05:51:55 +0000834 // If the first operand is simple, swap operands.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000835 ICmpInst::Predicate SwappedRelation =
836 evaluateICmpRelation(V2, V1, isSigned);
837 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
838 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner504e8fb2004-01-13 05:51:55 +0000839
Chris Lattner2c822cc2006-01-05 07:19:51 +0000840 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
Chris Lattnerb97e2782004-02-01 01:23:19 +0000841 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000842 ICmpInst::Predicate SwappedRelation =
843 evaluateICmpRelation(V2, V1, isSigned);
844 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
845 return ICmpInst::getSwappedPredicate(SwappedRelation);
Chris Lattner2c822cc2006-01-05 07:19:51 +0000846 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000847 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerb97e2782004-02-01 01:23:19 +0000848 }
Chris Lattner504e8fb2004-01-13 05:51:55 +0000849
Reid Spencer79703962004-07-17 23:47:01 +0000850 // Now we know that the RHS is a GlobalValue or simple constant,
Chris Lattner504e8fb2004-01-13 05:51:55 +0000851 // which (since the types must match) means that it's a ConstantPointerNull.
Reid Spencer79703962004-07-17 23:47:01 +0000852 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
Reid Spencer87d5f6c2006-12-06 00:25:09 +0000853 if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
Reid Spencere4d87aa2006-12-23 06:05:41 +0000854 return ICmpInst::ICMP_NE;
Chris Lattner504e8fb2004-01-13 05:51:55 +0000855 } else {
Reid Spencer87d5f6c2006-12-06 00:25:09 +0000856 // GlobalVals can never be null.
Chris Lattner504e8fb2004-01-13 05:51:55 +0000857 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
Reid Spencer87d5f6c2006-12-06 00:25:09 +0000858 if (!CPR1->hasExternalWeakLinkage())
Reid Spencere4d87aa2006-12-23 06:05:41 +0000859 return ICmpInst::ICMP_NE;
Chris Lattner504e8fb2004-01-13 05:51:55 +0000860 }
Chris Lattner504e8fb2004-01-13 05:51:55 +0000861 } else {
862 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
863 // constantexpr, a CPR, or a simple constant.
Chris Lattner2f690c82006-01-05 07:49:30 +0000864 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
Chris Lattner504e8fb2004-01-13 05:51:55 +0000865 Constant *CE1Op0 = CE1->getOperand(0);
866
867 switch (CE1->getOpcode()) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000868 case Instruction::Trunc:
869 case Instruction::FPTrunc:
870 case Instruction::FPExt:
871 case Instruction::FPToUI:
872 case Instruction::FPToSI:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000873 break; // We can't evaluate floating point casts or truncations.
874
Reid Spencer3da59db2006-11-27 01:05:10 +0000875 case Instruction::UIToFP:
876 case Instruction::SIToFP:
Reid Spencer3da59db2006-11-27 01:05:10 +0000877 case Instruction::IntToPtr:
878 case Instruction::BitCast:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000879 case Instruction::ZExt:
880 case Instruction::SExt:
881 case Instruction::PtrToInt:
Chris Lattner504e8fb2004-01-13 05:51:55 +0000882 // If the cast is not actually changing bits, and the second operand is a
883 // null pointer, do the comparison with the pre-casted value.
884 if (V2->isNullValue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +0000885 (isa<PointerType>(CE1->getType()) || CE1->getType()->isIntegral())) {
886 bool isSigned = CE1->getOpcode() == Instruction::ZExt ? false :
887 (CE1->getOpcode() == Instruction::SExt ? true :
888 (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
889 return evaluateICmpRelation(
890 CE1Op0, Constant::getNullValue(CE1Op0->getType()), isSigned);
891 }
Chris Lattner2f690c82006-01-05 07:49:30 +0000892
893 // If the dest type is a pointer type, and the RHS is a constantexpr cast
894 // from the same type as the src of the LHS, evaluate the inputs. This is
Reid Spencere4d87aa2006-12-23 06:05:41 +0000895 // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
Chris Lattner2f690c82006-01-05 07:49:30 +0000896 // which happens a lot in compilers with tagged integers.
897 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000898 if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
Chris Lattner2f690c82006-01-05 07:49:30 +0000899 CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
900 CE1->getOperand(0)->getType()->isIntegral()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000901 bool isSigned = CE1->getOpcode() == Instruction::ZExt ? false :
902 (CE1->getOpcode() == Instruction::SExt ? true :
903 (CE1->getOpcode() == Instruction::PtrToInt ? false : isSigned));
904 return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
905 isSigned);
Chris Lattner2f690c82006-01-05 07:49:30 +0000906 }
Chris Lattnera0ae8192004-04-11 01:29:30 +0000907 break;
Chris Lattner504e8fb2004-01-13 05:51:55 +0000908
909 case Instruction::GetElementPtr:
910 // Ok, since this is a getelementptr, we know that the constant has a
911 // pointer type. Check the various cases.
912 if (isa<ConstantPointerNull>(V2)) {
913 // If we are comparing a GEP to a null pointer, check to see if the base
914 // of the GEP equals the null pointer.
Reid Spencer87d5f6c2006-12-06 00:25:09 +0000915 if (GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
916 if (GV->hasExternalWeakLinkage())
917 // Weak linkage GVals could be zero or not. We're comparing that
918 // to null pointer so its greater-or-equal
Reid Spencere4d87aa2006-12-23 06:05:41 +0000919 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
Reid Spencer87d5f6c2006-12-06 00:25:09 +0000920 else
921 // If its not weak linkage, the GVal must have a non-zero address
922 // so the result is greater-than
Reid Spencere4d87aa2006-12-23 06:05:41 +0000923 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner504e8fb2004-01-13 05:51:55 +0000924 } else if (isa<ConstantPointerNull>(CE1Op0)) {
925 // If we are indexing from a null pointer, check to see if we have any
926 // non-zero indices.
927 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
928 if (!CE1->getOperand(i)->isNullValue())
929 // Offsetting from null, must not be equal.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000930 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner504e8fb2004-01-13 05:51:55 +0000931 // Only zero indexes from null, must still be zero.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000932 return ICmpInst::ICMP_EQ;
Chris Lattner504e8fb2004-01-13 05:51:55 +0000933 }
934 // Otherwise, we can't really say if the first operand is null or not.
Reid Spencer79703962004-07-17 23:47:01 +0000935 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
Chris Lattner504e8fb2004-01-13 05:51:55 +0000936 if (isa<ConstantPointerNull>(CE1Op0)) {
Reid Spencer87d5f6c2006-12-06 00:25:09 +0000937 if (CPR2->hasExternalWeakLinkage())
938 // Weak linkage GVals could be zero or not. We're comparing it to
939 // a null pointer, so its less-or-equal
Reid Spencere4d87aa2006-12-23 06:05:41 +0000940 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
Reid Spencer87d5f6c2006-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 less-than
Reid Spencere4d87aa2006-12-23 06:05:41 +0000944 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Reid Spencer79703962004-07-17 23:47:01 +0000945 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
Chris Lattner504e8fb2004-01-13 05:51:55 +0000946 if (CPR1 == CPR2) {
947 // If this is a getelementptr of the same global, then it must be
948 // different. Because the types must match, the getelementptr could
949 // only have at most one index, and because we fold getelementptr's
950 // with a single zero index, it must be nonzero.
951 assert(CE1->getNumOperands() == 2 &&
952 !CE1->getOperand(1)->isNullValue() &&
953 "Suprising getelementptr!");
Reid Spencere4d87aa2006-12-23 06:05:41 +0000954 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattner504e8fb2004-01-13 05:51:55 +0000955 } else {
956 // If they are different globals, we don't know what the value is,
957 // but they can't be equal.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000958 return ICmpInst::ICMP_NE;
Chris Lattner504e8fb2004-01-13 05:51:55 +0000959 }
960 }
961 } else {
962 const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
963 const Constant *CE2Op0 = CE2->getOperand(0);
964
965 // There are MANY other foldings that we could perform here. They will
966 // probably be added on demand, as they seem needed.
967 switch (CE2->getOpcode()) {
968 default: break;
969 case Instruction::GetElementPtr:
970 // By far the most common case to handle is when the base pointers are
971 // obviously to the same or different globals.
Reid Spencer79703962004-07-17 23:47:01 +0000972 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
Chris Lattner504e8fb2004-01-13 05:51:55 +0000973 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
Reid Spencere4d87aa2006-12-23 06:05:41 +0000974 return ICmpInst::ICMP_NE;
Chris Lattner504e8fb2004-01-13 05:51:55 +0000975 // Ok, we know that both getelementptr instructions are based on the
976 // same global. From this, we can precisely determine the relative
977 // ordering of the resultant pointers.
978 unsigned i = 1;
Misha Brukmanfd939082005-04-21 23:48:37 +0000979
Chris Lattner504e8fb2004-01-13 05:51:55 +0000980 // Compare all of the operands the GEP's have in common.
Chris Lattnerce04a6d2005-01-28 19:09:51 +0000981 gep_type_iterator GTI = gep_type_begin(CE1);
982 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
983 ++i, ++GTI)
984 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
985 GTI.getIndexedType())) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000986 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
987 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
988 case -2: return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner504e8fb2004-01-13 05:51:55 +0000989 }
990
991 // Ok, we ran out of things they have in common. If any leftovers
992 // are non-zero then we have a difference, otherwise we are equal.
993 for (; i < CE1->getNumOperands(); ++i)
994 if (!CE1->getOperand(i)->isNullValue())
Chris Lattnerce04a6d2005-01-28 19:09:51 +0000995 if (isa<ConstantIntegral>(CE1->getOperand(i)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000996 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
Chris Lattnerce04a6d2005-01-28 19:09:51 +0000997 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000998 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
Misha Brukmanfd939082005-04-21 23:48:37 +0000999
Chris Lattner504e8fb2004-01-13 05:51:55 +00001000 for (; i < CE2->getNumOperands(); ++i)
1001 if (!CE2->getOperand(i)->isNullValue())
Chris Lattnerce04a6d2005-01-28 19:09:51 +00001002 if (isa<ConstantIntegral>(CE2->getOperand(i)))
Reid Spencere4d87aa2006-12-23 06:05:41 +00001003 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Chris Lattnerce04a6d2005-01-28 19:09:51 +00001004 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001005 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1006 return ICmpInst::ICMP_EQ;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001007 }
1008 }
1009 }
Chris Lattner504e8fb2004-01-13 05:51:55 +00001010 default:
1011 break;
1012 }
1013 }
1014
Reid Spencere4d87aa2006-12-23 06:05:41 +00001015 return ICmpInst::BAD_ICMP_PREDICATE;
Chris Lattner504e8fb2004-01-13 05:51:55 +00001016}
1017
Reid Spencere4d87aa2006-12-23 06:05:41 +00001018Constant *llvm::ConstantFoldCompareInstruction(unsigned short predicate,
1019 Constant *C1, Constant *C2) {
1020
1021 // Handle some degenerate cases first
1022 if (isa<UndefValue>(C1) || isa<UndefValue>(C2))
1023 return UndefValue::get(Type::BoolTy);
1024
1025 // icmp eq/ne(null,GV) -> false/true
1026 if (C1->isNullValue()) {
1027 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1028 if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
1029 if (predicate == ICmpInst::ICMP_EQ)
Reid Spencerb8611ec2006-12-01 03:56:30 +00001030 return ConstantBool::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001031 else if (predicate == ICmpInst::ICMP_NE)
1032 return ConstantBool::getTrue();
1033 // icmp eq/ne(GV,null) -> false/true
1034 } else if (C2->isNullValue()) {
1035 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1036 if (!GV->hasExternalWeakLinkage()) // External weak GV can be null
1037 if (predicate == ICmpInst::ICMP_EQ)
Reid Spencerb8611ec2006-12-01 03:56:30 +00001038 return ConstantBool::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00001039 else if (predicate == ICmpInst::ICMP_NE)
Reid Spencerb8611ec2006-12-01 03:56:30 +00001040 return ConstantBool::getTrue();
Chris Lattnereab20b52004-01-12 22:07:24 +00001041 }
1042
Reid Spencere4d87aa2006-12-23 06:05:41 +00001043 if (isa<ConstantBool>(C1) && isa<ConstantBool>(C2)) {
1044 bool C1Val = cast<ConstantBool>(C1)->getValue();
1045 bool C2Val = cast<ConstantBool>(C2)->getValue();
1046 switch (predicate) {
1047 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1048 case ICmpInst::ICMP_EQ: return ConstantBool::get(C1Val == C2Val);
1049 case ICmpInst::ICMP_NE: return ConstantBool::get(C1Val != C2Val);
1050 case ICmpInst::ICMP_ULT:return ConstantBool::get(C1Val < C2Val);
1051 case ICmpInst::ICMP_UGT:return ConstantBool::get(C1Val > C2Val);
1052 case ICmpInst::ICMP_ULE:return ConstantBool::get(C1Val <= C2Val);
1053 case ICmpInst::ICMP_UGE:return ConstantBool::get(C1Val >= C2Val);
1054 case ICmpInst::ICMP_SLT:return ConstantBool::get(C1Val < C2Val);
1055 case ICmpInst::ICMP_SGT:return ConstantBool::get(C1Val > C2Val);
1056 case ICmpInst::ICMP_SLE:return ConstantBool::get(C1Val <= C2Val);
1057 case ICmpInst::ICMP_SGE:return ConstantBool::get(C1Val >= C2Val);
Chris Lattner504e8fb2004-01-13 05:51:55 +00001058 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001059 } else if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1060 if (ICmpInst::isSignedPredicate(ICmpInst::Predicate(predicate))) {
1061 int64_t V1 = cast<ConstantInt>(C1)->getSExtValue();
1062 int64_t V2 = cast<ConstantInt>(C2)->getSExtValue();
1063 switch (predicate) {
1064 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1065 case ICmpInst::ICMP_SLT:return ConstantBool::get(V1 < V2);
1066 case ICmpInst::ICMP_SGT:return ConstantBool::get(V1 > V2);
1067 case ICmpInst::ICMP_SLE:return ConstantBool::get(V1 <= V2);
1068 case ICmpInst::ICMP_SGE:return ConstantBool::get(V1 >= V2);
1069 }
Chris Lattner504e8fb2004-01-13 05:51:55 +00001070 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001071 uint64_t V1 = cast<ConstantInt>(C1)->getZExtValue();
1072 uint64_t V2 = cast<ConstantInt>(C2)->getZExtValue();
1073 switch (predicate) {
1074 default: assert(0 && "Invalid ICmp Predicate"); return 0;
1075 case ICmpInst::ICMP_EQ: return ConstantBool::get(V1 == V2);
1076 case ICmpInst::ICMP_NE: return ConstantBool::get(V1 != V2);
1077 case ICmpInst::ICMP_ULT:return ConstantBool::get(V1 < V2);
1078 case ICmpInst::ICMP_UGT:return ConstantBool::get(V1 > V2);
1079 case ICmpInst::ICMP_ULE:return ConstantBool::get(V1 <= V2);
1080 case ICmpInst::ICMP_UGE:return ConstantBool::get(V1 >= V2);
Chris Lattner504e8fb2004-01-13 05:51:55 +00001081 }
1082 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001083 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1084 double C1Val = cast<ConstantFP>(C1)->getValue();
1085 double C2Val = cast<ConstantFP>(C2)->getValue();
1086 switch (predicate) {
1087 default: assert(0 && "Invalid FCmp Predicate"); return 0;
1088 case FCmpInst::FCMP_FALSE: return ConstantBool::getFalse();
1089 case FCmpInst::FCMP_TRUE: return ConstantBool::getTrue();
1090 case FCmpInst::FCMP_UNO:
1091 case FCmpInst::FCMP_ORD: break; // Can't fold these
1092 case FCmpInst::FCMP_UEQ:
1093 case FCmpInst::FCMP_OEQ: return ConstantBool::get(C1Val == C2Val);
1094 case FCmpInst::FCMP_ONE:
1095 case FCmpInst::FCMP_UNE: return ConstantBool::get(C1Val != C2Val);
1096 case FCmpInst::FCMP_OLT:
1097 case FCmpInst::FCMP_ULT: return ConstantBool::get(C1Val < C2Val);
1098 case FCmpInst::FCMP_UGT:
1099 case FCmpInst::FCMP_OGT: return ConstantBool::get(C1Val > C2Val);
1100 case FCmpInst::FCMP_OLE:
1101 case FCmpInst::FCMP_ULE: return ConstantBool::get(C1Val <= C2Val);
1102 case FCmpInst::FCMP_UGE:
1103 case FCmpInst::FCMP_OGE: return ConstantBool::get(C1Val >= C2Val);
1104 }
1105 } else if (ConstantPacked *CP1 = dyn_cast<ConstantPacked>(C1)) {
1106 if (ConstantPacked *CP2 = dyn_cast<ConstantPacked>(C2)) {
1107 if (predicate == FCmpInst::FCMP_OEQ || predicate == FCmpInst::FCMP_UEQ) {
1108 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1109 Constant *C= ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1110 const_cast<Constant*>(CP1->getOperand(i)),
1111 const_cast<Constant*>(CP2->getOperand(i)));
1112 if (ConstantBool *CB = dyn_cast<ConstantBool>(C))
1113 return CB;
1114 }
1115 // Otherwise, could not decide from any element pairs.
1116 return 0;
1117 } else if (predicate == ICmpInst::ICMP_EQ) {
1118 for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1119 Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1120 const_cast<Constant*>(CP1->getOperand(i)),
1121 const_cast<Constant*>(CP2->getOperand(i)));
1122 if (ConstantBool *CB = dyn_cast<ConstantBool>(C))
1123 return CB;
1124 }
1125 // Otherwise, could not decide from any element pairs.
1126 return 0;
1127 }
1128 }
1129 }
Chris Lattner504e8fb2004-01-13 05:51:55 +00001130
Reid Spencere4d87aa2006-12-23 06:05:41 +00001131 // Evaluate the relation between the two constants, per the predicate.
1132 switch (evaluateICmpRelation(const_cast<Constant*>(C1),
1133 const_cast<Constant*>(C2),
1134 CmpInst::isSigned(predicate))) {
1135 default: assert(0 && "Unknown relational!");
1136 case ICmpInst::BAD_ICMP_PREDICATE:
1137 break; // Couldn't determine anything about these constants.
1138 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1139 // If we know the constants are equal, we can decide the result of this
1140 // computation precisely.
1141 return ConstantBool::get(predicate == ICmpInst::ICMP_EQ ||
1142 predicate == ICmpInst::ICMP_ULE ||
1143 predicate == ICmpInst::ICMP_SLE ||
1144 predicate == ICmpInst::ICMP_UGE ||
1145 predicate == ICmpInst::ICMP_SGE);
1146 case ICmpInst::ICMP_ULT:
1147 // If we know that C1 < C2, we can decide the result of this computation
1148 // precisely.
1149 return ConstantBool::get(predicate == ICmpInst::ICMP_ULT ||
1150 predicate == ICmpInst::ICMP_NE ||
1151 predicate == ICmpInst::ICMP_ULE);
1152 case ICmpInst::ICMP_SLT:
1153 // If we know that C1 < C2, we can decide the result of this computation
1154 // precisely.
1155 return ConstantBool::get(predicate == ICmpInst::ICMP_SLT ||
1156 predicate == ICmpInst::ICMP_NE ||
1157 predicate == ICmpInst::ICMP_SLE);
1158 case ICmpInst::ICMP_UGT:
1159 // If we know that C1 > C2, we can decide the result of this computation
1160 // precisely.
1161 return ConstantBool::get(predicate == ICmpInst::ICMP_UGT ||
1162 predicate == ICmpInst::ICMP_NE ||
1163 predicate == ICmpInst::ICMP_UGE);
1164 case ICmpInst::ICMP_SGT:
1165 // If we know that C1 > C2, we can decide the result of this computation
1166 // precisely.
1167 return ConstantBool::get(predicate == ICmpInst::ICMP_SGT ||
1168 predicate == ICmpInst::ICMP_NE ||
1169 predicate == ICmpInst::ICMP_SGE);
1170 case ICmpInst::ICMP_ULE:
1171 // If we know that C1 <= C2, we can only partially decide this relation.
1172 if (predicate == ICmpInst::ICMP_UGT) return ConstantBool::getFalse();
1173 if (predicate == ICmpInst::ICMP_ULT) return ConstantBool::getTrue();
1174 break;
1175 case ICmpInst::ICMP_SLE:
1176 // If we know that C1 <= C2, we can only partially decide this relation.
1177 if (predicate == ICmpInst::ICMP_SGT) return ConstantBool::getFalse();
1178 if (predicate == ICmpInst::ICMP_SLT) return ConstantBool::getTrue();
1179 break;
1180
1181 case ICmpInst::ICMP_UGE:
1182 // If we know that C1 >= C2, we can only partially decide this relation.
1183 if (predicate == ICmpInst::ICMP_ULT) return ConstantBool::getFalse();
1184 if (predicate == ICmpInst::ICMP_UGT) return ConstantBool::getTrue();
1185 break;
1186 case ICmpInst::ICMP_SGE:
1187 // If we know that C1 >= C2, we can only partially decide this relation.
1188 if (predicate == ICmpInst::ICMP_SLT) return ConstantBool::getFalse();
1189 if (predicate == ICmpInst::ICMP_SGT) return ConstantBool::getTrue();
1190 break;
1191
1192 case ICmpInst::ICMP_NE:
1193 // If we know that C1 != C2, we can only partially decide this relation.
1194 if (predicate == ICmpInst::ICMP_EQ) return ConstantBool::getFalse();
1195 if (predicate == ICmpInst::ICMP_NE) return ConstantBool::getTrue();
1196 break;
1197 }
1198
1199 if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1200 // If C2 is a constant expr and C1 isn't, flop them around and fold the
Chris Lattner504e8fb2004-01-13 05:51:55 +00001201 // other way if possible.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001202 switch (predicate) {
1203 case ICmpInst::ICMP_EQ:
1204 case ICmpInst::ICMP_NE:
1205 // No change of predicate required.
1206 return ConstantFoldCompareInstruction(predicate, C2, C1);
Chris Lattner504e8fb2004-01-13 05:51:55 +00001207
Reid Spencere4d87aa2006-12-23 06:05:41 +00001208 case ICmpInst::ICMP_ULT:
1209 case ICmpInst::ICMP_SLT:
1210 case ICmpInst::ICMP_UGT:
1211 case ICmpInst::ICMP_SGT:
1212 case ICmpInst::ICMP_ULE:
1213 case ICmpInst::ICMP_SLE:
1214 case ICmpInst::ICMP_UGE:
1215 case ICmpInst::ICMP_SGE:
1216 // Change the predicate as necessary to swap the operands.
1217 predicate = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)predicate);
1218 return ConstantFoldCompareInstruction(predicate, C2, C1);
Chris Lattner504e8fb2004-01-13 05:51:55 +00001219
Reid Spencere4d87aa2006-12-23 06:05:41 +00001220 default: // These predicates cannot be flopped around.
Chris Lattner504e8fb2004-01-13 05:51:55 +00001221 break;
1222 }
1223 }
1224 return 0;
Chris Lattnereab20b52004-01-12 22:07:24 +00001225}
1226
1227Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
Chris Lattner7fa6e662004-10-11 22:52:25 +00001228 const std::vector<Value*> &IdxList) {
Chris Lattnereab20b52004-01-12 22:07:24 +00001229 if (IdxList.size() == 0 ||
Chris Lattner7fa6e662004-10-11 22:52:25 +00001230 (IdxList.size() == 1 && cast<Constant>(IdxList[0])->isNullValue()))
Chris Lattnereab20b52004-01-12 22:07:24 +00001231 return const_cast<Constant*>(C);
1232
Chris Lattnercfbf9fa2004-10-17 21:54:55 +00001233 if (isa<UndefValue>(C)) {
1234 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1235 true);
1236 assert(Ty != 0 && "Invalid indices for GEP!");
1237 return UndefValue::get(PointerType::get(Ty));
1238 }
1239
1240 Constant *Idx0 = cast<Constant>(IdxList[0]);
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001241 if (C->isNullValue()) {
1242 bool isNull = true;
1243 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
Chris Lattner7fa6e662004-10-11 22:52:25 +00001244 if (!cast<Constant>(IdxList[i])->isNullValue()) {
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001245 isNull = false;
1246 break;
1247 }
1248 if (isNull) {
Chris Lattner7fa6e662004-10-11 22:52:25 +00001249 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001250 true);
1251 assert(Ty != 0 && "Invalid indices for GEP!");
1252 return ConstantPointerNull::get(PointerType::get(Ty));
1253 }
Chris Lattnerdd684692004-07-15 01:16:59 +00001254
1255 if (IdxList.size() == 1) {
1256 const Type *ElTy = cast<PointerType>(C->getType())->getElementType();
Reid Spencerb83eb642006-10-20 07:07:24 +00001257 if (uint32_t ElSize = ElTy->getPrimitiveSize()) {
Chris Lattnerdd684692004-07-15 01:16:59 +00001258 // gep null, C is equal to C*sizeof(nullty). If nullty is a known llvm
1259 // type, we can statically fold this.
Reid Spencerb83eb642006-10-20 07:07:24 +00001260 Constant *R = ConstantInt::get(Type::UIntTy, ElSize);
Reid Spencer575d95c2006-12-04 02:46:44 +00001261 // We know R is unsigned, Idx0 is signed because it must be an index
1262 // through a sequential type (gep pointer operand) which is always
1263 // signed.
Reid Spencer57c69932006-12-05 03:30:09 +00001264 R = ConstantExpr::getSExtOrBitCast(R, Idx0->getType());
Reid Spencer575d95c2006-12-04 02:46:44 +00001265 R = ConstantExpr::getMul(R, Idx0); // signed multiply
1266 // R is a signed integer, C is the GEP pointer so -> IntToPtr
Reid Spencerd977d862006-12-12 23:36:14 +00001267 return ConstantExpr::getIntToPtr(R, C->getType());
Chris Lattnerdd684692004-07-15 01:16:59 +00001268 }
1269 }
Chris Lattner2e9bb1a2004-02-16 20:46:13 +00001270 }
Chris Lattnereab20b52004-01-12 22:07:24 +00001271
1272 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1273 // Combine Indices - If the source pointer to this getelementptr instruction
1274 // is a getelementptr instruction, combine the indices of the two
1275 // getelementptr instructions into a single instruction.
1276 //
1277 if (CE->getOpcode() == Instruction::GetElementPtr) {
1278 const Type *LastTy = 0;
1279 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1280 I != E; ++I)
1281 LastTy = *I;
1282
Chris Lattner7fa6e662004-10-11 22:52:25 +00001283 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1284 std::vector<Value*> NewIndices;
Chris Lattnereab20b52004-01-12 22:07:24 +00001285 NewIndices.reserve(IdxList.size() + CE->getNumOperands());
1286 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
Chris Lattner7fa6e662004-10-11 22:52:25 +00001287 NewIndices.push_back(CE->getOperand(i));
Chris Lattnereab20b52004-01-12 22:07:24 +00001288
1289 // Add the last index of the source with the first index of the new GEP.
1290 // Make sure to handle the case when they are actually different types.
1291 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
Chris Lattner7fa6e662004-10-11 22:52:25 +00001292 // Otherwise it must be an array.
1293 if (!Idx0->isNullValue()) {
Chris Lattnerd3408672004-07-07 04:45:13 +00001294 const Type *IdxTy = Combined->getType();
Reid Spencer575d95c2006-12-04 02:46:44 +00001295 if (IdxTy != Idx0->getType()) {
Reid Spencer57c69932006-12-05 03:30:09 +00001296 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::LongTy);
1297 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined,
1298 Type::LongTy);
Reid Spencer575d95c2006-12-04 02:46:44 +00001299 Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1300 } else {
1301 Combined =
1302 ConstantExpr::get(Instruction::Add, Idx0, Combined);
1303 }
Chris Lattnerd3408672004-07-07 04:45:13 +00001304 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001305
Chris Lattnereab20b52004-01-12 22:07:24 +00001306 NewIndices.push_back(Combined);
1307 NewIndices.insert(NewIndices.end(), IdxList.begin()+1, IdxList.end());
1308 return ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices);
1309 }
1310 }
1311
1312 // Implement folding of:
1313 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1314 // long 0, long 0)
1315 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1316 //
Reid Spencer3da59db2006-11-27 01:05:10 +00001317 if (CE->isCast() && IdxList.size() > 1 && Idx0->isNullValue())
Misha Brukmanfd939082005-04-21 23:48:37 +00001318 if (const PointerType *SPT =
Chris Lattnereab20b52004-01-12 22:07:24 +00001319 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1320 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1321 if (const ArrayType *CAT =
Chris Lattnerf190d382006-06-28 21:38:54 +00001322 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
Chris Lattnereab20b52004-01-12 22:07:24 +00001323 if (CAT->getElementType() == SAT->getElementType())
1324 return ConstantExpr::getGetElementPtr(
1325 (Constant*)CE->getOperand(0), IdxList);
1326 }
1327 return 0;
1328}
1329