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"
35 struct VISIBILITY_HIDDEN ConstRules {
37 virtual ~ConstRules() {}
39 // Binary Operators...
40 virtual Constant *add(const Constant *V1, const Constant *V2) const = 0;
41 virtual Constant *sub(const Constant *V1, const Constant *V2) const = 0;
42 virtual Constant *mul(const Constant *V1, const Constant *V2) const = 0;
43 virtual Constant *udiv(const Constant *V1, const Constant *V2) const = 0;
44 virtual Constant *sdiv(const Constant *V1, const Constant *V2) const = 0;
45 virtual Constant *fdiv(const Constant *V1, const Constant *V2) const = 0;
46 virtual Constant *rem(const Constant *V1, const Constant *V2) const = 0;
47 virtual Constant *op_and(const Constant *V1, const Constant *V2) const = 0;
48 virtual Constant *op_or (const Constant *V1, const Constant *V2) const = 0;
49 virtual Constant *op_xor(const Constant *V1, const Constant *V2) const = 0;
50 virtual Constant *shl(const Constant *V1, const Constant *V2) const = 0;
51 virtual Constant *shr(const Constant *V1, const Constant *V2) const = 0;
52 virtual Constant *lessthan(const Constant *V1, const Constant *V2) const =0;
53 virtual Constant *equalto(const Constant *V1, const Constant *V2) const = 0;
56 virtual Constant *castToBool (const Constant *V) const = 0;
57 virtual Constant *castToSByte (const Constant *V) const = 0;
58 virtual Constant *castToUByte (const Constant *V) const = 0;
59 virtual Constant *castToShort (const Constant *V) const = 0;
60 virtual Constant *castToUShort(const Constant *V) const = 0;
61 virtual Constant *castToInt (const Constant *V) const = 0;
62 virtual Constant *castToUInt (const Constant *V) const = 0;
63 virtual Constant *castToLong (const Constant *V) const = 0;
64 virtual Constant *castToULong (const Constant *V) const = 0;
65 virtual Constant *castToFloat (const Constant *V) const = 0;
66 virtual Constant *castToDouble(const Constant *V) const = 0;
67 virtual Constant *castToPointer(const Constant *V,
68 const PointerType *Ty) const = 0;
70 // ConstRules::get - Return an instance of ConstRules for the specified
73 static ConstRules &get(const Constant *V1, const Constant *V2);
75 ConstRules(const ConstRules &); // Do not implement
76 ConstRules &operator=(const ConstRules &); // Do not implement
81 //===----------------------------------------------------------------------===//
82 // TemplateRules Class
83 //===----------------------------------------------------------------------===//
85 // TemplateRules - Implement a subclass of ConstRules that provides all
86 // operations as noops. All other rules classes inherit from this class so
87 // that if functionality is needed in the future, it can simply be added here
88 // and to ConstRules without changing anything else...
90 // This class also provides subclasses with typesafe implementations of methods
91 // so that don't have to do type casting.
94 template<class ArgType, class SubClassName>
95 class VISIBILITY_HIDDEN TemplateRules : public ConstRules {
98 //===--------------------------------------------------------------------===//
99 // Redirecting functions that cast to the appropriate types
100 //===--------------------------------------------------------------------===//
102 virtual Constant *add(const Constant *V1, const Constant *V2) const {
103 return SubClassName::Add((const ArgType *)V1, (const ArgType *)V2);
105 virtual Constant *sub(const Constant *V1, const Constant *V2) const {
106 return SubClassName::Sub((const ArgType *)V1, (const ArgType *)V2);
108 virtual Constant *mul(const Constant *V1, const Constant *V2) const {
109 return SubClassName::Mul((const ArgType *)V1, (const ArgType *)V2);
111 virtual Constant *udiv(const Constant *V1, const Constant *V2) const {
112 return SubClassName::UDiv((const ArgType *)V1, (const ArgType *)V2);
114 virtual Constant *sdiv(const Constant *V1, const Constant *V2) const {
115 return SubClassName::SDiv((const ArgType *)V1, (const ArgType *)V2);
117 virtual Constant *fdiv(const Constant *V1, const Constant *V2) const {
118 return SubClassName::FDiv((const ArgType *)V1, (const ArgType *)V2);
120 virtual Constant *rem(const Constant *V1, const Constant *V2) const {
121 return SubClassName::Rem((const ArgType *)V1, (const ArgType *)V2);
123 virtual Constant *op_and(const Constant *V1, const Constant *V2) const {
124 return SubClassName::And((const ArgType *)V1, (const ArgType *)V2);
126 virtual Constant *op_or(const Constant *V1, const Constant *V2) const {
127 return SubClassName::Or((const ArgType *)V1, (const ArgType *)V2);
129 virtual Constant *op_xor(const Constant *V1, const Constant *V2) const {
130 return SubClassName::Xor((const ArgType *)V1, (const ArgType *)V2);
132 virtual Constant *shl(const Constant *V1, const Constant *V2) const {
133 return SubClassName::Shl((const ArgType *)V1, (const ArgType *)V2);
135 virtual Constant *shr(const Constant *V1, const Constant *V2) const {
136 return SubClassName::Shr((const ArgType *)V1, (const ArgType *)V2);
139 virtual Constant *lessthan(const Constant *V1, const Constant *V2) const {
140 return SubClassName::LessThan((const ArgType *)V1, (const ArgType *)V2);
142 virtual Constant *equalto(const Constant *V1, const Constant *V2) const {
143 return SubClassName::EqualTo((const ArgType *)V1, (const ArgType *)V2);
146 // Casting operators. ick
147 virtual Constant *castToBool(const Constant *V) const {
148 return SubClassName::CastToBool((const ArgType*)V);
150 virtual Constant *castToSByte(const Constant *V) const {
151 return SubClassName::CastToSByte((const ArgType*)V);
153 virtual Constant *castToUByte(const Constant *V) const {
154 return SubClassName::CastToUByte((const ArgType*)V);
156 virtual Constant *castToShort(const Constant *V) const {
157 return SubClassName::CastToShort((const ArgType*)V);
159 virtual Constant *castToUShort(const Constant *V) const {
160 return SubClassName::CastToUShort((const ArgType*)V);
162 virtual Constant *castToInt(const Constant *V) const {
163 return SubClassName::CastToInt((const ArgType*)V);
165 virtual Constant *castToUInt(const Constant *V) const {
166 return SubClassName::CastToUInt((const ArgType*)V);
168 virtual Constant *castToLong(const Constant *V) const {
169 return SubClassName::CastToLong((const ArgType*)V);
171 virtual Constant *castToULong(const Constant *V) const {
172 return SubClassName::CastToULong((const ArgType*)V);
174 virtual Constant *castToFloat(const Constant *V) const {
175 return SubClassName::CastToFloat((const ArgType*)V);
177 virtual Constant *castToDouble(const Constant *V) const {
178 return SubClassName::CastToDouble((const ArgType*)V);
180 virtual Constant *castToPointer(const Constant *V,
181 const PointerType *Ty) const {
182 return SubClassName::CastToPointer((const ArgType*)V, Ty);
185 //===--------------------------------------------------------------------===//
186 // Default "noop" implementations
187 //===--------------------------------------------------------------------===//
189 static Constant *Add (const ArgType *V1, const ArgType *V2) { return 0; }
190 static Constant *Sub (const ArgType *V1, const ArgType *V2) { return 0; }
191 static Constant *Mul (const ArgType *V1, const ArgType *V2) { return 0; }
192 static Constant *SDiv(const ArgType *V1, const ArgType *V2) { return 0; }
193 static Constant *UDiv(const ArgType *V1, const ArgType *V2) { return 0; }
194 static Constant *FDiv(const ArgType *V1, const ArgType *V2) { return 0; }
195 static Constant *Rem (const ArgType *V1, const ArgType *V2) { return 0; }
196 static Constant *And (const ArgType *V1, const ArgType *V2) { return 0; }
197 static Constant *Or (const ArgType *V1, const ArgType *V2) { return 0; }
198 static Constant *Xor (const ArgType *V1, const ArgType *V2) { return 0; }
199 static Constant *Shl (const ArgType *V1, const ArgType *V2) { return 0; }
200 static Constant *Shr (const ArgType *V1, const ArgType *V2) { return 0; }
201 static Constant *LessThan(const ArgType *V1, const ArgType *V2) {
204 static Constant *EqualTo(const ArgType *V1, const ArgType *V2) {
208 // Casting operators. ick
209 static Constant *CastToBool (const Constant *V) { return 0; }
210 static Constant *CastToSByte (const Constant *V) { return 0; }
211 static Constant *CastToUByte (const Constant *V) { return 0; }
212 static Constant *CastToShort (const Constant *V) { return 0; }
213 static Constant *CastToUShort(const Constant *V) { return 0; }
214 static Constant *CastToInt (const Constant *V) { return 0; }
215 static Constant *CastToUInt (const Constant *V) { return 0; }
216 static Constant *CastToLong (const Constant *V) { return 0; }
217 static Constant *CastToULong (const Constant *V) { return 0; }
218 static Constant *CastToFloat (const Constant *V) { return 0; }
219 static Constant *CastToDouble(const Constant *V) { return 0; }
220 static Constant *CastToPointer(const Constant *,
221 const PointerType *) {return 0;}
224 virtual ~TemplateRules() {}
226 } // end anonymous namespace
229 //===----------------------------------------------------------------------===//
231 //===----------------------------------------------------------------------===//
233 // EmptyRules provides a concrete base class of ConstRules that does nothing
236 struct VISIBILITY_HIDDEN EmptyRules
237 : public TemplateRules<Constant, EmptyRules> {
238 static Constant *EqualTo(const Constant *V1, const Constant *V2) {
239 if (V1 == V2) return ConstantBool::getTrue();
243 } // end anonymous namespace
247 //===----------------------------------------------------------------------===//
249 //===----------------------------------------------------------------------===//
251 // BoolRules provides a concrete base class of ConstRules for the 'bool' type.
254 struct VISIBILITY_HIDDEN BoolRules
255 : public TemplateRules<ConstantBool, BoolRules> {
257 static Constant *LessThan(const ConstantBool *V1, const ConstantBool *V2) {
258 return ConstantBool::get(V1->getValue() < V2->getValue());
261 static Constant *EqualTo(const Constant *V1, const Constant *V2) {
262 return ConstantBool::get(V1 == V2);
265 static Constant *And(const ConstantBool *V1, const ConstantBool *V2) {
266 return ConstantBool::get(V1->getValue() & V2->getValue());
269 static Constant *Or(const ConstantBool *V1, const ConstantBool *V2) {
270 return ConstantBool::get(V1->getValue() | V2->getValue());
273 static Constant *Xor(const ConstantBool *V1, const ConstantBool *V2) {
274 return ConstantBool::get(V1->getValue() ^ V2->getValue());
277 // Casting operators. ick
278 #define DEF_CAST(TYPE, CLASS, CTYPE) \
279 static Constant *CastTo##TYPE (const ConstantBool *V) { \
280 return CLASS::get(Type::TYPE##Ty, (CTYPE)(bool)V->getValue()); \
283 DEF_CAST(Bool , ConstantBool, bool)
284 DEF_CAST(SByte , ConstantInt, signed char)
285 DEF_CAST(UByte , ConstantInt, unsigned char)
286 DEF_CAST(Short , ConstantInt, signed short)
287 DEF_CAST(UShort, ConstantInt, unsigned short)
288 DEF_CAST(Int , ConstantInt, signed int)
289 DEF_CAST(UInt , ConstantInt, unsigned int)
290 DEF_CAST(Long , ConstantInt, int64_t)
291 DEF_CAST(ULong , ConstantInt, uint64_t)
292 DEF_CAST(Float , ConstantFP , float)
293 DEF_CAST(Double, ConstantFP , double)
296 } // end anonymous namespace
299 //===----------------------------------------------------------------------===//
300 // NullPointerRules Class
301 //===----------------------------------------------------------------------===//
303 // NullPointerRules provides a concrete base class of ConstRules for null
307 struct VISIBILITY_HIDDEN NullPointerRules
308 : public TemplateRules<ConstantPointerNull, NullPointerRules> {
309 static Constant *EqualTo(const Constant *V1, const Constant *V2) {
310 return ConstantBool::getTrue(); // Null pointers are always equal
312 static Constant *CastToBool(const Constant *V) {
313 return ConstantBool::getFalse();
315 static Constant *CastToSByte (const Constant *V) {
316 return ConstantInt::get(Type::SByteTy, 0);
318 static Constant *CastToUByte (const Constant *V) {
319 return ConstantInt::get(Type::UByteTy, 0);
321 static Constant *CastToShort (const Constant *V) {
322 return ConstantInt::get(Type::ShortTy, 0);
324 static Constant *CastToUShort(const Constant *V) {
325 return ConstantInt::get(Type::UShortTy, 0);
327 static Constant *CastToInt (const Constant *V) {
328 return ConstantInt::get(Type::IntTy, 0);
330 static Constant *CastToUInt (const Constant *V) {
331 return ConstantInt::get(Type::UIntTy, 0);
333 static Constant *CastToLong (const Constant *V) {
334 return ConstantInt::get(Type::LongTy, 0);
336 static Constant *CastToULong (const Constant *V) {
337 return ConstantInt::get(Type::ULongTy, 0);
339 static Constant *CastToFloat (const Constant *V) {
340 return ConstantFP::get(Type::FloatTy, 0);
342 static Constant *CastToDouble(const Constant *V) {
343 return ConstantFP::get(Type::DoubleTy, 0);
346 static Constant *CastToPointer(const ConstantPointerNull *V,
347 const PointerType *PTy) {
348 return ConstantPointerNull::get(PTy);
351 } // end anonymous namespace
353 //===----------------------------------------------------------------------===//
354 // ConstantPackedRules Class
355 //===----------------------------------------------------------------------===//
357 /// DoVectorOp - Given two packed constants and a function pointer, apply the
358 /// function pointer to each element pair, producing a new ConstantPacked
360 static Constant *EvalVectorOp(const ConstantPacked *V1,
361 const ConstantPacked *V2,
362 Constant *(*FP)(Constant*, Constant*)) {
363 std::vector<Constant*> Res;
364 for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i)
365 Res.push_back(FP(const_cast<Constant*>(V1->getOperand(i)),
366 const_cast<Constant*>(V2->getOperand(i))));
367 return ConstantPacked::get(Res);
370 /// PackedTypeRules provides a concrete base class of ConstRules for
371 /// ConstantPacked operands.
374 struct VISIBILITY_HIDDEN ConstantPackedRules
375 : public TemplateRules<ConstantPacked, ConstantPackedRules> {
377 static Constant *Add(const ConstantPacked *V1, const ConstantPacked *V2) {
378 return EvalVectorOp(V1, V2, ConstantExpr::getAdd);
380 static Constant *Sub(const ConstantPacked *V1, const ConstantPacked *V2) {
381 return EvalVectorOp(V1, V2, ConstantExpr::getSub);
383 static Constant *Mul(const ConstantPacked *V1, const ConstantPacked *V2) {
384 return EvalVectorOp(V1, V2, ConstantExpr::getMul);
386 static Constant *UDiv(const ConstantPacked *V1, const ConstantPacked *V2) {
387 return EvalVectorOp(V1, V2, ConstantExpr::getUDiv);
389 static Constant *SDiv(const ConstantPacked *V1, const ConstantPacked *V2) {
390 return EvalVectorOp(V1, V2, ConstantExpr::getSDiv);
392 static Constant *FDiv(const ConstantPacked *V1, const ConstantPacked *V2) {
393 return EvalVectorOp(V1, V2, ConstantExpr::getFDiv);
395 static Constant *Rem(const ConstantPacked *V1, const ConstantPacked *V2) {
396 return EvalVectorOp(V1, V2, ConstantExpr::getRem);
398 static Constant *And(const ConstantPacked *V1, const ConstantPacked *V2) {
399 return EvalVectorOp(V1, V2, ConstantExpr::getAnd);
401 static Constant *Or (const ConstantPacked *V1, const ConstantPacked *V2) {
402 return EvalVectorOp(V1, V2, ConstantExpr::getOr);
404 static Constant *Xor(const ConstantPacked *V1, const ConstantPacked *V2) {
405 return EvalVectorOp(V1, V2, ConstantExpr::getXor);
407 static Constant *Shl(const ConstantPacked *V1, const ConstantPacked *V2) {
408 return EvalVectorOp(V1, V2, ConstantExpr::getShl);
410 static Constant *Shr(const ConstantPacked *V1, const ConstantPacked *V2) {
411 return EvalVectorOp(V1, V2, ConstantExpr::getShr);
413 static Constant *LessThan(const ConstantPacked *V1, const ConstantPacked *V2){
416 static Constant *EqualTo(const ConstantPacked *V1, const ConstantPacked *V2) {
417 for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i) {
419 ConstantExpr::getSetEQ(const_cast<Constant*>(V1->getOperand(i)),
420 const_cast<Constant*>(V2->getOperand(i)));
421 if (ConstantBool *CB = dyn_cast<ConstantBool>(C))
424 // Otherwise, could not decide from any element pairs.
428 } // end anonymous namespace
431 //===----------------------------------------------------------------------===//
432 // GeneralPackedRules Class
433 //===----------------------------------------------------------------------===//
435 /// GeneralPackedRules provides a concrete base class of ConstRules for
436 /// PackedType operands, where both operands are not ConstantPacked. The usual
437 /// cause for this is that one operand is a ConstantAggregateZero.
440 struct VISIBILITY_HIDDEN GeneralPackedRules
441 : public TemplateRules<Constant, GeneralPackedRules> {
443 } // end anonymous namespace
446 //===----------------------------------------------------------------------===//
447 // DirectIntRules Class
448 //===----------------------------------------------------------------------===//
450 // DirectIntRules provides implementations of functions that are valid on
451 // integer types, but not all types in general.
454 template <class BuiltinType, Type **Ty>
455 struct VISIBILITY_HIDDEN DirectIntRules
456 : public TemplateRules<ConstantInt, DirectIntRules<BuiltinType, Ty> > {
458 static Constant *Add(const ConstantInt *V1, const ConstantInt *V2) {
459 BuiltinType R = (BuiltinType)V1->getZExtValue() +
460 (BuiltinType)V2->getZExtValue();
461 return ConstantInt::get(*Ty, R);
464 static Constant *Sub(const ConstantInt *V1, const ConstantInt *V2) {
465 BuiltinType R = (BuiltinType)V1->getZExtValue() -
466 (BuiltinType)V2->getZExtValue();
467 return ConstantInt::get(*Ty, R);
470 static Constant *Mul(const ConstantInt *V1, const ConstantInt *V2) {
471 BuiltinType R = (BuiltinType)V1->getZExtValue() *
472 (BuiltinType)V2->getZExtValue();
473 return ConstantInt::get(*Ty, R);
476 static Constant *LessThan(const ConstantInt *V1, const ConstantInt *V2) {
477 bool R = (BuiltinType)V1->getZExtValue() < (BuiltinType)V2->getZExtValue();
478 return ConstantBool::get(R);
481 static Constant *EqualTo(const ConstantInt *V1, const ConstantInt *V2) {
482 bool R = (BuiltinType)V1->getZExtValue() == (BuiltinType)V2->getZExtValue();
483 return ConstantBool::get(R);
486 static Constant *CastToPointer(const ConstantInt *V,
487 const PointerType *PTy) {
488 if (V->isNullValue()) // Is it a FP or Integral null value?
489 return ConstantPointerNull::get(PTy);
490 return 0; // Can't const prop other types of pointers
493 // Casting operators. ick
494 #define DEF_CAST(TYPE, CLASS, CTYPE) \
495 static Constant *CastTo##TYPE (const ConstantInt *V) { \
496 return CLASS::get(Type::TYPE##Ty, (CTYPE)(BuiltinType)V->getZExtValue()); \
499 DEF_CAST(Bool , ConstantBool, bool)
500 DEF_CAST(SByte , ConstantInt, signed char)
501 DEF_CAST(UByte , ConstantInt, unsigned char)
502 DEF_CAST(Short , ConstantInt, signed short)
503 DEF_CAST(UShort, ConstantInt, unsigned short)
504 DEF_CAST(Int , ConstantInt, signed int)
505 DEF_CAST(UInt , ConstantInt, unsigned int)
506 DEF_CAST(Long , ConstantInt, int64_t)
507 DEF_CAST(ULong , ConstantInt, uint64_t)
508 DEF_CAST(Float , ConstantFP , float)
509 DEF_CAST(Double, ConstantFP , double)
512 static Constant *UDiv(const ConstantInt *V1, const ConstantInt *V2) {
513 if (V2->isNullValue())
515 BuiltinType R = (BuiltinType)(V1->getZExtValue() / V2->getZExtValue());
516 return ConstantInt::get(*Ty, R);
519 static Constant *SDiv(const ConstantInt *V1, const ConstantInt *V2) {
520 if (V2->isNullValue())
522 if (V2->isAllOnesValue() && // MIN_INT / -1
523 (BuiltinType)V1->getSExtValue() == -(BuiltinType)V1->getSExtValue())
526 (BuiltinType)(V1->getSExtValue() / V2->getSExtValue());
527 return ConstantInt::get(*Ty, R);
530 static Constant *Rem(const ConstantInt *V1, const ConstantInt *V2) {
531 if (V2->isNullValue()) return 0; // X / 0
532 if (V2->isAllOnesValue() && // MIN_INT / -1
533 (BuiltinType)V1->getZExtValue() == -(BuiltinType)V1->getZExtValue())
536 (BuiltinType)V1->getZExtValue() % (BuiltinType)V2->getZExtValue();
537 return ConstantInt::get(*Ty, R);
540 static Constant *And(const ConstantInt *V1, const ConstantInt *V2) {
542 (BuiltinType)V1->getZExtValue() & (BuiltinType)V2->getZExtValue();
543 return ConstantInt::get(*Ty, R);
545 static Constant *Or(const ConstantInt *V1, const ConstantInt *V2) {
547 (BuiltinType)V1->getZExtValue() | (BuiltinType)V2->getZExtValue();
548 return ConstantInt::get(*Ty, R);
550 static Constant *Xor(const ConstantInt *V1, const ConstantInt *V2) {
552 (BuiltinType)V1->getZExtValue() ^ (BuiltinType)V2->getZExtValue();
553 return ConstantInt::get(*Ty, R);
556 static Constant *Shl(const ConstantInt *V1, const ConstantInt *V2) {
558 (BuiltinType)V1->getZExtValue() << (BuiltinType)V2->getZExtValue();
559 return ConstantInt::get(*Ty, R);
562 static Constant *Shr(const ConstantInt *V1, const ConstantInt *V2) {
564 (BuiltinType)V1->getZExtValue() >> (BuiltinType)V2->getZExtValue();
565 return ConstantInt::get(*Ty, R);
568 } // end anonymous namespace
571 //===----------------------------------------------------------------------===//
572 // DirectFPRules Class
573 //===----------------------------------------------------------------------===//
575 /// DirectFPRules provides implementations of functions that are valid on
576 /// floating point types, but not all types in general.
579 template <class BuiltinType, Type **Ty>
580 struct VISIBILITY_HIDDEN DirectFPRules
581 : public TemplateRules<ConstantFP, DirectFPRules<BuiltinType, Ty> > {
583 static Constant *Add(const ConstantFP *V1, const ConstantFP *V2) {
584 BuiltinType R = (BuiltinType)V1->getValue() +
585 (BuiltinType)V2->getValue();
586 return ConstantFP::get(*Ty, R);
589 static Constant *Sub(const ConstantFP *V1, const ConstantFP *V2) {
590 BuiltinType R = (BuiltinType)V1->getValue() - (BuiltinType)V2->getValue();
591 return ConstantFP::get(*Ty, R);
594 static Constant *Mul(const ConstantFP *V1, const ConstantFP *V2) {
595 BuiltinType R = (BuiltinType)V1->getValue() * (BuiltinType)V2->getValue();
596 return ConstantFP::get(*Ty, R);
599 static Constant *LessThan(const ConstantFP *V1, const ConstantFP *V2) {
600 bool R = (BuiltinType)V1->getValue() < (BuiltinType)V2->getValue();
601 return ConstantBool::get(R);
604 static Constant *EqualTo(const ConstantFP *V1, const ConstantFP *V2) {
605 bool R = (BuiltinType)V1->getValue() == (BuiltinType)V2->getValue();
606 return ConstantBool::get(R);
609 static Constant *CastToPointer(const ConstantFP *V,
610 const PointerType *PTy) {
611 if (V->isNullValue()) // Is it a FP or Integral null value?
612 return ConstantPointerNull::get(PTy);
613 return 0; // Can't const prop other types of pointers
616 // Casting operators. ick
617 #define DEF_CAST(TYPE, CLASS, CTYPE) \
618 static Constant *CastTo##TYPE (const ConstantFP *V) { \
619 return CLASS::get(Type::TYPE##Ty, (CTYPE)(BuiltinType)V->getValue()); \
622 DEF_CAST(Bool , ConstantBool, bool)
623 DEF_CAST(SByte , ConstantInt, signed char)
624 DEF_CAST(UByte , ConstantInt, unsigned char)
625 DEF_CAST(Short , ConstantInt, signed short)
626 DEF_CAST(UShort, ConstantInt, unsigned short)
627 DEF_CAST(Int , ConstantInt, signed int)
628 DEF_CAST(UInt , ConstantInt, unsigned int)
629 DEF_CAST(Long , ConstantInt, int64_t)
630 DEF_CAST(ULong , ConstantInt, uint64_t)
631 DEF_CAST(Float , ConstantFP , float)
632 DEF_CAST(Double, ConstantFP , double)
635 static Constant *Rem(const ConstantFP *V1, const ConstantFP *V2) {
636 if (V2->isNullValue()) return 0;
637 BuiltinType Result = std::fmod((BuiltinType)V1->getValue(),
638 (BuiltinType)V2->getValue());
639 return ConstantFP::get(*Ty, Result);
641 static Constant *FDiv(const ConstantFP *V1, const ConstantFP *V2) {
642 BuiltinType inf = std::numeric_limits<BuiltinType>::infinity();
643 if (V2->isExactlyValue(0.0)) return ConstantFP::get(*Ty, inf);
644 if (V2->isExactlyValue(-0.0)) return ConstantFP::get(*Ty, -inf);
645 BuiltinType R = (BuiltinType)V1->getValue() / (BuiltinType)V2->getValue();
646 return ConstantFP::get(*Ty, R);
649 } // end anonymous namespace
651 static ManagedStatic<EmptyRules> EmptyR;
652 static ManagedStatic<BoolRules> BoolR;
653 static ManagedStatic<NullPointerRules> NullPointerR;
654 static ManagedStatic<ConstantPackedRules> ConstantPackedR;
655 static ManagedStatic<GeneralPackedRules> GeneralPackedR;
656 static ManagedStatic<DirectIntRules<signed char , &Type::SByteTy> > SByteR;
657 static ManagedStatic<DirectIntRules<unsigned char , &Type::UByteTy> > UByteR;
658 static ManagedStatic<DirectIntRules<signed short , &Type::ShortTy> > ShortR;
659 static ManagedStatic<DirectIntRules<unsigned short, &Type::UShortTy> > UShortR;
660 static ManagedStatic<DirectIntRules<signed int , &Type::IntTy> > IntR;
661 static ManagedStatic<DirectIntRules<unsigned int , &Type::UIntTy> > UIntR;
662 static ManagedStatic<DirectIntRules<int64_t , &Type::LongTy> > LongR;
663 static ManagedStatic<DirectIntRules<uint64_t , &Type::ULongTy> > ULongR;
664 static ManagedStatic<DirectFPRules <float , &Type::FloatTy> > FloatR;
665 static ManagedStatic<DirectFPRules <double , &Type::DoubleTy> > DoubleR;
667 /// ConstRules::get - This method returns the constant rules implementation that
668 /// implements the semantics of the two specified constants.
669 ConstRules &ConstRules::get(const Constant *V1, const Constant *V2) {
670 if (isa<ConstantExpr>(V1) || isa<ConstantExpr>(V2) ||
671 isa<GlobalValue>(V1) || isa<GlobalValue>(V2) ||
672 isa<UndefValue>(V1) || isa<UndefValue>(V2))
675 switch (V1->getType()->getTypeID()) {
676 default: assert(0 && "Unknown value type for constant folding!");
677 case Type::BoolTyID: return *BoolR;
678 case Type::PointerTyID: return *NullPointerR;
679 case Type::SByteTyID: return *SByteR;
680 case Type::UByteTyID: return *UByteR;
681 case Type::ShortTyID: return *ShortR;
682 case Type::UShortTyID: return *UShortR;
683 case Type::IntTyID: return *IntR;
684 case Type::UIntTyID: return *UIntR;
685 case Type::LongTyID: return *LongR;
686 case Type::ULongTyID: return *ULongR;
687 case Type::FloatTyID: return *FloatR;
688 case Type::DoubleTyID: return *DoubleR;
689 case Type::PackedTyID:
690 if (isa<ConstantPacked>(V1) && isa<ConstantPacked>(V2))
691 return *ConstantPackedR;
692 return *GeneralPackedR; // Constant folding rules for ConstantAggregateZero.
697 //===----------------------------------------------------------------------===//
698 // ConstantFold*Instruction Implementations
699 //===----------------------------------------------------------------------===//
701 // These methods contain the special case hackery required to symbolically
702 // evaluate some constant expression cases, and use the ConstantRules class to
703 // evaluate normal constants.
705 static unsigned getSize(const Type *Ty) {
706 unsigned S = Ty->getPrimitiveSize();
707 return S ? S : 8; // Treat pointers at 8 bytes
710 /// CastConstantPacked - Convert the specified ConstantPacked node to the
711 /// specified packed type. At this point, we know that the elements of the
712 /// input packed constant are all simple integer or FP values.
713 static Constant *CastConstantPacked(ConstantPacked *CP,
714 const PackedType *DstTy) {
715 unsigned SrcNumElts = CP->getType()->getNumElements();
716 unsigned DstNumElts = DstTy->getNumElements();
717 const Type *SrcEltTy = CP->getType()->getElementType();
718 const Type *DstEltTy = DstTy->getElementType();
720 // If both vectors have the same number of elements (thus, the elements
721 // are the same size), perform the conversion now.
722 if (SrcNumElts == DstNumElts) {
723 std::vector<Constant*> Result;
725 // If the src and dest elements are both integers, just cast each one
726 // which will do the appropriate bit-convert.
727 if (SrcEltTy->isIntegral() && DstEltTy->isIntegral()) {
728 for (unsigned i = 0; i != SrcNumElts; ++i)
729 Result.push_back(ConstantExpr::getCast(CP->getOperand(i),
731 return ConstantPacked::get(Result);
734 if (SrcEltTy->isIntegral()) {
735 // Otherwise, this is an int-to-fp cast.
736 assert(DstEltTy->isFloatingPoint());
737 if (DstEltTy->getTypeID() == Type::DoubleTyID) {
738 for (unsigned i = 0; i != SrcNumElts; ++i) {
740 BitsToDouble(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
741 Result.push_back(ConstantFP::get(Type::DoubleTy, V));
743 return ConstantPacked::get(Result);
745 assert(DstEltTy == Type::FloatTy && "Unknown fp type!");
746 for (unsigned i = 0; i != SrcNumElts; ++i) {
748 BitsToFloat(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
749 Result.push_back(ConstantFP::get(Type::FloatTy, V));
751 return ConstantPacked::get(Result);
754 // Otherwise, this is an fp-to-int cast.
755 assert(SrcEltTy->isFloatingPoint() && DstEltTy->isIntegral());
757 if (SrcEltTy->getTypeID() == Type::DoubleTyID) {
758 for (unsigned i = 0; i != SrcNumElts; ++i) {
760 DoubleToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
761 Constant *C = ConstantInt::get(Type::ULongTy, V);
762 Result.push_back(ConstantExpr::getCast(C, DstEltTy));
764 return ConstantPacked::get(Result);
767 assert(SrcEltTy->getTypeID() == Type::FloatTyID);
768 for (unsigned i = 0; i != SrcNumElts; ++i) {
769 uint32_t V = FloatToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
770 Constant *C = ConstantInt::get(Type::UIntTy, V);
771 Result.push_back(ConstantExpr::getCast(C, DstEltTy));
773 return ConstantPacked::get(Result);
776 // Otherwise, this is a cast that changes element count and size. Handle
777 // casts which shrink the elements here.
779 // FIXME: We need to know endianness to do this!
785 Constant *llvm::ConstantFoldCastInstruction(const Constant *V,
786 const Type *DestTy) {
787 if (V->getType() == DestTy) return (Constant*)V;
789 // Cast of a global address to boolean is always true.
790 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
791 if (DestTy == Type::BoolTy)
792 // FIXME: When we support 'external weak' references, we have to prevent
793 // this transformation from happening. This code will need to be updated
794 // to ignore external weak symbols when we support it.
795 return ConstantBool::getTrue();
796 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
797 if (CE->getOpcode() == Instruction::Cast) {
798 Constant *Op = const_cast<Constant*>(CE->getOperand(0));
799 // Try to not produce a cast of a cast, which is almost always redundant.
800 if (!Op->getType()->isFloatingPoint() &&
801 !CE->getType()->isFloatingPoint() &&
802 !DestTy->isFloatingPoint()) {
803 unsigned S1 = getSize(Op->getType()), S2 = getSize(CE->getType());
804 unsigned S3 = getSize(DestTy);
805 if (Op->getType() == DestTy && S3 >= S2)
807 if (S1 >= S2 && S2 >= S3)
808 return ConstantExpr::getCast(Op, DestTy);
809 if (S1 <= S2 && S2 >= S3 && S1 <= S3)
810 return ConstantExpr::getCast(Op, DestTy);
812 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
813 // If all of the indexes in the GEP are null values, there is no pointer
814 // adjustment going on. We might as well cast the source pointer.
815 bool isAllNull = true;
816 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
817 if (!CE->getOperand(i)->isNullValue()) {
822 return ConstantExpr::getCast(CE->getOperand(0), DestTy);
824 } else if (isa<UndefValue>(V)) {
825 return UndefValue::get(DestTy);
828 // Check to see if we are casting an pointer to an aggregate to a pointer to
829 // the first element. If so, return the appropriate GEP instruction.
830 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
831 if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
832 std::vector<Value*> IdxList;
833 IdxList.push_back(Constant::getNullValue(Type::IntTy));
834 const Type *ElTy = PTy->getElementType();
835 while (ElTy != DPTy->getElementType()) {
836 if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
837 if (STy->getNumElements() == 0) break;
838 ElTy = STy->getElementType(0);
839 IdxList.push_back(Constant::getNullValue(Type::UIntTy));
840 } else if (const SequentialType *STy = dyn_cast<SequentialType>(ElTy)) {
841 if (isa<PointerType>(ElTy)) break; // Can't index into pointers!
842 ElTy = STy->getElementType();
843 IdxList.push_back(IdxList[0]);
849 if (ElTy == DPTy->getElementType())
850 return ConstantExpr::getGetElementPtr(const_cast<Constant*>(V),IdxList);
853 // Handle casts from one packed constant to another. We know that the src and
854 // dest type have the same size.
855 if (const PackedType *DestPTy = dyn_cast<PackedType>(DestTy)) {
856 if (const PackedType *SrcTy = dyn_cast<PackedType>(V->getType())) {
857 assert(DestPTy->getElementType()->getPrimitiveSizeInBits() *
858 DestPTy->getNumElements() ==
859 SrcTy->getElementType()->getPrimitiveSizeInBits() *
860 SrcTy->getNumElements() && "Not cast between same sized vectors!");
861 if (isa<ConstantAggregateZero>(V))
862 return Constant::getNullValue(DestTy);
863 if (isa<UndefValue>(V))
864 return UndefValue::get(DestTy);
865 if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
866 // This is a cast from a ConstantPacked of one type to a ConstantPacked
867 // of another type. Check to see if all elements of the input are
869 bool AllSimpleConstants = true;
870 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
871 if (!isa<ConstantInt>(CP->getOperand(i)) &&
872 !isa<ConstantFP>(CP->getOperand(i))) {
873 AllSimpleConstants = false;
878 // If all of the elements are simple constants, we can fold this.
879 if (AllSimpleConstants)
880 return CastConstantPacked(const_cast<ConstantPacked*>(CP), DestPTy);
885 ConstRules &Rules = ConstRules::get(V, V);
887 switch (DestTy->getTypeID()) {
888 case Type::BoolTyID: return Rules.castToBool(V);
889 case Type::UByteTyID: return Rules.castToUByte(V);
890 case Type::SByteTyID: return Rules.castToSByte(V);
891 case Type::UShortTyID: return Rules.castToUShort(V);
892 case Type::ShortTyID: return Rules.castToShort(V);
893 case Type::UIntTyID: return Rules.castToUInt(V);
894 case Type::IntTyID: return Rules.castToInt(V);
895 case Type::ULongTyID: return Rules.castToULong(V);
896 case Type::LongTyID: return Rules.castToLong(V);
897 case Type::FloatTyID: return Rules.castToFloat(V);
898 case Type::DoubleTyID: return Rules.castToDouble(V);
899 case Type::PointerTyID:
900 return Rules.castToPointer(V, cast<PointerType>(DestTy));
905 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
907 const Constant *V2) {
908 if (const ConstantBool *CB = dyn_cast<ConstantBool>(Cond))
909 return const_cast<Constant*>(CB->getValue() ? V1 : V2);
911 if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
912 if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
913 if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
914 if (V1 == V2) return const_cast<Constant*>(V1);
918 Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
919 const Constant *Idx) {
920 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef
921 return UndefValue::get(cast<PackedType>(Val->getType())->getElementType());
922 if (Val->isNullValue()) // ee(zero, x) -> zero
923 return Constant::getNullValue(
924 cast<PackedType>(Val->getType())->getElementType());
926 if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
927 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
928 return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
929 } else if (isa<UndefValue>(Idx)) {
930 // ee({w,x,y,z}, undef) -> w (an arbitrary value).
931 return const_cast<Constant*>(CVal->getOperand(0));
937 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
939 const Constant *Idx) {
940 const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
942 uint64_t idxVal = CIdx->getZExtValue();
943 if (const UndefValue *UVal = dyn_cast<UndefValue>(Val)) {
944 // Insertion of scalar constant into packed undef
945 // Optimize away insertion of undef
946 if (isa<UndefValue>(Elt))
947 return const_cast<Constant*>(Val);
948 // Otherwise break the aggregate undef into multiple undefs and do
951 cast<PackedType>(Val->getType())->getNumElements();
952 std::vector<Constant*> Ops;
954 for (unsigned i = 0; i < numOps; ++i) {
956 (i == idxVal) ? Elt : UndefValue::get(Elt->getType());
957 Ops.push_back(const_cast<Constant*>(Op));
959 return ConstantPacked::get(Ops);
961 if (const ConstantAggregateZero *CVal =
962 dyn_cast<ConstantAggregateZero>(Val)) {
963 // Insertion of scalar constant into packed aggregate zero
964 // Optimize away insertion of zero
965 if (Elt->isNullValue())
966 return const_cast<Constant*>(Val);
967 // Otherwise break the aggregate zero into multiple zeros and do
970 cast<PackedType>(Val->getType())->getNumElements();
971 std::vector<Constant*> Ops;
973 for (unsigned i = 0; i < numOps; ++i) {
975 (i == idxVal) ? Elt : Constant::getNullValue(Elt->getType());
976 Ops.push_back(const_cast<Constant*>(Op));
978 return ConstantPacked::get(Ops);
980 if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
981 // Insertion of scalar constant into packed constant
982 std::vector<Constant*> Ops;
983 Ops.reserve(CVal->getNumOperands());
984 for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
986 (i == idxVal) ? Elt : cast<Constant>(CVal->getOperand(i));
987 Ops.push_back(const_cast<Constant*>(Op));
989 return ConstantPacked::get(Ops);
994 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
996 const Constant *Mask) {
1002 /// isZeroSizedType - This type is zero sized if its an array or structure of
1003 /// zero sized types. The only leaf zero sized type is an empty structure.
1004 static bool isMaybeZeroSizedType(const Type *Ty) {
1005 if (isa<OpaqueType>(Ty)) return true; // Can't say.
1006 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1008 // If all of elements have zero size, this does too.
1009 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1010 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1013 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1014 return isMaybeZeroSizedType(ATy->getElementType());
1019 /// IdxCompare - Compare the two constants as though they were getelementptr
1020 /// indices. This allows coersion of the types to be the same thing.
1022 /// If the two constants are the "same" (after coersion), return 0. If the
1023 /// first is less than the second, return -1, if the second is less than the
1024 /// first, return 1. If the constants are not integral, return -2.
1026 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
1027 if (C1 == C2) return 0;
1029 // Ok, we found a different index. Are either of the operands
1030 // ConstantExprs? If so, we can't do anything with them.
1031 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1032 return -2; // don't know!
1034 // Ok, we have two differing integer indices. Sign extend them to be the same
1035 // type. Long is always big enough, so we use it.
1036 C1 = ConstantExpr::getSignExtend(C1, Type::LongTy);
1037 C2 = ConstantExpr::getSignExtend(C2, Type::LongTy);
1038 if (C1 == C2) return 0; // Are they just differing types?
1040 // If the type being indexed over is really just a zero sized type, there is
1041 // no pointer difference being made here.
1042 if (isMaybeZeroSizedType(ElTy))
1043 return -2; // dunno.
1045 // If they are really different, now that they are the same type, then we
1046 // found a difference!
1047 if (cast<ConstantInt>(C1)->getSExtValue() <
1048 cast<ConstantInt>(C2)->getSExtValue())
1054 /// evaluateRelation - This function determines if there is anything we can
1055 /// decide about the two constants provided. This doesn't need to handle simple
1056 /// things like integer comparisons, but should instead handle ConstantExprs
1057 /// and GlobalValuess. If we can determine that the two constants have a
1058 /// particular relation to each other, we should return the corresponding SetCC
1059 /// code, otherwise return Instruction::BinaryOpsEnd.
1061 /// To simplify this code we canonicalize the relation so that the first
1062 /// operand is always the most "complex" of the two. We consider simple
1063 /// constants (like ConstantInt) to be the simplest, followed by
1064 /// GlobalValues, followed by ConstantExpr's (the most complex).
1066 static Instruction::BinaryOps evaluateRelation(Constant *V1, Constant *V2) {
1067 assert(V1->getType() == V2->getType() &&
1068 "Cannot compare different types of values!");
1069 if (V1 == V2) return Instruction::SetEQ;
1071 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
1072 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
1073 // We distilled this down to a simple case, use the standard constant
1075 ConstantBool *R = dyn_cast<ConstantBool>(ConstantExpr::getSetEQ(V1, V2));
1076 if (R && R->getValue()) return Instruction::SetEQ;
1077 R = dyn_cast<ConstantBool>(ConstantExpr::getSetLT(V1, V2));
1078 if (R && R->getValue()) return Instruction::SetLT;
1079 R = dyn_cast<ConstantBool>(ConstantExpr::getSetGT(V1, V2));
1080 if (R && R->getValue()) return Instruction::SetGT;
1082 // If we couldn't figure it out, bail.
1083 return Instruction::BinaryOpsEnd;
1086 // If the first operand is simple, swap operands.
1087 Instruction::BinaryOps SwappedRelation = evaluateRelation(V2, V1);
1088 if (SwappedRelation != Instruction::BinaryOpsEnd)
1089 return SetCondInst::getSwappedCondition(SwappedRelation);
1091 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
1092 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1093 Instruction::BinaryOps SwappedRelation = evaluateRelation(V2, V1);
1094 if (SwappedRelation != Instruction::BinaryOpsEnd)
1095 return SetCondInst::getSwappedCondition(SwappedRelation);
1097 return Instruction::BinaryOpsEnd;
1100 // Now we know that the RHS is a GlobalValue or simple constant,
1101 // which (since the types must match) means that it's a ConstantPointerNull.
1102 if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1103 assert(CPR1 != CPR2 &&
1104 "GVs for the same value exist at different addresses??");
1105 // FIXME: If both globals are external weak, they might both be null!
1106 return Instruction::SetNE;
1108 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1109 // Global can never be null. FIXME: if we implement external weak
1110 // linkage, this is not necessarily true!
1111 return Instruction::SetNE;
1115 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1116 // constantexpr, a CPR, or a simple constant.
1117 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1118 Constant *CE1Op0 = CE1->getOperand(0);
1120 switch (CE1->getOpcode()) {
1121 case Instruction::Cast:
1122 // If the cast is not actually changing bits, and the second operand is a
1123 // null pointer, do the comparison with the pre-casted value.
1124 if (V2->isNullValue() &&
1125 (isa<PointerType>(CE1->getType()) || CE1->getType()->isIntegral()))
1126 return evaluateRelation(CE1Op0,
1127 Constant::getNullValue(CE1Op0->getType()));
1129 // If the dest type is a pointer type, and the RHS is a constantexpr cast
1130 // from the same type as the src of the LHS, evaluate the inputs. This is
1131 // important for things like "seteq (cast 4 to int*), (cast 5 to int*)",
1132 // which happens a lot in compilers with tagged integers.
1133 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
1134 if (isa<PointerType>(CE1->getType()) &&
1135 CE2->getOpcode() == Instruction::Cast &&
1136 CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
1137 CE1->getOperand(0)->getType()->isIntegral()) {
1138 return evaluateRelation(CE1->getOperand(0), CE2->getOperand(0));
1142 case Instruction::GetElementPtr:
1143 // Ok, since this is a getelementptr, we know that the constant has a
1144 // pointer type. Check the various cases.
1145 if (isa<ConstantPointerNull>(V2)) {
1146 // If we are comparing a GEP to a null pointer, check to see if the base
1147 // of the GEP equals the null pointer.
1148 if (isa<GlobalValue>(CE1Op0)) {
1149 // FIXME: this is not true when we have external weak references!
1150 // No offset can go from a global to a null pointer.
1151 return Instruction::SetGT;
1152 } else if (isa<ConstantPointerNull>(CE1Op0)) {
1153 // If we are indexing from a null pointer, check to see if we have any
1154 // non-zero indices.
1155 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1156 if (!CE1->getOperand(i)->isNullValue())
1157 // Offsetting from null, must not be equal.
1158 return Instruction::SetGT;
1159 // Only zero indexes from null, must still be zero.
1160 return Instruction::SetEQ;
1162 // Otherwise, we can't really say if the first operand is null or not.
1163 } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1164 if (isa<ConstantPointerNull>(CE1Op0)) {
1165 // FIXME: This is not true with external weak references.
1166 return Instruction::SetLT;
1167 } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1169 // If this is a getelementptr of the same global, then it must be
1170 // different. Because the types must match, the getelementptr could
1171 // only have at most one index, and because we fold getelementptr's
1172 // with a single zero index, it must be nonzero.
1173 assert(CE1->getNumOperands() == 2 &&
1174 !CE1->getOperand(1)->isNullValue() &&
1175 "Suprising getelementptr!");
1176 return Instruction::SetGT;
1178 // If they are different globals, we don't know what the value is,
1179 // but they can't be equal.
1180 return Instruction::SetNE;
1184 const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1185 const Constant *CE2Op0 = CE2->getOperand(0);
1187 // There are MANY other foldings that we could perform here. They will
1188 // probably be added on demand, as they seem needed.
1189 switch (CE2->getOpcode()) {
1191 case Instruction::GetElementPtr:
1192 // By far the most common case to handle is when the base pointers are
1193 // obviously to the same or different globals.
1194 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1195 if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1196 return Instruction::SetNE;
1197 // Ok, we know that both getelementptr instructions are based on the
1198 // same global. From this, we can precisely determine the relative
1199 // ordering of the resultant pointers.
1202 // Compare all of the operands the GEP's have in common.
1203 gep_type_iterator GTI = gep_type_begin(CE1);
1204 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1206 switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1207 GTI.getIndexedType())) {
1208 case -1: return Instruction::SetLT;
1209 case 1: return Instruction::SetGT;
1210 case -2: return Instruction::BinaryOpsEnd;
1213 // Ok, we ran out of things they have in common. If any leftovers
1214 // are non-zero then we have a difference, otherwise we are equal.
1215 for (; i < CE1->getNumOperands(); ++i)
1216 if (!CE1->getOperand(i)->isNullValue())
1217 if (isa<ConstantIntegral>(CE1->getOperand(i)))
1218 return Instruction::SetGT;
1220 return Instruction::BinaryOpsEnd; // Might be equal.
1222 for (; i < CE2->getNumOperands(); ++i)
1223 if (!CE2->getOperand(i)->isNullValue())
1224 if (isa<ConstantIntegral>(CE2->getOperand(i)))
1225 return Instruction::SetLT;
1227 return Instruction::BinaryOpsEnd; // Might be equal.
1228 return Instruction::SetEQ;
1238 return Instruction::BinaryOpsEnd;
1241 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
1243 const Constant *V2) {
1247 case Instruction::Add: C = ConstRules::get(V1, V2).add(V1, V2); break;
1248 case Instruction::Sub: C = ConstRules::get(V1, V2).sub(V1, V2); break;
1249 case Instruction::Mul: C = ConstRules::get(V1, V2).mul(V1, V2); break;
1250 case Instruction::UDiv: C = ConstRules::get(V1, V2).udiv(V1, V2); break;
1251 case Instruction::SDiv: C = ConstRules::get(V1, V2).sdiv(V1, V2); break;
1252 case Instruction::FDiv: C = ConstRules::get(V1, V2).fdiv(V1, V2); break;
1253 case Instruction::Rem: C = ConstRules::get(V1, V2).rem(V1, V2); break;
1254 case Instruction::And: C = ConstRules::get(V1, V2).op_and(V1, V2); break;
1255 case Instruction::Or: C = ConstRules::get(V1, V2).op_or (V1, V2); break;
1256 case Instruction::Xor: C = ConstRules::get(V1, V2).op_xor(V1, V2); break;
1257 case Instruction::Shl: C = ConstRules::get(V1, V2).shl(V1, V2); break;
1258 case Instruction::Shr: C = ConstRules::get(V1, V2).shr(V1, V2); break;
1259 case Instruction::SetEQ: C = ConstRules::get(V1, V2).equalto(V1, V2); break;
1260 case Instruction::SetLT: C = ConstRules::get(V1, V2).lessthan(V1, V2);break;
1261 case Instruction::SetGT: C = ConstRules::get(V1, V2).lessthan(V2, V1);break;
1262 case Instruction::SetNE: // V1 != V2 === !(V1 == V2)
1263 C = ConstRules::get(V1, V2).equalto(V1, V2);
1264 if (C) return ConstantExpr::getNot(C);
1266 case Instruction::SetLE: // V1 <= V2 === !(V2 < V1)
1267 C = ConstRules::get(V1, V2).lessthan(V2, V1);
1268 if (C) return ConstantExpr::getNot(C);
1270 case Instruction::SetGE: // V1 >= V2 === !(V1 < V2)
1271 C = ConstRules::get(V1, V2).lessthan(V1, V2);
1272 if (C) return ConstantExpr::getNot(C);
1276 // If we successfully folded the expression, return it now.
1279 if (SetCondInst::isComparison(Opcode)) {
1280 if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1281 return UndefValue::get(Type::BoolTy);
1282 switch (evaluateRelation(const_cast<Constant*>(V1),
1283 const_cast<Constant*>(V2))) {
1284 default: assert(0 && "Unknown relational!");
1285 case Instruction::BinaryOpsEnd:
1286 break; // Couldn't determine anything about these constants.
1287 case Instruction::SetEQ: // We know the constants are equal!
1288 // If we know the constants are equal, we can decide the result of this
1289 // computation precisely.
1290 return ConstantBool::get(Opcode == Instruction::SetEQ ||
1291 Opcode == Instruction::SetLE ||
1292 Opcode == Instruction::SetGE);
1293 case Instruction::SetLT:
1294 // If we know that V1 < V2, we can decide the result of this computation
1296 return ConstantBool::get(Opcode == Instruction::SetLT ||
1297 Opcode == Instruction::SetNE ||
1298 Opcode == Instruction::SetLE);
1299 case Instruction::SetGT:
1300 // If we know that V1 > V2, we can decide the result of this computation
1302 return ConstantBool::get(Opcode == Instruction::SetGT ||
1303 Opcode == Instruction::SetNE ||
1304 Opcode == Instruction::SetGE);
1305 case Instruction::SetLE:
1306 // If we know that V1 <= V2, we can only partially decide this relation.
1307 if (Opcode == Instruction::SetGT) return ConstantBool::getFalse();
1308 if (Opcode == Instruction::SetLT) return ConstantBool::getTrue();
1311 case Instruction::SetGE:
1312 // If we know that V1 >= V2, we can only partially decide this relation.
1313 if (Opcode == Instruction::SetLT) return ConstantBool::getFalse();
1314 if (Opcode == Instruction::SetGT) return ConstantBool::getTrue();
1317 case Instruction::SetNE:
1318 // If we know that V1 != V2, we can only partially decide this relation.
1319 if (Opcode == Instruction::SetEQ) return ConstantBool::getFalse();
1320 if (Opcode == Instruction::SetNE) return ConstantBool::getTrue();
1325 if (isa<UndefValue>(V1) || isa<UndefValue>(V2)) {
1327 case Instruction::Add:
1328 case Instruction::Sub:
1329 case Instruction::Xor:
1330 return UndefValue::get(V1->getType());
1332 case Instruction::Mul:
1333 case Instruction::And:
1334 return Constant::getNullValue(V1->getType());
1335 case Instruction::UDiv:
1336 case Instruction::SDiv:
1337 case Instruction::FDiv:
1338 case Instruction::Rem:
1339 if (!isa<UndefValue>(V2)) // undef/X -> 0
1340 return Constant::getNullValue(V1->getType());
1341 return const_cast<Constant*>(V2); // X/undef -> undef
1342 case Instruction::Or: // X|undef -> -1
1343 return ConstantInt::getAllOnesValue(V1->getType());
1344 case Instruction::Shr:
1345 if (!isa<UndefValue>(V2)) {
1346 if (V1->getType()->isSigned())
1347 return const_cast<Constant*>(V1); // undef >>s X -> undef
1349 } else if (isa<UndefValue>(V1)) {
1350 return const_cast<Constant*>(V1); // undef >> undef -> undef
1352 if (V1->getType()->isSigned())
1353 return const_cast<Constant*>(V1); // X >>s undef -> X
1356 return Constant::getNullValue(V1->getType());
1358 case Instruction::Shl:
1359 // undef << X -> 0 X << undef -> 0
1360 return Constant::getNullValue(V1->getType());
1364 if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(V1)) {
1365 if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2)) {
1366 // There are many possible foldings we could do here. We should probably
1367 // at least fold add of a pointer with an integer into the appropriate
1368 // getelementptr. This will improve alias analysis a bit.
1374 // Just implement a couple of simple identities.
1376 case Instruction::Add:
1377 if (V2->isNullValue()) return const_cast<Constant*>(V1); // X + 0 == X
1379 case Instruction::Sub:
1380 if (V2->isNullValue()) return const_cast<Constant*>(V1); // X - 0 == X
1382 case Instruction::Mul:
1383 if (V2->isNullValue()) return const_cast<Constant*>(V2); // X * 0 == 0
1384 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1385 if (CI->getZExtValue() == 1)
1386 return const_cast<Constant*>(V1); // X * 1 == X
1388 case Instruction::UDiv:
1389 case Instruction::SDiv:
1390 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1391 if (CI->getZExtValue() == 1)
1392 return const_cast<Constant*>(V1); // X / 1 == X
1394 case Instruction::Rem:
1395 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1396 if (CI->getZExtValue() == 1)
1397 return Constant::getNullValue(CI->getType()); // X % 1 == 0
1399 case Instruction::And:
1400 if (cast<ConstantIntegral>(V2)->isAllOnesValue())
1401 return const_cast<Constant*>(V1); // X & -1 == X
1402 if (V2->isNullValue()) return const_cast<Constant*>(V2); // X & 0 == 0
1403 if (CE1->getOpcode() == Instruction::Cast &&
1404 isa<GlobalValue>(CE1->getOperand(0))) {
1405 GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
1407 // Functions are at least 4-byte aligned. If and'ing the address of a
1408 // function with a constant < 4, fold it to zero.
1409 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1410 if (CI->getZExtValue() < 4 && isa<Function>(CPR))
1411 return Constant::getNullValue(CI->getType());
1414 case Instruction::Or:
1415 if (V2->isNullValue()) return const_cast<Constant*>(V1); // X | 0 == X
1416 if (cast<ConstantIntegral>(V2)->isAllOnesValue())
1417 return const_cast<Constant*>(V2); // X | -1 == -1
1419 case Instruction::Xor:
1420 if (V2->isNullValue()) return const_cast<Constant*>(V1); // X ^ 0 == X
1425 } else if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2)) {
1426 // If V2 is a constant expr and V1 isn't, flop them around and fold the
1427 // other way if possible.
1429 case Instruction::Add:
1430 case Instruction::Mul:
1431 case Instruction::And:
1432 case Instruction::Or:
1433 case Instruction::Xor:
1434 case Instruction::SetEQ:
1435 case Instruction::SetNE:
1436 // No change of opcode required.
1437 return ConstantFoldBinaryInstruction(Opcode, V2, V1);
1439 case Instruction::SetLT:
1440 case Instruction::SetGT:
1441 case Instruction::SetLE:
1442 case Instruction::SetGE:
1443 // Change the opcode as necessary to swap the operands.
1444 Opcode = SetCondInst::getSwappedCondition((Instruction::BinaryOps)Opcode);
1445 return ConstantFoldBinaryInstruction(Opcode, V2, V1);
1447 case Instruction::Shl:
1448 case Instruction::Shr:
1449 case Instruction::Sub:
1450 case Instruction::SDiv:
1451 case Instruction::UDiv:
1452 case Instruction::FDiv:
1453 case Instruction::Rem:
1454 default: // These instructions cannot be flopped around.
1461 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1462 const std::vector<Value*> &IdxList) {
1463 if (IdxList.size() == 0 ||
1464 (IdxList.size() == 1 && cast<Constant>(IdxList[0])->isNullValue()))
1465 return const_cast<Constant*>(C);
1467 if (isa<UndefValue>(C)) {
1468 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1470 assert(Ty != 0 && "Invalid indices for GEP!");
1471 return UndefValue::get(PointerType::get(Ty));
1474 Constant *Idx0 = cast<Constant>(IdxList[0]);
1475 if (C->isNullValue()) {
1477 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1478 if (!cast<Constant>(IdxList[i])->isNullValue()) {
1483 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1485 assert(Ty != 0 && "Invalid indices for GEP!");
1486 return ConstantPointerNull::get(PointerType::get(Ty));
1489 if (IdxList.size() == 1) {
1490 const Type *ElTy = cast<PointerType>(C->getType())->getElementType();
1491 if (uint32_t ElSize = ElTy->getPrimitiveSize()) {
1492 // gep null, C is equal to C*sizeof(nullty). If nullty is a known llvm
1493 // type, we can statically fold this.
1494 Constant *R = ConstantInt::get(Type::UIntTy, ElSize);
1495 R = ConstantExpr::getCast(R, Idx0->getType());
1496 R = ConstantExpr::getMul(R, Idx0);
1497 return ConstantExpr::getCast(R, C->getType());
1502 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1503 // Combine Indices - If the source pointer to this getelementptr instruction
1504 // is a getelementptr instruction, combine the indices of the two
1505 // getelementptr instructions into a single instruction.
1507 if (CE->getOpcode() == Instruction::GetElementPtr) {
1508 const Type *LastTy = 0;
1509 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1513 if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1514 std::vector<Value*> NewIndices;
1515 NewIndices.reserve(IdxList.size() + CE->getNumOperands());
1516 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1517 NewIndices.push_back(CE->getOperand(i));
1519 // Add the last index of the source with the first index of the new GEP.
1520 // Make sure to handle the case when they are actually different types.
1521 Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1522 // Otherwise it must be an array.
1523 if (!Idx0->isNullValue()) {
1524 const Type *IdxTy = Combined->getType();
1525 if (IdxTy != Idx0->getType()) IdxTy = Type::LongTy;
1527 ConstantExpr::get(Instruction::Add,
1528 ConstantExpr::getCast(Idx0, IdxTy),
1529 ConstantExpr::getCast(Combined, IdxTy));
1532 NewIndices.push_back(Combined);
1533 NewIndices.insert(NewIndices.end(), IdxList.begin()+1, IdxList.end());
1534 return ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices);
1538 // Implement folding of:
1539 // int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1541 // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1543 if (CE->getOpcode() == Instruction::Cast && IdxList.size() > 1 &&
1544 Idx0->isNullValue())
1545 if (const PointerType *SPT =
1546 dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1547 if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1548 if (const ArrayType *CAT =
1549 dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1550 if (CAT->getElementType() == SAT->getElementType())
1551 return ConstantExpr::getGetElementPtr(
1552 (Constant*)CE->getOperand(0), IdxList);