clang 24.0.0git
RangedConstraintManager.h
Go to the documentation of this file.
1//== RangedConstraintManager.h ----------------------------------*- C++ -*--==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Ranged constraint manager, built on SimpleConstraintManager.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_RANGEDCONSTRAINTMANAGER_H
14#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_RANGEDCONSTRAINTMANAGER_H
15
19#include "llvm/ADT/APSInt.h"
20#include "llvm/Support/Allocator.h"
21
22namespace clang {
23
24namespace ento {
25
26/// A Range represents the closed range [from, to]. The caller must
27/// guarantee that from <= to. Note that Range is immutable, so as not
28/// to subvert RangeSet's immutability.
29class Range {
30public:
31 Range(const llvm::APSInt &From, const llvm::APSInt &To) : Impl(&From, &To) {
32 assert(From <= To);
33 }
34
35 Range(const llvm::APSInt &Point) : Range(Point, Point) {}
36
37 bool Includes(const llvm::APSInt &Point) const {
38 return From() <= Point && Point <= To();
39 }
40 const llvm::APSInt &From() const { return *Impl.first; }
41 const llvm::APSInt &To() const { return *Impl.second; }
42 const llvm::APSInt *getConcreteValue() const {
43 return &From() == &To() ? &From() : nullptr;
44 }
45
46 void Profile(llvm::FoldingSetNodeID &ID) const {
47 ID.AddPointer(&From());
48 ID.AddPointer(&To());
49 }
50 void dump(raw_ostream &OS) const;
51 void dump() const;
52
53 // In order to keep non-overlapping ranges sorted, we can compare only From
54 // points.
55 bool operator<(const Range &RHS) const { return From() < RHS.From(); }
56
57 bool operator==(const Range &RHS) const { return Impl == RHS.Impl; }
58 bool operator!=(const Range &RHS) const { return !operator==(RHS); }
59
60private:
61 std::pair<const llvm::APSInt *, const llvm::APSInt *> Impl;
62};
63
64/// @class RangeSet is a persistent set of non-overlapping ranges.
65///
66/// New RangeSet objects can be ONLY produced by RangeSet::Factory object, which
67/// also supports the most common operations performed on range sets.
68///
69/// Empty set corresponds to an overly constrained symbol meaning that there
70/// are no possible values for that symbol.
71class RangeSet {
72public:
73 class Factory;
74
75private:
76 // We use llvm::SmallVector as the underlying container for the following
77 // reasons:
78 //
79 // * Range sets are usually very simple, 1 or 2 ranges.
80 // That's why llvm::ImmutableSet is not perfect.
81 //
82 // * Ranges in sets are NOT overlapping, so it is natural to keep them
83 // sorted for efficient operations and queries. For this reason,
84 // llvm::SmallSet doesn't fit the requirements, it is not sorted when it
85 // is a vector.
86 //
87 // * Range set operations usually a bit harder than add/remove a range.
88 // Complex operations might do many of those for just one range set.
89 // Formerly it used to be llvm::ImmutableSet, which is inefficient for our
90 // purposes as we want to make these operations BOTH immutable AND
91 // efficient.
92 //
93 // * Iteration over ranges is widespread and a more cache-friendly
94 // structure is preferred.
95 using ImplType = llvm::SmallVector<Range, 4>;
96
97 struct ContainerType : public ImplType, public llvm::FoldingSetNode {
98 void Profile(llvm::FoldingSetNodeID &ID) const {
99 for (const Range &It : *this) {
100 It.Profile(ID);
101 }
102 }
103 };
104 // This is a non-owning pointer to an actual container.
105 // The memory is fully managed by the factory and is alive as long as the
106 // factory itself is alive.
107 // It is a pointer as opposed to a reference, so we can easily reassign
108 // RangeSet objects.
109 using UnderlyingType = const ContainerType *;
110 UnderlyingType Impl;
111
112public:
113 using const_iterator = ImplType::const_iterator;
114
115 const_iterator begin() const { return Impl->begin(); }
116 const_iterator end() const { return Impl->end(); }
117 size_t size() const { return Impl->size(); }
118
119 bool isEmpty() const { return Impl->empty(); }
120
121 class Factory {
122 public:
123 Factory(BasicValueFactory &BV) : ValueFactory(BV) {}
124
125 /// Create a new set with all ranges from both LHS and RHS.
126 /// Possible intersections are not checked here.
127 ///
128 /// Complexity: O(N + M)
129 /// where N = size(LHS), M = size(RHS)
130 RangeSet add(RangeSet LHS, RangeSet RHS);
131 /// Create a new set with all ranges from the original set plus the new one.
132 /// Possible intersections are not checked here.
133 ///
134 /// Complexity: O(N)
135 /// where N = size(Original)
136 RangeSet add(RangeSet Original, Range Element);
137 /// Create a new set with all ranges from the original set plus the point.
138 /// Possible intersections are not checked here.
139 ///
140 /// Complexity: O(N)
141 /// where N = size(Original)
142 RangeSet add(RangeSet Original, const llvm::APSInt &Point);
143 /// Create a new set which is a union of two given ranges.
144 /// Possible intersections are not checked here.
145 ///
146 /// Complexity: O(N + M)
147 /// where N = size(LHS), M = size(RHS)
149 /// Create a new set by uniting given range set with the given range.
150 /// All intersections and adjacent ranges are handled here.
151 ///
152 /// Complexity: O(N)
153 /// where N = size(Original)
154 RangeSet unite(RangeSet Original, Range Element);
155 /// Create a new set by uniting given range set with the given point.
156 /// All intersections and adjacent ranges are handled here.
157 ///
158 /// Complexity: O(N)
159 /// where N = size(Original)
160 RangeSet unite(RangeSet Original, llvm::APSInt Point);
161 /// Create a new set by uniting given range set with the given range
162 /// between points. All intersections and adjacent ranges are handled here.
163 ///
164 /// Complexity: O(N)
165 /// where N = size(Original)
166 RangeSet unite(RangeSet Original, llvm::APSInt From, llvm::APSInt To);
167
168 RangeSet getEmptySet() { return &EmptySet; }
169
170 /// Create a new set with just one range.
171 /// @{
172 RangeSet getRangeSet(Range Origin);
173 RangeSet getRangeSet(const llvm::APSInt &From, const llvm::APSInt &To) {
174 return getRangeSet(Range(From, To));
175 }
176 RangeSet getRangeSet(const llvm::APSInt &Origin) {
177 return getRangeSet(Origin, Origin);
178 }
179 /// @}
180
181 /// Create a set with all values of the given type.
183
184 /// Intersect the given range sets.
185 ///
186 /// Complexity: O(N + M)
187 /// where N = size(LHS), M = size(RHS)
189 /// Intersect the given set with the closed range [Lower, Upper].
190 ///
191 /// Unlike the Range type, this range uses modular arithmetic, corresponding
192 /// to the common treatment of C integer overflow. Thus, if the Lower bound
193 /// is greater than the Upper bound, the range is taken to wrap around. This
194 /// is equivalent to taking the intersection with the two ranges [Min,
195 /// Upper] and [Lower, Max], or, alternatively, /removing/ all integers
196 /// between Upper and Lower.
197 ///
198 /// Complexity: O(N)
199 /// where N = size(What)
200 RangeSet intersect(RangeSet What, llvm::APSInt Lower, llvm::APSInt Upper);
201 /// Intersect the given range with the given point.
202 ///
203 /// The result can be either an empty set or a set containing the given
204 /// point depending on whether the point is in the range set.
205 ///
206 /// Complexity: O(logN)
207 /// where N = size(What)
208 RangeSet intersect(RangeSet What, llvm::APSInt Point);
209
210 /// Delete the given point from the range set.
211 ///
212 /// Complexity: O(N)
213 /// where N = size(From)
214 RangeSet deletePoint(RangeSet From, const llvm::APSInt &Point);
215 /// Negate the given range set.
216 ///
217 /// Turn all [A, B] ranges to [-B, -A], when "-" is a C-like unary minus
218 /// operation under the values of the type.
219 ///
220 /// We also handle MIN because applying unary minus to MIN does not change
221 /// it.
222 /// Example 1:
223 /// char x = -128; // -128 is a MIN value in a range of 'char'
224 /// char y = -x; // y: -128
225 ///
226 /// Example 2:
227 /// unsigned char x = 0; // 0 is a MIN value in a range of 'unsigned char'
228 /// unsigned char y = -x; // y: 0
229 ///
230 /// And it makes us to separate the range
231 /// like [MIN, N] to [MIN, MIN] U [-N, MAX].
232 /// For instance, whole range is {-128..127} and subrange is [-128,-126],
233 /// thus [-128,-127,-126,...] negates to [-128,...,126,127].
234 ///
235 /// Negate restores disrupted ranges on bounds,
236 /// e.g. [MIN, B] => [MIN, MIN] U [-B, MAX] => [MIN, B].
237 ///
238 /// Negate is a self-inverse function, i.e. negate(negate(R)) == R.
239 ///
240 /// Complexity: O(N)
241 /// where N = size(What)
243 /// Performs promotions, truncations and conversions of the given set.
244 ///
245 /// This function is optimized for each of the six cast cases:
246 /// - noop
247 /// - conversion
248 /// - truncation
249 /// - truncation-conversion
250 /// - promotion
251 /// - promotion-conversion
252 ///
253 /// NOTE: This function is NOT self-inverse for truncations, because of
254 /// the higher bits loss:
255 /// - castTo(castTo(OrigRangeOfInt, char), int) != OrigRangeOfInt.
256 /// - castTo(castTo(OrigRangeOfChar, int), char) == OrigRangeOfChar.
257 /// But it is self-inverse for all the rest casts.
258 ///
259 /// Complexity:
260 /// - Noop O(1);
261 /// - Truncation O(N^2);
262 /// - Another case O(N);
263 /// where N = size(What)
266
267 /// Return associated value factory.
268 BasicValueFactory &getValueFactory() const { return ValueFactory; }
269
270 private:
271 /// Return a persistent version of the given container.
272 RangeSet makePersistent(ContainerType &&From);
273 /// Construct a new persistent version of the given container.
274 ContainerType *construct(ContainerType &&From);
275
276 RangeSet intersect(const ContainerType &LHS, const ContainerType &RHS);
277 /// NOTE: This function relies on the fact that all values in the
278 /// containers are persistent (created via BasicValueFactory::getValue).
279 ContainerType unite(const ContainerType &LHS, const ContainerType &RHS);
280
281 /// This is a helper function for `castTo` method. Implies not to be used
282 /// separately.
283 /// Performs a truncation case of a cast operation.
284 ContainerType truncateTo(RangeSet What, APSIntType Ty);
285
286 /// This is a helper function for `castTo` method. Implies not to be used
287 /// separately.
288 /// Performs a conversion case and a promotion-conversion case for signeds
289 /// of a cast operation.
290 ContainerType convertTo(RangeSet What, APSIntType Ty);
291
292 /// This is a helper function for `castTo` method. Implies not to be used
293 /// separately.
294 /// Performs a promotion for unsigneds only.
295 ContainerType promoteTo(RangeSet What, APSIntType Ty);
296
297 // Many operations include producing new APSInt values and that's why
298 // we need this factory.
299 BasicValueFactory &ValueFactory;
300 // Allocator for all the created containers.
301 // Containers might own their own memory and that's why it is specific
302 // for the type, so it calls container destructors upon deletion.
303 llvm::SpecificBumpPtrAllocator<ContainerType> Arena;
304 // Usually we deal with the same ranges and range sets over and over.
305 // Here we track all created containers and try not to repeat ourselves.
306 llvm::FoldingSet<ContainerType> Cache;
307 // Full range sets per integer type. Bounded by the number of distinct
308 // (bit width, signedness) pairs.
310 FullRangeSets;
311 static const ContainerType EmptySet;
312 };
313
314 RangeSet(const RangeSet &) = default;
315 RangeSet &operator=(const RangeSet &) = default;
316 RangeSet(RangeSet &&) = default;
318 ~RangeSet() = default;
319
320 /// Construct a new RangeSet representing '{ [From, To] }'.
321 RangeSet(Factory &F, const llvm::APSInt &From, const llvm::APSInt &To)
322 : RangeSet(F.getRangeSet(From, To)) {}
323
324 /// Construct a new RangeSet representing the given point as a range.
325 RangeSet(Factory &F, const llvm::APSInt &Point)
326 : RangeSet(F.getRangeSet(Point)) {}
327
328 static void Profile(llvm::FoldingSetNodeID &ID, const RangeSet &RS) {
329 ID.AddPointer(RS.Impl);
330 }
331
332 /// Profile - Generates a hash profile of this RangeSet for use
333 /// by FoldingSet.
334 void Profile(llvm::FoldingSetNodeID &ID) const { Profile(ID, *this); }
335
336 /// getConcreteValue - If a symbol is constrained to equal a specific integer
337 /// constant then this method returns that value. Otherwise, it returns
338 /// NULL.
339 const llvm::APSInt *getConcreteValue() const {
340 return Impl->size() == 1 ? begin()->getConcreteValue() : nullptr;
341 }
342
343 /// Get the minimal value covered by the ranges in the set.
344 ///
345 /// Complexity: O(1)
346 const llvm::APSInt &getMinValue() const;
347 /// Get the maximal value covered by the ranges in the set.
348 ///
349 /// Complexity: O(1)
350 const llvm::APSInt &getMaxValue() const;
351
352 bool isUnsigned() const;
353 uint32_t getBitWidth() const;
355
356 /// Test whether the given point is contained by any of the ranges.
357 ///
358 /// Complexity: O(logN)
359 /// where N = size(this)
360 bool contains(llvm::APSInt Point) const { return containsImpl(Point); }
361
362 bool containsZero() const {
364 return contains(T.getZeroValue());
365 }
366
367 /// Test if the range is the [0,0] range.
368 ///
369 /// Complexity: O(1)
370 bool encodesFalseRange() const {
371 const llvm::APSInt *Constant = getConcreteValue();
372 return Constant && Constant->isZero();
373 }
374
375 /// Test if the range doesn't contain zero.
376 ///
377 /// Complexity: O(logN)
378 /// where N = size(this)
379 bool encodesTrueRange() const { return !containsZero(); }
380
381 void dump(raw_ostream &OS) const;
382 void dump() const;
383
384 bool operator==(const RangeSet &Other) const { return *Impl == *Other.Impl; }
385 bool operator!=(const RangeSet &Other) const { return !(*this == Other); }
386
387private:
388 /* implicit */ RangeSet(ContainerType *RawContainer) : Impl(RawContainer) {}
389 /* implicit */ RangeSet(UnderlyingType Ptr) : Impl(Ptr) {}
390
391 /// Pin given points to the type represented by the current range set.
392 ///
393 /// This makes parameter points to be in-out parameters.
394 /// In order to maintain consistent types across all of the ranges in the set
395 /// and to keep all the operations to compare ONLY points of the same type, we
396 /// need to pin every point before any operation.
397 ///
398 /// @Returns true if the given points can be converted to the target type
399 /// without changing the values (i.e. trivially) and false otherwise.
400 /// @{
401 bool pin(llvm::APSInt &Lower, llvm::APSInt &Upper) const;
402 bool pin(llvm::APSInt &Point) const;
403 /// @}
404
405 // This version of this function modifies its arguments (pins it).
406 bool containsImpl(llvm::APSInt &Point) const;
407
408 friend class Factory;
409};
410
411using ConstraintMap = llvm::ImmutableMap<SymbolRef, RangeSet>;
413
415public:
418
419 ~RangedConstraintManager() override;
420
421 //===------------------------------------------------------------------===//
422 // Implementation for interface from SimpleConstraintManager.
423 //===------------------------------------------------------------------===//
424
426 bool Assumption) override;
427
429 const llvm::APSInt &From,
430 const llvm::APSInt &To,
431 bool InRange) override;
432
434 bool Assumption) override;
435
436protected:
437 /// Assume a constraint between a symbolic expression and a concrete integer.
440 const llvm::APSInt &Int);
441
442 //===------------------------------------------------------------------===//
443 // Interface that subclasses must implement.
444 //===------------------------------------------------------------------===//
445
446 // Each of these is of the form "$Sym+Adj <> V", where "<>" is the comparison
447 // operation for the method being invoked.
448
450 const llvm::APSInt &V,
451 const llvm::APSInt &Adjustment) = 0;
452
454 const llvm::APSInt &V,
455 const llvm::APSInt &Adjustment) = 0;
456
458 const llvm::APSInt &V,
459 const llvm::APSInt &Adjustment) = 0;
460
462 const llvm::APSInt &V,
463 const llvm::APSInt &Adjustment) = 0;
464
466 const llvm::APSInt &V,
467 const llvm::APSInt &Adjustment) = 0;
468
470 const llvm::APSInt &V,
471 const llvm::APSInt &Adjustment) = 0;
472
474 ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
475 const llvm::APSInt &To, const llvm::APSInt &Adjustment) = 0;
476
478 ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
479 const llvm::APSInt &To, const llvm::APSInt &Adjustment) = 0;
480
481 //===------------------------------------------------------------------===//
482 // Internal implementation.
483 //===------------------------------------------------------------------===//
484private:
485 static void computeAdjustment(SymbolRef &Sym, llvm::APSInt &Adjustment);
486};
487
488/// Try to simplify a given symbolic expression's associated `SVal` based on the
489/// constraints in State.
491
492} // namespace ento
493} // namespace clang
494
496
497#endif
#define V(N, I)
#define REGISTER_FACTORY_WITH_PROGRAMSTATE(Type)
Declares a factory for objects of type Type in the program state manager.
BinaryOperatorKind Opcode
Definition Expr.h:4112
A (possibly-)qualified type.
Definition TypeBase.h:938
A record of the "type" of an APSInt, used for conversions.
Definition APSIntType.h:19
RangeSet getRangeSet(const llvm::APSInt &Origin)
RangeSet unite(RangeSet LHS, RangeSet RHS)
Create a new set which is a union of two given ranges.
RangeSet negate(RangeSet What)
Negate the given range set.
RangeSet intersect(RangeSet LHS, RangeSet RHS)
Intersect the given range sets.
RangeSet deletePoint(RangeSet From, const llvm::APSInt &Point)
Delete the given point from the range set.
RangeSet getRangeSet(Range Origin)
Create a new set with just one range.
BasicValueFactory & getValueFactory() const
Return associated value factory.
RangeSet add(RangeSet LHS, RangeSet RHS)
Create a new set with all ranges from both LHS and RHS.
RangeSet castTo(RangeSet What, APSIntType Ty)
Performs promotions, truncations and conversions of the given set.
RangeSet getRangeSet(const llvm::APSInt &From, const llvm::APSInt &To)
RangeSet getFullRangeSet(APSIntType Ty)
Create a set with all values of the given type.
const_iterator end() const
const llvm::APSInt & getMaxValue() const
Get the maximal value covered by the ranges in the set.
RangeSet(const RangeSet &)=default
bool encodesTrueRange() const
Test if the range doesn't contain zero.
RangeSet & operator=(const RangeSet &)=default
RangeSet(Factory &F, const llvm::APSInt &Point)
Construct a new RangeSet representing the given point as a range.
bool encodesFalseRange() const
Test if the range is the [0,0] range.
const_iterator begin() const
const llvm::APSInt & getMinValue() const
Get the minimal value covered by the ranges in the set.
bool operator!=(const RangeSet &Other) const
ImplType::const_iterator const_iterator
RangeSet & operator=(RangeSet &&)=default
RangeSet(Factory &F, const llvm::APSInt &From, const llvm::APSInt &To)
Construct a new RangeSet representing '{ [From, To] }'.
RangeSet(RangeSet &&)=default
static void Profile(llvm::FoldingSetNodeID &ID, const RangeSet &RS)
bool contains(llvm::APSInt Point) const
Test whether the given point is contained by any of the ranges.
void Profile(llvm::FoldingSetNodeID &ID) const
Profile - Generates a hash profile of this RangeSet for use by FoldingSet.
bool operator==(const RangeSet &Other) const
const llvm::APSInt * getConcreteValue() const
getConcreteValue - If a symbol is constrained to equal a specific integer constant then this method r...
A Range represents the closed range [from, to].
const llvm::APSInt & From() const
Range(const llvm::APSInt &From, const llvm::APSInt &To)
bool operator!=(const Range &RHS) const
void Profile(llvm::FoldingSetNodeID &ID) const
Range(const llvm::APSInt &Point)
bool operator<(const Range &RHS) const
bool Includes(const llvm::APSInt &Point) const
const llvm::APSInt * getConcreteValue() const
bool operator==(const Range &RHS) const
const llvm::APSInt & To() const
virtual ProgramStateRef assumeSymNE(ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &V, const llvm::APSInt &Adjustment)=0
virtual ProgramStateRef assumeSymLE(ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &V, const llvm::APSInt &Adjustment)=0
virtual ProgramStateRef assumeSymWithinInclusiveRange(ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From, const llvm::APSInt &To, const llvm::APSInt &Adjustment)=0
ProgramStateRef assumeSym(ProgramStateRef State, SymbolRef Sym, bool Assumption) override
Given a symbolic expression that can be reasoned about, assume that it is true/false and generate the...
ProgramStateRef assumeSymRel(ProgramStateRef State, SymbolRef Sym, BinaryOperator::Opcode op, const llvm::APSInt &Int)
Assume a constraint between a symbolic expression and a concrete integer.
ProgramStateRef assumeSymUnsupported(ProgramStateRef State, SymbolRef Sym, bool Assumption) override
Given a symbolic expression that cannot be reasoned about, assume that it is zero/nonzero and add it ...
virtual ProgramStateRef assumeSymOutsideInclusiveRange(ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From, const llvm::APSInt &To, const llvm::APSInt &Adjustment)=0
virtual ProgramStateRef assumeSymGE(ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &V, const llvm::APSInt &Adjustment)=0
virtual ProgramStateRef assumeSymGT(ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &V, const llvm::APSInt &Adjustment)=0
ProgramStateRef assumeSymInclusiveRange(ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From, const llvm::APSInt &To, bool InRange) override
Given a symbolic expression within the range [From, To], assume that it is true/false and generate th...
virtual ProgramStateRef assumeSymEQ(ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &V, const llvm::APSInt &Adjustment)=0
RangedConstraintManager(ExprEngine *EE, SValBuilder &SB)
virtual ProgramStateRef assumeSymLT(ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &V, const llvm::APSInt &Adjustment)=0
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
SimpleConstraintManager(ExprEngine *exprengine, SValBuilder &SB)
SVal simplifyToSVal(ProgramStateRef State, SymbolRef Sym)
Try to simplify a given symbolic expression's associated SVal based on the constraints in State.
llvm::ImmutableMap< SymbolRef, RangeSet > ConstraintMap
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:166
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
ConstraintMap getConstraintMap(ProgramStateRef State)
Top level wrappers for InstallAPI frontend operations.