1 //== RangeConstraintManager.cpp - Manage range constraints.------*- C++ -*--==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines RangeConstraintManager, a class that tracks simple
11 //  equality and inequality constraints on symbolic values of ProgramState.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "SimpleConstraintManager.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/ImmutableSet.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 using namespace clang;
25 using namespace ento;
26 
27 namespace { class ConstraintRange {}; }
28 static int ConstraintRangeIndex = 0;
29 
30 /// A Range represents the closed range [from, to].  The caller must
31 /// guarantee that from <= to.  Note that Range is immutable, so as not
32 /// to subvert RangeSet's immutability.
33 namespace {
34 class Range : public std::pair<const llvm::APSInt*,
35                                                 const llvm::APSInt*> {
36 public:
37   Range(const llvm::APSInt &from, const llvm::APSInt &to)
38     : std::pair<const llvm::APSInt*, const llvm::APSInt*>(&from, &to) {
39     assert(from <= to);
40   }
41   bool Includes(const llvm::APSInt &v) const {
42     return *first <= v && v <= *second;
43   }
44   const llvm::APSInt &From() const {
45     return *first;
46   }
47   const llvm::APSInt &To() const {
48     return *second;
49   }
50   const llvm::APSInt *getConcreteValue() const {
51     return &From() == &To() ? &From() : NULL;
52   }
53 
54   void Profile(llvm::FoldingSetNodeID &ID) const {
55     ID.AddPointer(&From());
56     ID.AddPointer(&To());
57   }
58 };
59 
60 
61 class RangeTrait : public llvm::ImutContainerInfo<Range> {
62 public:
63   // When comparing if one Range is less than another, we should compare
64   // the actual APSInt values instead of their pointers.  This keeps the order
65   // consistent (instead of comparing by pointer values) and can potentially
66   // be used to speed up some of the operations in RangeSet.
67   static inline bool isLess(key_type_ref lhs, key_type_ref rhs) {
68     return *lhs.first < *rhs.first || (!(*rhs.first < *lhs.first) &&
69                                        *lhs.second < *rhs.second);
70   }
71 };
72 
73 /// RangeSet contains a set of ranges. If the set is empty, then
74 ///  there the value of a symbol is overly constrained and there are no
75 ///  possible values for that symbol.
76 class RangeSet {
77   typedef llvm::ImmutableSet<Range, RangeTrait> PrimRangeSet;
78   PrimRangeSet ranges; // no need to make const, since it is an
79                        // ImmutableSet - this allows default operator=
80                        // to work.
81 public:
82   typedef PrimRangeSet::Factory Factory;
83   typedef PrimRangeSet::iterator iterator;
84 
85   RangeSet(PrimRangeSet RS) : ranges(RS) {}
86 
87   iterator begin() const { return ranges.begin(); }
88   iterator end() const { return ranges.end(); }
89 
90   bool isEmpty() const { return ranges.isEmpty(); }
91 
92   /// Construct a new RangeSet representing '{ [from, to] }'.
93   RangeSet(Factory &F, const llvm::APSInt &from, const llvm::APSInt &to)
94     : ranges(F.add(F.getEmptySet(), Range(from, to))) {}
95 
96   /// Profile - Generates a hash profile of this RangeSet for use
97   ///  by FoldingSet.
98   void Profile(llvm::FoldingSetNodeID &ID) const { ranges.Profile(ID); }
99 
100   /// getConcreteValue - If a symbol is contrained to equal a specific integer
101   ///  constant then this method returns that value.  Otherwise, it returns
102   ///  NULL.
103   const llvm::APSInt* getConcreteValue() const {
104     return ranges.isSingleton() ? ranges.begin()->getConcreteValue() : 0;
105   }
106 
107 private:
108   void IntersectInRange(BasicValueFactory &BV, Factory &F,
109                         const llvm::APSInt &Lower,
110                         const llvm::APSInt &Upper,
111                         PrimRangeSet &newRanges,
112                         PrimRangeSet::iterator &i,
113                         PrimRangeSet::iterator &e) const {
114     // There are six cases for each range R in the set:
115     //   1. R is entirely before the intersection range.
116     //   2. R is entirely after the intersection range.
117     //   3. R contains the entire intersection range.
118     //   4. R starts before the intersection range and ends in the middle.
119     //   5. R starts in the middle of the intersection range and ends after it.
120     //   6. R is entirely contained in the intersection range.
121     // These correspond to each of the conditions below.
122     for (/* i = begin(), e = end() */; i != e; ++i) {
123       if (i->To() < Lower) {
124         continue;
125       }
126       if (i->From() > Upper) {
127         break;
128       }
129 
130       if (i->Includes(Lower)) {
131         if (i->Includes(Upper)) {
132           newRanges = F.add(newRanges, Range(BV.getValue(Lower),
133                                              BV.getValue(Upper)));
134           break;
135         } else
136           newRanges = F.add(newRanges, Range(BV.getValue(Lower), i->To()));
137       } else {
138         if (i->Includes(Upper)) {
139           newRanges = F.add(newRanges, Range(i->From(), BV.getValue(Upper)));
140           break;
141         } else
142           newRanges = F.add(newRanges, *i);
143       }
144     }
145   }
146 
147   const llvm::APSInt &getMinValue() const {
148     assert(!isEmpty());
149     return ranges.begin()->From();
150   }
151 
152   bool pin(llvm::APSInt &Lower, llvm::APSInt &Upper) const {
153     // This function has nine cases, the cartesian product of range-testing
154     // both the upper and lower bounds against the symbol's type.
155     // Each case requires a different pinning operation.
156     // The function returns false if the described range is entirely outside
157     // the range of values for the associated symbol.
158     APSIntType Type(getMinValue());
159     APSIntType::RangeTestResultKind LowerTest = Type.testInRange(Lower);
160     APSIntType::RangeTestResultKind UpperTest = Type.testInRange(Upper);
161 
162     switch (LowerTest) {
163     case APSIntType::RTR_Below:
164       switch (UpperTest) {
165       case APSIntType::RTR_Below:
166         // The entire range is outside the symbol's set of possible values.
167         // If this is a conventionally-ordered range, the state is infeasible.
168         if (Lower < Upper)
169           return false;
170 
171         // However, if the range wraps around, it spans all possible values.
172         Lower = Type.getMinValue();
173         Upper = Type.getMaxValue();
174         break;
175       case APSIntType::RTR_Within:
176         // The range starts below what's possible but ends within it. Pin.
177         Lower = Type.getMinValue();
178         Type.apply(Upper);
179         break;
180       case APSIntType::RTR_Above:
181         // The range spans all possible values for the symbol. Pin.
182         Lower = Type.getMinValue();
183         Upper = Type.getMaxValue();
184         break;
185       }
186       break;
187     case APSIntType::RTR_Within:
188       switch (UpperTest) {
189       case APSIntType::RTR_Below:
190         // The range wraps around, but all lower values are not possible.
191         Type.apply(Lower);
192         Upper = Type.getMaxValue();
193         break;
194       case APSIntType::RTR_Within:
195         // The range may or may not wrap around, but both limits are valid.
196         Type.apply(Lower);
197         Type.apply(Upper);
198         break;
199       case APSIntType::RTR_Above:
200         // The range starts within what's possible but ends above it. Pin.
201         Type.apply(Lower);
202         Upper = Type.getMaxValue();
203         break;
204       }
205       break;
206     case APSIntType::RTR_Above:
207       switch (UpperTest) {
208       case APSIntType::RTR_Below:
209         // The range wraps but is outside the symbol's set of possible values.
210         return false;
211       case APSIntType::RTR_Within:
212         // The range starts above what's possible but ends within it (wrap).
213         Lower = Type.getMinValue();
214         Type.apply(Upper);
215         break;
216       case APSIntType::RTR_Above:
217         // The entire range is outside the symbol's set of possible values.
218         // If this is a conventionally-ordered range, the state is infeasible.
219         if (Lower < Upper)
220           return false;
221 
222         // However, if the range wraps around, it spans all possible values.
223         Lower = Type.getMinValue();
224         Upper = Type.getMaxValue();
225         break;
226       }
227       break;
228     }
229 
230     return true;
231   }
232 
233 public:
234   // Returns a set containing the values in the receiving set, intersected with
235   // the closed range [Lower, Upper]. Unlike the Range type, this range uses
236   // modular arithmetic, corresponding to the common treatment of C integer
237   // overflow. Thus, if the Lower bound is greater than the Upper bound, the
238   // range is taken to wrap around. This is equivalent to taking the
239   // intersection with the two ranges [Min, Upper] and [Lower, Max],
240   // or, alternatively, /removing/ all integers between Upper and Lower.
241   RangeSet Intersect(BasicValueFactory &BV, Factory &F,
242                      llvm::APSInt Lower, llvm::APSInt Upper) const {
243     if (!pin(Lower, Upper))
244       return F.getEmptySet();
245 
246     PrimRangeSet newRanges = F.getEmptySet();
247 
248     PrimRangeSet::iterator i = begin(), e = end();
249     if (Lower <= Upper)
250       IntersectInRange(BV, F, Lower, Upper, newRanges, i, e);
251     else {
252       // The order of the next two statements is important!
253       // IntersectInRange() does not reset the iteration state for i and e.
254       // Therefore, the lower range most be handled first.
255       IntersectInRange(BV, F, BV.getMinValue(Upper), Upper, newRanges, i, e);
256       IntersectInRange(BV, F, Lower, BV.getMaxValue(Lower), newRanges, i, e);
257     }
258 
259     return newRanges;
260   }
261 
262   void print(raw_ostream &os) const {
263     bool isFirst = true;
264     os << "{ ";
265     for (iterator i = begin(), e = end(); i != e; ++i) {
266       if (isFirst)
267         isFirst = false;
268       else
269         os << ", ";
270 
271       os << '[' << i->From().toString(10) << ", " << i->To().toString(10)
272          << ']';
273     }
274     os << " }";
275   }
276 
277   bool operator==(const RangeSet &other) const {
278     return ranges == other.ranges;
279   }
280 };
281 } // end anonymous namespace
282 
283 typedef llvm::ImmutableMap<SymbolRef,RangeSet> ConstraintRangeTy;
284 
285 namespace clang {
286 namespace ento {
287 template<>
288 struct ProgramStateTrait<ConstraintRange>
289   : public ProgramStatePartialTrait<ConstraintRangeTy> {
290   static inline void *GDMIndex() { return &ConstraintRangeIndex; }
291 };
292 }
293 }
294 
295 namespace {
296 class RangeConstraintManager : public SimpleConstraintManager{
297   RangeSet GetRange(ProgramStateRef state, SymbolRef sym);
298 public:
299   RangeConstraintManager(SubEngine *subengine, BasicValueFactory &BVF)
300     : SimpleConstraintManager(subengine, BVF) {}
301 
302   ProgramStateRef assumeSymNE(ProgramStateRef state, SymbolRef sym,
303                              const llvm::APSInt& Int,
304                              const llvm::APSInt& Adjustment);
305 
306   ProgramStateRef assumeSymEQ(ProgramStateRef state, SymbolRef sym,
307                              const llvm::APSInt& Int,
308                              const llvm::APSInt& Adjustment);
309 
310   ProgramStateRef assumeSymLT(ProgramStateRef state, SymbolRef sym,
311                              const llvm::APSInt& Int,
312                              const llvm::APSInt& Adjustment);
313 
314   ProgramStateRef assumeSymGT(ProgramStateRef state, SymbolRef sym,
315                              const llvm::APSInt& Int,
316                              const llvm::APSInt& Adjustment);
317 
318   ProgramStateRef assumeSymGE(ProgramStateRef state, SymbolRef sym,
319                              const llvm::APSInt& Int,
320                              const llvm::APSInt& Adjustment);
321 
322   ProgramStateRef assumeSymLE(ProgramStateRef state, SymbolRef sym,
323                              const llvm::APSInt& Int,
324                              const llvm::APSInt& Adjustment);
325 
326   const llvm::APSInt* getSymVal(ProgramStateRef St, SymbolRef sym) const;
327   ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym);
328 
329   ProgramStateRef removeDeadBindings(ProgramStateRef St, SymbolReaper& SymReaper);
330 
331   void print(ProgramStateRef St, raw_ostream &Out,
332              const char* nl, const char *sep);
333 
334 private:
335   RangeSet::Factory F;
336 };
337 
338 } // end anonymous namespace
339 
340 ConstraintManager *
341 ento::CreateRangeConstraintManager(ProgramStateManager &StMgr, SubEngine *Eng) {
342   return new RangeConstraintManager(Eng, StMgr.getBasicVals());
343 }
344 
345 const llvm::APSInt* RangeConstraintManager::getSymVal(ProgramStateRef St,
346                                                       SymbolRef sym) const {
347   const ConstraintRangeTy::data_type *T = St->get<ConstraintRange>(sym);
348   return T ? T->getConcreteValue() : NULL;
349 }
350 
351 ConditionTruthVal RangeConstraintManager::checkNull(ProgramStateRef State,
352                                                     SymbolRef Sym) {
353   const RangeSet *Ranges = State->get<ConstraintRange>(Sym);
354 
355   // If we don't have any information about this symbol, it's underconstrained.
356   if (!Ranges)
357     return ConditionTruthVal();
358 
359   // If we have a concrete value, see if it's zero.
360   if (const llvm::APSInt *Value = Ranges->getConcreteValue())
361     return *Value == 0;
362 
363   BasicValueFactory &BV = getBasicVals();
364   APSIntType IntType = BV.getAPSIntType(Sym->getType());
365   llvm::APSInt Zero = IntType.getZeroValue();
366 
367   // Check if zero is in the set of possible values.
368   if (Ranges->Intersect(BV, F, Zero, Zero).isEmpty())
369     return false;
370 
371   // Zero is a possible value, but it is not the /only/ possible value.
372   return ConditionTruthVal();
373 }
374 
375 /// Scan all symbols referenced by the constraints. If the symbol is not alive
376 /// as marked in LSymbols, mark it as dead in DSymbols.
377 ProgramStateRef
378 RangeConstraintManager::removeDeadBindings(ProgramStateRef state,
379                                            SymbolReaper& SymReaper) {
380 
381   ConstraintRangeTy CR = state->get<ConstraintRange>();
382   ConstraintRangeTy::Factory& CRFactory = state->get_context<ConstraintRange>();
383 
384   for (ConstraintRangeTy::iterator I = CR.begin(), E = CR.end(); I != E; ++I) {
385     SymbolRef sym = I.getKey();
386     if (SymReaper.maybeDead(sym))
387       CR = CRFactory.remove(CR, sym);
388   }
389 
390   return state->set<ConstraintRange>(CR);
391 }
392 
393 RangeSet
394 RangeConstraintManager::GetRange(ProgramStateRef state, SymbolRef sym) {
395   if (ConstraintRangeTy::data_type* V = state->get<ConstraintRange>(sym))
396     return *V;
397 
398   // Lazily generate a new RangeSet representing all possible values for the
399   // given symbol type.
400   BasicValueFactory &BV = getBasicVals();
401   QualType T = sym->getType();
402 
403   RangeSet Result(F, BV.getMinValue(T), BV.getMaxValue(T));
404 
405   // Special case: references are known to be non-zero.
406   if (T->isReferenceType()) {
407     APSIntType IntType = BV.getAPSIntType(T);
408     Result = Result.Intersect(BV, F, ++IntType.getZeroValue(),
409                                      --IntType.getZeroValue());
410   }
411 
412   return Result;
413 }
414 
415 //===------------------------------------------------------------------------===
416 // assumeSymX methods: public interface for RangeConstraintManager.
417 //===------------------------------------------------------------------------===/
418 
419 // The syntax for ranges below is mathematical, using [x, y] for closed ranges
420 // and (x, y) for open ranges. These ranges are modular, corresponding with
421 // a common treatment of C integer overflow. This means that these methods
422 // do not have to worry about overflow; RangeSet::Intersect can handle such a
423 // "wraparound" range.
424 // As an example, the range [UINT_MAX-1, 3) contains five values: UINT_MAX-1,
425 // UINT_MAX, 0, 1, and 2.
426 
427 ProgramStateRef
428 RangeConstraintManager::assumeSymNE(ProgramStateRef St, SymbolRef Sym,
429                                     const llvm::APSInt &Int,
430                                     const llvm::APSInt &Adjustment) {
431   // Before we do any real work, see if the value can even show up.
432   APSIntType AdjustmentType(Adjustment);
433   if (AdjustmentType.testInRange(Int) != APSIntType::RTR_Within)
434     return St;
435 
436   llvm::APSInt Lower = AdjustmentType.convert(Int) - Adjustment;
437   llvm::APSInt Upper = Lower;
438   --Lower;
439   ++Upper;
440 
441   // [Int-Adjustment+1, Int-Adjustment-1]
442   // Notice that the lower bound is greater than the upper bound.
443   RangeSet New = GetRange(St, Sym).Intersect(getBasicVals(), F, Upper, Lower);
444   return New.isEmpty() ? NULL : St->set<ConstraintRange>(Sym, New);
445 }
446 
447 ProgramStateRef
448 RangeConstraintManager::assumeSymEQ(ProgramStateRef St, SymbolRef Sym,
449                                     const llvm::APSInt &Int,
450                                     const llvm::APSInt &Adjustment) {
451   // Before we do any real work, see if the value can even show up.
452   APSIntType AdjustmentType(Adjustment);
453   if (AdjustmentType.testInRange(Int) != APSIntType::RTR_Within)
454     return NULL;
455 
456   // [Int-Adjustment, Int-Adjustment]
457   llvm::APSInt AdjInt = AdjustmentType.convert(Int) - Adjustment;
458   RangeSet New = GetRange(St, Sym).Intersect(getBasicVals(), F, AdjInt, AdjInt);
459   return New.isEmpty() ? NULL : St->set<ConstraintRange>(Sym, New);
460 }
461 
462 ProgramStateRef
463 RangeConstraintManager::assumeSymLT(ProgramStateRef St, SymbolRef Sym,
464                                     const llvm::APSInt &Int,
465                                     const llvm::APSInt &Adjustment) {
466   // Before we do any real work, see if the value can even show up.
467   APSIntType AdjustmentType(Adjustment);
468   switch (AdjustmentType.testInRange(Int)) {
469   case APSIntType::RTR_Below:
470     return NULL;
471   case APSIntType::RTR_Within:
472     break;
473   case APSIntType::RTR_Above:
474     return St;
475   }
476 
477   // Special case for Int == Min. This is always false.
478   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
479   llvm::APSInt Min = AdjustmentType.getMinValue();
480   if (ComparisonVal == Min)
481     return NULL;
482 
483   llvm::APSInt Lower = Min-Adjustment;
484   llvm::APSInt Upper = ComparisonVal-Adjustment;
485   --Upper;
486 
487   RangeSet New = GetRange(St, Sym).Intersect(getBasicVals(), F, Lower, Upper);
488   return New.isEmpty() ? NULL : St->set<ConstraintRange>(Sym, New);
489 }
490 
491 ProgramStateRef
492 RangeConstraintManager::assumeSymGT(ProgramStateRef St, SymbolRef Sym,
493                                     const llvm::APSInt &Int,
494                                     const llvm::APSInt &Adjustment) {
495   // Before we do any real work, see if the value can even show up.
496   APSIntType AdjustmentType(Adjustment);
497   switch (AdjustmentType.testInRange(Int)) {
498   case APSIntType::RTR_Below:
499     return St;
500   case APSIntType::RTR_Within:
501     break;
502   case APSIntType::RTR_Above:
503     return NULL;
504   }
505 
506   // Special case for Int == Max. This is always false.
507   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
508   llvm::APSInt Max = AdjustmentType.getMaxValue();
509   if (ComparisonVal == Max)
510     return NULL;
511 
512   llvm::APSInt Lower = ComparisonVal-Adjustment;
513   llvm::APSInt Upper = Max-Adjustment;
514   ++Lower;
515 
516   RangeSet New = GetRange(St, Sym).Intersect(getBasicVals(), F, Lower, Upper);
517   return New.isEmpty() ? NULL : St->set<ConstraintRange>(Sym, New);
518 }
519 
520 ProgramStateRef
521 RangeConstraintManager::assumeSymGE(ProgramStateRef St, SymbolRef Sym,
522                                     const llvm::APSInt &Int,
523                                     const llvm::APSInt &Adjustment) {
524   // Before we do any real work, see if the value can even show up.
525   APSIntType AdjustmentType(Adjustment);
526   switch (AdjustmentType.testInRange(Int)) {
527   case APSIntType::RTR_Below:
528     return St;
529   case APSIntType::RTR_Within:
530     break;
531   case APSIntType::RTR_Above:
532     return NULL;
533   }
534 
535   // Special case for Int == Min. This is always feasible.
536   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
537   llvm::APSInt Min = AdjustmentType.getMinValue();
538   if (ComparisonVal == Min)
539     return St;
540 
541   llvm::APSInt Max = AdjustmentType.getMaxValue();
542   llvm::APSInt Lower = ComparisonVal-Adjustment;
543   llvm::APSInt Upper = Max-Adjustment;
544 
545   RangeSet New = GetRange(St, Sym).Intersect(getBasicVals(), F, Lower, Upper);
546   return New.isEmpty() ? NULL : St->set<ConstraintRange>(Sym, New);
547 }
548 
549 ProgramStateRef
550 RangeConstraintManager::assumeSymLE(ProgramStateRef St, SymbolRef Sym,
551                                     const llvm::APSInt &Int,
552                                     const llvm::APSInt &Adjustment) {
553   // Before we do any real work, see if the value can even show up.
554   APSIntType AdjustmentType(Adjustment);
555   switch (AdjustmentType.testInRange(Int)) {
556   case APSIntType::RTR_Below:
557     return NULL;
558   case APSIntType::RTR_Within:
559     break;
560   case APSIntType::RTR_Above:
561     return St;
562   }
563 
564   // Special case for Int == Max. This is always feasible.
565   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
566   llvm::APSInt Max = AdjustmentType.getMaxValue();
567   if (ComparisonVal == Max)
568     return St;
569 
570   llvm::APSInt Min = AdjustmentType.getMinValue();
571   llvm::APSInt Lower = Min-Adjustment;
572   llvm::APSInt Upper = ComparisonVal-Adjustment;
573 
574   RangeSet New = GetRange(St, Sym).Intersect(getBasicVals(), F, Lower, Upper);
575   return New.isEmpty() ? NULL : St->set<ConstraintRange>(Sym, New);
576 }
577 
578 //===------------------------------------------------------------------------===
579 // Pretty-printing.
580 //===------------------------------------------------------------------------===/
581 
582 void RangeConstraintManager::print(ProgramStateRef St, raw_ostream &Out,
583                                    const char* nl, const char *sep) {
584 
585   ConstraintRangeTy Ranges = St->get<ConstraintRange>();
586 
587   if (Ranges.isEmpty()) {
588     Out << nl << sep << "Ranges are empty." << nl;
589     return;
590   }
591 
592   Out << nl << sep << "Ranges of symbol values:";
593   for (ConstraintRangeTy::iterator I=Ranges.begin(), E=Ranges.end(); I!=E; ++I){
594     Out << nl << ' ' << I.getKey() << " : ";
595     I.getData().print(Out);
596   }
597   Out << nl;
598 }
599