1 //===- ConstantFolding.cpp - LLVM constant folder -------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // 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.
14 // 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.
19 //===----------------------------------------------------------------------===//
21 #include "ConstantFolding.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
34 struct VISIBILITY_HIDDEN ConstRules {
36 virtual ~ConstRules() {}
38 // Binary Operators...
39 virtual Constant *add(const Constant *V1, const Constant *V2) const = 0;
40 virtual Constant *sub(const Constant *V1, const Constant *V2) const = 0;
41 virtual Constant *mul(const Constant *V1, const Constant *V2) const = 0;
42 virtual Constant *urem(const Constant *V1, const Constant *V2) const = 0;
43 virtual Constant *srem(const Constant *V1, const Constant *V2) const = 0;
44 virtual Constant *frem(const Constant *V1, const Constant *V2) const = 0;
45 virtual Constant *udiv(const Constant *V1, const Constant *V2) const = 0;
46 virtual Constant *sdiv(const Constant *V1, const Constant *V2) const = 0;
47 virtual Constant *fdiv(const Constant *V1, const Constant *V2) const = 0;
48 virtual Constant *op_and(const Constant *V1, const Constant *V2) const = 0;
49 virtual Constant *op_or (const Constant *V1, const Constant *V2) const = 0;
50 virtual Constant *op_xor(const Constant *V1, const Constant *V2) const = 0;
51 virtual Constant *shl(const Constant *V1, const Constant *V2) const = 0;
52 virtual Constant *lshr(const Constant *V1, const Constant *V2) const = 0;
53 virtual Constant *ashr(const Constant *V1, const Constant *V2) const = 0;
54 virtual Constant *lessthan(const Constant *V1, const Constant *V2) const =0;
55 virtual Constant *equalto(const Constant *V1, const Constant *V2) const = 0;
58 virtual Constant *castToBool (const Constant *V) const = 0;
59 virtual Constant *castToSByte (const Constant *V) const = 0;
60 virtual Constant *castToUByte (const Constant *V) const = 0;
61 virtual Constant *castToShort (const Constant *V) const = 0;
62 virtual Constant *castToUShort(const Constant *V) const = 0;
63 virtual Constant *castToInt (const Constant *V) const = 0;
64 virtual Constant *castToUInt (const Constant *V) const = 0;
65 virtual Constant *castToLong (const Constant *V) const = 0;
66 virtual Constant *castToULong (const Constant *V) const = 0;
67 virtual Constant *castToFloat (const Constant *V) const = 0;
68 virtual Constant *castToDouble(const Constant *V) const = 0;
69 virtual Constant *castToPointer(const Constant *V,
70 const PointerType *Ty) const = 0;
72 // ConstRules::get - Return an instance of ConstRules for the specified
75 static ConstRules &get(const Constant *V1, const Constant *V2);
77 ConstRules(const ConstRules &); // Do not implement
78 ConstRules &operator=(const ConstRules &); // Do not implement
83 //===----------------------------------------------------------------------===//
84 // TemplateRules Class
85 //===----------------------------------------------------------------------===//
87 // TemplateRules - Implement a subclass of ConstRules that provides all
88 // operations as noops. All other rules classes inherit from this class so
89 // that if functionality is needed in the future, it can simply be added here
90 // and to ConstRules without changing anything else...
92 // This class also provides subclasses with typesafe implementations of methods
93 // so that don't have to do type casting.
96 template<class ArgType, class SubClassName>
97 class VISIBILITY_HIDDEN TemplateRules : public ConstRules {
100 //===--------------------------------------------------------------------===//
101 // Redirecting functions that cast to the appropriate types
102 //===--------------------------------------------------------------------===//
104 virtual Constant *add(const Constant *V1, const Constant *V2) const {
105 return SubClassName::Add((const ArgType *)V1, (const ArgType *)V2);
107 virtual Constant *sub(const Constant *V1, const Constant *V2) const {
108 return SubClassName::Sub((const ArgType *)V1, (const ArgType *)V2);
110 virtual Constant *mul(const Constant *V1, const Constant *V2) const {
111 return SubClassName::Mul((const ArgType *)V1, (const ArgType *)V2);
113 virtual Constant *udiv(const Constant *V1, const Constant *V2) const {
114 return SubClassName::UDiv((const ArgType *)V1, (const ArgType *)V2);
116 virtual Constant *sdiv(const Constant *V1, const Constant *V2) const {
117 return SubClassName::SDiv((const ArgType *)V1, (const ArgType *)V2);
119 virtual Constant *fdiv(const Constant *V1, const Constant *V2) const {
120 return SubClassName::FDiv((const ArgType *)V1, (const ArgType *)V2);
122 virtual Constant *urem(const Constant *V1, const Constant *V2) const {
123 return SubClassName::URem((const ArgType *)V1, (const ArgType *)V2);
125 virtual Constant *srem(const Constant *V1, const Constant *V2) const {
126 return SubClassName::SRem((const ArgType *)V1, (const ArgType *)V2);
128 virtual Constant *frem(const Constant *V1, const Constant *V2) const {
129 return SubClassName::FRem((const ArgType *)V1, (const ArgType *)V2);
131 virtual Constant *op_and(const Constant *V1, const Constant *V2) const {
132 return SubClassName::And((const ArgType *)V1, (const ArgType *)V2);
134 virtual Constant *op_or(const Constant *V1, const Constant *V2) const {
135 return SubClassName::Or((const ArgType *)V1, (const ArgType *)V2);
137 virtual Constant *op_xor(const Constant *V1, const Constant *V2) const {
138 return SubClassName::Xor((const ArgType *)V1, (const ArgType *)V2);
140 virtual Constant *shl(const Constant *V1, const Constant *V2) const {
141 return SubClassName::Shl((const ArgType *)V1, (const ArgType *)V2);
143 virtual Constant *lshr(const Constant *V1, const Constant *V2) const {
144 return SubClassName::LShr((const ArgType *)V1, (const ArgType *)V2);
146 virtual Constant *ashr(const Constant *V1, const Constant *V2) const {
147 return SubClassName::AShr((const ArgType *)V1, (const ArgType *)V2);
150 virtual Constant *lessthan(const Constant *V1, const Constant *V2) const {
151 return SubClassName::LessThan((const ArgType *)V1, (const ArgType *)V2);
153 virtual Constant *equalto(const Constant *V1, const Constant *V2) const {
154 return SubClassName::EqualTo((const ArgType *)V1, (const ArgType *)V2);
157 // Casting operators. ick
158 virtual Constant *castToBool(const Constant *V) const {
159 return SubClassName::CastToBool((const ArgType*)V);
161 virtual Constant *castToSByte(const Constant *V) const {
162 return SubClassName::CastToSByte((const ArgType*)V);
164 virtual Constant *castToUByte(const Constant *V) const {
165 return SubClassName::CastToUByte((const ArgType*)V);
167 virtual Constant *castToShort(const Constant *V) const {
168 return SubClassName::CastToShort((const ArgType*)V);
170 virtual Constant *castToUShort(const Constant *V) const {
171 return SubClassName::CastToUShort((const ArgType*)V);
173 virtual Constant *castToInt(const Constant *V) const {
174 return SubClassName::CastToInt((const ArgType*)V);
176 virtual Constant *castToUInt(const Constant *V) const {
177 return SubClassName::CastToUInt((const ArgType*)V);
179 virtual Constant *castToLong(const Constant *V) const {
180 return SubClassName::CastToLong((const ArgType*)V);
182 virtual Constant *castToULong(const Constant *V) const {
183 return SubClassName::CastToULong((const ArgType*)V);
185 virtual Constant *castToFloat(const Constant *V) const {
186 return SubClassName::CastToFloat((const ArgType*)V);
188 virtual Constant *castToDouble(const Constant *V) const {
189 return SubClassName::CastToDouble((const ArgType*)V);
191 virtual Constant *castToPointer(const Constant *V,
192 const PointerType *Ty) const {
193 return SubClassName::CastToPointer((const ArgType*)V, Ty);
196 //===--------------------------------------------------------------------===//
197 // Default "noop" implementations
198 //===--------------------------------------------------------------------===//
200 static Constant *Add (const ArgType *V1, const ArgType *V2) { return 0; }
201 static Constant *Sub (const ArgType *V1, const ArgType *V2) { return 0; }
202 static Constant *Mul (const ArgType *V1, const ArgType *V2) { return 0; }
203 static Constant *SDiv(const ArgType *V1, const ArgType *V2) { return 0; }
204 static Constant *UDiv(const ArgType *V1, const ArgType *V2) { return 0; }
205 static Constant *FDiv(const ArgType *V1, const ArgType *V2) { return 0; }
206 static Constant *URem(const ArgType *V1, const ArgType *V2) { return 0; }
207 static Constant *SRem(const ArgType *V1, const ArgType *V2) { return 0; }
208 static Constant *FRem(const ArgType *V1, const ArgType *V2) { return 0; }
209 static Constant *And (const ArgType *V1, const ArgType *V2) { return 0; }
210 static Constant *Or (const ArgType *V1, const ArgType *V2) { return 0; }
211 static Constant *Xor (const ArgType *V1, const ArgType *V2) { return 0; }
212 static Constant *Shl (const ArgType *V1, const ArgType *V2) { return 0; }
213 static Constant *LShr(const ArgType *V1, const ArgType *V2) { return 0; }
214 static Constant *AShr(const ArgType *V1, const ArgType *V2) { return 0; }
215 static Constant *LessThan(const ArgType *V1, const ArgType *V2) {
218 static Constant *EqualTo(const ArgType *V1, const ArgType *V2) {
222 // Casting operators. ick
223 static Constant *CastToBool (const Constant *V) { return 0; }
224 static Constant *CastToSByte (const Constant *V) { return 0; }
225 static Constant *CastToUByte (const Constant *V) { return 0; }
226 static Constant *CastToShort (const Constant *V) { return 0; }
227 static Constant *CastToUShort(const Constant *V) { return 0; }
228 static Constant *CastToInt (const Constant *V) { return 0; }
229 static Constant *CastToUInt (const Constant *V) { return 0; }
230 static Constant *CastToLong (const Constant *V) { return 0; }
231 static Constant *CastToULong (const Constant *V) { return 0; }
232 static Constant *CastToFloat (const Constant *V) { return 0; }
233 static Constant *CastToDouble(const Constant *V) { return 0; }
234 static Constant *CastToPointer(const Constant *,
235 const PointerType *) {return 0;}
238 virtual ~TemplateRules() {}
240 } // end anonymous namespace
243 //===----------------------------------------------------------------------===//
245 //===----------------------------------------------------------------------===//
247 // EmptyRules provides a concrete base class of ConstRules that does nothing
250 struct VISIBILITY_HIDDEN EmptyRules
251 : public TemplateRules<Constant, EmptyRules> {
252 static Constant *EqualTo(const Constant *V1, const Constant *V2) {
253 if (V1 == V2) return ConstantBool::getTrue();
257 } // end anonymous namespace
261 //===----------------------------------------------------------------------===//
263 //===----------------------------------------------------------------------===//
265 // BoolRules provides a concrete base class of ConstRules for the 'bool' type.
268 struct VISIBILITY_HIDDEN BoolRules
269 : public TemplateRules<ConstantBool, BoolRules> {
271 static Constant *LessThan(const ConstantBool *V1, const ConstantBool *V2) {
272 return ConstantBool::get(V1->getValue() < V2->getValue());
275 static Constant *EqualTo(const Constant *V1, const Constant *V2) {
276 return ConstantBool::get(V1 == V2);
279 static Constant *And(const ConstantBool *V1, const ConstantBool *V2) {
280 return ConstantBool::get(V1->getValue() & V2->getValue());
283 static Constant *Or(const ConstantBool *V1, const ConstantBool *V2) {
284 return ConstantBool::get(V1->getValue() | V2->getValue());
287 static Constant *Xor(const ConstantBool *V1, const ConstantBool *V2) {
288 return ConstantBool::get(V1->getValue() ^ V2->getValue());
291 // Casting operators. ick
292 #define DEF_CAST(TYPE, CLASS, CTYPE) \
293 static Constant *CastTo##TYPE (const ConstantBool *V) { \
294 return CLASS::get(Type::TYPE##Ty, (CTYPE)(bool)V->getValue()); \
297 DEF_CAST(Bool , ConstantBool, bool)
298 DEF_CAST(SByte , ConstantInt, signed char)
299 DEF_CAST(UByte , ConstantInt, unsigned char)
300 DEF_CAST(Short , ConstantInt, signed short)
301 DEF_CAST(UShort, ConstantInt, unsigned short)
302 DEF_CAST(Int , ConstantInt, signed int)
303 DEF_CAST(UInt , ConstantInt, unsigned int)
304 DEF_CAST(Long , ConstantInt, int64_t)
305 DEF_CAST(ULong , ConstantInt, uint64_t)
306 DEF_CAST(Float , ConstantFP , float)
307 DEF_CAST(Double, ConstantFP , double)
310 } // end anonymous namespace
313 //===----------------------------------------------------------------------===//
314 // NullPointerRules Class
315 //===----------------------------------------------------------------------===//
317 // NullPointerRules provides a concrete base class of ConstRules for null
321 struct VISIBILITY_HIDDEN NullPointerRules
322 : public TemplateRules<ConstantPointerNull, NullPointerRules> {
323 static Constant *EqualTo(const Constant *V1, const Constant *V2) {
324 return ConstantBool::getTrue(); // Null pointers are always equal
326 static Constant *CastToBool(const Constant *V) {
327 return ConstantBool::getFalse();
329 static Constant *CastToSByte (const Constant *V) {
330 return ConstantInt::get(Type::SByteTy, 0);
332 static Constant *CastToUByte (const Constant *V) {
333 return ConstantInt::get(Type::UByteTy, 0);
335 static Constant *CastToShort (const Constant *V) {
336 return ConstantInt::get(Type::ShortTy, 0);
338 static Constant *CastToUShort(const Constant *V) {
339 return ConstantInt::get(Type::UShortTy, 0);
341 static Constant *CastToInt (const Constant *V) {
342 return ConstantInt::get(Type::IntTy, 0);
344 static Constant *CastToUInt (const Constant *V) {
345 return ConstantInt::get(Type::UIntTy, 0);
347 static Constant *CastToLong (const Constant *V) {
348 return ConstantInt::get(Type::LongTy, 0);
350 static Constant *CastToULong (const Constant *V) {
351 return ConstantInt::get(Type::ULongTy, 0);
353 static Constant *CastToFloat (const Constant *V) {
354 return ConstantFP::get(Type::FloatTy, 0);
356 static Constant *CastToDouble(const Constant *V) {
357 return ConstantFP::get(Type::DoubleTy, 0);
360 static Constant *CastToPointer(const ConstantPointerNull *V,
361 const PointerType *PTy) {
362 return ConstantPointerNull::get(PTy);
365 } // end anonymous namespace
367 //===----------------------------------------------------------------------===//
368 // ConstantPackedRules Class
369 //===----------------------------------------------------------------------===//
371 /// DoVectorOp - Given two packed constants and a function pointer, apply the
372 /// function pointer to each element pair, producing a new ConstantPacked
374 static Constant *EvalVectorOp(const ConstantPacked *V1,
375 const ConstantPacked *V2,
376 Constant *(*FP)(Constant*, Constant*)) {
377 std::vector<Constant*> Res;
378 for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i)
379 Res.push_back(FP(const_cast<Constant*>(V1->getOperand(i)),
380 const_cast<Constant*>(V2->getOperand(i))));
381 return ConstantPacked::get(Res);
384 /// PackedTypeRules provides a concrete base class of ConstRules for
385 /// ConstantPacked operands.
388 struct VISIBILITY_HIDDEN ConstantPackedRules
389 : public TemplateRules<ConstantPacked, ConstantPackedRules> {
391 static Constant *Add(const ConstantPacked *V1, const ConstantPacked *V2) {
392 return EvalVectorOp(V1, V2, ConstantExpr::getAdd);
394 static Constant *Sub(const ConstantPacked *V1, const ConstantPacked *V2) {
395 return EvalVectorOp(V1, V2, ConstantExpr::getSub);
397 static Constant *Mul(const ConstantPacked *V1, const ConstantPacked *V2) {
398 return EvalVectorOp(V1, V2, ConstantExpr::getMul);
400 static Constant *UDiv(const ConstantPacked *V1, const ConstantPacked *V2) {
401 return EvalVectorOp(V1, V2, ConstantExpr::getUDiv);
403 static Constant *SDiv(const ConstantPacked *V1, const ConstantPacked *V2) {
404 return EvalVectorOp(V1, V2, ConstantExpr::getSDiv);
406 static Constant *FDiv(const ConstantPacked *V1, const ConstantPacked *V2) {
407 return EvalVectorOp(V1, V2, ConstantExpr::getFDiv);
409 static Constant *URem(const ConstantPacked *V1, const ConstantPacked *V2) {
410 return EvalVectorOp(V1, V2, ConstantExpr::getURem);
412 static Constant *SRem(const ConstantPacked *V1, const ConstantPacked *V2) {
413 return EvalVectorOp(V1, V2, ConstantExpr::getSRem);
415 static Constant *FRem(const ConstantPacked *V1, const ConstantPacked *V2) {
416 return EvalVectorOp(V1, V2, ConstantExpr::getFRem);
418 static Constant *And(const ConstantPacked *V1, const ConstantPacked *V2) {
419 return EvalVectorOp(V1, V2, ConstantExpr::getAnd);
421 static Constant *Or (const ConstantPacked *V1, const ConstantPacked *V2) {
422 return EvalVectorOp(V1, V2, ConstantExpr::getOr);
424 static Constant *Xor(const ConstantPacked *V1, const ConstantPacked *V2) {
425 return EvalVectorOp(V1, V2, ConstantExpr::getXor);
427 static Constant *LessThan(const ConstantPacked *V1, const ConstantPacked *V2){
430 static Constant *EqualTo(const ConstantPacked *V1, const ConstantPacked *V2) {
431 for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i) {
433 ConstantExpr::getSetEQ(const_cast<Constant*>(V1->getOperand(i)),
434 const_cast<Constant*>(V2->getOperand(i)));
435 if (ConstantBool *CB = dyn_cast<ConstantBool>(C))
438 // Otherwise, could not decide from any element pairs.
442 } // end anonymous namespace
445 //===----------------------------------------------------------------------===//
446 // GeneralPackedRules Class
447 //===----------------------------------------------------------------------===//
449 /// GeneralPackedRules provides a concrete base class of ConstRules for
450 /// PackedType operands, where both operands are not ConstantPacked. The usual
451 /// cause for this is that one operand is a ConstantAggregateZero.
454 struct VISIBILITY_HIDDEN GeneralPackedRules
455 : public TemplateRules<Constant, GeneralPackedRules> {
457 } // end anonymous namespace
460 //===----------------------------------------------------------------------===//
461 // DirectIntRules Class
462 //===----------------------------------------------------------------------===//
464 // DirectIntRules provides implementations of functions that are valid on
465 // integer types, but not all types in general.
468 template <class BuiltinType, Type **Ty>
469 struct VISIBILITY_HIDDEN DirectIntRules
470 : public TemplateRules<ConstantInt, DirectIntRules<BuiltinType, Ty> > {
472 static Constant *Add(const ConstantInt *V1, const ConstantInt *V2) {
473 BuiltinType R = (BuiltinType)V1->getZExtValue() +
474 (BuiltinType)V2->getZExtValue();
475 return ConstantInt::get(*Ty, R);
478 static Constant *Sub(const ConstantInt *V1, const ConstantInt *V2) {
479 BuiltinType R = (BuiltinType)V1->getZExtValue() -
480 (BuiltinType)V2->getZExtValue();
481 return ConstantInt::get(*Ty, R);
484 static Constant *Mul(const ConstantInt *V1, const ConstantInt *V2) {
485 BuiltinType R = (BuiltinType)V1->getZExtValue() *
486 (BuiltinType)V2->getZExtValue();
487 return ConstantInt::get(*Ty, R);
490 static Constant *LessThan(const ConstantInt *V1, const ConstantInt *V2) {
491 bool R = (BuiltinType)V1->getZExtValue() < (BuiltinType)V2->getZExtValue();
492 return ConstantBool::get(R);
495 static Constant *EqualTo(const ConstantInt *V1, const ConstantInt *V2) {
496 bool R = (BuiltinType)V1->getZExtValue() == (BuiltinType)V2->getZExtValue();
497 return ConstantBool::get(R);
500 static Constant *CastToPointer(const ConstantInt *V,
501 const PointerType *PTy) {
502 if (V->isNullValue()) // Is it a FP or Integral null value?
503 return ConstantPointerNull::get(PTy);
504 return 0; // Can't const prop other types of pointers
507 // Casting operators. ick
508 #define DEF_CAST(TYPE, CLASS, CTYPE) \
509 static Constant *CastTo##TYPE (const ConstantInt *V) { \
510 return CLASS::get(Type::TYPE##Ty, (CTYPE)(BuiltinType)V->getZExtValue()); \
513 DEF_CAST(Bool , ConstantBool, bool)
514 DEF_CAST(SByte , ConstantInt, signed char)
515 DEF_CAST(UByte , ConstantInt, unsigned char)
516 DEF_CAST(Short , ConstantInt, signed short)
517 DEF_CAST(UShort, ConstantInt, unsigned short)
518 DEF_CAST(Int , ConstantInt, signed int)
519 DEF_CAST(UInt , ConstantInt, unsigned int)
520 DEF_CAST(Long , ConstantInt, int64_t)
521 DEF_CAST(ULong , ConstantInt, uint64_t)
522 DEF_CAST(Float , ConstantFP , float)
523 DEF_CAST(Double, ConstantFP , double)
526 static Constant *UDiv(const ConstantInt *V1, const ConstantInt *V2) {
527 if (V2->isNullValue()) // X / 0
529 BuiltinType R = (BuiltinType)(V1->getZExtValue() / V2->getZExtValue());
530 return ConstantInt::get(*Ty, R);
533 static Constant *SDiv(const ConstantInt *V1, const ConstantInt *V2) {
534 if (V2->isNullValue()) // X / 0
536 if (V2->isAllOnesValue() && // MIN_INT / -1
537 (BuiltinType)V1->getSExtValue() == -(BuiltinType)V1->getSExtValue())
539 BuiltinType R = (BuiltinType)(V1->getSExtValue() / V2->getSExtValue());
540 return ConstantInt::get(*Ty, R);
543 static Constant *URem(const ConstantInt *V1,
544 const ConstantInt *V2) {
545 if (V2->isNullValue()) return 0; // X / 0
546 BuiltinType R = (BuiltinType)(V1->getZExtValue() % V2->getZExtValue());
547 return ConstantInt::get(*Ty, R);
550 static Constant *SRem(const ConstantInt *V1,
551 const ConstantInt *V2) {
552 if (V2->isNullValue()) return 0; // X % 0
553 if (V2->isAllOnesValue() && // MIN_INT % -1
554 (BuiltinType)V1->getSExtValue() == -(BuiltinType)V1->getSExtValue())
556 BuiltinType R = (BuiltinType)(V1->getSExtValue() % V2->getSExtValue());
557 return ConstantInt::get(*Ty, R);
560 static Constant *And(const ConstantInt *V1, const ConstantInt *V2) {
562 (BuiltinType)V1->getZExtValue() & (BuiltinType)V2->getZExtValue();
563 return ConstantInt::get(*Ty, R);
565 static Constant *Or(const ConstantInt *V1, const ConstantInt *V2) {
567 (BuiltinType)V1->getZExtValue() | (BuiltinType)V2->getZExtValue();
568 return ConstantInt::get(*Ty, R);
570 static Constant *Xor(const ConstantInt *V1, const ConstantInt *V2) {
572 (BuiltinType)V1->getZExtValue() ^ (BuiltinType)V2->getZExtValue();
573 return ConstantInt::get(*Ty, R);
576 static Constant *Shl(const ConstantInt *V1, const ConstantInt *V2) {
578 (BuiltinType)V1->getZExtValue() << (BuiltinType)V2->getZExtValue();
579 return ConstantInt::get(*Ty, R);
582 static Constant *LShr(const ConstantInt *V1, const ConstantInt *V2) {
583 BuiltinType R = BuiltinType(V1->getZExtValue() >> V2->getZExtValue());
584 return ConstantInt::get(*Ty, R);
587 static Constant *AShr(const ConstantInt *V1, const ConstantInt *V2) {
588 BuiltinType R = BuiltinType(V1->getSExtValue() >> V2->getZExtValue());
589 return ConstantInt::get(*Ty, R);
592 } // end anonymous namespace
595 //===----------------------------------------------------------------------===//
596 // DirectFPRules Class
597 //===----------------------------------------------------------------------===//
599 /// DirectFPRules provides implementations of functions that are valid on
600 /// floating point types, but not all types in general.
603 template <class BuiltinType, Type **Ty>
604 struct VISIBILITY_HIDDEN DirectFPRules
605 : public TemplateRules<ConstantFP, DirectFPRules<BuiltinType, Ty> > {
607 static Constant *Add(const ConstantFP *V1, const ConstantFP *V2) {
608 BuiltinType R = (BuiltinType)V1->getValue() +
609 (BuiltinType)V2->getValue();
610 return ConstantFP::get(*Ty, R);
613 static Constant *Sub(const ConstantFP *V1, const ConstantFP *V2) {
614 BuiltinType R = (BuiltinType)V1->getValue() - (BuiltinType)V2->getValue();
615 return ConstantFP::get(*Ty, R);
618 static Constant *Mul(const ConstantFP *V1, const ConstantFP *V2) {
619 BuiltinType R = (BuiltinType)V1->getValue() * (BuiltinType)V2->getValue();
620 return ConstantFP::get(*Ty, R);
623 static Constant *LessThan(const ConstantFP *V1, const ConstantFP *V2) {
624 bool R = (BuiltinType)V1->getValue() < (BuiltinType)V2->getValue();
625 return ConstantBool::get(R);
628 static Constant *EqualTo(const ConstantFP *V1, const ConstantFP *V2) {
629 bool R = (BuiltinType)V1->getValue() == (BuiltinType)V2->getValue();
630 return ConstantBool::get(R);
633 static Constant *CastToPointer(const ConstantFP *V,
634 const PointerType *PTy) {
635 if (V->isNullValue()) // Is it a FP or Integral null value?
636 return ConstantPointerNull::get(PTy);
637 return 0; // Can't const prop other types of pointers
640 // Casting operators. ick
641 #define DEF_CAST(TYPE, CLASS, CTYPE) \
642 static Constant *CastTo##TYPE (const ConstantFP *V) { \
643 return CLASS::get(Type::TYPE##Ty, (CTYPE)(BuiltinType)V->getValue()); \
646 DEF_CAST(Bool , ConstantBool, bool)
647 DEF_CAST(SByte , ConstantInt, signed char)
648 DEF_CAST(UByte , ConstantInt, unsigned char)
649 DEF_CAST(Short , ConstantInt, signed short)
650 DEF_CAST(UShort, ConstantInt, unsigned short)
651 DEF_CAST(Int , ConstantInt, signed int)
652 DEF_CAST(UInt , ConstantInt, unsigned int)
653 DEF_CAST(Long , ConstantInt, int64_t)
654 DEF_CAST(ULong , ConstantInt, uint64_t)
655 DEF_CAST(Float , ConstantFP , float)
656 DEF_CAST(Double, ConstantFP , double)
659 static Constant *FRem(const ConstantFP *V1, const ConstantFP *V2) {
660 if (V2->isNullValue()) return 0;
661 BuiltinType Result = std::fmod((BuiltinType)V1->getValue(),
662 (BuiltinType)V2->getValue());
663 return ConstantFP::get(*Ty, Result);
665 static Constant *FDiv(const ConstantFP *V1, const ConstantFP *V2) {
666 BuiltinType inf = std::numeric_limits<BuiltinType>::infinity();
667 if (V2->isExactlyValue(0.0)) return ConstantFP::get(*Ty, inf);
668 if (V2->isExactlyValue(-0.0)) return ConstantFP::get(*Ty, -inf);
669 BuiltinType R = (BuiltinType)V1->getValue() / (BuiltinType)V2->getValue();
670 return ConstantFP::get(*Ty, R);
673 } // end anonymous namespace
675 static ManagedStatic<EmptyRules> EmptyR;
676 static ManagedStatic<BoolRules> BoolR;
677 static ManagedStatic<NullPointerRules> NullPointerR;
678 static ManagedStatic<ConstantPackedRules> ConstantPackedR;
679 static ManagedStatic<GeneralPackedRules> GeneralPackedR;
680 static ManagedStatic<DirectIntRules<signed char , &Type::SByteTy> > SByteR;
681 static ManagedStatic<DirectIntRules<unsigned char , &Type::UByteTy> > UByteR;
682 static ManagedStatic<DirectIntRules<signed short , &Type::ShortTy> > ShortR;
683 static ManagedStatic<DirectIntRules<unsigned short, &Type::UShortTy> > UShortR;
684 static ManagedStatic<DirectIntRules<signed int , &Type::IntTy> > IntR;
685 static ManagedStatic<DirectIntRules<unsigned int , &Type::UIntTy> > UIntR;
686 static ManagedStatic<DirectIntRules<int64_t , &Type::LongTy> > LongR;
687 static ManagedStatic<DirectIntRules<uint64_t , &Type::ULongTy> > ULongR;
688 static ManagedStatic<DirectFPRules <float , &Type::FloatTy> > FloatR;
689 static ManagedStatic<DirectFPRules <double , &Type::DoubleTy> > DoubleR;
691 /// ConstRules::get - This method returns the constant rules implementation that
692 /// implements the semantics of the two specified constants.
693 ConstRules &ConstRules::get(const Constant *V1, const Constant *V2) {
694 if (isa<ConstantExpr>(V1) || isa<ConstantExpr>(V2) ||
695 isa<GlobalValue>(V1) || isa<GlobalValue>(V2) ||
696 isa<UndefValue>(V1) || isa<UndefValue>(V2))
699 switch (V1->getType()->getTypeID()) {
700 default: assert(0 && "Unknown value type for constant folding!");
701 case Type::BoolTyID: return *BoolR;
702 case Type::PointerTyID: return *NullPointerR;
703 case Type::SByteTyID: return *SByteR;
704 case Type::UByteTyID: return *UByteR;
705 case Type::ShortTyID: return *ShortR;
706 case Type::UShortTyID: return *UShortR;
707 case Type::IntTyID: return *IntR;
708 case Type::UIntTyID: return *UIntR;
709 case Type::LongTyID: return *LongR;
710 case Type::ULongTyID: return *ULongR;
711 case Type::FloatTyID: return *FloatR;
712 case Type::DoubleTyID: return *DoubleR;
713 case Type::PackedTyID:
714 if (isa<ConstantPacked>(V1) && isa<ConstantPacked>(V2))
715 return *ConstantPackedR;
716 return *GeneralPackedR; // Constant folding rules for ConstantAggregateZero.
721 //===----------------------------------------------------------------------===//
722 // ConstantFold*Instruction Implementations
723 //===----------------------------------------------------------------------===//
725 // These methods contain the special case hackery required to symbolically
726 // evaluate some constant expression cases, and use the ConstantRules class to
727 // evaluate normal constants.
729 static unsigned getSize(const Type *Ty) {
730 unsigned S = Ty->getPrimitiveSize();
731 return S ? S : 8; // Treat pointers at 8 bytes
734 /// CastConstantPacked - Convert the specified ConstantPacked node to the
735 /// specified packed type. At this point, we know that the elements of the
736 /// input packed constant are all simple integer or FP values.
737 static Constant *CastConstantPacked(ConstantPacked *CP,
738 const PackedType *DstTy) {
739 unsigned SrcNumElts = CP->getType()->getNumElements();
740 unsigned DstNumElts = DstTy->getNumElements();
741 const Type *SrcEltTy = CP->getType()->getElementType();
742 const Type *DstEltTy = DstTy->getElementType();
744 // If both vectors have the same number of elements (thus, the elements
745 // are the same size), perform the conversion now.
746 if (SrcNumElts == DstNumElts) {
747 std::vector<Constant*> Result;
749 // If the src and dest elements are both integers, just cast each one
750 // which will do the appropriate bit-convert.
751 if (SrcEltTy->isIntegral() && DstEltTy->isIntegral()) {
752 for (unsigned i = 0; i != SrcNumElts; ++i)
753 Result.push_back(ConstantExpr::getCast(CP->getOperand(i),
755 return ConstantPacked::get(Result);
758 if (SrcEltTy->isIntegral()) {
759 // Otherwise, this is an int-to-fp cast.
760 assert(DstEltTy->isFloatingPoint());
761 if (DstEltTy->getTypeID() == Type::DoubleTyID) {
762 for (unsigned i = 0; i != SrcNumElts; ++i) {
764 BitsToDouble(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
765 Result.push_back(ConstantFP::get(Type::DoubleTy, V));
767 return ConstantPacked::get(Result);
769 assert(DstEltTy == Type::FloatTy && "Unknown fp type!");
770 for (unsigned i = 0; i != SrcNumElts; ++i) {
772 BitsToFloat(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
773 Result.push_back(ConstantFP::get(Type::FloatTy, V));
775 return ConstantPacked::get(Result);
778 // Otherwise, this is an fp-to-int cast.
779 assert(SrcEltTy->isFloatingPoint() && DstEltTy->isIntegral());
781 if (SrcEltTy->getTypeID() == Type::DoubleTyID) {
782 for (unsigned i = 0; i != SrcNumElts; ++i) {
784 DoubleToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
785 Constant *C = ConstantInt::get(Type::ULongTy, V);
786 Result.push_back(ConstantExpr::getCast(C, DstEltTy));
788 return ConstantPacked::get(Result);
791 assert(SrcEltTy->getTypeID() == Type::FloatTyID);
792 for (unsigned i = 0; i != SrcNumElts; ++i) {
793 uint32_t V = FloatToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
794 Constant *C = ConstantInt::get(Type::UIntTy, V);
795 Result.push_back(ConstantExpr::getCast(C, DstEltTy));
797 return ConstantPacked::get(Result);
800 // Otherwise, this is a cast that changes element count and size. Handle
801 // casts which shrink the elements here.
803 // FIXME: We need to know endianness to do this!
809 Constant *llvm::ConstantFoldCastInstruction(const Constant *V,
810 const Type *DestTy) {
811 if (V->getType() == DestTy) return (Constant*)V;
813 // Cast of a global address to boolean is always true.
814 if (isa<GlobalValue>(V)) {
815 if (DestTy == Type::BoolTy)
816 // FIXME: When we support 'external weak' references, we have to prevent
817 // this transformation from happening. This code will need to be updated
818 // to ignore external weak symbols when we support it.
819 return ConstantBool::getTrue();
820 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
821 if (CE->getOpcode() == Instruction::Cast) {
822 Constant *Op = const_cast<Constant*>(CE->getOperand(0));
823 // Try to not produce a cast of a cast, which is almost always redundant.
824 if (!Op->getType()->isFloatingPoint() &&
825 !CE->getType()->isFloatingPoint() &&
826 !DestTy->isFloatingPoint()) {
827 unsigned S1 = getSize(Op->getType()), S2 = getSize(CE->getType());
828 unsigned S3 = getSize(DestTy);
829 if (Op->getType() == DestTy && S3 >= S2)
831 if (S1 >= S2 && S2 >= S3)
832 return ConstantExpr::getCast(Op, DestTy);
833 if (S1 <= S2 && S2 >= S3 && S1 <= S3)
834 return ConstantExpr::getCast(Op, DestTy);
836 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
837 // If all of the indexes in the GEP are null values, there is no pointer
838 // adjustment going on. We might as well cast the source pointer.
839 bool isAllNull = true;
840 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
841 if (!CE->getOperand(i)->isNullValue()) {
846 return ConstantExpr::getCast(CE->getOperand(0), DestTy);
848 } else if (isa<UndefValue>(V)) {
849 return UndefValue::get(DestTy);
852 // Check to see if we are casting an pointer to an aggregate to a pointer to
853 // the first element. If so, return the appropriate GEP instruction.
854 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
855 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
856 std::vector<Value*> IdxList;
857 IdxList.push_back(Constant::getNullValue(Type::IntTy));
858 const Type *ElTy = PTy->getElementType();
859 while (ElTy != DPTy->getElementType()) {
860 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
861 if (STy->getNumElements() == 0) break;
862 ElTy = STy->getElementType(0);
863 IdxList.push_back(Constant::getNullValue(Type::UIntTy));
864 } else if (const SequentialType *STy = dyn_cast<SequentialType>(ElTy)) {
865 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
866 ElTy = STy->getElementType();
867 IdxList.push_back(IdxList[0]);
873 if (ElTy == DPTy->getElementType())
874 return ConstantExpr::getGetElementPtr(const_cast<Constant*>(V),IdxList);
877 // Handle casts from one packed constant to another. We know that the src and
878 // dest type have the same size.
879 if (const PackedType *DestPTy = dyn_cast<PackedType>(DestTy)) {
880 if (const PackedType *SrcTy = dyn_cast<PackedType>(V->getType())) {
881 assert(DestPTy->getElementType()->getPrimitiveSizeInBits() *
882 DestPTy->getNumElements() ==
883 SrcTy->getElementType()->getPrimitiveSizeInBits() *
884 SrcTy->getNumElements() && "Not cast between same sized vectors!");
885 if (isa<ConstantAggregateZero>(V))
886 return Constant::getNullValue(DestTy);
887 if (isa<UndefValue>(V))
888 return UndefValue::get(DestTy);
889 if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
890 // This is a cast from a ConstantPacked of one type to a ConstantPacked
891 // of another type. Check to see if all elements of the input are
893 bool AllSimpleConstants = true;
894 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
895 if (!isa<ConstantInt>(CP->getOperand(i)) &&
896 !isa<ConstantFP>(CP->getOperand(i))) {
897 AllSimpleConstants = false;
902 // If all of the elements are simple constants, we can fold this.
903 if (AllSimpleConstants)
904 return CastConstantPacked(const_cast<ConstantPacked*>(CP), DestPTy);
909 ConstRules &Rules = ConstRules::get(V, V);
911 switch (DestTy->getTypeID()) {
912 case Type::BoolTyID: return Rules.castToBool(V);
913 case Type::UByteTyID: return Rules.castToUByte(V);
914 case Type::SByteTyID: return Rules.castToSByte(V);
915 case Type::UShortTyID: return Rules.castToUShort(V);
916 case Type::ShortTyID: return Rules.castToShort(V);
917 case Type::UIntTyID: return Rules.castToUInt(V);
918 case Type::IntTyID: return Rules.castToInt(V);
919 case Type::ULongTyID: return Rules.castToULong(V);
920 case Type::LongTyID: return Rules.castToLong(V);
921 case Type::FloatTyID: return Rules.castToFloat(V);
922 case Type::DoubleTyID: return Rules.castToDouble(V);
923 case Type::PointerTyID:
924 return Rules.castToPointer(V, cast<PointerType>(DestTy));
929 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
931 const Constant *V2) {
932 if (const ConstantBool *CB = dyn_cast<ConstantBool>(Cond))
933 return const_cast<Constant*>(CB->getValue() ? V1 : V2);
935 if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
936 if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
937 if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
938 if (V1 == V2) return const_cast<Constant*>(V1);
942 Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
943 const Constant *Idx) {
944 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
945 return UndefValue::get(cast<PackedType>(Val->getType())->getElementType());
946 if (Val->isNullValue()) // ee(zero, x) -> zero
947 return Constant::getNullValue(
948 cast<PackedType>(Val->getType())->getElementType());
950 if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
951 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
952 return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
953 } else if (isa<UndefValue>(Idx)) {
954 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
955 return const_cast<Constant*>(CVal->getOperand(0));
961 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
963 const Constant *Idx) {
964 const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
966 uint64_t idxVal = CIdx->getZExtValue();
967 if (isa<UndefValue>(Val)) {
968 // Insertion of scalar constant into packed undef
969 // Optimize away insertion of undef
970 if (isa<UndefValue>(Elt))
971 return const_cast<Constant*>(Val);
972 // Otherwise break the aggregate undef into multiple undefs and do
975 cast<PackedType>(Val->getType())->getNumElements();
976 std::vector<Constant*> Ops;
978 for (unsigned i = 0; i < numOps; ++i) {
980 (i == idxVal) ? Elt : UndefValue::get(Elt->getType());
981 Ops.push_back(const_cast<Constant*>(Op));
983 return ConstantPacked::get(Ops);
985 if (isa<ConstantAggregateZero>(Val)) {
986 // Insertion of scalar constant into packed aggregate zero
987 // Optimize away insertion of zero
988 if (Elt->isNullValue())
989 return const_cast<Constant*>(Val);
990 // Otherwise break the aggregate zero into multiple zeros and do
993 cast<PackedType>(Val->getType())->getNumElements();
994 std::vector<Constant*> Ops;
996 for (unsigned i = 0; i < numOps; ++i) {
998 (i == idxVal) ? Elt : Constant::getNullValue(Elt->getType());
999 Ops.push_back(const_cast<Constant*>(Op));
1001 return ConstantPacked::get(Ops);
1003 if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
1004 // Insertion of scalar constant into packed constant
1005 std::vector<Constant*> Ops;
1006 Ops.reserve(CVal->getNumOperands());
1007 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
1008 const Constant *Op =
1009 (i == idxVal) ? Elt : cast<Constant>(CVal->getOperand(i));
1010 Ops.push_back(const_cast<Constant*>(Op));
1012 return ConstantPacked::get(Ops);
1017 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
1019 const Constant *Mask) {
1025 /// isZeroSizedType - This type is zero sized if its an array or structure of
1026 /// zero sized types. The only leaf zero sized type is an empty structure.
1027 static bool isMaybeZeroSizedType(const Type *Ty) {
1028 if (isa<OpaqueType>(Ty)) return true; // Can't say.
1029 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1031 // If all of elements have zero size, this does too.
1032 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1033 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1036 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1037 return isMaybeZeroSizedType(ATy->getElementType());
1042 /// IdxCompare - Compare the two constants as though they were getelementptr
1043 /// indices. This allows coersion of the types to be the same thing.
1045 /// If the two constants are the "same" (after coersion), return 0. If the
1046 /// first is less than the second, return -1, if the second is less than the
1047 /// first, return 1. If the constants are not integral, return -2.
1049 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
1050 if (C1 == C2) return 0;
1052 // Ok, we found a different index. Are either of the operands
1053 // ConstantExprs? If so, we can't do anything with them.
1054 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1055 return -2; // don't know!
1057 // Ok, we have two differing integer indices. Sign extend them to be the same
1058 // type. Long is always big enough, so we use it.
1059 C1 = ConstantExpr::getSignExtend(C1, Type::LongTy);
1060 C2 = ConstantExpr::getSignExtend(C2, Type::LongTy);
1061 if (C1 == C2) return 0; // Are they just differing types?
1063 // If the type being indexed over is really just a zero sized type, there is
1064 // no pointer difference being made here.
1065 if (isMaybeZeroSizedType(ElTy))
1066 return -2; // dunno.
1068 // If they are really different, now that they are the same type, then we
1069 // found a difference!
1070 if (cast<ConstantInt>(C1)->getSExtValue() <
1071 cast<ConstantInt>(C2)->getSExtValue())
1077 /// evaluateRelation - This function determines if there is anything we can
1078 /// decide about the two constants provided. This doesn't need to handle simple
1079 /// things like integer comparisons, but should instead handle ConstantExprs
1080 /// and GlobalValuess. If we can determine that the two constants have a
1081 /// particular relation to each other, we should return the corresponding SetCC
1082 /// code, otherwise return Instruction::BinaryOpsEnd.
1084 /// To simplify this code we canonicalize the relation so that the first
1085 /// operand is always the most "complex" of the two. We consider simple
1086 /// constants (like ConstantInt) to be the simplest, followed by
1087 /// GlobalValues, followed by ConstantExpr's (the most complex).
1089 static Instruction::BinaryOps evaluateRelation(Constant *V1, Constant *V2) {
1090 assert(V1->getType() == V2->getType() &&
1091 "Cannot compare different types of values!");
1092 if (V1 == V2) return Instruction::SetEQ;
1094 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
1095 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
1096 // We distilled this down to a simple case, use the standard constant
1098 ConstantBool *R = dyn_cast<ConstantBool>(ConstantExpr::getSetEQ(V1, V2));
1099 if (R && R->getValue()) return Instruction::SetEQ;
1100 R = dyn_cast<ConstantBool>(ConstantExpr::getSetLT(V1, V2));
1101 if (R && R->getValue()) return Instruction::SetLT;
1102 R = dyn_cast<ConstantBool>(ConstantExpr::getSetGT(V1, V2));
1103 if (R && R->getValue()) return Instruction::SetGT;
1105 // If we couldn't figure it out, bail.
1106 return Instruction::BinaryOpsEnd;
1109 // If the first operand is simple, swap operands.
1110 Instruction::BinaryOps SwappedRelation = evaluateRelation(V2, V1);
1111 if (SwappedRelation != Instruction::BinaryOpsEnd)
1112 return SetCondInst::getSwappedCondition(SwappedRelation);
1114 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
1115 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1116 Instruction::BinaryOps SwappedRelation = evaluateRelation(V2, V1);
1117 if (SwappedRelation != Instruction::BinaryOpsEnd)
1118 return SetCondInst::getSwappedCondition(SwappedRelation);
1120 return Instruction::BinaryOpsEnd;
1123 // Now we know that the RHS is a GlobalValue or simple constant,
1124 // which (since the types must match) means that it's a ConstantPointerNull.
1125 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1126 assert(CPR1 != CPR2 &&
1127 "GVs for the same value exist at different addresses??");
1128 // FIXME: If both globals are external weak, they might both be null!
1129 return Instruction::SetNE;
1131 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1132 // Global can never be null. FIXME: if we implement external weak
1133 // linkage, this is not necessarily true!
1134 return Instruction::SetNE;
1138 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1139 // constantexpr, a CPR, or a simple constant.
1140 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1141 Constant *CE1Op0 = CE1->getOperand(0);
1143 switch (CE1->getOpcode()) {
1144 case Instruction::Cast:
1145 // If the cast is not actually changing bits, and the second operand is a
1146 // null pointer, do the comparison with the pre-casted value.
1147 if (V2->isNullValue() &&
1148 (isa<PointerType>(CE1->getType()) || CE1->getType()->isIntegral()))
1149 return evaluateRelation(CE1Op0,
1150 Constant::getNullValue(CE1Op0->getType()));
1152 // If the dest type is a pointer type, and the RHS is a constantexpr cast
1153 // from the same type as the src of the LHS, evaluate the inputs. This is
1154 // important for things like "seteq (cast 4 to int*), (cast 5 to int*)",
1155 // which happens a lot in compilers with tagged integers.
1156 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
1157 if (isa<PointerType>(CE1->getType()) &&
1158 CE2->getOpcode() == Instruction::Cast &&
1159 CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
1160 CE1->getOperand(0)->getType()->isIntegral()) {
1161 return evaluateRelation(CE1->getOperand(0), CE2->getOperand(0));
1165 case Instruction::GetElementPtr:
1166 // Ok, since this is a getelementptr, we know that the constant has a
1167 // pointer type. Check the various cases.
1168 if (isa<ConstantPointerNull>(V2)) {
1169 // If we are comparing a GEP to a null pointer, check to see if the base
1170 // of the GEP equals the null pointer.
1171 if (isa<GlobalValue>(CE1Op0)) {
1172 // FIXME: this is not true when we have external weak references!
1173 // No offset can go from a global to a null pointer.
1174 return Instruction::SetGT;
1175 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1176 // If we are indexing from a null pointer, check to see if we have any
1177 // non-zero indices.
1178 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1179 if (!CE1->getOperand(i)->isNullValue())
1180 // Offsetting from null, must not be equal.
1181 return Instruction::SetGT;
1182 // Only zero indexes from null, must still be zero.
1183 return Instruction::SetEQ;
1185 // Otherwise, we can't really say if the first operand is null or not.
1186 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1187 if (isa<ConstantPointerNull>(CE1Op0)) {
1188 // FIXME: This is not true with external weak references.
1189 return Instruction::SetLT;
1190 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1192 // If this is a getelementptr of the same global, then it must be
1193 // different. Because the types must match, the getelementptr could
1194 // only have at most one index, and because we fold getelementptr's
1195 // with a single zero index, it must be nonzero.
1196 assert(CE1->getNumOperands() == 2 &&
1197 !CE1->getOperand(1)->isNullValue() &&
1198 "Suprising getelementptr!");
1199 return Instruction::SetGT;
1201 // If they are different globals, we don't know what the value is,
1202 // but they can't be equal.
1203 return Instruction::SetNE;
1207 const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1208 const Constant *CE2Op0 = CE2->getOperand(0);
1210 // There are MANY other foldings that we could perform here. They will
1211 // probably be added on demand, as they seem needed.
1212 switch (CE2->getOpcode()) {
1214 case Instruction::GetElementPtr:
1215 // By far the most common case to handle is when the base pointers are
1216 // obviously to the same or different globals.
1217 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1218 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1219 return Instruction::SetNE;
1220 // Ok, we know that both getelementptr instructions are based on the
1221 // same global. From this, we can precisely determine the relative
1222 // ordering of the resultant pointers.
1225 // Compare all of the operands the GEP's have in common.
1226 gep_type_iterator GTI = gep_type_begin(CE1);
1227 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1229 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1230 GTI.getIndexedType())) {
1231 case -1: return Instruction::SetLT;
1232 case 1: return Instruction::SetGT;
1233 case -2: return Instruction::BinaryOpsEnd;
1236 // Ok, we ran out of things they have in common. If any leftovers
1237 // are non-zero then we have a difference, otherwise we are equal.
1238 for (; i < CE1->getNumOperands(); ++i)
1239 if (!CE1->getOperand(i)->isNullValue())
1240 if (isa<ConstantIntegral>(CE1->getOperand(i)))
1241 return Instruction::SetGT;
1243 return Instruction::BinaryOpsEnd; // Might be equal.
1245 for (; i < CE2->getNumOperands(); ++i)
1246 if (!CE2->getOperand(i)->isNullValue())
1247 if (isa<ConstantIntegral>(CE2->getOperand(i)))
1248 return Instruction::SetLT;
1250 return Instruction::BinaryOpsEnd; // Might be equal.
1251 return Instruction::SetEQ;
1261 return Instruction::BinaryOpsEnd;
1264 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
1266 const Constant *V2) {
1270 case Instruction::Add: C = ConstRules::get(V1, V2).add(V1, V2); break;
1271 case Instruction::Sub: C = ConstRules::get(V1, V2).sub(V1, V2); break;
1272 case Instruction::Mul: C = ConstRules::get(V1, V2).mul(V1, V2); break;
1273 case Instruction::UDiv: C = ConstRules::get(V1, V2).udiv(V1, V2); break;
1274 case Instruction::SDiv: C = ConstRules::get(V1, V2).sdiv(V1, V2); break;
1275 case Instruction::FDiv: C = ConstRules::get(V1, V2).fdiv(V1, V2); break;
1276 case Instruction::URem: C = ConstRules::get(V1, V2).urem(V1, V2); break;
1277 case Instruction::SRem: C = ConstRules::get(V1, V2).srem(V1, V2); break;
1278 case Instruction::FRem: C = ConstRules::get(V1, V2).frem(V1, V2); break;
1279 case Instruction::And: C = ConstRules::get(V1, V2).op_and(V1, V2); break;
1280 case Instruction::Or: C = ConstRules::get(V1, V2).op_or (V1, V2); break;
1281 case Instruction::Xor: C = ConstRules::get(V1, V2).op_xor(V1, V2); break;
1282 case Instruction::Shl: C = ConstRules::get(V1, V2).shl(V1, V2); break;
1283 case Instruction::LShr: C = ConstRules::get(V1, V2).lshr(V1, V2); break;
1284 case Instruction::AShr: C = ConstRules::get(V1, V2).ashr(V1, V2); break;
1285 case Instruction::SetEQ: C = ConstRules::get(V1, V2).equalto(V1, V2); break;
1286 case Instruction::SetLT: C = ConstRules::get(V1, V2).lessthan(V1, V2);break;
1287 case Instruction::SetGT: C = ConstRules::get(V1, V2).lessthan(V2, V1);break;
1288 case Instruction::SetNE: // V1 != V2 === !(V1 == V2)
1289 C = ConstRules::get(V1, V2).equalto(V1, V2);
1290 if (C) return ConstantExpr::getNot(C);
1292 case Instruction::SetLE: // V1 <= V2 === !(V2 < V1)
1293 C = ConstRules::get(V1, V2).lessthan(V2, V1);
1294 if (C) return ConstantExpr::getNot(C);
1296 case Instruction::SetGE: // V1 >= V2 === !(V1 < V2)
1297 C = ConstRules::get(V1, V2).lessthan(V1, V2);
1298 if (C) return ConstantExpr::getNot(C);
1302 // If we successfully folded the expression, return it now.
1305 if (SetCondInst::isComparison(Opcode)) {
1306 if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1307 return UndefValue::get(Type::BoolTy);
1308 switch (evaluateRelation(const_cast<Constant*>(V1),
1309 const_cast<Constant*>(V2))) {
1310 default: assert(0 && "Unknown relational!");
1311 case Instruction::BinaryOpsEnd:
1312 break; // Couldn't determine anything about these constants.
1313 case Instruction::SetEQ: // We know the constants are equal!
1314 // If we know the constants are equal, we can decide the result of this
1315 // computation precisely.
1316 return ConstantBool::get(Opcode == Instruction::SetEQ ||
1317 Opcode == Instruction::SetLE ||
1318 Opcode == Instruction::SetGE);
1319 case Instruction::SetLT:
1320 // If we know that V1 < V2, we can decide the result of this computation
1322 return ConstantBool::get(Opcode == Instruction::SetLT ||
1323 Opcode == Instruction::SetNE ||
1324 Opcode == Instruction::SetLE);
1325 case Instruction::SetGT:
1326 // If we know that V1 > V2, we can decide the result of this computation
1328 return ConstantBool::get(Opcode == Instruction::SetGT ||
1329 Opcode == Instruction::SetNE ||
1330 Opcode == Instruction::SetGE);
1331 case Instruction::SetLE:
1332 // If we know that V1 <= V2, we can only partially decide this relation.
1333 if (Opcode == Instruction::SetGT) return ConstantBool::getFalse();
1334 if (Opcode == Instruction::SetLT) return ConstantBool::getTrue();
1337 case Instruction::SetGE:
1338 // If we know that V1 >= V2, we can only partially decide this relation.
1339 if (Opcode == Instruction::SetLT) return ConstantBool::getFalse();
1340 if (Opcode == Instruction::SetGT) return ConstantBool::getTrue();
1343 case Instruction::SetNE:
1344 // If we know that V1 != V2, we can only partially decide this relation.
1345 if (Opcode == Instruction::SetEQ) return ConstantBool::getFalse();
1346 if (Opcode == Instruction::SetNE) return ConstantBool::getTrue();
1351 if (isa<UndefValue>(V1) || isa<UndefValue>(V2)) {
1353 case Instruction::Add:
1354 case Instruction::Sub:
1355 case Instruction::Xor:
1356 return UndefValue::get(V1->getType());
1358 case Instruction::Mul:
1359 case Instruction::And:
1360 return Constant::getNullValue(V1->getType());
1361 case Instruction::UDiv:
1362 case Instruction::SDiv:
1363 case Instruction::FDiv:
1364 case Instruction::URem:
1365 case Instruction::SRem:
1366 case Instruction::FRem:
1367 if (!isa<UndefValue>(V2)) // undef / X -> 0
1368 return Constant::getNullValue(V1->getType());
1369 return const_cast<Constant*>(V2); // X / undef -> undef
1370 case Instruction::Or: // X | undef -> -1
1371 return ConstantInt::getAllOnesValue(V1->getType());
1372 case Instruction::LShr:
1373 if (isa<UndefValue>(V2) && isa<UndefValue>(V1))
1374 return const_cast<Constant*>(V1); // undef lshr undef -> undef
1375 return Constant::getNullValue(V1->getType()); // X lshr undef -> 0
1376 // undef lshr X -> 0
1377 case Instruction::AShr:
1378 if (!isa<UndefValue>(V2))
1379 return const_cast<Constant*>(V1); // undef ashr X --> undef
1380 else if (isa<UndefValue>(V1))
1381 return const_cast<Constant*>(V1); // undef ashr undef -> undef
1383 return const_cast<Constant*>(V1); // X ashr undef --> X
1384 case Instruction::Shl:
1385 // undef << X -> 0 or X << undef -> 0
1386 return Constant::getNullValue(V1->getType());
1390 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(V1)) {
1391 if (isa<ConstantExpr>(V2)) {
1392 // There are many possible foldings we could do here. We should probably
1393 // at least fold add of a pointer with an integer into the appropriate
1394 // getelementptr. This will improve alias analysis a bit.
1396 // Just implement a couple of simple identities.
1398 case Instruction::Add:
1399 if (V2->isNullValue()) return const_cast<Constant*>(V1); // X + 0 == X
1401 case Instruction::Sub:
1402 if (V2->isNullValue()) return const_cast<Constant*>(V1); // X - 0 == X
1404 case Instruction::Mul:
1405 if (V2->isNullValue()) return const_cast<Constant*>(V2); // X * 0 == 0
1406 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1407 if (CI->getZExtValue() == 1)
1408 return const_cast<Constant*>(V1); // X * 1 == X
1410 case Instruction::UDiv:
1411 case Instruction::SDiv:
1412 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1413 if (CI->getZExtValue() == 1)
1414 return const_cast<Constant*>(V1); // X / 1 == X
1416 case Instruction::URem:
1417 case Instruction::SRem:
1418 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1419 if (CI->getZExtValue() == 1)
1420 return Constant::getNullValue(CI->getType()); // X % 1 == 0
1422 case Instruction::And:
1423 if (cast<ConstantIntegral>(V2)->isAllOnesValue())
1424 return const_cast<Constant*>(V1); // X & -1 == X
1425 if (V2->isNullValue()) return const_cast<Constant*>(V2); // X & 0 == 0
1426 if (CE1->getOpcode() == Instruction::Cast &&
1427 isa<GlobalValue>(CE1->getOperand(0))) {
1428 GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
1430 // Functions are at least 4-byte aligned. If and'ing the address of a
1431 // function with a constant < 4, fold it to zero.
1432 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1433 if (CI->getZExtValue() < 4 && isa<Function>(CPR))
1434 return Constant::getNullValue(CI->getType());
1437 case Instruction::Or:
1438 if (V2->isNullValue()) return const_cast<Constant*>(V1); // X | 0 == X
1439 if (cast<ConstantIntegral>(V2)->isAllOnesValue())
1440 return const_cast<Constant*>(V2); // X | -1 == -1
1442 case Instruction::Xor:
1443 if (V2->isNullValue()) return const_cast<Constant*>(V1); // X ^ 0 == X
1448 } else if (isa<ConstantExpr>(V2)) {
1449 // If V2 is a constant expr and V1 isn't, flop them around and fold the
1450 // other way if possible.
1452 case Instruction::Add:
1453 case Instruction::Mul:
1454 case Instruction::And:
1455 case Instruction::Or:
1456 case Instruction::Xor:
1457 case Instruction::SetEQ:
1458 case Instruction::SetNE:
1459 // No change of opcode required.
1460 return ConstantFoldBinaryInstruction(Opcode, V2, V1);
1462 case Instruction::SetLT:
1463 case Instruction::SetGT:
1464 case Instruction::SetLE:
1465 case Instruction::SetGE:
1466 // Change the opcode as necessary to swap the operands.
1467 Opcode = SetCondInst::getSwappedCondition((Instruction::BinaryOps)Opcode);
1468 return ConstantFoldBinaryInstruction(Opcode, V2, V1);
1470 case Instruction::Shl:
1471 case Instruction::LShr:
1472 case Instruction::AShr:
1473 case Instruction::Sub:
1474 case Instruction::SDiv:
1475 case Instruction::UDiv:
1476 case Instruction::FDiv:
1477 case Instruction::URem:
1478 case Instruction::SRem:
1479 case Instruction::FRem:
1480 default: // These instructions cannot be flopped around.
1487 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1488 const std::vector<Value*> &IdxList) {
1489 if (IdxList.size() == 0 ||
1490 (IdxList.size() == 1 && cast<Constant>(IdxList[0])->isNullValue()))
1491 return const_cast<Constant*>(C);
1493 if (isa<UndefValue>(C)) {
1494 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1496 assert(Ty != 0 && "Invalid indices for GEP!");
1497 return UndefValue::get(PointerType::get(Ty));
1500 Constant *Idx0 = cast<Constant>(IdxList[0]);
1501 if (C->isNullValue()) {
1503 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1504 if (!cast<Constant>(IdxList[i])->isNullValue()) {
1509 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1511 assert(Ty != 0 && "Invalid indices for GEP!");
1512 return ConstantPointerNull::get(PointerType::get(Ty));
1515 if (IdxList.size() == 1) {
1516 const Type *ElTy = cast<PointerType>(C->getType())->getElementType();
1517 if (uint32_t ElSize = ElTy->getPrimitiveSize()) {
1518 // gep null, C is equal to C*sizeof(nullty). If nullty is a known llvm
1519 // type, we can statically fold this.
1520 Constant *R = ConstantInt::get(Type::UIntTy, ElSize);
1521 R = ConstantExpr::getCast(R, Idx0->getType());
1522 R = ConstantExpr::getMul(R, Idx0);
1523 return ConstantExpr::getCast(R, C->getType());
1528 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1529 // Combine Indices - If the source pointer to this getelementptr instruction
1530 // is a getelementptr instruction, combine the indices of the two
1531 // getelementptr instructions into a single instruction.
1533 if (CE->getOpcode() == Instruction::GetElementPtr) {
1534 const Type *LastTy = 0;
1535 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1539 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1540 std::vector<Value*> NewIndices;
1541 NewIndices.reserve(IdxList.size() + CE->getNumOperands());
1542 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1543 NewIndices.push_back(CE->getOperand(i));
1545 // Add the last index of the source with the first index of the new GEP.
1546 // Make sure to handle the case when they are actually different types.
1547 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1548 // Otherwise it must be an array.
1549 if (!Idx0->isNullValue()) {
1550 const Type *IdxTy = Combined->getType();
1551 if (IdxTy != Idx0->getType()) IdxTy = Type::LongTy;
1553 ConstantExpr::get(Instruction::Add,
1554 ConstantExpr::getCast(Idx0, IdxTy),
1555 ConstantExpr::getCast(Combined, IdxTy));
1558 NewIndices.push_back(Combined);
1559 NewIndices.insert(NewIndices.end(), IdxList.begin()+1, IdxList.end());
1560 return ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices);
1564 // Implement folding of:
1565 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1567 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1569 if (CE->getOpcode() == Instruction::Cast && IdxList.size() > 1 &&
1570 Idx0->isNullValue())
1571 if (const PointerType *SPT =
1572 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1573 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1574 if (const ArrayType *CAT =
1575 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1576 if (CAT->getElementType() == SAT->getElementType())
1577 return ConstantExpr::getGetElementPtr(
1578 (Constant*)CE->getOperand(0), IdxList);