Bug Summary

File:tools/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp
Warning:line 179, column 1
Potential leak of memory pointed to by 'AttrNonNull.X'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name NonNullParamChecker.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/lib/StaticAnalyzer/Checkers -I /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/StaticAnalyzer/Checkers -I /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn350071/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/lib/StaticAnalyzer/Checkers -fdebug-prefix-map=/build/llvm-toolchain-snapshot-8~svn350071=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-12-27-042839-1215-1 -x c++ /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp

1//===--- NonNullParamChecker.cpp - Undefined arguments checker -*- 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 defines NonNullParamChecker, which checks for arguments expected not to
11// be null due to:
12// - the corresponding parameters being declared to have nonnull attribute
13// - the corresponding parameters being references; since the call would form
14// a reference to a null pointer
15//
16//===----------------------------------------------------------------------===//
17
18#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
19#include "clang/AST/Attr.h"
20#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
21#include "clang/StaticAnalyzer/Core/Checker.h"
22#include "clang/StaticAnalyzer/Core/CheckerManager.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
24#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
25
26using namespace clang;
27using namespace ento;
28
29namespace {
30class NonNullParamChecker
31 : public Checker< check::PreCall, EventDispatcher<ImplicitNullDerefEvent> > {
32 mutable std::unique_ptr<BugType> BTAttrNonNull;
33 mutable std::unique_ptr<BugType> BTNullRefArg;
34
35public:
36
37 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
38
39 std::unique_ptr<BugReport>
40 genReportNullAttrNonNull(const ExplodedNode *ErrorN, const Expr *ArgE) const;
41 std::unique_ptr<BugReport>
42 genReportReferenceToNullPointer(const ExplodedNode *ErrorN,
43 const Expr *ArgE) const;
44};
45} // end anonymous namespace
46
47/// \return Bitvector marking non-null attributes.
48static llvm::SmallBitVector getNonNullAttrs(const CallEvent &Call) {
49 const Decl *FD = Call.getDecl();
50 unsigned NumArgs = Call.getNumArgs();
51 llvm::SmallBitVector AttrNonNull(NumArgs);
4
Calling constructor for 'SmallBitVector'
8
Returning from constructor for 'SmallBitVector'
52 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
53 if (!NonNull->args_size()) {
54 AttrNonNull.set(0, NumArgs);
55 break;
56 }
57 for (const ParamIdx &Idx : NonNull->args()) {
58 unsigned IdxAST = Idx.getASTIndex();
59 if (IdxAST >= NumArgs)
60 continue;
61 AttrNonNull.set(IdxAST);
62 }
63 }
64 return AttrNonNull;
65}
66
67void NonNullParamChecker::checkPreCall(const CallEvent &Call,
68 CheckerContext &C) const {
69 if (!Call.getDecl())
1
Assuming the condition is false
2
Taking false branch
70 return;
71
72 llvm::SmallBitVector AttrNonNull = getNonNullAttrs(Call);
3
Calling 'getNonNullAttrs'
9
Returned allocated memory
73 unsigned NumArgs = Call.getNumArgs();
74
75 ProgramStateRef state = C.getState();
76 ArrayRef<ParmVarDecl*> parms = Call.parameters();
77
78 for (unsigned idx = 0; idx < NumArgs; ++idx) {
10
Assuming 'idx' is >= 'NumArgs'
11
Loop condition is false. Execution continues on line 178
79 // For vararg functions, a corresponding parameter decl may not exist.
80 bool HasParam = idx < parms.size();
81
82 // Check if the parameter is a reference. We want to report when reference
83 // to a null pointer is passed as a parameter.
84 bool haveRefTypeParam =
85 HasParam ? parms[idx]->getType()->isReferenceType() : false;
86 bool haveAttrNonNull = AttrNonNull[idx];
87
88 // Check if the parameter is also marked 'nonnull'.
89 if (!haveAttrNonNull && HasParam)
90 haveAttrNonNull = parms[idx]->hasAttr<NonNullAttr>();
91
92 if (!haveAttrNonNull && !haveRefTypeParam)
93 continue;
94
95 // If the value is unknown or undefined, we can't perform this check.
96 const Expr *ArgE = Call.getArgExpr(idx);
97 SVal V = Call.getArgSVal(idx);
98 auto DV = V.getAs<DefinedSVal>();
99 if (!DV)
100 continue;
101
102 assert(!haveRefTypeParam || DV->getAs<Loc>())((!haveRefTypeParam || DV->getAs<Loc>()) ? static_cast
<void> (0) : __assert_fail ("!haveRefTypeParam || DV->getAs<Loc>()"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp"
, 102, __PRETTY_FUNCTION__))
;
103
104 // Process the case when the argument is not a location.
105 if (haveAttrNonNull && !DV->getAs<Loc>()) {
106 // If the argument is a union type, we want to handle a potential
107 // transparent_union GCC extension.
108 if (!ArgE)
109 continue;
110
111 QualType T = ArgE->getType();
112 const RecordType *UT = T->getAsUnionType();
113 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
114 continue;
115
116 auto CSV = DV->getAs<nonloc::CompoundVal>();
117
118 // FIXME: Handle LazyCompoundVals?
119 if (!CSV)
120 continue;
121
122 V = *(CSV->begin());
123 DV = V.getAs<DefinedSVal>();
124 assert(++CSV->begin() == CSV->end())((++CSV->begin() == CSV->end()) ? static_cast<void>
(0) : __assert_fail ("++CSV->begin() == CSV->end()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp"
, 124, __PRETTY_FUNCTION__))
;
125 // FIXME: Handle (some_union){ some_other_union_val }, which turns into
126 // a LazyCompoundVal inside a CompoundVal.
127 if (!V.getAs<Loc>())
128 continue;
129
130 // Retrieve the corresponding expression.
131 if (const auto *CE = dyn_cast<CompoundLiteralExpr>(ArgE))
132 if (const auto *IE = dyn_cast<InitListExpr>(CE->getInitializer()))
133 ArgE = dyn_cast<Expr>(*(IE->begin()));
134 }
135
136 ConstraintManager &CM = C.getConstraintManager();
137 ProgramStateRef stateNotNull, stateNull;
138 std::tie(stateNotNull, stateNull) = CM.assumeDual(state, *DV);
139
140 // Generate an error node. Check for a null node in case
141 // we cache out.
142 if (stateNull && !stateNotNull) {
143 if (ExplodedNode *errorNode = C.generateErrorNode(stateNull)) {
144
145 std::unique_ptr<BugReport> R;
146 if (haveAttrNonNull)
147 R = genReportNullAttrNonNull(errorNode, ArgE);
148 else if (haveRefTypeParam)
149 R = genReportReferenceToNullPointer(errorNode, ArgE);
150
151 // Highlight the range of the argument that was null.
152 R->addRange(Call.getArgSourceRange(idx));
153
154 // Emit the bug report.
155 C.emitReport(std::move(R));
156 }
157
158 // Always return. Either we cached out or we just emitted an error.
159 return;
160 }
161
162 if (stateNull) {
163 if (ExplodedNode *N = C.generateSink(stateNull, C.getPredecessor())) {
164 ImplicitNullDerefEvent event = {
165 V, false, N, &C.getBugReporter(),
166 /*IsDirectDereference=*/haveRefTypeParam};
167 dispatchEvent(event);
168 }
169 }
170
171 // If a pointer value passed the check we should assume that it is
172 // indeed not null from this point forward.
173 state = stateNotNull;
174 }
175
176 // If we reach here all of the arguments passed the nonnull check.
177 // If 'state' has been updated generated a new node.
178 C.addTransition(state);
179}
12
Potential leak of memory pointed to by 'AttrNonNull.X'
180
181std::unique_ptr<BugReport>
182NonNullParamChecker::genReportNullAttrNonNull(const ExplodedNode *ErrorNode,
183 const Expr *ArgE) const {
184 // Lazily allocate the BugType object if it hasn't already been
185 // created. Ownership is transferred to the BugReporter object once
186 // the BugReport is passed to 'EmitWarning'.
187 if (!BTAttrNonNull)
188 BTAttrNonNull.reset(new BugType(
189 this, "Argument with 'nonnull' attribute passed null", "API"));
190
191 auto R = llvm::make_unique<BugReport>(
192 *BTAttrNonNull,
193 "Null pointer passed as an argument to a 'nonnull' parameter", ErrorNode);
194 if (ArgE)
195 bugreporter::trackExpressionValue(ErrorNode, ArgE, *R);
196
197 return R;
198}
199
200std::unique_ptr<BugReport> NonNullParamChecker::genReportReferenceToNullPointer(
201 const ExplodedNode *ErrorNode, const Expr *ArgE) const {
202 if (!BTNullRefArg)
203 BTNullRefArg.reset(new BuiltinBug(this, "Dereference of null pointer"));
204
205 auto R = llvm::make_unique<BugReport>(
206 *BTNullRefArg, "Forming reference to null pointer", ErrorNode);
207 if (ArgE) {
208 const Expr *ArgEDeref = bugreporter::getDerefExpr(ArgE);
209 if (!ArgEDeref)
210 ArgEDeref = ArgE;
211 bugreporter::trackExpressionValue(ErrorNode, ArgEDeref, *R);
212 }
213 return R;
214
215}
216
217void ento::registerNonNullParamChecker(CheckerManager &mgr) {
218 mgr.registerChecker<NonNullParamChecker>();
219}

/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h

1//===- llvm/ADT/SmallBitVector.h - 'Normally small' bit vectors -*- 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 implements the SmallBitVector class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_SMALLBITVECTOR_H
15#define LLVM_ADT_SMALLBITVECTOR_H
16
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/iterator_range.h"
19#include "llvm/Support/MathExtras.h"
20#include <algorithm>
21#include <cassert>
22#include <climits>
23#include <cstddef>
24#include <cstdint>
25#include <limits>
26#include <utility>
27
28namespace llvm {
29
30/// This is a 'bitvector' (really, a variable-sized bit array), optimized for
31/// the case when the array is small. It contains one pointer-sized field, which
32/// is directly used as a plain collection of bits when possible, or as a
33/// pointer to a larger heap-allocated array when necessary. This allows normal
34/// "small" cases to be fast without losing generality for large inputs.
35class SmallBitVector {
36 // TODO: In "large" mode, a pointer to a BitVector is used, leading to an
37 // unnecessary level of indirection. It would be more efficient to use a
38 // pointer to memory containing size, allocation size, and the array of bits.
39 uintptr_t X = 1;
40
41 enum {
42 // The number of bits in this class.
43 NumBaseBits = sizeof(uintptr_t) * CHAR_BIT8,
44
45 // One bit is used to discriminate between small and large mode. The
46 // remaining bits are used for the small-mode representation.
47 SmallNumRawBits = NumBaseBits - 1,
48
49 // A few more bits are used to store the size of the bit set in small mode.
50 // Theoretically this is a ceil-log2. These bits are encoded in the most
51 // significant bits of the raw bits.
52 SmallNumSizeBits = (NumBaseBits == 32 ? 5 :
53 NumBaseBits == 64 ? 6 :
54 SmallNumRawBits),
55
56 // The remaining bits are used to store the actual set in small mode.
57 SmallNumDataBits = SmallNumRawBits - SmallNumSizeBits
58 };
59
60 static_assert(NumBaseBits == 64 || NumBaseBits == 32,
61 "Unsupported word size");
62
63public:
64 using size_type = unsigned;
65
66 // Encapsulation of a single bit.
67 class reference {
68 SmallBitVector &TheVector;
69 unsigned BitPos;
70
71 public:
72 reference(SmallBitVector &b, unsigned Idx) : TheVector(b), BitPos(Idx) {}
73
74 reference(const reference&) = default;
75
76 reference& operator=(reference t) {
77 *this = bool(t);
78 return *this;
79 }
80
81 reference& operator=(bool t) {
82 if (t)
83 TheVector.set(BitPos);
84 else
85 TheVector.reset(BitPos);
86 return *this;
87 }
88
89 operator bool() const {
90 return const_cast<const SmallBitVector &>(TheVector).operator[](BitPos);
91 }
92 };
93
94private:
95 BitVector *getPointer() const {
96 assert(!isSmall())((!isSmall()) ? static_cast<void> (0) : __assert_fail (
"!isSmall()", "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h"
, 96, __PRETTY_FUNCTION__))
;
97 return reinterpret_cast<BitVector *>(X);
98 }
99
100 void switchToSmall(uintptr_t NewSmallBits, size_t NewSize) {
101 X = 1;
102 setSmallSize(NewSize);
103 setSmallBits(NewSmallBits);
104 }
105
106 void switchToLarge(BitVector *BV) {
107 X = reinterpret_cast<uintptr_t>(BV);
108 assert(!isSmall() && "Tried to use an unaligned pointer")((!isSmall() && "Tried to use an unaligned pointer") ?
static_cast<void> (0) : __assert_fail ("!isSmall() && \"Tried to use an unaligned pointer\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h"
, 108, __PRETTY_FUNCTION__))
;
109 }
110
111 // Return all the bits used for the "small" representation; this includes
112 // bits for the size as well as the element bits.
113 uintptr_t getSmallRawBits() const {
114 assert(isSmall())((isSmall()) ? static_cast<void> (0) : __assert_fail ("isSmall()"
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h"
, 114, __PRETTY_FUNCTION__))
;
115 return X >> 1;
116 }
117
118 void setSmallRawBits(uintptr_t NewRawBits) {
119 assert(isSmall())((isSmall()) ? static_cast<void> (0) : __assert_fail ("isSmall()"
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h"
, 119, __PRETTY_FUNCTION__))
;
120 X = (NewRawBits << 1) | uintptr_t(1);
121 }
122
123 // Return the size.
124 size_t getSmallSize() const { return getSmallRawBits() >> SmallNumDataBits; }
125
126 void setSmallSize(size_t Size) {
127 setSmallRawBits(getSmallBits() | (Size << SmallNumDataBits));
128 }
129
130 // Return the element bits.
131 uintptr_t getSmallBits() const {
132 return getSmallRawBits() & ~(~uintptr_t(0) << getSmallSize());
133 }
134
135 void setSmallBits(uintptr_t NewBits) {
136 setSmallRawBits((NewBits & ~(~uintptr_t(0) << getSmallSize())) |
137 (getSmallSize() << SmallNumDataBits));
138 }
139
140public:
141 /// Creates an empty bitvector.
142 SmallBitVector() = default;
143
144 /// Creates a bitvector of specified number of bits. All bits are initialized
145 /// to the specified value.
146 explicit SmallBitVector(unsigned s, bool t = false) {
147 if (s <= SmallNumDataBits)
5
Assuming 's' is > SmallNumDataBits
6
Taking false branch
148 switchToSmall(t ? ~uintptr_t(0) : 0, s);
149 else
150 switchToLarge(new BitVector(s, t));
7
Memory is allocated
151 }
152
153 /// SmallBitVector copy ctor.
154 SmallBitVector(const SmallBitVector &RHS) {
155 if (RHS.isSmall())
156 X = RHS.X;
157 else
158 switchToLarge(new BitVector(*RHS.getPointer()));
159 }
160
161 SmallBitVector(SmallBitVector &&RHS) : X(RHS.X) {
162 RHS.X = 1;
163 }
164
165 ~SmallBitVector() {
166 if (!isSmall())
167 delete getPointer();
168 }
169
170 using const_set_bits_iterator = const_set_bits_iterator_impl<SmallBitVector>;
171 using set_iterator = const_set_bits_iterator;
172
173 const_set_bits_iterator set_bits_begin() const {
174 return const_set_bits_iterator(*this);
175 }
176
177 const_set_bits_iterator set_bits_end() const {
178 return const_set_bits_iterator(*this, -1);
179 }
180
181 iterator_range<const_set_bits_iterator> set_bits() const {
182 return make_range(set_bits_begin(), set_bits_end());
183 }
184
185 bool isSmall() const { return X & uintptr_t(1); }
186
187 /// Tests whether there are no bits in this bitvector.
188 bool empty() const {
189 return isSmall() ? getSmallSize() == 0 : getPointer()->empty();
190 }
191
192 /// Returns the number of bits in this bitvector.
193 size_t size() const {
194 return isSmall() ? getSmallSize() : getPointer()->size();
195 }
196
197 /// Returns the number of bits which are set.
198 size_type count() const {
199 if (isSmall()) {
200 uintptr_t Bits = getSmallBits();
201 return countPopulation(Bits);
202 }
203 return getPointer()->count();
204 }
205
206 /// Returns true if any bit is set.
207 bool any() const {
208 if (isSmall())
209 return getSmallBits() != 0;
210 return getPointer()->any();
211 }
212
213 /// Returns true if all bits are set.
214 bool all() const {
215 if (isSmall())
216 return getSmallBits() == (uintptr_t(1) << getSmallSize()) - 1;
217 return getPointer()->all();
218 }
219
220 /// Returns true if none of the bits are set.
221 bool none() const {
222 if (isSmall())
223 return getSmallBits() == 0;
224 return getPointer()->none();
225 }
226
227 /// Returns the index of the first set bit, -1 if none of the bits are set.
228 int find_first() const {
229 if (isSmall()) {
230 uintptr_t Bits = getSmallBits();
231 if (Bits == 0)
232 return -1;
233 return countTrailingZeros(Bits);
234 }
235 return getPointer()->find_first();
236 }
237
238 int find_last() const {
239 if (isSmall()) {
240 uintptr_t Bits = getSmallBits();
241 if (Bits == 0)
242 return -1;
243 return NumBaseBits - countLeadingZeros(Bits) - 1;
244 }
245 return getPointer()->find_last();
246 }
247
248 /// Returns the index of the first unset bit, -1 if all of the bits are set.
249 int find_first_unset() const {
250 if (isSmall()) {
251 if (count() == getSmallSize())
252 return -1;
253
254 uintptr_t Bits = getSmallBits();
255 return countTrailingOnes(Bits);
256 }
257 return getPointer()->find_first_unset();
258 }
259
260 int find_last_unset() const {
261 if (isSmall()) {
262 if (count() == getSmallSize())
263 return -1;
264
265 uintptr_t Bits = getSmallBits();
266 // Set unused bits.
267 Bits |= ~uintptr_t(0) << getSmallSize();
268 return NumBaseBits - countLeadingOnes(Bits) - 1;
269 }
270 return getPointer()->find_last_unset();
271 }
272
273 /// Returns the index of the next set bit following the "Prev" bit.
274 /// Returns -1 if the next set bit is not found.
275 int find_next(unsigned Prev) const {
276 if (isSmall()) {
277 uintptr_t Bits = getSmallBits();
278 // Mask off previous bits.
279 Bits &= ~uintptr_t(0) << (Prev + 1);
280 if (Bits == 0 || Prev + 1 >= getSmallSize())
281 return -1;
282 return countTrailingZeros(Bits);
283 }
284 return getPointer()->find_next(Prev);
285 }
286
287 /// Returns the index of the next unset bit following the "Prev" bit.
288 /// Returns -1 if the next unset bit is not found.
289 int find_next_unset(unsigned Prev) const {
290 if (isSmall()) {
291 ++Prev;
292 uintptr_t Bits = getSmallBits();
293 // Mask in previous bits.
294 uintptr_t Mask = (1 << Prev) - 1;
295 Bits |= Mask;
296
297 if (Bits == ~uintptr_t(0) || Prev + 1 >= getSmallSize())
298 return -1;
299 return countTrailingOnes(Bits);
300 }
301 return getPointer()->find_next_unset(Prev);
302 }
303
304 /// find_prev - Returns the index of the first set bit that precedes the
305 /// the bit at \p PriorTo. Returns -1 if all previous bits are unset.
306 int find_prev(unsigned PriorTo) const {
307 if (isSmall()) {
308 if (PriorTo == 0)
309 return -1;
310
311 --PriorTo;
312 uintptr_t Bits = getSmallBits();
313 Bits &= maskTrailingOnes<uintptr_t>(PriorTo + 1);
314 if (Bits == 0)
315 return -1;
316
317 return NumBaseBits - countLeadingZeros(Bits) - 1;
318 }
319 return getPointer()->find_prev(PriorTo);
320 }
321
322 /// Clear all bits.
323 void clear() {
324 if (!isSmall())
325 delete getPointer();
326 switchToSmall(0, 0);
327 }
328
329 /// Grow or shrink the bitvector.
330 void resize(unsigned N, bool t = false) {
331 if (!isSmall()) {
332 getPointer()->resize(N, t);
333 } else if (SmallNumDataBits >= N) {
334 uintptr_t NewBits = t ? ~uintptr_t(0) << getSmallSize() : 0;
335 setSmallSize(N);
336 setSmallBits(NewBits | getSmallBits());
337 } else {
338 BitVector *BV = new BitVector(N, t);
339 uintptr_t OldBits = getSmallBits();
340 for (size_t i = 0, e = getSmallSize(); i != e; ++i)
341 (*BV)[i] = (OldBits >> i) & 1;
342 switchToLarge(BV);
343 }
344 }
345
346 void reserve(unsigned N) {
347 if (isSmall()) {
348 if (N > SmallNumDataBits) {
349 uintptr_t OldBits = getSmallRawBits();
350 size_t SmallSize = getSmallSize();
351 BitVector *BV = new BitVector(SmallSize);
352 for (size_t i = 0; i < SmallSize; ++i)
353 if ((OldBits >> i) & 1)
354 BV->set(i);
355 BV->reserve(N);
356 switchToLarge(BV);
357 }
358 } else {
359 getPointer()->reserve(N);
360 }
361 }
362
363 // Set, reset, flip
364 SmallBitVector &set() {
365 if (isSmall())
366 setSmallBits(~uintptr_t(0));
367 else
368 getPointer()->set();
369 return *this;
370 }
371
372 SmallBitVector &set(unsigned Idx) {
373 if (isSmall()) {
374 assert(Idx <= static_cast<unsigned>(((Idx <= static_cast<unsigned>( std::numeric_limits<
uintptr_t>::digits) && "undefined behavior") ? static_cast
<void> (0) : __assert_fail ("Idx <= static_cast<unsigned>( std::numeric_limits<uintptr_t>::digits) && \"undefined behavior\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h"
, 376, __PRETTY_FUNCTION__))
375 std::numeric_limits<uintptr_t>::digits) &&((Idx <= static_cast<unsigned>( std::numeric_limits<
uintptr_t>::digits) && "undefined behavior") ? static_cast
<void> (0) : __assert_fail ("Idx <= static_cast<unsigned>( std::numeric_limits<uintptr_t>::digits) && \"undefined behavior\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h"
, 376, __PRETTY_FUNCTION__))
376 "undefined behavior")((Idx <= static_cast<unsigned>( std::numeric_limits<
uintptr_t>::digits) && "undefined behavior") ? static_cast
<void> (0) : __assert_fail ("Idx <= static_cast<unsigned>( std::numeric_limits<uintptr_t>::digits) && \"undefined behavior\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h"
, 376, __PRETTY_FUNCTION__))
;
377 setSmallBits(getSmallBits() | (uintptr_t(1) << Idx));
378 }
379 else
380 getPointer()->set(Idx);
381 return *this;
382 }
383
384 /// Efficiently set a range of bits in [I, E)
385 SmallBitVector &set(unsigned I, unsigned E) {
386 assert(I <= E && "Attempted to set backwards range!")((I <= E && "Attempted to set backwards range!") ?
static_cast<void> (0) : __assert_fail ("I <= E && \"Attempted to set backwards range!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h"
, 386, __PRETTY_FUNCTION__))
;
387 assert(E <= size() && "Attempted to set out-of-bounds range!")((E <= size() && "Attempted to set out-of-bounds range!"
) ? static_cast<void> (0) : __assert_fail ("E <= size() && \"Attempted to set out-of-bounds range!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h"
, 387, __PRETTY_FUNCTION__))
;
388 if (I == E) return *this;
389 if (isSmall()) {
390 uintptr_t EMask = ((uintptr_t)1) << E;
391 uintptr_t IMask = ((uintptr_t)1) << I;
392 uintptr_t Mask = EMask - IMask;
393 setSmallBits(getSmallBits() | Mask);
394 } else
395 getPointer()->set(I, E);
396 return *this;
397 }
398
399 SmallBitVector &reset() {
400 if (isSmall())
401 setSmallBits(0);
402 else
403 getPointer()->reset();
404 return *this;
405 }
406
407 SmallBitVector &reset(unsigned Idx) {
408 if (isSmall())
409 setSmallBits(getSmallBits() & ~(uintptr_t(1) << Idx));
410 else
411 getPointer()->reset(Idx);
412 return *this;
413 }
414
415 /// Efficiently reset a range of bits in [I, E)
416 SmallBitVector &reset(unsigned I, unsigned E) {
417 assert(I <= E && "Attempted to reset backwards range!")((I <= E && "Attempted to reset backwards range!")
? static_cast<void> (0) : __assert_fail ("I <= E && \"Attempted to reset backwards range!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h"
, 417, __PRETTY_FUNCTION__))
;
418 assert(E <= size() && "Attempted to reset out-of-bounds range!")((E <= size() && "Attempted to reset out-of-bounds range!"
) ? static_cast<void> (0) : __assert_fail ("E <= size() && \"Attempted to reset out-of-bounds range!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h"
, 418, __PRETTY_FUNCTION__))
;
419 if (I == E) return *this;
420 if (isSmall()) {
421 uintptr_t EMask = ((uintptr_t)1) << E;
422 uintptr_t IMask = ((uintptr_t)1) << I;
423 uintptr_t Mask = EMask - IMask;
424 setSmallBits(getSmallBits() & ~Mask);
425 } else
426 getPointer()->reset(I, E);
427 return *this;
428 }
429
430 SmallBitVector &flip() {
431 if (isSmall())
432 setSmallBits(~getSmallBits());
433 else
434 getPointer()->flip();
435 return *this;
436 }
437
438 SmallBitVector &flip(unsigned Idx) {
439 if (isSmall())
440 setSmallBits(getSmallBits() ^ (uintptr_t(1) << Idx));
441 else
442 getPointer()->flip(Idx);
443 return *this;
444 }
445
446 // No argument flip.
447 SmallBitVector operator~() const {
448 return SmallBitVector(*this).flip();
449 }
450
451 // Indexing.
452 reference operator[](unsigned Idx) {
453 assert(Idx < size() && "Out-of-bounds Bit access.")((Idx < size() && "Out-of-bounds Bit access.") ? static_cast
<void> (0) : __assert_fail ("Idx < size() && \"Out-of-bounds Bit access.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h"
, 453, __PRETTY_FUNCTION__))
;
454 return reference(*this, Idx);
455 }
456
457 bool operator[](unsigned Idx) const {
458 assert(Idx < size() && "Out-of-bounds Bit access.")((Idx < size() && "Out-of-bounds Bit access.") ? static_cast
<void> (0) : __assert_fail ("Idx < size() && \"Out-of-bounds Bit access.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h"
, 458, __PRETTY_FUNCTION__))
;
459 if (isSmall())
460 return ((getSmallBits() >> Idx) & 1) != 0;
461 return getPointer()->operator[](Idx);
462 }
463
464 bool test(unsigned Idx) const {
465 return (*this)[Idx];
466 }
467
468 // Push single bit to end of vector.
469 void push_back(bool Val) {
470 resize(size() + 1, Val);
471 }
472
473 /// Test if any common bits are set.
474 bool anyCommon(const SmallBitVector &RHS) const {
475 if (isSmall() && RHS.isSmall())
476 return (getSmallBits() & RHS.getSmallBits()) != 0;
477 if (!isSmall() && !RHS.isSmall())
478 return getPointer()->anyCommon(*RHS.getPointer());
479
480 for (unsigned i = 0, e = std::min(size(), RHS.size()); i != e; ++i)
481 if (test(i) && RHS.test(i))
482 return true;
483 return false;
484 }
485
486 // Comparison operators.
487 bool operator==(const SmallBitVector &RHS) const {
488 if (size() != RHS.size())
489 return false;
490 if (isSmall() && RHS.isSmall())
491 return getSmallBits() == RHS.getSmallBits();
492 else if (!isSmall() && !RHS.isSmall())
493 return *getPointer() == *RHS.getPointer();
494 else {
495 for (size_t i = 0, e = size(); i != e; ++i) {
496 if ((*this)[i] != RHS[i])
497 return false;
498 }
499 return true;
500 }
501 }
502
503 bool operator!=(const SmallBitVector &RHS) const {
504 return !(*this == RHS);
505 }
506
507 // Intersection, union, disjoint union.
508 // FIXME BitVector::operator&= does not resize the LHS but this does
509 SmallBitVector &operator&=(const SmallBitVector &RHS) {
510 resize(std::max(size(), RHS.size()));
511 if (isSmall() && RHS.isSmall())
512 setSmallBits(getSmallBits() & RHS.getSmallBits());
513 else if (!isSmall() && !RHS.isSmall())
514 getPointer()->operator&=(*RHS.getPointer());
515 else {
516 size_t i, e;
517 for (i = 0, e = std::min(size(), RHS.size()); i != e; ++i)
518 (*this)[i] = test(i) && RHS.test(i);
519 for (e = size(); i != e; ++i)
520 reset(i);
521 }
522 return *this;
523 }
524
525 /// Reset bits that are set in RHS. Same as *this &= ~RHS.
526 SmallBitVector &reset(const SmallBitVector &RHS) {
527 if (isSmall() && RHS.isSmall())
528 setSmallBits(getSmallBits() & ~RHS.getSmallBits());
529 else if (!isSmall() && !RHS.isSmall())
530 getPointer()->reset(*RHS.getPointer());
531 else
532 for (unsigned i = 0, e = std::min(size(), RHS.size()); i != e; ++i)
533 if (RHS.test(i))
534 reset(i);
535
536 return *this;
537 }
538
539 /// Check if (This - RHS) is zero. This is the same as reset(RHS) and any().
540 bool test(const SmallBitVector &RHS) const {
541 if (isSmall() && RHS.isSmall())
542 return (getSmallBits() & ~RHS.getSmallBits()) != 0;
543 if (!isSmall() && !RHS.isSmall())
544 return getPointer()->test(*RHS.getPointer());
545
546 unsigned i, e;
547 for (i = 0, e = std::min(size(), RHS.size()); i != e; ++i)
548 if (test(i) && !RHS.test(i))
549 return true;
550
551 for (e = size(); i != e; ++i)
552 if (test(i))
553 return true;
554
555 return false;
556 }
557
558 SmallBitVector &operator|=(const SmallBitVector &RHS) {
559 resize(std::max(size(), RHS.size()));
560 if (isSmall() && RHS.isSmall())
561 setSmallBits(getSmallBits() | RHS.getSmallBits());
562 else if (!isSmall() && !RHS.isSmall())
563 getPointer()->operator|=(*RHS.getPointer());
564 else {
565 for (size_t i = 0, e = RHS.size(); i != e; ++i)
566 (*this)[i] = test(i) || RHS.test(i);
567 }
568 return *this;
569 }
570
571 SmallBitVector &operator^=(const SmallBitVector &RHS) {
572 resize(std::max(size(), RHS.size()));
573 if (isSmall() && RHS.isSmall())
574 setSmallBits(getSmallBits() ^ RHS.getSmallBits());
575 else if (!isSmall() && !RHS.isSmall())
576 getPointer()->operator^=(*RHS.getPointer());
577 else {
578 for (size_t i = 0, e = RHS.size(); i != e; ++i)
579 (*this)[i] = test(i) != RHS.test(i);
580 }
581 return *this;
582 }
583
584 SmallBitVector &operator<<=(unsigned N) {
585 if (isSmall())
586 setSmallBits(getSmallBits() << N);
587 else
588 getPointer()->operator<<=(N);
589 return *this;
590 }
591
592 SmallBitVector &operator>>=(unsigned N) {
593 if (isSmall())
594 setSmallBits(getSmallBits() >> N);
595 else
596 getPointer()->operator>>=(N);
597 return *this;
598 }
599
600 // Assignment operator.
601 const SmallBitVector &operator=(const SmallBitVector &RHS) {
602 if (isSmall()) {
603 if (RHS.isSmall())
604 X = RHS.X;
605 else
606 switchToLarge(new BitVector(*RHS.getPointer()));
607 } else {
608 if (!RHS.isSmall())
609 *getPointer() = *RHS.getPointer();
610 else {
611 delete getPointer();
612 X = RHS.X;
613 }
614 }
615 return *this;
616 }
617
618 const SmallBitVector &operator=(SmallBitVector &&RHS) {
619 if (this != &RHS) {
620 clear();
621 swap(RHS);
622 }
623 return *this;
624 }
625
626 void swap(SmallBitVector &RHS) {
627 std::swap(X, RHS.X);
628 }
629
630 /// Add '1' bits from Mask to this vector. Don't resize.
631 /// This computes "*this |= Mask".
632 void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
633 if (isSmall())
634 applyMask<true, false>(Mask, MaskWords);
635 else
636 getPointer()->setBitsInMask(Mask, MaskWords);
637 }
638
639 /// Clear any bits in this vector that are set in Mask. Don't resize.
640 /// This computes "*this &= ~Mask".
641 void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
642 if (isSmall())
643 applyMask<false, false>(Mask, MaskWords);
644 else
645 getPointer()->clearBitsInMask(Mask, MaskWords);
646 }
647
648 /// Add a bit to this vector for every '0' bit in Mask. Don't resize.
649 /// This computes "*this |= ~Mask".
650 void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
651 if (isSmall())
652 applyMask<true, true>(Mask, MaskWords);
653 else
654 getPointer()->setBitsNotInMask(Mask, MaskWords);
655 }
656
657 /// Clear a bit in this vector for every '0' bit in Mask. Don't resize.
658 /// This computes "*this &= Mask".
659 void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
660 if (isSmall())
661 applyMask<false, true>(Mask, MaskWords);
662 else
663 getPointer()->clearBitsNotInMask(Mask, MaskWords);
664 }
665
666private:
667 template <bool AddBits, bool InvertMask>
668 void applyMask(const uint32_t *Mask, unsigned MaskWords) {
669 assert(MaskWords <= sizeof(uintptr_t) && "Mask is larger than base!")((MaskWords <= sizeof(uintptr_t) && "Mask is larger than base!"
) ? static_cast<void> (0) : __assert_fail ("MaskWords <= sizeof(uintptr_t) && \"Mask is larger than base!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/ADT/SmallBitVector.h"
, 669, __PRETTY_FUNCTION__))
;
670 uintptr_t M = Mask[0];
671 if (NumBaseBits == 64)
672 M |= uint64_t(Mask[1]) << 32;
673 if (InvertMask)
674 M = ~M;
675 if (AddBits)
676 setSmallBits(getSmallBits() | M);
677 else
678 setSmallBits(getSmallBits() & ~M);
679 }
680};
681
682inline SmallBitVector
683operator&(const SmallBitVector &LHS, const SmallBitVector &RHS) {
684 SmallBitVector Result(LHS);
685 Result &= RHS;
686 return Result;
687}
688
689inline SmallBitVector
690operator|(const SmallBitVector &LHS, const SmallBitVector &RHS) {
691 SmallBitVector Result(LHS);
692 Result |= RHS;
693 return Result;
694}
695
696inline SmallBitVector
697operator^(const SmallBitVector &LHS, const SmallBitVector &RHS) {
698 SmallBitVector Result(LHS);
699 Result ^= RHS;
700 return Result;
701}
702
703} // end namespace llvm
704
705namespace std {
706
707/// Implement std::swap in terms of BitVector swap.
708inline void
709swap(llvm::SmallBitVector &LHS, llvm::SmallBitVector &RHS) {
710 LHS.swap(RHS);
711}
712
713} // end namespace std
714
715#endif // LLVM_ADT_SMALLBITVECTOR_H