1 //===-- llvm/IntegersSubset.h - The subset of integers ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file contains class that implements constant set of ranges:
12 /// [<Low0,High0>,...,<LowN,HighN>]. Initially, this class was created for
13 /// SwitchInst and was used for case value representation that may contain
14 /// multiple ranges for a single successor.
16 //===----------------------------------------------------------------------===//
18 #ifndef CONSTANTRANGESSET_H_
19 #define CONSTANTRANGESSET_H_
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/LLVMContext.h"
29 // The IntItem is a wrapper for APInt.
30 // 1. It determines sign of integer, it allows to use
31 // comparison operators >,<,>=,<=, and as result we got shorter and cleaner
33 // 2. It helps to implement PR1255 (case ranges) as a series of small patches.
34 // 3. Currently we can interpret IntItem both as ConstantInt and as APInt.
35 // It allows to provide SwitchInst methods that works with ConstantInt for
36 // non-updated passes. And it allows to use APInt interface for new methods.
37 // 4. IntItem can be easily replaced with APInt.
39 // The set of macros that allows to propagate APInt operators to the IntItem.
41 #define INT_ITEM_DEFINE_COMPARISON(op,func) \
42 bool operator op (const APInt& RHS) const { \
43 return getAPIntValue().func(RHS); \
46 #define INT_ITEM_DEFINE_UNARY_OP(op) \
47 IntItem operator op () const { \
48 APInt res = op(getAPIntValue()); \
49 Constant *NewVal = ConstantInt::get(ConstantIntVal->getContext(), res); \
50 return IntItem(cast<ConstantInt>(NewVal)); \
53 #define INT_ITEM_DEFINE_BINARY_OP(op) \
54 IntItem operator op (const APInt& RHS) const { \
55 APInt res = getAPIntValue() op RHS; \
56 Constant *NewVal = ConstantInt::get(ConstantIntVal->getContext(), res); \
57 return IntItem(cast<ConstantInt>(NewVal)); \
60 #define INT_ITEM_DEFINE_ASSIGNMENT_BY_OP(op) \
61 IntItem& operator op (const APInt& RHS) {\
62 APInt res = getAPIntValue();\
64 Constant *NewVal = ConstantInt::get(ConstantIntVal->getContext(), res); \
65 ConstantIntVal = cast<ConstantInt>(NewVal); \
69 #define INT_ITEM_DEFINE_PREINCDEC(op) \
70 IntItem& operator op () { \
71 APInt res = getAPIntValue(); \
73 Constant *NewVal = ConstantInt::get(ConstantIntVal->getContext(), res); \
74 ConstantIntVal = cast<ConstantInt>(NewVal); \
78 #define INT_ITEM_DEFINE_POSTINCDEC(op) \
79 IntItem& operator op (int) { \
80 APInt res = getAPIntValue();\
82 Constant *NewVal = ConstantInt::get(ConstantIntVal->getContext(), res); \
83 OldConstantIntVal = ConstantIntVal; \
84 ConstantIntVal = cast<ConstantInt>(NewVal); \
85 return IntItem(OldConstantIntVal); \
88 #define INT_ITEM_DEFINE_OP_STANDARD_INT(RetTy, op, IntTy) \
89 RetTy operator op (IntTy RHS) const { \
90 return (*this) op APInt(getAPIntValue().getBitWidth(), RHS); \
94 ConstantInt *ConstantIntVal;
95 const APInt* APIntVal;
96 IntItem(const ConstantInt *V) :
97 ConstantIntVal(const_cast<ConstantInt*>(V)),
98 APIntVal(&ConstantIntVal->getValue()){}
99 const APInt& getAPIntValue() const {
106 operator const APInt&() const {
107 return getAPIntValue();
110 // Propagate APInt operators.
112 // /,/=,>>,>>= are not implemented in APInt.
113 // <<= is implemented for unsigned RHS, but not implemented for APInt RHS.
115 INT_ITEM_DEFINE_COMPARISON(<, ult)
116 INT_ITEM_DEFINE_COMPARISON(>, ugt)
117 INT_ITEM_DEFINE_COMPARISON(<=, ule)
118 INT_ITEM_DEFINE_COMPARISON(>=, uge)
120 INT_ITEM_DEFINE_COMPARISON(==, eq)
121 INT_ITEM_DEFINE_OP_STANDARD_INT(bool,==,uint64_t)
123 INT_ITEM_DEFINE_COMPARISON(!=, ne)
124 INT_ITEM_DEFINE_OP_STANDARD_INT(bool,!=,uint64_t)
126 INT_ITEM_DEFINE_BINARY_OP(*)
127 INT_ITEM_DEFINE_BINARY_OP(+)
128 INT_ITEM_DEFINE_OP_STANDARD_INT(IntItem,+,uint64_t)
129 INT_ITEM_DEFINE_BINARY_OP(-)
130 INT_ITEM_DEFINE_OP_STANDARD_INT(IntItem,-,uint64_t)
131 INT_ITEM_DEFINE_BINARY_OP(<<)
132 INT_ITEM_DEFINE_OP_STANDARD_INT(IntItem,<<,unsigned)
133 INT_ITEM_DEFINE_BINARY_OP(&)
134 INT_ITEM_DEFINE_BINARY_OP(^)
135 INT_ITEM_DEFINE_BINARY_OP(|)
137 INT_ITEM_DEFINE_ASSIGNMENT_BY_OP(*=)
138 INT_ITEM_DEFINE_ASSIGNMENT_BY_OP(+=)
139 INT_ITEM_DEFINE_ASSIGNMENT_BY_OP(-=)
140 INT_ITEM_DEFINE_ASSIGNMENT_BY_OP(&=)
141 INT_ITEM_DEFINE_ASSIGNMENT_BY_OP(^=)
142 INT_ITEM_DEFINE_ASSIGNMENT_BY_OP(|=)
144 // Special case for <<=
145 IntItem& operator <<= (unsigned RHS) {
146 APInt res = getAPIntValue();
148 Constant *NewVal = ConstantInt::get(ConstantIntVal->getContext(), res);
149 ConstantIntVal = cast<ConstantInt>(NewVal);
153 INT_ITEM_DEFINE_UNARY_OP(-)
154 INT_ITEM_DEFINE_UNARY_OP(~)
156 INT_ITEM_DEFINE_PREINCDEC(++)
157 INT_ITEM_DEFINE_PREINCDEC(--)
159 // The set of workarounds, since currently we use ConstantInt implemented
162 static IntItem fromConstantInt(const ConstantInt *V) {
165 static IntItem fromType(Type* Ty, const APInt& V) {
166 ConstantInt *C = cast<ConstantInt>(ConstantInt::get(Ty, V));
167 return fromConstantInt(C);
169 static IntItem withImplLikeThis(const IntItem& LikeThis, const APInt& V) {
170 ConstantInt *C = cast<ConstantInt>(ConstantInt::get(
171 LikeThis.ConstantIntVal->getContext(), V));
172 return fromConstantInt(C);
174 ConstantInt *toConstantInt() const {
175 return ConstantIntVal;
179 template<class IntType>
193 typedef IntRange<IntType> self;
194 typedef std::pair<self, self> SubRes;
196 IntRange() : IsEmpty(true) {}
197 IntRange(const self &RHS) :
198 Low(RHS.Low), High(RHS.High),
199 IsEmpty(RHS.IsEmpty), RangeType(RHS.RangeType) {}
200 IntRange(const IntType &C) :
201 Low(C), High(C), IsEmpty(false), RangeType(SINGLE_NUMBER) {}
203 IntRange(const IntType &L, const IntType &H) : Low(L), High(H),
204 IsEmpty(false), RangeType(UNKNOWN) {}
206 bool isEmpty() const { return IsEmpty; }
207 bool isSingleNumber() const {
215 const_cast<Type&>(RangeType) = SINGLE_NUMBER;
218 const_cast<Type&>(RangeType) = RANGE;
223 const IntType& getLow() const {
224 assert(!IsEmpty && "Range is empty.");
227 const IntType& getHigh() const {
228 assert(!IsEmpty && "Range is empty.");
232 bool operator<(const self &RHS) const {
233 assert(!IsEmpty && "Left range is empty.");
234 assert(!RHS.IsEmpty && "Right range is empty.");
237 if (Low == RHS.Low) {
245 bool operator==(const self &RHS) const {
246 assert(!IsEmpty && "Left range is empty.");
247 assert(!RHS.IsEmpty && "Right range is empty.");
248 return Low == RHS.Low && High == RHS.High;
251 bool operator!=(const self &RHS) const {
252 return !operator ==(RHS);
255 static bool LessBySize(const self &LHS, const self &RHS) {
256 return (LHS.High - LHS.Low) < (RHS.High - RHS.Low);
259 bool isInRange(const IntType &IntVal) const {
260 assert(!IsEmpty && "Range is empty.");
261 return IntVal >= Low && IntVal <= High;
264 SubRes sub(const self &RHS) const {
267 // RHS is either more global and includes this range or
268 // if it doesn't intersected with this range.
269 if (!isInRange(RHS.Low) && !isInRange(RHS.High)) {
271 // If RHS more global (it is enough to check
272 // only one border in this case.
273 if (RHS.isInRange(Low))
274 return std::make_pair(self(Low, High), self());
281 IntType NewHigh = RHS.Low;
283 Res.first.High = NewHigh;
285 if (High > RHS.High) {
286 IntType NewLow = RHS.High;
288 Res.second.Low = NewLow;
289 Res.second.High = High;
295 //===----------------------------------------------------------------------===//
296 /// IntegersSubsetGeneric - class that implements the subset of integers. It
297 /// consists from ranges and single numbers.
298 template <class IntTy>
299 class IntegersSubsetGeneric {
301 // Use Chris Lattner idea, that was initially described here:
302 // http://lists.cs.uiuc.edu/pipermail/llvm-commits/Week-of-Mon-20120213/136954.html
303 // In short, for more compact memory consumption we can store flat
304 // numbers collection, and define range as pair of indices.
305 // In that case we can safe some memory on 32 bit machines.
306 typedef std::vector<IntTy> FlatCollectionTy;
307 typedef std::pair<IntTy*, IntTy*> RangeLinkTy;
308 typedef std::vector<RangeLinkTy> RangeLinksTy;
309 typedef typename RangeLinksTy::const_iterator RangeLinksConstIt;
311 typedef IntegersSubsetGeneric<IntTy> self;
315 FlatCollectionTy FlatCollection;
316 RangeLinksTy RangeLinks;
319 bool IsSingleNumbersOnly;
323 template<class RangesCollectionTy>
324 explicit IntegersSubsetGeneric(const RangesCollectionTy& Links) {
325 assert(Links.size() && "Empty ranges are not allowed.");
327 // In case of big set of single numbers consumes additional RAM space,
328 // but allows to avoid additional reallocation.
329 FlatCollection.reserve(Links.size() * 2);
330 RangeLinks.reserve(Links.size());
331 IsSingleNumbersOnly = true;
332 for (typename RangesCollectionTy::const_iterator i = Links.begin(),
333 e = Links.end(); i != e; ++i) {
334 RangeLinkTy RangeLink;
335 FlatCollection.push_back(i->getLow());
336 RangeLink.first = &FlatCollection.back();
337 if (i->getLow() != i->getHigh()) {
338 FlatCollection.push_back(i->getHigh());
339 IsSingleNumbersOnly = false;
341 RangeLink.second = &FlatCollection.back();
342 RangeLinks.push_back(RangeLink);
344 IsSingleNumber = IsSingleNumbersOnly && RangeLinks.size() == 1;
347 IntegersSubsetGeneric(const self& RHS) {
351 self& operator=(const self& RHS) {
352 FlatCollection.clear();
354 FlatCollection.reserve(RHS.RangeLinks.size() * 2);
355 RangeLinks.reserve(RHS.RangeLinks.size());
356 for (RangeLinksConstIt i = RHS.RangeLinks.begin(), e = RHS.RangeLinks.end();
358 RangeLinkTy RangeLink;
359 FlatCollection.push_back(*(i->first));
360 RangeLink.first = &FlatCollection.back();
361 if (i->first != i->second)
362 FlatCollection.push_back(*(i->second));
363 RangeLink.second = &FlatCollection.back();
364 RangeLinks.push_back(RangeLink);
366 IsSingleNumber = RHS.IsSingleNumber;
367 IsSingleNumbersOnly = RHS.IsSingleNumbersOnly;
371 typedef IntRange<IntTy> Range;
373 /// Checks is the given constant satisfies this case. Returns
374 /// true if it equals to one of contained values or belongs to the one of
375 /// contained ranges.
376 bool isSatisfies(const IntTy &CheckingVal) const {
378 return FlatCollection.front() == CheckingVal;
379 if (IsSingleNumbersOnly)
380 return std::find(FlatCollection.begin(),
381 FlatCollection.end(),
382 CheckingVal) != FlatCollection.end();
384 for (unsigned i = 0, e = getNumItems(); i < e; ++i) {
385 if (RangeLinks[i].first == RangeLinks[i].second) {
386 if (*RangeLinks[i].first == CheckingVal)
388 } else if (*RangeLinks[i].first <= CheckingVal &&
389 *RangeLinks[i].second >= CheckingVal)
395 /// Returns set's item with given index.
396 Range getItem(unsigned idx) const {
397 const RangeLinkTy &Link = RangeLinks[idx];
398 if (Link.first != Link.second)
399 return Range(*Link.first, *Link.second);
401 return Range(*Link.first);
404 /// Return number of items (ranges) stored in set.
405 unsigned getNumItems() const {
406 return RangeLinks.size();
409 /// Returns true if whole subset contains single element.
410 bool isSingleNumber() const {
411 return IsSingleNumber;
414 /// Returns true if whole subset contains only single numbers, no ranges.
415 bool isSingleNumbersOnly() const {
416 return IsSingleNumbersOnly;
419 /// Does the same like getItem(idx).isSingleNumber(), but
420 /// works faster, since we avoid creation of temporary range object.
421 bool isSingleNumber(unsigned idx) const {
422 return RangeLinks[idx].first == RangeLinks[idx].second;
425 /// Returns set the size, that equals number of all values + sizes of all
427 /// Ranges set is considered as flat numbers collection.
428 /// E.g.: for range [<0>, <1>, <4,8>] the size will 7;
429 /// for range [<0>, <1>, <5>] the size will 3
430 unsigned getSize() const {
431 APInt sz(((const APInt&)getItem(0).getLow()).getBitWidth(), 0);
432 for (unsigned i = 0, e = getNumItems(); i != e; ++i) {
433 const APInt &Low = getItem(i).getLow();
434 const APInt &High = getItem(i).getHigh();
435 APInt S = High - Low + 1;
438 return sz.getZExtValue();
441 /// Allows to access single value even if it belongs to some range.
442 /// Ranges set is considered as flat numbers collection.
443 /// [<1>, <4,8>] is considered as [1,4,5,6,7,8]
444 /// For range [<1>, <4,8>] getSingleValue(3) returns 6.
445 APInt getSingleValue(unsigned idx) const {
446 APInt sz(((const APInt&)getItem(0).getLow()).getBitWidth(), 0);
447 for (unsigned i = 0, e = getNumItems(); i != e; ++i) {
448 const APInt &Low = getItem(i).getLow();
449 const APInt &High = getItem(i).getHigh();
450 APInt S = High - Low + 1;
455 APInt Offset(oldSz.getBitWidth(), idx);
461 assert(0 && "Index exceeds high border.");
465 /// Does the same as getSingleValue, but works only if subset contains
466 /// single numbers only.
467 const IntTy& getSingleNumber(unsigned idx) const {
468 assert(IsSingleNumbersOnly && "This method works properly if subset "
469 "contains single numbers only.");
470 return FlatCollection[idx];
474 //===----------------------------------------------------------------------===//
475 /// IntegersSubset - currently is extension of IntegersSubsetGeneric
476 /// that also supports conversion to/from Constant* object.
477 class IntegersSubset : public IntegersSubsetGeneric<IntItem> {
479 typedef IntegersSubsetGeneric<IntItem> ParentTy;
483 static unsigned getNumItemsFromConstant(Constant *C) {
484 return cast<ArrayType>(C->getType())->getNumElements();
487 static Range getItemFromConstant(Constant *C, unsigned idx) {
488 const Constant *CV = C->getAggregateElement(idx);
490 unsigned NumEls = cast<VectorType>(CV->getType())->getNumElements();
493 return Range(IntItem::fromConstantInt(
494 cast<ConstantInt>(CV->getAggregateElement(0U))),
495 IntItem::fromConstantInt(cast<ConstantInt>(
496 cast<ConstantInt>(CV->getAggregateElement(0U)))));
498 return Range(IntItem::fromConstantInt(
499 cast<ConstantInt>(CV->getAggregateElement(0U))),
500 IntItem::fromConstantInt(
501 cast<ConstantInt>(CV->getAggregateElement(1))));
503 assert(0 && "Only pairs and single numbers are allowed here.");
508 std::vector<Range> rangesFromConstant(Constant *C) {
509 unsigned NumItems = getNumItemsFromConstant(C);
510 std::vector<Range> r;
512 for (unsigned i = 0, e = NumItems; i != e; ++i)
513 r.push_back(getItemFromConstant(C, i));
519 explicit IntegersSubset(Constant *C) : ParentTy(rangesFromConstant(C)),
522 IntegersSubset(const IntegersSubset& RHS) :
523 ParentTy(*(const ParentTy *)&RHS), // FIXME: tweak for msvc.
524 Holder(RHS.Holder) {}
526 template<class RangesCollectionTy>
527 explicit IntegersSubset(const RangesCollectionTy& Src) : ParentTy(Src) {
528 std::vector<Constant*> Elts;
529 Elts.reserve(Src.size());
530 for (typename RangesCollectionTy::const_iterator i = Src.begin(),
531 e = Src.end(); i != e; ++i) {
533 std::vector<Constant*> r;
534 if (!R.isSingleNumber()) {
536 // FIXME: Since currently we have ConstantInt based numbers
537 // use hack-conversion of IntItem to ConstantInt
538 r.push_back(R.getLow().toConstantInt());
539 r.push_back(R.getHigh().toConstantInt());
542 r.push_back(R.getLow().toConstantInt());
544 Constant *CV = ConstantVector::get(r);
548 ArrayType::get(Elts.front()->getType(), (uint64_t)Elts.size());
549 Holder = ConstantArray::get(ArrTy, Elts);
552 operator Constant*() { return Holder; }
553 operator const Constant*() const { return Holder; }
554 Constant *operator->() { return Holder; }
555 const Constant *operator->() const { return Holder; }
560 #endif /* CONSTANTRANGESSET_H_ */