/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //== RegionStore.cpp - Field-sensitive store model --------------*- 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 | | // This file defines a basic region store model. In this model, we do have field |
10 | | // sensitivity. But we assume nothing about the heap shape. So recursive data |
11 | | // structures are largely ignored. Basically we do 1-limiting analysis. |
12 | | // Parameter pointers are assumed with no aliasing. Pointee objects of |
13 | | // parameters are created lazily. |
14 | | // |
15 | | //===----------------------------------------------------------------------===// |
16 | | |
17 | | #include "clang/AST/Attr.h" |
18 | | #include "clang/AST/CharUnits.h" |
19 | | #include "clang/ASTMatchers/ASTMatchFinder.h" |
20 | | #include "clang/Analysis/Analyses/LiveVariables.h" |
21 | | #include "clang/Analysis/AnalysisDeclContext.h" |
22 | | #include "clang/Basic/JsonSupport.h" |
23 | | #include "clang/Basic/TargetInfo.h" |
24 | | #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" |
25 | | #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" |
26 | | #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" |
27 | | #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" |
28 | | #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" |
29 | | #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" |
30 | | #include "llvm/ADT/ImmutableMap.h" |
31 | | #include "llvm/ADT/STLExtras.h" |
32 | | #include "llvm/Support/raw_ostream.h" |
33 | | #include <optional> |
34 | | #include <utility> |
35 | | |
36 | | using namespace clang; |
37 | | using namespace ento; |
38 | | |
39 | | //===----------------------------------------------------------------------===// |
40 | | // Representation of binding keys. |
41 | | //===----------------------------------------------------------------------===// |
42 | | |
43 | | namespace { |
44 | | class BindingKey { |
45 | | public: |
46 | | enum Kind { Default = 0x0, Direct = 0x1 }; |
47 | | private: |
48 | | enum { Symbolic = 0x2 }; |
49 | | |
50 | | llvm::PointerIntPair<const MemRegion *, 2> P; |
51 | | uint64_t Data; |
52 | | |
53 | | /// Create a key for a binding to region \p r, which has a symbolic offset |
54 | | /// from region \p Base. |
55 | | explicit BindingKey(const SubRegion *r, const SubRegion *Base, Kind k) |
56 | 99.7k | : P(r, k | Symbolic), Data(reinterpret_cast<uintptr_t>(Base)) { |
57 | 99.7k | assert(r && Base && "Must have known regions."); |
58 | 99.7k | assert(getConcreteOffsetRegion() == Base && "Failed to store base region"); |
59 | 99.7k | } |
60 | | |
61 | | /// Create a key for a binding at \p offset from base region \p r. |
62 | | explicit BindingKey(const MemRegion *r, uint64_t offset, Kind k) |
63 | 1.85M | : P(r, k), Data(offset) { |
64 | 1.85M | assert(r && "Must have known regions."); |
65 | 1.85M | assert(getOffset() == offset && "Failed to store offset"); |
66 | 1.85M | assert((r == r->getBaseRegion() || |
67 | 1.85M | isa<ObjCIvarRegion, CXXDerivedObjectRegion>(r)) && |
68 | 1.85M | "Not a base"); |
69 | 1.85M | } |
70 | | public: |
71 | | |
72 | 366k | bool isDirect() const { return P.getInt() & Direct; } |
73 | 4.38M | bool hasSymbolicOffset() const { return P.getInt() & Symbolic; } |
74 | | |
75 | 3.89M | const MemRegion *getRegion() const { return P.getPointer(); } |
76 | 2.13M | uint64_t getOffset() const { |
77 | 2.13M | assert(!hasSymbolicOffset()); |
78 | 2.13M | return Data; |
79 | 2.13M | } |
80 | | |
81 | 203k | const SubRegion *getConcreteOffsetRegion() const { |
82 | 203k | assert(hasSymbolicOffset()); |
83 | 203k | return reinterpret_cast<const SubRegion *>(static_cast<uintptr_t>(Data)); |
84 | 203k | } |
85 | | |
86 | 1.95M | const MemRegion *getBaseRegion() const { |
87 | 1.95M | if (hasSymbolicOffset()) |
88 | 99.7k | return getConcreteOffsetRegion()->getBaseRegion(); |
89 | 1.85M | return getRegion()->getBaseRegion(); |
90 | 1.95M | } |
91 | | |
92 | 366k | void Profile(llvm::FoldingSetNodeID& ID) const { |
93 | 366k | ID.AddPointer(P.getOpaqueValue()); |
94 | 366k | ID.AddInteger(Data); |
95 | 366k | } |
96 | | |
97 | | static BindingKey Make(const MemRegion *R, Kind k); |
98 | | |
99 | 180k | bool operator<(const BindingKey &X) const { |
100 | 180k | if (P.getOpaqueValue() < X.P.getOpaqueValue()) |
101 | 86.4k | return true; |
102 | 94.4k | if (P.getOpaqueValue() > X.P.getOpaqueValue()) |
103 | 29.6k | return false; |
104 | 64.8k | return Data < X.Data; |
105 | 94.4k | } |
106 | | |
107 | 836k | bool operator==(const BindingKey &X) const { |
108 | 836k | return P.getOpaqueValue() == X.P.getOpaqueValue() && |
109 | 836k | Data == X.Data720k ; |
110 | 836k | } |
111 | | |
112 | | LLVM_DUMP_METHOD void dump() const; |
113 | | }; |
114 | | } // end anonymous namespace |
115 | | |
116 | 1.95M | BindingKey BindingKey::Make(const MemRegion *R, Kind k) { |
117 | 1.95M | const RegionOffset &RO = R->getAsOffset(); |
118 | 1.95M | if (RO.hasSymbolicOffset()) |
119 | 99.7k | return BindingKey(cast<SubRegion>(R), cast<SubRegion>(RO.getRegion()), k); |
120 | | |
121 | 1.85M | return BindingKey(RO.getRegion(), RO.getOffset(), k); |
122 | 1.95M | } |
123 | | |
124 | | namespace llvm { |
125 | 200 | static inline raw_ostream &operator<<(raw_ostream &Out, BindingKey K) { |
126 | 200 | Out << "\"kind\": \"" << (K.isDirect() ? "Direct"112 : "Default"88 ) |
127 | 200 | << "\", \"offset\": "; |
128 | | |
129 | 200 | if (!K.hasSymbolicOffset()) |
130 | 200 | Out << K.getOffset(); |
131 | 0 | else |
132 | 0 | Out << "null"; |
133 | | |
134 | 200 | return Out; |
135 | 200 | } |
136 | | |
137 | | } // namespace llvm |
138 | | |
139 | | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
140 | 0 | void BindingKey::dump() const { llvm::errs() << *this; } |
141 | | #endif |
142 | | |
143 | | //===----------------------------------------------------------------------===// |
144 | | // Actual Store type. |
145 | | //===----------------------------------------------------------------------===// |
146 | | |
147 | | typedef llvm::ImmutableMap<BindingKey, SVal> ClusterBindings; |
148 | | typedef llvm::ImmutableMapRef<BindingKey, SVal> ClusterBindingsRef; |
149 | | typedef std::pair<BindingKey, SVal> BindingPair; |
150 | | |
151 | | typedef llvm::ImmutableMap<const MemRegion *, ClusterBindings> |
152 | | RegionBindings; |
153 | | |
154 | | namespace { |
155 | | class RegionBindingsRef : public llvm::ImmutableMapRef<const MemRegion *, |
156 | | ClusterBindings> { |
157 | | ClusterBindings::Factory *CBFactory; |
158 | | |
159 | | // This flag indicates whether the current bindings are within the analysis |
160 | | // that has started from main(). It affects how we perform loads from |
161 | | // global variables that have initializers: if we have observed the |
162 | | // program execution from the start and we know that these variables |
163 | | // have not been overwritten yet, we can be sure that their initializers |
164 | | // are still relevant. This flag never gets changed when the bindings are |
165 | | // updated, so it could potentially be moved into RegionStoreManager |
166 | | // (as if it's the same bindings but a different loading procedure) |
167 | | // however that would have made the manager needlessly stateful. |
168 | | bool IsMainAnalysis; |
169 | | |
170 | | public: |
171 | | typedef llvm::ImmutableMapRef<const MemRegion *, ClusterBindings> |
172 | | ParentTy; |
173 | | |
174 | | RegionBindingsRef(ClusterBindings::Factory &CBFactory, |
175 | | const RegionBindings::TreeTy *T, |
176 | | RegionBindings::TreeTy::Factory *F, |
177 | | bool IsMainAnalysis) |
178 | 14.1M | : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(T, F), |
179 | 14.1M | CBFactory(&CBFactory), IsMainAnalysis(IsMainAnalysis) {} |
180 | | |
181 | | RegionBindingsRef(const ParentTy &P, |
182 | | ClusterBindings::Factory &CBFactory, |
183 | | bool IsMainAnalysis) |
184 | 700k | : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(P), |
185 | 700k | CBFactory(&CBFactory), IsMainAnalysis(IsMainAnalysis) {} |
186 | | |
187 | 334k | RegionBindingsRef add(key_type_ref K, data_type_ref D) const { |
188 | 334k | return RegionBindingsRef(static_cast<const ParentTy *>(this)->add(K, D), |
189 | 334k | *CBFactory, IsMainAnalysis); |
190 | 334k | } |
191 | | |
192 | 348k | RegionBindingsRef remove(key_type_ref K) const { |
193 | 348k | return RegionBindingsRef(static_cast<const ParentTy *>(this)->remove(K), |
194 | 348k | *CBFactory, IsMainAnalysis); |
195 | 348k | } |
196 | | |
197 | | RegionBindingsRef addBinding(BindingKey K, SVal V) const; |
198 | | |
199 | | RegionBindingsRef addBinding(const MemRegion *R, |
200 | | BindingKey::Kind k, SVal V) const; |
201 | | |
202 | | const SVal *lookup(BindingKey K) const; |
203 | | const SVal *lookup(const MemRegion *R, BindingKey::Kind k) const; |
204 | | using llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>::lookup; |
205 | | |
206 | | RegionBindingsRef removeBinding(BindingKey K); |
207 | | |
208 | | RegionBindingsRef removeBinding(const MemRegion *R, |
209 | | BindingKey::Kind k); |
210 | | |
211 | 68.4k | RegionBindingsRef removeBinding(const MemRegion *R) { |
212 | 68.4k | return removeBinding(R, BindingKey::Direct). |
213 | 68.4k | removeBinding(R, BindingKey::Default); |
214 | 68.4k | } |
215 | | |
216 | | std::optional<SVal> getDirectBinding(const MemRegion *R) const; |
217 | | |
218 | | /// getDefaultBinding - Returns an SVal* representing an optional default |
219 | | /// binding associated with a region and its subregions. |
220 | | std::optional<SVal> getDefaultBinding(const MemRegion *R) const; |
221 | | |
222 | | /// Return the internal tree as a Store. |
223 | 747k | Store asStore() const { |
224 | 747k | llvm::PointerIntPair<Store, 1, bool> Ptr = { |
225 | 747k | asImmutableMap().getRootWithoutRetain(), IsMainAnalysis}; |
226 | 747k | return reinterpret_cast<Store>(Ptr.getOpaqueValue()); |
227 | 747k | } |
228 | | |
229 | 32.4k | bool isMainAnalysis() const { |
230 | 32.4k | return IsMainAnalysis; |
231 | 32.4k | } |
232 | | |
233 | | void printJson(raw_ostream &Out, const char *NL = "\n", |
234 | 108 | unsigned int Space = 0, bool IsDot = false) const { |
235 | 304 | for (iterator I = begin(), E = end(); I != E; ++I196 ) { |
236 | | // TODO: We might need a .printJson for I.getKey() as well. |
237 | 196 | Indent(Out, Space, IsDot) |
238 | 196 | << "{ \"cluster\": \"" << I.getKey() << "\", \"pointer\": \"" |
239 | 196 | << (const void *)I.getKey() << "\", \"items\": [" << NL; |
240 | | |
241 | 196 | ++Space; |
242 | 196 | const ClusterBindings &CB = I.getData(); |
243 | 396 | for (ClusterBindings::iterator CI = CB.begin(), CE = CB.end(); CI != CE; |
244 | 200 | ++CI) { |
245 | 200 | Indent(Out, Space, IsDot) << "{ " << CI.getKey() << ", \"value\": "; |
246 | 200 | CI.getData().printJson(Out, /*AddQuotes=*/true); |
247 | 200 | Out << " }"; |
248 | 200 | if (std::next(CI) != CE) |
249 | 4 | Out << ','; |
250 | 200 | Out << NL; |
251 | 200 | } |
252 | | |
253 | 196 | --Space; |
254 | 196 | Indent(Out, Space, IsDot) << "]}"; |
255 | 196 | if (std::next(I) != E) |
256 | 88 | Out << ','; |
257 | 196 | Out << NL; |
258 | 196 | } |
259 | 108 | } |
260 | | |
261 | 0 | LLVM_DUMP_METHOD void dump() const { printJson(llvm::errs()); } |
262 | | }; |
263 | | } // end anonymous namespace |
264 | | |
265 | | typedef const RegionBindingsRef& RegionBindingsConstRef; |
266 | | |
267 | | std::optional<SVal> |
268 | 596k | RegionBindingsRef::getDirectBinding(const MemRegion *R) const { |
269 | 596k | const SVal *V = lookup(R, BindingKey::Direct); |
270 | 596k | return V ? std::optional<SVal>(*V)298k : std::nullopt298k ; |
271 | 596k | } |
272 | | |
273 | | std::optional<SVal> |
274 | 634k | RegionBindingsRef::getDefaultBinding(const MemRegion *R) const { |
275 | 634k | const SVal *V = lookup(R, BindingKey::Default); |
276 | 634k | return V ? std::optional<SVal>(*V)41.7k : std::nullopt592k ; |
277 | 634k | } |
278 | | |
279 | 310k | RegionBindingsRef RegionBindingsRef::addBinding(BindingKey K, SVal V) const { |
280 | 310k | const MemRegion *Base = K.getBaseRegion(); |
281 | | |
282 | 310k | const ClusterBindings *ExistingCluster = lookup(Base); |
283 | 310k | ClusterBindings Cluster = |
284 | 310k | (ExistingCluster ? *ExistingCluster25.0k : CBFactory->getEmptyMap()285k ); |
285 | | |
286 | 310k | ClusterBindings NewCluster = CBFactory->add(Cluster, K, V); |
287 | 310k | return add(Base, NewCluster); |
288 | 310k | } |
289 | | |
290 | | |
291 | | RegionBindingsRef RegionBindingsRef::addBinding(const MemRegion *R, |
292 | | BindingKey::Kind k, |
293 | 31.9k | SVal V) const { |
294 | 31.9k | return addBinding(BindingKey::Make(R, k), V); |
295 | 31.9k | } |
296 | | |
297 | 1.29M | const SVal *RegionBindingsRef::lookup(BindingKey K) const { |
298 | 1.29M | const ClusterBindings *Cluster = lookup(K.getBaseRegion()); |
299 | 1.29M | if (!Cluster) |
300 | 803k | return nullptr; |
301 | 493k | return Cluster->lookup(K); |
302 | 1.29M | } |
303 | | |
304 | | const SVal *RegionBindingsRef::lookup(const MemRegion *R, |
305 | 1.29M | BindingKey::Kind k) const { |
306 | 1.29M | return lookup(BindingKey::Make(R, k)); |
307 | 1.29M | } |
308 | | |
309 | 136k | RegionBindingsRef RegionBindingsRef::removeBinding(BindingKey K) { |
310 | 136k | const MemRegion *Base = K.getBaseRegion(); |
311 | 136k | const ClusterBindings *Cluster = lookup(Base); |
312 | 136k | if (!Cluster) |
313 | 136k | return *this; |
314 | | |
315 | 256 | ClusterBindings NewCluster = CBFactory->remove(*Cluster, K); |
316 | 256 | if (NewCluster.isEmpty()) |
317 | 174 | return remove(Base); |
318 | 82 | return add(Base, NewCluster); |
319 | 256 | } |
320 | | |
321 | | RegionBindingsRef RegionBindingsRef::removeBinding(const MemRegion *R, |
322 | 136k | BindingKey::Kind k){ |
323 | 136k | return removeBinding(BindingKey::Make(R, k)); |
324 | 136k | } |
325 | | |
326 | | //===----------------------------------------------------------------------===// |
327 | | // Main RegionStore logic. |
328 | | //===----------------------------------------------------------------------===// |
329 | | |
330 | | namespace { |
331 | | class InvalidateRegionsWorker; |
332 | | |
333 | | class RegionStoreManager : public StoreManager { |
334 | | public: |
335 | | RegionBindings::Factory RBFactory; |
336 | | mutable ClusterBindings::Factory CBFactory; |
337 | | |
338 | | typedef std::vector<SVal> SValListTy; |
339 | | private: |
340 | | typedef llvm::DenseMap<const LazyCompoundValData *, |
341 | | SValListTy> LazyBindingsMapTy; |
342 | | LazyBindingsMapTy LazyBindingsMap; |
343 | | |
344 | | /// The largest number of fields a struct can have and still be |
345 | | /// considered "small". |
346 | | /// |
347 | | /// This is currently used to decide whether or not it is worth "forcing" a |
348 | | /// LazyCompoundVal on bind. |
349 | | /// |
350 | | /// This is controlled by 'region-store-small-struct-limit' option. |
351 | | /// To disable all small-struct-dependent behavior, set the option to "0". |
352 | | unsigned SmallStructLimit; |
353 | | |
354 | | /// The largest number of element an array can have and still be |
355 | | /// considered "small". |
356 | | /// |
357 | | /// This is currently used to decide whether or not it is worth "forcing" a |
358 | | /// LazyCompoundVal on bind. |
359 | | /// |
360 | | /// This is controlled by 'region-store-small-struct-limit' option. |
361 | | /// To disable all small-struct-dependent behavior, set the option to "0". |
362 | | unsigned SmallArrayLimit; |
363 | | |
364 | | /// A helper used to populate the work list with the given set of |
365 | | /// regions. |
366 | | void populateWorkList(InvalidateRegionsWorker &W, |
367 | | ArrayRef<SVal> Values, |
368 | | InvalidatedRegions *TopLevelRegions); |
369 | | |
370 | | public: |
371 | | RegionStoreManager(ProgramStateManager &mgr) |
372 | 16.2k | : StoreManager(mgr), RBFactory(mgr.getAllocator()), |
373 | 16.2k | CBFactory(mgr.getAllocator()), SmallStructLimit(0), SmallArrayLimit(0) { |
374 | 16.2k | ExprEngine &Eng = StateMgr.getOwningEngine(); |
375 | 16.2k | AnalyzerOptions &Options = Eng.getAnalysisManager().options; |
376 | 16.2k | SmallStructLimit = Options.RegionStoreSmallStructLimit; |
377 | 16.2k | SmallArrayLimit = Options.RegionStoreSmallArrayLimit; |
378 | 16.2k | } |
379 | | |
380 | | /// setImplicitDefaultValue - Set the default binding for the provided |
381 | | /// MemRegion to the value implicitly defined for compound literals when |
382 | | /// the value is not specified. |
383 | | RegionBindingsRef setImplicitDefaultValue(RegionBindingsConstRef B, |
384 | | const MemRegion *R, QualType T); |
385 | | |
386 | | /// ArrayToPointer - Emulates the "decay" of an array to a pointer |
387 | | /// type. 'Array' represents the lvalue of the array being decayed |
388 | | /// to a pointer, and the returned SVal represents the decayed |
389 | | /// version of that lvalue (i.e., a pointer to the first element of |
390 | | /// the array). This is called by ExprEngine when evaluating |
391 | | /// casts from arrays to pointers. |
392 | | SVal ArrayToPointer(Loc Array, QualType ElementTy) override; |
393 | | |
394 | | /// Creates the Store that correctly represents memory contents before |
395 | | /// the beginning of the analysis of the given top-level stack frame. |
396 | 16.2k | StoreRef getInitialStore(const LocationContext *InitLoc) override { |
397 | 16.2k | bool IsMainAnalysis = false; |
398 | 16.2k | if (const auto *FD = dyn_cast<FunctionDecl>(InitLoc->getDecl())) |
399 | 14.9k | IsMainAnalysis = FD->isMain() && !Ctx.getLangOpts().CPlusPlus67 ; |
400 | 16.2k | return StoreRef(RegionBindingsRef( |
401 | 16.2k | RegionBindingsRef::ParentTy(RBFactory.getEmptyMap(), RBFactory), |
402 | 16.2k | CBFactory, IsMainAnalysis).asStore(), *this); |
403 | 16.2k | } |
404 | | |
405 | | //===-------------------------------------------------------------------===// |
406 | | // Binding values to regions. |
407 | | //===-------------------------------------------------------------------===// |
408 | | RegionBindingsRef invalidateGlobalRegion(MemRegion::Kind K, |
409 | | const Expr *Ex, |
410 | | unsigned Count, |
411 | | const LocationContext *LCtx, |
412 | | RegionBindingsRef B, |
413 | | InvalidatedRegions *Invalidated); |
414 | | |
415 | | StoreRef invalidateRegions(Store store, |
416 | | ArrayRef<SVal> Values, |
417 | | const Expr *E, unsigned Count, |
418 | | const LocationContext *LCtx, |
419 | | const CallEvent *Call, |
420 | | InvalidatedSymbols &IS, |
421 | | RegionAndSymbolInvalidationTraits &ITraits, |
422 | | InvalidatedRegions *Invalidated, |
423 | | InvalidatedRegions *InvalidatedTopLevel) override; |
424 | | |
425 | | bool scanReachableSymbols(Store S, const MemRegion *R, |
426 | | ScanReachableSymbols &Callbacks) override; |
427 | | |
428 | | RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B, |
429 | | const SubRegion *R); |
430 | | std::optional<SVal> |
431 | | getConstantValFromConstArrayInitializer(RegionBindingsConstRef B, |
432 | | const ElementRegion *R); |
433 | | std::optional<SVal> |
434 | | getSValFromInitListExpr(const InitListExpr *ILE, |
435 | | const SmallVector<uint64_t, 2> &ConcreteOffsets, |
436 | | QualType ElemT); |
437 | | SVal getSValFromStringLiteral(const StringLiteral *SL, uint64_t Offset, |
438 | | QualType ElemT); |
439 | | |
440 | | public: // Part of public interface to class. |
441 | | |
442 | 205k | StoreRef Bind(Store store, Loc LV, SVal V) override { |
443 | 205k | return StoreRef(bind(getRegionBindings(store), LV, V).asStore(), *this); |
444 | 205k | } |
445 | | |
446 | | RegionBindingsRef bind(RegionBindingsConstRef B, Loc LV, SVal V); |
447 | | |
448 | | // BindDefaultInitial is only used to initialize a region with |
449 | | // a default value. |
450 | | StoreRef BindDefaultInitial(Store store, const MemRegion *R, |
451 | 1.76k | SVal V) override { |
452 | 1.76k | RegionBindingsRef B = getRegionBindings(store); |
453 | | // Use other APIs when you have to wipe the region that was initialized |
454 | | // earlier. |
455 | 1.76k | assert(!(B.getDefaultBinding(R) || B.getDirectBinding(R)) && |
456 | 1.76k | "Double initialization!"); |
457 | 1.76k | B = B.addBinding(BindingKey::Make(R, BindingKey::Default), V); |
458 | 1.76k | return StoreRef(B.asImmutableMap().getRootWithoutRetain(), *this); |
459 | 1.76k | } |
460 | | |
461 | | // BindDefaultZero is used for zeroing constructors that may accidentally |
462 | | // overwrite existing bindings. |
463 | 2.07k | StoreRef BindDefaultZero(Store store, const MemRegion *R) override { |
464 | | // FIXME: The offsets of empty bases can be tricky because of |
465 | | // of the so called "empty base class optimization". |
466 | | // If a base class has been optimized out |
467 | | // we should not try to create a binding, otherwise we should. |
468 | | // Unfortunately, at the moment ASTRecordLayout doesn't expose |
469 | | // the actual sizes of the empty bases |
470 | | // and trying to infer them from offsets/alignments |
471 | | // seems to be error-prone and non-trivial because of the trailing padding. |
472 | | // As a temporary mitigation we don't create bindings for empty bases. |
473 | 2.07k | if (const auto *BR = dyn_cast<CXXBaseObjectRegion>(R)) |
474 | 16 | if (BR->getDecl()->isEmpty()) |
475 | 4 | return StoreRef(store, *this); |
476 | | |
477 | 2.07k | RegionBindingsRef B = getRegionBindings(store); |
478 | 2.07k | SVal V = svalBuilder.makeZeroVal(Ctx.CharTy); |
479 | 2.07k | B = removeSubRegionBindings(B, cast<SubRegion>(R)); |
480 | 2.07k | B = B.addBinding(BindingKey::Make(R, BindingKey::Default), V); |
481 | 2.07k | return StoreRef(B.asImmutableMap().getRootWithoutRetain(), *this); |
482 | 2.07k | } |
483 | | |
484 | | /// Attempt to extract the fields of \p LCV and bind them to the struct region |
485 | | /// \p R. |
486 | | /// |
487 | | /// This path is used when it seems advantageous to "force" loading the values |
488 | | /// within a LazyCompoundVal to bind memberwise to the struct region, rather |
489 | | /// than using a Default binding at the base of the entire region. This is a |
490 | | /// heuristic attempting to avoid building long chains of LazyCompoundVals. |
491 | | /// |
492 | | /// \returns The updated store bindings, or \c std::nullopt if binding |
493 | | /// non-lazily would be too expensive. |
494 | | std::optional<RegionBindingsRef> |
495 | | tryBindSmallStruct(RegionBindingsConstRef B, const TypedValueRegion *R, |
496 | | const RecordDecl *RD, nonloc::LazyCompoundVal LCV); |
497 | | |
498 | | /// BindStruct - Bind a compound value to a structure. |
499 | | RegionBindingsRef bindStruct(RegionBindingsConstRef B, |
500 | | const TypedValueRegion* R, SVal V); |
501 | | |
502 | | /// BindVector - Bind a compound value to a vector. |
503 | | RegionBindingsRef bindVector(RegionBindingsConstRef B, |
504 | | const TypedValueRegion* R, SVal V); |
505 | | |
506 | | std::optional<RegionBindingsRef> |
507 | | tryBindSmallArray(RegionBindingsConstRef B, const TypedValueRegion *R, |
508 | | const ArrayType *AT, nonloc::LazyCompoundVal LCV); |
509 | | |
510 | | RegionBindingsRef bindArray(RegionBindingsConstRef B, |
511 | | const TypedValueRegion* R, |
512 | | SVal V); |
513 | | |
514 | | /// Clears out all bindings in the given region and assigns a new value |
515 | | /// as a Default binding. |
516 | | RegionBindingsRef bindAggregate(RegionBindingsConstRef B, |
517 | | const TypedRegion *R, |
518 | | SVal DefaultVal); |
519 | | |
520 | | /// Create a new store with the specified binding removed. |
521 | | /// \param ST the original store, that is the basis for the new store. |
522 | | /// \param L the location whose binding should be removed. |
523 | | StoreRef killBinding(Store ST, Loc L) override; |
524 | | |
525 | 6.71M | void incrementReferenceCount(Store store) override { |
526 | 6.71M | getRegionBindings(store).manualRetain(); |
527 | 6.71M | } |
528 | | |
529 | | /// If the StoreManager supports it, decrement the reference count of |
530 | | /// the specified Store object. If the reference count hits 0, the memory |
531 | | /// associated with the object is recycled. |
532 | 5.18M | void decrementReferenceCount(Store store) override { |
533 | 5.18M | getRegionBindings(store).manualRelease(); |
534 | 5.18M | } |
535 | | |
536 | | bool includedInBindings(Store store, const MemRegion *region) const override; |
537 | | |
538 | | /// Return the value bound to specified location in a given state. |
539 | | /// |
540 | | /// The high level logic for this method is this: |
541 | | /// getBinding (L) |
542 | | /// if L has binding |
543 | | /// return L's binding |
544 | | /// else if L is in killset |
545 | | /// return unknown |
546 | | /// else |
547 | | /// if L is on stack or heap |
548 | | /// return undefined |
549 | | /// else |
550 | | /// return symbolic |
551 | 705k | SVal getBinding(Store S, Loc L, QualType T) override { |
552 | 705k | return getBinding(getRegionBindings(S), L, T); |
553 | 705k | } |
554 | | |
555 | 53 | std::optional<SVal> getDefaultBinding(Store S, const MemRegion *R) override { |
556 | 53 | RegionBindingsRef B = getRegionBindings(S); |
557 | | // Default bindings are always applied over a base region so look up the |
558 | | // base region's default binding, otherwise the lookup will fail when R |
559 | | // is at an offset from R->getBaseRegion(). |
560 | 53 | return B.getDefaultBinding(R->getBaseRegion()); |
561 | 53 | } |
562 | | |
563 | | SVal getBinding(RegionBindingsConstRef B, Loc L, QualType T = QualType()); |
564 | | |
565 | | SVal getBindingForElement(RegionBindingsConstRef B, const ElementRegion *R); |
566 | | |
567 | | SVal getBindingForField(RegionBindingsConstRef B, const FieldRegion *R); |
568 | | |
569 | | SVal getBindingForObjCIvar(RegionBindingsConstRef B, const ObjCIvarRegion *R); |
570 | | |
571 | | SVal getBindingForVar(RegionBindingsConstRef B, const VarRegion *R); |
572 | | |
573 | | SVal getBindingForLazySymbol(const TypedValueRegion *R); |
574 | | |
575 | | SVal getBindingForFieldOrElementCommon(RegionBindingsConstRef B, |
576 | | const TypedValueRegion *R, |
577 | | QualType Ty); |
578 | | |
579 | | SVal getLazyBinding(const SubRegion *LazyBindingRegion, |
580 | | RegionBindingsRef LazyBinding); |
581 | | |
582 | | /// Get bindings for the values in a struct and return a CompoundVal, used |
583 | | /// when doing struct copy: |
584 | | /// struct s x, y; |
585 | | /// x = y; |
586 | | /// y's value is retrieved by this method. |
587 | | SVal getBindingForStruct(RegionBindingsConstRef B, const TypedValueRegion *R); |
588 | | SVal getBindingForArray(RegionBindingsConstRef B, const TypedValueRegion *R); |
589 | | NonLoc createLazyBinding(RegionBindingsConstRef B, const TypedValueRegion *R); |
590 | | |
591 | | /// Used to lazily generate derived symbols for bindings that are defined |
592 | | /// implicitly by default bindings in a super region. |
593 | | /// |
594 | | /// Note that callers may need to specially handle LazyCompoundVals, which |
595 | | /// are returned as is in case the caller needs to treat them differently. |
596 | | std::optional<SVal> |
597 | | getBindingForDerivedDefaultValue(RegionBindingsConstRef B, |
598 | | const MemRegion *superR, |
599 | | const TypedValueRegion *R, QualType Ty); |
600 | | |
601 | | /// Get the state and region whose binding this region \p R corresponds to. |
602 | | /// |
603 | | /// If there is no lazy binding for \p R, the returned value will have a null |
604 | | /// \c second. Note that a null pointer can represents a valid Store. |
605 | | std::pair<Store, const SubRegion *> |
606 | | findLazyBinding(RegionBindingsConstRef B, const SubRegion *R, |
607 | | const SubRegion *originalRegion); |
608 | | |
609 | | /// Returns the cached set of interesting SVals contained within a lazy |
610 | | /// binding. |
611 | | /// |
612 | | /// The precise value of "interesting" is determined for the purposes of |
613 | | /// RegionStore's internal analysis. It must always contain all regions and |
614 | | /// symbols, but may omit constants and other kinds of SVal. |
615 | | /// |
616 | | /// In contrast to compound values, LazyCompoundVals are also added |
617 | | /// to the 'interesting values' list in addition to the child interesting |
618 | | /// values. |
619 | | const SValListTy &getInterestingValues(nonloc::LazyCompoundVal LCV); |
620 | | |
621 | | //===------------------------------------------------------------------===// |
622 | | // State pruning. |
623 | | //===------------------------------------------------------------------===// |
624 | | |
625 | | /// removeDeadBindings - Scans the RegionStore of 'state' for dead values. |
626 | | /// It returns a new Store with these values removed. |
627 | | StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx, |
628 | | SymbolReaper& SymReaper) override; |
629 | | |
630 | | //===------------------------------------------------------------------===// |
631 | | // Utility methods. |
632 | | //===------------------------------------------------------------------===// |
633 | | |
634 | 14.1M | RegionBindingsRef getRegionBindings(Store store) const { |
635 | 14.1M | llvm::PointerIntPair<Store, 1, bool> Ptr; |
636 | 14.1M | Ptr.setFromOpaqueValue(const_cast<void *>(store)); |
637 | 14.1M | return RegionBindingsRef( |
638 | 14.1M | CBFactory, |
639 | 14.1M | static_cast<const RegionBindings::TreeTy *>(Ptr.getPointer()), |
640 | 14.1M | RBFactory.getTreeFactory(), |
641 | 14.1M | Ptr.getInt()); |
642 | 14.1M | } |
643 | | |
644 | | void printJson(raw_ostream &Out, Store S, const char *NL = "\n", |
645 | | unsigned int Space = 0, bool IsDot = false) const override; |
646 | | |
647 | 77.3k | void iterBindings(Store store, BindingsHandler& f) override { |
648 | 77.3k | RegionBindingsRef B = getRegionBindings(store); |
649 | 279k | for (const auto &[Region, Cluster] : B) { |
650 | 353k | for (const auto &[Key, Value] : Cluster) { |
651 | 353k | if (!Key.isDirect()) |
652 | 150k | continue; |
653 | 202k | if (const SubRegion *R = dyn_cast<SubRegion>(Key.getRegion())) { |
654 | | // FIXME: Possibly incorporate the offset? |
655 | 202k | if (!f.HandleBinding(*this, store, R, Value)) |
656 | 638 | return; |
657 | 202k | } |
658 | 202k | } |
659 | 279k | } |
660 | 77.3k | } |
661 | | }; |
662 | | |
663 | | } // end anonymous namespace |
664 | | |
665 | | //===----------------------------------------------------------------------===// |
666 | | // RegionStore creation. |
667 | | //===----------------------------------------------------------------------===// |
668 | | |
669 | | std::unique_ptr<StoreManager> |
670 | 16.2k | ento::CreateRegionStoreManager(ProgramStateManager &StMgr) { |
671 | 16.2k | return std::make_unique<RegionStoreManager>(StMgr); |
672 | 16.2k | } |
673 | | |
674 | | //===----------------------------------------------------------------------===// |
675 | | // Region Cluster analysis. |
676 | | //===----------------------------------------------------------------------===// |
677 | | |
678 | | namespace { |
679 | | /// Used to determine which global regions are automatically included in the |
680 | | /// initial worklist of a ClusterAnalysis. |
681 | | enum GlobalsFilterKind { |
682 | | /// Don't include any global regions. |
683 | | GFK_None, |
684 | | /// Only include system globals. |
685 | | GFK_SystemOnly, |
686 | | /// Include all global regions. |
687 | | GFK_All |
688 | | }; |
689 | | |
690 | | template <typename DERIVED> |
691 | | class ClusterAnalysis { |
692 | | protected: |
693 | | typedef llvm::DenseMap<const MemRegion *, const ClusterBindings *> ClusterMap; |
694 | | typedef const MemRegion * WorkListElement; |
695 | | typedef SmallVector<WorkListElement, 10> WorkList; |
696 | | |
697 | | llvm::SmallPtrSet<const ClusterBindings *, 16> Visited; |
698 | | |
699 | | WorkList WL; |
700 | | |
701 | | RegionStoreManager &RM; |
702 | | ASTContext &Ctx; |
703 | | SValBuilder &svalBuilder; |
704 | | |
705 | | RegionBindingsRef B; |
706 | | |
707 | | |
708 | | protected: |
709 | 4.96M | const ClusterBindings *getCluster(const MemRegion *R) { |
710 | 4.96M | return B.lookup(R); |
711 | 4.96M | } RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::RemoveDeadBindingsWorker>::getCluster(clang::ento::MemRegion const*) Line | Count | Source | 709 | 4.82M | const ClusterBindings *getCluster(const MemRegion *R) { | 710 | 4.82M | return B.lookup(R); | 711 | 4.82M | } |
RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::InvalidateRegionsWorker>::getCluster(clang::ento::MemRegion const*) Line | Count | Source | 709 | 134k | const ClusterBindings *getCluster(const MemRegion *R) { | 710 | 134k | return B.lookup(R); | 711 | 134k | } |
|
712 | | |
713 | | /// Returns true if all clusters in the given memspace should be initially |
714 | | /// included in the cluster analysis. Subclasses may provide their |
715 | | /// own implementation. |
716 | 1.51M | bool includeEntireMemorySpace(const MemRegion *Base) { |
717 | 1.51M | return false; |
718 | 1.51M | } |
719 | | |
720 | | public: |
721 | | ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr, |
722 | | RegionBindingsRef b) |
723 | 466k | : RM(rm), Ctx(StateMgr.getContext()), |
724 | 466k | svalBuilder(StateMgr.getSValBuilder()), B(std::move(b)) {} RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::RemoveDeadBindingsWorker>::ClusterAnalysis((anonymous namespace)::RegionStoreManager&, clang::ento::ProgramStateManager&, (anonymous namespace)::RegionBindingsRef) Line | Count | Source | 723 | 427k | : RM(rm), Ctx(StateMgr.getContext()), | 724 | 427k | svalBuilder(StateMgr.getSValBuilder()), B(std::move(b)) {} |
RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::InvalidateRegionsWorker>::ClusterAnalysis((anonymous namespace)::RegionStoreManager&, clang::ento::ProgramStateManager&, (anonymous namespace)::RegionBindingsRef) Line | Count | Source | 723 | 38.8k | : RM(rm), Ctx(StateMgr.getContext()), | 724 | 38.8k | svalBuilder(StateMgr.getSValBuilder()), B(std::move(b)) {} |
|
725 | | |
726 | 38.8k | RegionBindingsRef getRegionBindings() const { return B; } |
727 | | |
728 | 1.51M | bool isVisited(const MemRegion *R) { |
729 | 1.51M | return Visited.count(getCluster(R)); |
730 | 1.51M | } |
731 | | |
732 | 466k | void GenerateClusters() { |
733 | | // Scan the entire set of bindings and record the region clusters. |
734 | 466k | for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); |
735 | 2.10M | RI != RE; ++RI1.63M ){ |
736 | 1.63M | const MemRegion *Base = RI.getKey(); |
737 | | |
738 | 1.63M | const ClusterBindings &Cluster = RI.getData(); |
739 | 1.63M | assert(!Cluster.isEmpty() && "Empty clusters should be removed"); |
740 | 1.63M | static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster); |
741 | | |
742 | | // If the base's memspace should be entirely invalidated, add the cluster |
743 | | // to the workspace up front. |
744 | 1.63M | if (static_cast<DERIVED*>(this)->includeEntireMemorySpace(Base)) |
745 | 53.3k | AddToWorkList(WorkListElement(Base), &Cluster); |
746 | 1.63M | } |
747 | 466k | } RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::RemoveDeadBindingsWorker>::GenerateClusters() Line | Count | Source | 732 | 427k | void GenerateClusters() { | 733 | | // Scan the entire set of bindings and record the region clusters. | 734 | 427k | for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); | 735 | 1.94M | RI != RE; ++RI1.51M ){ | 736 | 1.51M | const MemRegion *Base = RI.getKey(); | 737 | | | 738 | 1.51M | const ClusterBindings &Cluster = RI.getData(); | 739 | 1.51M | assert(!Cluster.isEmpty() && "Empty clusters should be removed"); | 740 | 1.51M | static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster); | 741 | | | 742 | | // If the base's memspace should be entirely invalidated, add the cluster | 743 | | // to the workspace up front. | 744 | 1.51M | if (static_cast<DERIVED*>(this)->includeEntireMemorySpace(Base)) | 745 | 0 | AddToWorkList(WorkListElement(Base), &Cluster); | 746 | 1.51M | } | 747 | 427k | } |
RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::InvalidateRegionsWorker>::GenerateClusters() Line | Count | Source | 732 | 38.8k | void GenerateClusters() { | 733 | | // Scan the entire set of bindings and record the region clusters. | 734 | 38.8k | for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); | 735 | 162k | RI != RE; ++RI123k ){ | 736 | 123k | const MemRegion *Base = RI.getKey(); | 737 | | | 738 | 123k | const ClusterBindings &Cluster = RI.getData(); | 739 | 123k | assert(!Cluster.isEmpty() && "Empty clusters should be removed"); | 740 | 123k | static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster); | 741 | | | 742 | | // If the base's memspace should be entirely invalidated, add the cluster | 743 | | // to the workspace up front. | 744 | 123k | if (static_cast<DERIVED*>(this)->includeEntireMemorySpace(Base)) | 745 | 53.3k | AddToWorkList(WorkListElement(Base), &Cluster); | 746 | 123k | } | 747 | 38.8k | } |
|
748 | | |
749 | 2.62M | bool AddToWorkList(WorkListElement E, const ClusterBindings *C) { |
750 | 2.62M | if (C && !Visited.insert(C).second1.88M ) |
751 | 427k | return false; |
752 | 2.19M | WL.push_back(E); |
753 | 2.19M | return true; |
754 | 2.62M | } RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::RemoveDeadBindingsWorker>::AddToWorkList(clang::ento::MemRegion const*, llvm::ImmutableMap<(anonymous namespace)::BindingKey, clang::ento::SVal, llvm::ImutKeyValueInfo<(anonymous namespace)::BindingKey, clang::ento::SVal> > const*) Line | Count | Source | 749 | 2.53M | bool AddToWorkList(WorkListElement E, const ClusterBindings *C) { | 750 | 2.53M | if (C && !Visited.insert(C).second1.81M ) | 751 | 427k | return false; | 752 | 2.10M | WL.push_back(E); | 753 | 2.10M | return true; | 754 | 2.53M | } |
RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::InvalidateRegionsWorker>::AddToWorkList(clang::ento::MemRegion const*, llvm::ImmutableMap<(anonymous namespace)::BindingKey, clang::ento::SVal, llvm::ImutKeyValueInfo<(anonymous namespace)::BindingKey, clang::ento::SVal> > const*) Line | Count | Source | 749 | 94.2k | bool AddToWorkList(WorkListElement E, const ClusterBindings *C) { | 750 | 94.2k | if (C && !Visited.insert(C).second75.4k ) | 751 | 151 | return false; | 752 | 94.0k | WL.push_back(E); | 753 | 94.0k | return true; | 754 | 94.2k | } |
|
755 | | |
756 | | bool AddToWorkList(const MemRegion *R) { |
757 | | return static_cast<DERIVED*>(this)->AddToWorkList(R); |
758 | | } |
759 | | |
760 | 467k | void RunWorkList() { |
761 | 2.66M | while (!WL.empty()) { |
762 | 2.19M | WorkListElement E = WL.pop_back_val(); |
763 | 2.19M | const MemRegion *BaseR = E; |
764 | | |
765 | 2.19M | static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR)); |
766 | 2.19M | } |
767 | 467k | } RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::RemoveDeadBindingsWorker>::RunWorkList() Line | Count | Source | 760 | 428k | void RunWorkList() { | 761 | 2.53M | while (!WL.empty()) { | 762 | 2.10M | WorkListElement E = WL.pop_back_val(); | 763 | 2.10M | const MemRegion *BaseR = E; | 764 | | | 765 | 2.10M | static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR)); | 766 | 2.10M | } | 767 | 428k | } |
RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::InvalidateRegionsWorker>::RunWorkList() Line | Count | Source | 760 | 38.8k | void RunWorkList() { | 761 | 132k | while (!WL.empty()) { | 762 | 94.0k | WorkListElement E = WL.pop_back_val(); | 763 | 94.0k | const MemRegion *BaseR = E; | 764 | | | 765 | 94.0k | static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR)); | 766 | 94.0k | } | 767 | 38.8k | } |
|
768 | | |
769 | 123k | void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C) {} |
770 | | void VisitCluster(const MemRegion *baseR, const ClusterBindings *C) {} |
771 | | |
772 | | void VisitCluster(const MemRegion *BaseR, const ClusterBindings *C, |
773 | | bool Flag) { |
774 | | static_cast<DERIVED*>(this)->VisitCluster(BaseR, C); |
775 | | } |
776 | | }; |
777 | | } |
778 | | |
779 | | //===----------------------------------------------------------------------===// |
780 | | // Binding invalidation. |
781 | | //===----------------------------------------------------------------------===// |
782 | | |
783 | | bool RegionStoreManager::scanReachableSymbols(Store S, const MemRegion *R, |
784 | 794k | ScanReachableSymbols &Callbacks) { |
785 | 794k | assert(R == R->getBaseRegion() && "Should only be called for base regions"); |
786 | 794k | RegionBindingsRef B = getRegionBindings(S); |
787 | 794k | const ClusterBindings *Cluster = B.lookup(R); |
788 | | |
789 | 794k | if (!Cluster) |
790 | 544k | return true; |
791 | | |
792 | 250k | for (ClusterBindings::iterator RI = Cluster->begin(), RE = Cluster->end(); |
793 | 748k | RI != RE; ++RI498k ) { |
794 | 498k | if (!Callbacks.scan(RI.getData())) |
795 | 0 | return false; |
796 | 498k | } |
797 | | |
798 | 250k | return true; |
799 | 250k | } |
800 | | |
801 | 151 | static inline bool isUnionField(const FieldRegion *FR) { |
802 | 151 | return FR->getDecl()->getParent()->isUnion(); |
803 | 151 | } |
804 | | |
805 | | typedef SmallVector<const FieldDecl *, 8> FieldVector; |
806 | | |
807 | 964 | static void getSymbolicOffsetFields(BindingKey K, FieldVector &Fields) { |
808 | 964 | assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys"); |
809 | | |
810 | 964 | const MemRegion *Base = K.getConcreteOffsetRegion(); |
811 | 964 | const MemRegion *R = K.getRegion(); |
812 | | |
813 | 2.11k | while (R != Base) { |
814 | 1.14k | if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) |
815 | 151 | if (!isUnionField(FR)) |
816 | 135 | Fields.push_back(FR->getDecl()); |
817 | | |
818 | 1.14k | R = cast<SubRegion>(R)->getSuperRegion(); |
819 | 1.14k | } |
820 | 964 | } |
821 | | |
822 | 917 | static bool isCompatibleWithFields(BindingKey K, const FieldVector &Fields) { |
823 | 917 | assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys"); |
824 | | |
825 | 917 | if (Fields.empty()) |
826 | 862 | return true; |
827 | | |
828 | 55 | FieldVector FieldsInBindingKey; |
829 | 55 | getSymbolicOffsetFields(K, FieldsInBindingKey); |
830 | | |
831 | 55 | ptrdiff_t Delta = FieldsInBindingKey.size() - Fields.size(); |
832 | 55 | if (Delta >= 0) |
833 | 51 | return std::equal(FieldsInBindingKey.begin() + Delta, |
834 | 51 | FieldsInBindingKey.end(), |
835 | 51 | Fields.begin()); |
836 | 4 | else |
837 | 4 | return std::equal(FieldsInBindingKey.begin(), FieldsInBindingKey.end(), |
838 | 4 | Fields.begin() - Delta); |
839 | 55 | } |
840 | | |
841 | | /// Collects all bindings in \p Cluster that may refer to bindings within |
842 | | /// \p Top. |
843 | | /// |
844 | | /// Each binding is a pair whose \c first is the key (a BindingKey) and whose |
845 | | /// \c second is the value (an SVal). |
846 | | /// |
847 | | /// The \p IncludeAllDefaultBindings parameter specifies whether to include |
848 | | /// default bindings that may extend beyond \p Top itself, e.g. if \p Top is |
849 | | /// an aggregate within a larger aggregate with a default binding. |
850 | | static void |
851 | | collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings, |
852 | | SValBuilder &SVB, const ClusterBindings &Cluster, |
853 | | const SubRegion *Top, BindingKey TopKey, |
854 | 26.7k | bool IncludeAllDefaultBindings) { |
855 | 26.7k | FieldVector FieldsInSymbolicSubregions; |
856 | 26.7k | if (TopKey.hasSymbolicOffset()) { |
857 | 909 | getSymbolicOffsetFields(TopKey, FieldsInSymbolicSubregions); |
858 | 909 | Top = TopKey.getConcreteOffsetRegion(); |
859 | 909 | TopKey = BindingKey::Make(Top, BindingKey::Default); |
860 | 909 | } |
861 | | |
862 | | // Find the length (in bits) of the region being invalidated. |
863 | 26.7k | uint64_t Length = UINT64_MAX; |
864 | 26.7k | SVal Extent = Top->getMemRegionManager().getStaticSize(Top, SVB); |
865 | 26.7k | if (std::optional<nonloc::ConcreteInt> ExtentCI = |
866 | 26.7k | Extent.getAs<nonloc::ConcreteInt>()) { |
867 | 25.9k | const llvm::APSInt &ExtentInt = ExtentCI->getValue(); |
868 | 25.9k | assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned()); |
869 | | // Extents are in bytes but region offsets are in bits. Be careful! |
870 | 25.9k | Length = ExtentInt.getLimitedValue() * SVB.getContext().getCharWidth(); |
871 | 25.9k | } else if (const FieldRegion *872 FR872 = dyn_cast<FieldRegion>(Top)) { |
872 | 41 | if (FR->getDecl()->isBitField()) |
873 | 37 | Length = FR->getDecl()->getBitWidthValue(SVB.getContext()); |
874 | 41 | } |
875 | | |
876 | 64.6k | for (const auto &StoreEntry : Cluster)26.7k { |
877 | 64.6k | BindingKey NextKey = StoreEntry.first; |
878 | 64.6k | if (NextKey.getRegion() == TopKey.getRegion()) { |
879 | | // FIXME: This doesn't catch the case where we're really invalidating a |
880 | | // region with a symbolic offset. Example: |
881 | | // R: points[i].y |
882 | | // Next: points[0].x |
883 | | |
884 | 63.6k | if (NextKey.getOffset() > TopKey.getOffset() && |
885 | 63.6k | NextKey.getOffset() - TopKey.getOffset() < Length10.9k ) { |
886 | | // Case 1: The next binding is inside the region we're invalidating. |
887 | | // Include it. |
888 | 390 | Bindings.push_back(StoreEntry); |
889 | | |
890 | 63.2k | } else if (NextKey.getOffset() == TopKey.getOffset()) { |
891 | | // Case 2: The next binding is at the same offset as the region we're |
892 | | // invalidating. In this case, we need to leave default bindings alone, |
893 | | // since they may be providing a default value for a regions beyond what |
894 | | // we're invalidating. |
895 | | // FIXME: This is probably incorrect; consider invalidating an outer |
896 | | // struct whose first field is bound to a LazyCompoundVal. |
897 | 14.1k | if (IncludeAllDefaultBindings || NextKey.isDirect()13.0k ) |
898 | 12.5k | Bindings.push_back(StoreEntry); |
899 | 14.1k | } |
900 | | |
901 | 63.6k | } else if (1.05k NextKey.hasSymbolicOffset()1.05k ) { |
902 | 953 | const MemRegion *Base = NextKey.getConcreteOffsetRegion(); |
903 | 953 | if (Top->isSubRegionOf(Base) && Top != Base917 ) { |
904 | | // Case 3: The next key is symbolic and we just changed something within |
905 | | // its concrete region. We don't know if the binding is still valid, so |
906 | | // we'll be conservative and include it. |
907 | 28 | if (IncludeAllDefaultBindings || NextKey.isDirect()) |
908 | 28 | if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions)) |
909 | 28 | Bindings.push_back(StoreEntry); |
910 | 925 | } else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) { |
911 | | // Case 4: The next key is symbolic, but we changed a known |
912 | | // super-region. In this case the binding is certainly included. |
913 | 925 | if (BaseSR->isSubRegionOf(Top)) |
914 | 889 | if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions)) |
915 | 847 | Bindings.push_back(StoreEntry); |
916 | 925 | } |
917 | 953 | } |
918 | 64.6k | } |
919 | 26.7k | } |
920 | | |
921 | | static void |
922 | | collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings, |
923 | | SValBuilder &SVB, const ClusterBindings &Cluster, |
924 | 1.06k | const SubRegion *Top, bool IncludeAllDefaultBindings) { |
925 | 1.06k | collectSubRegionBindings(Bindings, SVB, Cluster, Top, |
926 | 1.06k | BindingKey::Make(Top, BindingKey::Default), |
927 | 1.06k | IncludeAllDefaultBindings); |
928 | 1.06k | } |
929 | | |
930 | | RegionBindingsRef |
931 | | RegionStoreManager::removeSubRegionBindings(RegionBindingsConstRef B, |
932 | 210k | const SubRegion *Top) { |
933 | 210k | BindingKey TopKey = BindingKey::Make(Top, BindingKey::Default); |
934 | 210k | const MemRegion *ClusterHead = TopKey.getBaseRegion(); |
935 | | |
936 | 210k | if (Top == ClusterHead) { |
937 | | // We can remove an entire cluster's bindings all in one go. |
938 | 147k | return B.remove(Top); |
939 | 147k | } |
940 | | |
941 | 62.8k | const ClusterBindings *Cluster = B.lookup(ClusterHead); |
942 | 62.8k | if (!Cluster) { |
943 | | // If we're invalidating a region with a symbolic offset, we need to make |
944 | | // sure we don't treat the base region as uninitialized anymore. |
945 | 37.1k | if (TopKey.hasSymbolicOffset()) { |
946 | 204 | const SubRegion *Concrete = TopKey.getConcreteOffsetRegion(); |
947 | 204 | return B.addBinding(Concrete, BindingKey::Default, UnknownVal()); |
948 | 204 | } |
949 | 36.9k | return B; |
950 | 37.1k | } |
951 | | |
952 | 25.7k | SmallVector<BindingPair, 32> Bindings; |
953 | 25.7k | collectSubRegionBindings(Bindings, svalBuilder, *Cluster, Top, TopKey, |
954 | 25.7k | /*IncludeAllDefaultBindings=*/false); |
955 | | |
956 | 25.7k | ClusterBindingsRef Result(*Cluster, CBFactory); |
957 | 25.7k | for (BindingKey Key : llvm::make_first_range(Bindings)) |
958 | 12.4k | Result = Result.remove(Key); |
959 | | |
960 | | // If we're invalidating a region with a symbolic offset, we need to make sure |
961 | | // we don't treat the base region as uninitialized anymore. |
962 | | // FIXME: This isn't very precise; see the example in |
963 | | // collectSubRegionBindings. |
964 | 25.7k | if (TopKey.hasSymbolicOffset()) { |
965 | 909 | const SubRegion *Concrete = TopKey.getConcreteOffsetRegion(); |
966 | 909 | Result = Result.add(BindingKey::Make(Concrete, BindingKey::Default), |
967 | 909 | UnknownVal()); |
968 | 909 | } |
969 | | |
970 | 25.7k | if (Result.isEmpty()) |
971 | 1.50k | return B.remove(ClusterHead); |
972 | 24.2k | return B.add(ClusterHead, Result.asImmutableMap()); |
973 | 25.7k | } |
974 | | |
975 | | namespace { |
976 | | class InvalidateRegionsWorker : public ClusterAnalysis<InvalidateRegionsWorker> |
977 | | { |
978 | | const Expr *Ex; |
979 | | unsigned Count; |
980 | | const LocationContext *LCtx; |
981 | | InvalidatedSymbols &IS; |
982 | | RegionAndSymbolInvalidationTraits &ITraits; |
983 | | StoreManager::InvalidatedRegions *Regions; |
984 | | GlobalsFilterKind GlobalsFilter; |
985 | | public: |
986 | | InvalidateRegionsWorker(RegionStoreManager &rm, |
987 | | ProgramStateManager &stateMgr, |
988 | | RegionBindingsRef b, |
989 | | const Expr *ex, unsigned count, |
990 | | const LocationContext *lctx, |
991 | | InvalidatedSymbols &is, |
992 | | RegionAndSymbolInvalidationTraits &ITraitsIn, |
993 | | StoreManager::InvalidatedRegions *r, |
994 | | GlobalsFilterKind GFK) |
995 | 38.8k | : ClusterAnalysis<InvalidateRegionsWorker>(rm, stateMgr, b), |
996 | 38.8k | Ex(ex), Count(count), LCtx(lctx), IS(is), ITraits(ITraitsIn), Regions(r), |
997 | 38.8k | GlobalsFilter(GFK) {} |
998 | | |
999 | | void VisitCluster(const MemRegion *baseR, const ClusterBindings *C); |
1000 | | void VisitBinding(SVal V); |
1001 | | |
1002 | | using ClusterAnalysis::AddToWorkList; |
1003 | | |
1004 | | bool AddToWorkList(const MemRegion *R); |
1005 | | |
1006 | | /// Returns true if all clusters in the memory space for \p Base should be |
1007 | | /// be invalidated. |
1008 | | bool includeEntireMemorySpace(const MemRegion *Base); |
1009 | | |
1010 | | /// Returns true if the memory space of the given region is one of the global |
1011 | | /// regions specially included at the start of invalidation. |
1012 | | bool isInitiallyIncludedGlobalRegion(const MemRegion *R); |
1013 | | }; |
1014 | | } |
1015 | | |
1016 | 40.8k | bool InvalidateRegionsWorker::AddToWorkList(const MemRegion *R) { |
1017 | 40.8k | bool doNotInvalidateSuperRegion = ITraits.hasTrait( |
1018 | 40.8k | R, RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion); |
1019 | 40.8k | const MemRegion *BaseR = doNotInvalidateSuperRegion ? R2.16k : R->getBaseRegion()38.6k ; |
1020 | 40.8k | return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR)); |
1021 | 40.8k | } |
1022 | | |
1023 | 80.3k | void InvalidateRegionsWorker::VisitBinding(SVal V) { |
1024 | | // A symbol? Mark it touched by the invalidation. |
1025 | 80.3k | if (SymbolRef Sym = V.getAsSymbol()) |
1026 | 72.9k | IS.insert(Sym); |
1027 | | |
1028 | 80.3k | if (const MemRegion *R = V.getAsRegion()) { |
1029 | 1.66k | AddToWorkList(R); |
1030 | 1.66k | return; |
1031 | 1.66k | } |
1032 | | |
1033 | | // Is it a LazyCompoundVal? All references get invalidated as well. |
1034 | 78.6k | if (std::optional<nonloc::LazyCompoundVal> LCS = |
1035 | 78.6k | V.getAs<nonloc::LazyCompoundVal>()) { |
1036 | | |
1037 | | // `getInterestingValues()` returns SVals contained within LazyCompoundVals, |
1038 | | // so there is no need to visit them. |
1039 | 161 | for (SVal V : RM.getInterestingValues(*LCS)) |
1040 | 19 | if (!isa<nonloc::LazyCompoundVal>(V)) |
1041 | 17 | VisitBinding(V); |
1042 | | |
1043 | 161 | return; |
1044 | 161 | } |
1045 | 78.6k | } |
1046 | | |
1047 | | void InvalidateRegionsWorker::VisitCluster(const MemRegion *baseR, |
1048 | 94.0k | const ClusterBindings *C) { |
1049 | | |
1050 | 94.0k | bool PreserveRegionsContents = |
1051 | 94.0k | ITraits.hasTrait(baseR, |
1052 | 94.0k | RegionAndSymbolInvalidationTraits::TK_PreserveContents); |
1053 | | |
1054 | 94.0k | if (C) { |
1055 | 75.8k | for (SVal Val : llvm::make_second_range(*C)) |
1056 | 80.3k | VisitBinding(Val); |
1057 | | |
1058 | | // Invalidate regions contents. |
1059 | 75.8k | if (!PreserveRegionsContents) |
1060 | 71.5k | B = B.remove(baseR); |
1061 | 75.8k | } |
1062 | | |
1063 | 94.0k | if (const auto *TO = dyn_cast<TypedValueRegion>(baseR)) { |
1064 | 28.9k | if (const auto *RD = TO->getValueType()->getAsCXXRecordDecl()) { |
1065 | | |
1066 | | // Lambdas can affect all static local variables without explicitly |
1067 | | // capturing those. |
1068 | | // We invalidate all static locals referenced inside the lambda body. |
1069 | 18.8k | if (RD->isLambda() && RD->getLambdaCallOperator()->getBody()8 ) { |
1070 | 8 | using namespace ast_matchers; |
1071 | | |
1072 | 8 | const char *DeclBind = "DeclBind"; |
1073 | 8 | StatementMatcher RefToStatic = stmt(hasDescendant(declRefExpr( |
1074 | 8 | to(varDecl(hasStaticStorageDuration()).bind(DeclBind))))); |
1075 | 8 | auto Matches = |
1076 | 8 | match(RefToStatic, *RD->getLambdaCallOperator()->getBody(), |
1077 | 8 | RD->getASTContext()); |
1078 | | |
1079 | 8 | for (BoundNodes &Match : Matches) { |
1080 | 2 | auto *VD = Match.getNodeAs<VarDecl>(DeclBind); |
1081 | 2 | const VarRegion *ToInvalidate = |
1082 | 2 | RM.getRegionManager().getVarRegion(VD, LCtx); |
1083 | 2 | AddToWorkList(ToInvalidate); |
1084 | 2 | } |
1085 | 8 | } |
1086 | 18.8k | } |
1087 | 28.9k | } |
1088 | | |
1089 | | // BlockDataRegion? If so, invalidate captured variables that are passed |
1090 | | // by reference. |
1091 | 94.0k | if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) { |
1092 | 143 | for (auto Var : BR->referenced_vars()) { |
1093 | 131 | const VarRegion *VR = Var.getCapturedRegion(); |
1094 | 131 | const VarDecl *VD = VR->getDecl(); |
1095 | 131 | if (VD->hasAttr<BlocksAttr>() || !VD->hasLocalStorage()114 ) { |
1096 | 33 | AddToWorkList(VR); |
1097 | 33 | } |
1098 | 98 | else if (Loc::isLocType(VR->getValueType())) { |
1099 | | // Map the current bindings to a Store to retrieve the value |
1100 | | // of the binding. If that binding itself is a region, we should |
1101 | | // invalidate that region. This is because a block may capture |
1102 | | // a pointer value, but the thing pointed by that pointer may |
1103 | | // get invalidated. |
1104 | 59 | SVal V = RM.getBinding(B, loc::MemRegionVal(VR)); |
1105 | 59 | if (std::optional<Loc> L = V.getAs<Loc>()) { |
1106 | 59 | if (const MemRegion *LR = L->getAsRegion()) |
1107 | 59 | AddToWorkList(LR); |
1108 | 59 | } |
1109 | 59 | } |
1110 | 131 | } |
1111 | 143 | return; |
1112 | 143 | } |
1113 | | |
1114 | | // Symbolic region? |
1115 | 93.9k | if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) |
1116 | 11.7k | IS.insert(SR->getSymbol()); |
1117 | | |
1118 | | // Nothing else should be done in the case when we preserve regions context. |
1119 | 93.9k | if (PreserveRegionsContents) |
1120 | 9.98k | return; |
1121 | | |
1122 | | // Otherwise, we have a normal data region. Record that we touched the region. |
1123 | 83.9k | if (Regions) |
1124 | 83.9k | Regions->push_back(baseR); |
1125 | | |
1126 | 83.9k | if (isa<AllocaRegion, SymbolicRegion>(baseR)) { |
1127 | | // Invalidate the region by setting its default value to |
1128 | | // conjured symbol. The type of the symbol is irrelevant. |
1129 | 9.26k | DefinedOrUnknownSVal V = |
1130 | 9.26k | svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count); |
1131 | 9.26k | B = B.addBinding(baseR, BindingKey::Default, V); |
1132 | 9.26k | return; |
1133 | 9.26k | } |
1134 | | |
1135 | 74.6k | if (!baseR->isBoundable()) |
1136 | 54.0k | return; |
1137 | | |
1138 | 20.6k | const TypedValueRegion *TR = cast<TypedValueRegion>(baseR); |
1139 | 20.6k | QualType T = TR->getValueType(); |
1140 | | |
1141 | 20.6k | if (isInitiallyIncludedGlobalRegion(baseR)) { |
1142 | | // If the region is a global and we are invalidating all globals, |
1143 | | // erasing the entry is good enough. This causes all globals to be lazily |
1144 | | // symbolicated from the same base symbol. |
1145 | 545 | return; |
1146 | 545 | } |
1147 | | |
1148 | 20.1k | if (T->isRecordType()) { |
1149 | | // Invalidate the region by setting its default value to |
1150 | | // conjured symbol. The type of the symbol is irrelevant. |
1151 | 16.8k | DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, |
1152 | 16.8k | Ctx.IntTy, Count); |
1153 | 16.8k | B = B.addBinding(baseR, BindingKey::Default, V); |
1154 | 16.8k | return; |
1155 | 16.8k | } |
1156 | | |
1157 | 3.24k | if (const ArrayType *AT = Ctx.getAsArrayType(T)) { |
1158 | 1.75k | bool doNotInvalidateSuperRegion = ITraits.hasTrait( |
1159 | 1.75k | baseR, |
1160 | 1.75k | RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion); |
1161 | | |
1162 | 1.75k | if (doNotInvalidateSuperRegion) { |
1163 | | // We are not doing blank invalidation of the whole array region so we |
1164 | | // have to manually invalidate each elements. |
1165 | 39 | std::optional<uint64_t> NumElements; |
1166 | | |
1167 | | // Compute lower and upper offsets for region within array. |
1168 | 39 | if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) |
1169 | 39 | NumElements = CAT->getSize().getZExtValue(); |
1170 | 39 | if (!NumElements) // We are not dealing with a constant size array |
1171 | 0 | goto conjure_default; |
1172 | 39 | QualType ElementTy = AT->getElementType(); |
1173 | 39 | uint64_t ElemSize = Ctx.getTypeSize(ElementTy); |
1174 | 39 | const RegionOffset &RO = baseR->getAsOffset(); |
1175 | 39 | const MemRegion *SuperR = baseR->getBaseRegion(); |
1176 | 39 | if (RO.hasSymbolicOffset()) { |
1177 | | // If base region has a symbolic offset, |
1178 | | // we revert to invalidating the super region. |
1179 | 4 | if (SuperR) |
1180 | 4 | AddToWorkList(SuperR); |
1181 | 4 | goto conjure_default; |
1182 | 4 | } |
1183 | | |
1184 | 35 | uint64_t LowerOffset = RO.getOffset(); |
1185 | 35 | uint64_t UpperOffset = LowerOffset + *NumElements * ElemSize; |
1186 | 35 | bool UpperOverflow = UpperOffset < LowerOffset; |
1187 | | |
1188 | | // Invalidate regions which are within array boundaries, |
1189 | | // or have a symbolic offset. |
1190 | 35 | if (!SuperR) |
1191 | 0 | goto conjure_default; |
1192 | | |
1193 | 35 | const ClusterBindings *C = B.lookup(SuperR); |
1194 | 35 | if (!C) |
1195 | 1 | goto conjure_default; |
1196 | | |
1197 | 128 | for (const auto &[BK, V] : *C)34 { |
1198 | 128 | std::optional<uint64_t> ROffset = |
1199 | 128 | BK.hasSymbolicOffset() ? std::optional<uint64_t>()5 : BK.getOffset()123 ; |
1200 | | |
1201 | | // Check offset is not symbolic and within array's boundaries. |
1202 | | // Handles arrays of 0 elements and of 0-sized elements as well. |
1203 | 128 | if (!ROffset || |
1204 | 128 | (123 (123 *ROffset >= LowerOffset123 && *ROffset < UpperOffset105 ) || |
1205 | 123 | (52 UpperOverflow52 && |
1206 | 52 | (11 *ROffset >= LowerOffset11 || *ROffset < UpperOffset5 )) || |
1207 | 123 | (44 LowerOffset == UpperOffset44 && *ROffset == LowerOffset1 ))) { |
1208 | 85 | B = B.removeBinding(BK); |
1209 | | // Bound symbolic regions need to be invalidated for dead symbol |
1210 | | // detection. |
1211 | 85 | const MemRegion *R = V.getAsRegion(); |
1212 | 85 | if (isa_and_nonnull<SymbolicRegion>(R)) |
1213 | 2 | VisitBinding(V); |
1214 | 85 | } |
1215 | 128 | } |
1216 | 34 | } |
1217 | 1.75k | conjure_default: |
1218 | | // Set the default value of the array to conjured symbol. |
1219 | 1.75k | DefinedOrUnknownSVal V = |
1220 | 1.75k | svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, |
1221 | 1.75k | AT->getElementType(), Count); |
1222 | 1.75k | B = B.addBinding(baseR, BindingKey::Default, V); |
1223 | 1.75k | return; |
1224 | 1.75k | } |
1225 | | |
1226 | 1.48k | DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, |
1227 | 1.48k | T,Count); |
1228 | 1.48k | assert(SymbolManager::canSymbolicate(T) || V.isUnknown()); |
1229 | 1.48k | B = B.addBinding(baseR, BindingKey::Direct, V); |
1230 | 1.48k | } |
1231 | | |
1232 | | bool InvalidateRegionsWorker::isInitiallyIncludedGlobalRegion( |
1233 | 144k | const MemRegion *R) { |
1234 | 144k | switch (GlobalsFilter) { |
1235 | 3.17k | case GFK_None: |
1236 | 3.17k | return false; |
1237 | 23.7k | case GFK_SystemOnly: |
1238 | 23.7k | return isa<GlobalSystemSpaceRegion>(R->getMemorySpace()); |
1239 | 117k | case GFK_All: |
1240 | 117k | return isa<NonStaticGlobalSpaceRegion>(R->getMemorySpace()); |
1241 | 144k | } |
1242 | | |
1243 | 0 | llvm_unreachable("unknown globals filter"); |
1244 | 0 | } |
1245 | | |
1246 | 123k | bool InvalidateRegionsWorker::includeEntireMemorySpace(const MemRegion *Base) { |
1247 | 123k | if (isInitiallyIncludedGlobalRegion(Base)) |
1248 | 53.3k | return true; |
1249 | | |
1250 | 70.5k | const MemSpaceRegion *MemSpace = Base->getMemorySpace(); |
1251 | 70.5k | return ITraits.hasTrait(MemSpace, |
1252 | 70.5k | RegionAndSymbolInvalidationTraits::TK_EntireMemSpace); |
1253 | 123k | } |
1254 | | |
1255 | | RegionBindingsRef |
1256 | | RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K, |
1257 | | const Expr *Ex, |
1258 | | unsigned Count, |
1259 | | const LocationContext *LCtx, |
1260 | | RegionBindingsRef B, |
1261 | 68.2k | InvalidatedRegions *Invalidated) { |
1262 | | // Bind the globals memory space to a new symbol that we will use to derive |
1263 | | // the bindings for all globals. |
1264 | 68.2k | const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K); |
1265 | 68.2k | SVal V = svalBuilder.conjureSymbolVal(/* symbolTag = */ (const void*) GS, Ex, LCtx, |
1266 | 68.2k | /* type does not matter */ Ctx.IntTy, |
1267 | 68.2k | Count); |
1268 | | |
1269 | 68.2k | B = B.removeBinding(GS) |
1270 | 68.2k | .addBinding(BindingKey::Make(GS, BindingKey::Default), V); |
1271 | | |
1272 | | // Even if there are no bindings in the global scope, we still need to |
1273 | | // record that we touched it. |
1274 | 68.2k | if (Invalidated) |
1275 | 68.2k | Invalidated->push_back(GS); |
1276 | | |
1277 | 68.2k | return B; |
1278 | 68.2k | } |
1279 | | |
1280 | | void RegionStoreManager::populateWorkList(InvalidateRegionsWorker &W, |
1281 | | ArrayRef<SVal> Values, |
1282 | 38.8k | InvalidatedRegions *TopLevelRegions) { |
1283 | 57.6k | for (SVal V : Values) { |
1284 | 57.6k | if (auto LCS = V.getAs<nonloc::LazyCompoundVal>()) { |
1285 | 9.66k | for (SVal S : getInterestingValues(*LCS)) |
1286 | 9.60k | if (const MemRegion *R = S.getAsRegion()) |
1287 | 441 | W.AddToWorkList(R); |
1288 | | |
1289 | 9.66k | continue; |
1290 | 9.66k | } |
1291 | | |
1292 | 47.9k | if (const MemRegion *R = V.getAsRegion()) { |
1293 | 38.6k | if (TopLevelRegions) |
1294 | 38.6k | TopLevelRegions->push_back(R); |
1295 | 38.6k | W.AddToWorkList(R); |
1296 | 38.6k | continue; |
1297 | 38.6k | } |
1298 | 47.9k | } |
1299 | 38.8k | } |
1300 | | |
1301 | | StoreRef |
1302 | | RegionStoreManager::invalidateRegions(Store store, |
1303 | | ArrayRef<SVal> Values, |
1304 | | const Expr *Ex, unsigned Count, |
1305 | | const LocationContext *LCtx, |
1306 | | const CallEvent *Call, |
1307 | | InvalidatedSymbols &IS, |
1308 | | RegionAndSymbolInvalidationTraits &ITraits, |
1309 | | InvalidatedRegions *TopLevelRegions, |
1310 | 38.8k | InvalidatedRegions *Invalidated) { |
1311 | 38.8k | GlobalsFilterKind GlobalsFilter; |
1312 | 38.8k | if (Call) { |
1313 | 37.7k | if (Call->isInSystemHeader()) |
1314 | 7.27k | GlobalsFilter = GFK_SystemOnly; |
1315 | 30.4k | else |
1316 | 30.4k | GlobalsFilter = GFK_All; |
1317 | 37.7k | } else { |
1318 | 1.08k | GlobalsFilter = GFK_None; |
1319 | 1.08k | } |
1320 | | |
1321 | 38.8k | RegionBindingsRef B = getRegionBindings(store); |
1322 | 38.8k | InvalidateRegionsWorker W(*this, StateMgr, B, Ex, Count, LCtx, IS, ITraits, |
1323 | 38.8k | Invalidated, GlobalsFilter); |
1324 | | |
1325 | | // Scan the bindings and generate the clusters. |
1326 | 38.8k | W.GenerateClusters(); |
1327 | | |
1328 | | // Add the regions to the worklist. |
1329 | 38.8k | populateWorkList(W, Values, TopLevelRegions); |
1330 | | |
1331 | 38.8k | W.RunWorkList(); |
1332 | | |
1333 | | // Return the new bindings. |
1334 | 38.8k | B = W.getRegionBindings(); |
1335 | | |
1336 | | // For calls, determine which global regions should be invalidated and |
1337 | | // invalidate them. (Note that function-static and immutable globals are never |
1338 | | // invalidated by this.) |
1339 | | // TODO: This could possibly be more precise with modules. |
1340 | 38.8k | switch (GlobalsFilter) { |
1341 | 30.4k | case GFK_All: |
1342 | 30.4k | B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind, |
1343 | 30.4k | Ex, Count, LCtx, B, Invalidated); |
1344 | 30.4k | [[fallthrough]]; |
1345 | 37.7k | case GFK_SystemOnly: |
1346 | 37.7k | B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind, |
1347 | 37.7k | Ex, Count, LCtx, B, Invalidated); |
1348 | 37.7k | [[fallthrough]]; |
1349 | 38.8k | case GFK_None: |
1350 | 38.8k | break; |
1351 | 38.8k | } |
1352 | | |
1353 | 38.8k | return StoreRef(B.asStore(), *this); |
1354 | 38.8k | } |
1355 | | |
1356 | | //===----------------------------------------------------------------------===// |
1357 | | // Location and region casting. |
1358 | | //===----------------------------------------------------------------------===// |
1359 | | |
1360 | | /// ArrayToPointer - Emulates the "decay" of an array to a pointer |
1361 | | /// type. 'Array' represents the lvalue of the array being decayed |
1362 | | /// to a pointer, and the returned SVal represents the decayed |
1363 | | /// version of that lvalue (i.e., a pointer to the first element of |
1364 | | /// the array). This is called by ExprEngine when evaluating casts |
1365 | | /// from arrays to pointers. |
1366 | 13.3k | SVal RegionStoreManager::ArrayToPointer(Loc Array, QualType T) { |
1367 | 13.3k | if (isa<loc::ConcreteInt>(Array)) |
1368 | 0 | return Array; |
1369 | | |
1370 | 13.3k | if (!isa<loc::MemRegionVal>(Array)) |
1371 | 0 | return UnknownVal(); |
1372 | | |
1373 | 13.3k | const SubRegion *R = |
1374 | 13.3k | cast<SubRegion>(Array.castAs<loc::MemRegionVal>().getRegion()); |
1375 | 13.3k | NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex(); |
1376 | 13.3k | return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, R, Ctx)); |
1377 | 13.3k | } |
1378 | | |
1379 | | //===----------------------------------------------------------------------===// |
1380 | | // Loading values from regions. |
1381 | | //===----------------------------------------------------------------------===// |
1382 | | |
1383 | 705k | SVal RegionStoreManager::getBinding(RegionBindingsConstRef B, Loc L, QualType T) { |
1384 | 705k | assert(!isa<UnknownVal>(L) && "location unknown"); |
1385 | 705k | assert(!isa<UndefinedVal>(L) && "location undefined"); |
1386 | | |
1387 | | // For access to concrete addresses, return UnknownVal. Checks |
1388 | | // for null dereferences (and similar errors) are done by checkers, not |
1389 | | // the Store. |
1390 | | // FIXME: We can consider lazily symbolicating such memory, but we really |
1391 | | // should defer this when we can reason easily about symbolicating arrays |
1392 | | // of bytes. |
1393 | 705k | if (L.getAs<loc::ConcreteInt>()) { |
1394 | 336 | return UnknownVal(); |
1395 | 336 | } |
1396 | 704k | if (!L.getAs<loc::MemRegionVal>()) { |
1397 | 0 | return UnknownVal(); |
1398 | 0 | } |
1399 | | |
1400 | 704k | const MemRegion *MR = L.castAs<loc::MemRegionVal>().getRegion(); |
1401 | | |
1402 | 704k | if (isa<BlockDataRegion>(MR)) { |
1403 | 1 | return UnknownVal(); |
1404 | 1 | } |
1405 | | |
1406 | | // Auto-detect the binding type. |
1407 | 704k | if (T.isNull()) { |
1408 | 447k | if (const auto *TVR = dyn_cast<TypedValueRegion>(MR)) |
1409 | 440k | T = TVR->getValueType(); |
1410 | 7.00k | else if (const auto *TR = dyn_cast<TypedRegion>(MR)) |
1411 | 5 | T = TR->getLocationType()->getPointeeType(); |
1412 | 7.00k | else if (const auto *SR = dyn_cast<SymbolicRegion>(MR)) |
1413 | 7.00k | T = SR->getPointeeStaticType(); |
1414 | 447k | } |
1415 | 704k | assert(!T.isNull() && "Unable to auto-detect binding type!"); |
1416 | 704k | assert(!T->isVoidType() && "Attempting to dereference a void pointer!"); |
1417 | | |
1418 | 704k | if (!isa<TypedValueRegion>(MR)) |
1419 | 10.5k | MR = GetElementZeroRegion(cast<SubRegion>(MR), T); |
1420 | | |
1421 | | // FIXME: Perhaps this method should just take a 'const MemRegion*' argument |
1422 | | // instead of 'Loc', and have the other Loc cases handled at a higher level. |
1423 | 704k | const TypedValueRegion *R = cast<TypedValueRegion>(MR); |
1424 | 704k | QualType RTy = R->getValueType(); |
1425 | | |
1426 | | // FIXME: we do not yet model the parts of a complex type, so treat the |
1427 | | // whole thing as "unknown". |
1428 | 704k | if (RTy->isAnyComplexType()) |
1429 | 87 | return UnknownVal(); |
1430 | | |
1431 | | // FIXME: We should eventually handle funny addressing. e.g.: |
1432 | | // |
1433 | | // int x = ...; |
1434 | | // int *p = &x; |
1435 | | // char *q = (char*) p; |
1436 | | // char c = *q; // returns the first byte of 'x'. |
1437 | | // |
1438 | | // Such funny addressing will occur due to layering of regions. |
1439 | 704k | if (RTy->isStructureOrClassType()) |
1440 | 64.6k | return getBindingForStruct(B, R); |
1441 | | |
1442 | | // FIXME: Handle unions. |
1443 | 640k | if (RTy->isUnionType()) |
1444 | 129 | return createLazyBinding(B, R); |
1445 | | |
1446 | 640k | if (RTy->isArrayType()) { |
1447 | 3.20k | if (RTy->isConstantArrayType()) |
1448 | 3.19k | return getBindingForArray(B, R); |
1449 | 2 | else |
1450 | 2 | return UnknownVal(); |
1451 | 3.20k | } |
1452 | | |
1453 | | // FIXME: handle Vector types. |
1454 | 636k | if (RTy->isVectorType()) |
1455 | 21 | return UnknownVal(); |
1456 | | |
1457 | 636k | if (const FieldRegion* FR = dyn_cast<FieldRegion>(R)) |
1458 | 77.9k | return svalBuilder.evalCast(getBindingForField(B, FR), T, QualType{}); |
1459 | | |
1460 | 558k | if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) { |
1461 | | // FIXME: Here we actually perform an implicit conversion from the loaded |
1462 | | // value to the element type. Eventually we want to compose these values |
1463 | | // more intelligently. For example, an 'element' can encompass multiple |
1464 | | // bound regions (e.g., several bound bytes), or could be a subset of |
1465 | | // a larger value. |
1466 | 33.9k | return svalBuilder.evalCast(getBindingForElement(B, ER), T, QualType{}); |
1467 | 33.9k | } |
1468 | | |
1469 | 524k | if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) { |
1470 | | // FIXME: Here we actually perform an implicit conversion from the loaded |
1471 | | // value to the ivar type. What we should model is stores to ivars |
1472 | | // that blow past the extent of the ivar. If the address of the ivar is |
1473 | | // reinterpretted, it is possible we stored a different value that could |
1474 | | // fit within the ivar. Either we need to cast these when storing them |
1475 | | // or reinterpret them lazily (as we do here). |
1476 | 2.71k | return svalBuilder.evalCast(getBindingForObjCIvar(B, IVR), T, QualType{}); |
1477 | 2.71k | } |
1478 | | |
1479 | 522k | if (const VarRegion *VR = dyn_cast<VarRegion>(R)) { |
1480 | | // FIXME: Here we actually perform an implicit conversion from the loaded |
1481 | | // value to the variable type. What we should model is stores to variables |
1482 | | // that blow past the extent of the variable. If the address of the |
1483 | | // variable is reinterpretted, it is possible we stored a different value |
1484 | | // that could fit within the variable. Either we need to cast these when |
1485 | | // storing them or reinterpret them lazily (as we do here). |
1486 | 457k | return svalBuilder.evalCast(getBindingForVar(B, VR), T, QualType{}); |
1487 | 457k | } |
1488 | | |
1489 | 64.9k | const SVal *V = B.lookup(R, BindingKey::Direct); |
1490 | | |
1491 | | // Check if the region has a binding. |
1492 | 64.9k | if (V) |
1493 | 61.0k | return *V; |
1494 | | |
1495 | | // The location does not have a bound value. This means that it has |
1496 | | // the value it had upon its creation and/or entry to the analyzed |
1497 | | // function/method. These are either symbolic values or 'undefined'. |
1498 | 3.93k | if (R->hasStackNonParametersStorage()) { |
1499 | | // All stack variables are considered to have undefined values |
1500 | | // upon creation. All heap allocated blocks are considered to |
1501 | | // have undefined values as well unless they are explicitly bound |
1502 | | // to specific values. |
1503 | 117 | return UndefinedVal(); |
1504 | 117 | } |
1505 | | |
1506 | | // All other values are symbolic. |
1507 | 3.81k | return svalBuilder.getRegionValueSymbolVal(R); |
1508 | 3.93k | } |
1509 | | |
1510 | 1.56k | static QualType getUnderlyingType(const SubRegion *R) { |
1511 | 1.56k | QualType RegionTy; |
1512 | 1.56k | if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R)) |
1513 | 1.54k | RegionTy = TVR->getValueType(); |
1514 | | |
1515 | 1.56k | if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) |
1516 | 12 | RegionTy = SR->getSymbol()->getType(); |
1517 | | |
1518 | 1.56k | return RegionTy; |
1519 | 1.56k | } |
1520 | | |
1521 | | /// Checks to see if store \p B has a lazy binding for region \p R. |
1522 | | /// |
1523 | | /// If \p AllowSubregionBindings is \c false, a lazy binding will be rejected |
1524 | | /// if there are additional bindings within \p R. |
1525 | | /// |
1526 | | /// Note that unlike RegionStoreManager::findLazyBinding, this will not search |
1527 | | /// for lazy bindings for super-regions of \p R. |
1528 | | static std::optional<nonloc::LazyCompoundVal> |
1529 | | getExistingLazyBinding(SValBuilder &SVB, RegionBindingsConstRef B, |
1530 | 195k | const SubRegion *R, bool AllowSubregionBindings) { |
1531 | 195k | std::optional<SVal> V = B.getDefaultBinding(R); |
1532 | 195k | if (!V) |
1533 | 171k | return std::nullopt; |
1534 | | |
1535 | 23.9k | std::optional<nonloc::LazyCompoundVal> LCV = |
1536 | 23.9k | V->getAs<nonloc::LazyCompoundVal>(); |
1537 | 23.9k | if (!LCV) |
1538 | 22.4k | return std::nullopt; |
1539 | | |
1540 | | // If the LCV is for a subregion, the types might not match, and we shouldn't |
1541 | | // reuse the binding. |
1542 | 1.56k | QualType RegionTy = getUnderlyingType(R); |
1543 | 1.56k | if (!RegionTy.isNull() && |
1544 | 1.56k | !RegionTy->isVoidPointerType()) { |
1545 | 1.55k | QualType SourceRegionTy = LCV->getRegion()->getValueType(); |
1546 | 1.55k | if (!SVB.getContext().hasSameUnqualifiedType(RegionTy, SourceRegionTy)) |
1547 | 600 | return std::nullopt; |
1548 | 1.55k | } |
1549 | | |
1550 | 960 | if (!AllowSubregionBindings) { |
1551 | | // If there are any other bindings within this region, we shouldn't reuse |
1552 | | // the top-level binding. |
1553 | 181 | SmallVector<BindingPair, 16> Bindings; |
1554 | 181 | collectSubRegionBindings(Bindings, SVB, *B.lookup(R->getBaseRegion()), R, |
1555 | 181 | /*IncludeAllDefaultBindings=*/true); |
1556 | 181 | if (Bindings.size() > 1) |
1557 | 2 | return std::nullopt; |
1558 | 181 | } |
1559 | | |
1560 | 958 | return *LCV; |
1561 | 960 | } |
1562 | | |
1563 | | std::pair<Store, const SubRegion *> |
1564 | | RegionStoreManager::findLazyBinding(RegionBindingsConstRef B, |
1565 | | const SubRegion *R, |
1566 | 221k | const SubRegion *originalRegion) { |
1567 | 221k | if (originalRegion != R) { |
1568 | 136k | if (std::optional<nonloc::LazyCompoundVal> V = |
1569 | 136k | getExistingLazyBinding(svalBuilder, B, R, true)) |
1570 | 779 | return std::make_pair(V->getStore(), V->getRegion()); |
1571 | 136k | } |
1572 | | |
1573 | 220k | typedef std::pair<Store, const SubRegion *> StoreRegionPair; |
1574 | 220k | StoreRegionPair Result = StoreRegionPair(); |
1575 | | |
1576 | 220k | if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) { |
1577 | 63.3k | Result = findLazyBinding(B, cast<SubRegion>(ER->getSuperRegion()), |
1578 | 63.3k | originalRegion); |
1579 | | |
1580 | 63.3k | if (Result.second) |
1581 | 471 | Result.second = MRMgr.getElementRegionWithSuper(ER, Result.second); |
1582 | | |
1583 | 157k | } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) { |
1584 | 72.2k | Result = findLazyBinding(B, cast<SubRegion>(FR->getSuperRegion()), |
1585 | 72.2k | originalRegion); |
1586 | | |
1587 | 72.2k | if (Result.second) |
1588 | 949 | Result.second = MRMgr.getFieldRegionWithSuper(FR, Result.second); |
1589 | | |
1590 | 84.8k | } else if (const CXXBaseObjectRegion *BaseReg = |
1591 | 84.8k | dyn_cast<CXXBaseObjectRegion>(R)) { |
1592 | | // C++ base object region is another kind of region that we should blast |
1593 | | // through to look for lazy compound value. It is like a field region. |
1594 | 1.22k | Result = findLazyBinding(B, cast<SubRegion>(BaseReg->getSuperRegion()), |
1595 | 1.22k | originalRegion); |
1596 | | |
1597 | 1.22k | if (Result.second) |
1598 | 46 | Result.second = MRMgr.getCXXBaseObjectRegionWithSuper(BaseReg, |
1599 | 46 | Result.second); |
1600 | 1.22k | } |
1601 | | |
1602 | 220k | return Result; |
1603 | 221k | } |
1604 | | |
1605 | | /// This is a helper function for `getConstantValFromConstArrayInitializer`. |
1606 | | /// |
1607 | | /// Return an array of extents of the declared array type. |
1608 | | /// |
1609 | | /// E.g. for `int x[1][2][3];` returns { 1, 2, 3 }. |
1610 | | static SmallVector<uint64_t, 2> |
1611 | 1.04k | getConstantArrayExtents(const ConstantArrayType *CAT) { |
1612 | 1.04k | assert(CAT && "ConstantArrayType should not be null"); |
1613 | 1.04k | CAT = cast<ConstantArrayType>(CAT->getCanonicalTypeInternal()); |
1614 | 1.04k | SmallVector<uint64_t, 2> Extents; |
1615 | 1.44k | do { |
1616 | 1.44k | Extents.push_back(CAT->getSize().getZExtValue()); |
1617 | 1.44k | } while ((CAT = dyn_cast<ConstantArrayType>(CAT->getElementType()))); |
1618 | 1.04k | return Extents; |
1619 | 1.04k | } |
1620 | | |
1621 | | /// This is a helper function for `getConstantValFromConstArrayInitializer`. |
1622 | | /// |
1623 | | /// Return an array of offsets from nested ElementRegions and a root base |
1624 | | /// region. The array is never empty and a base region is never null. |
1625 | | /// |
1626 | | /// E.g. for `Element{Element{Element{VarRegion},1},2},3}` returns { 3, 2, 1 }. |
1627 | | /// This represents an access through indirection: `arr[1][2][3];` |
1628 | | /// |
1629 | | /// \param ER The given (possibly nested) ElementRegion. |
1630 | | /// |
1631 | | /// \note The result array is in the reverse order of indirection expression: |
1632 | | /// arr[1][2][3] -> { 3, 2, 1 }. This helps to provide complexity O(n), where n |
1633 | | /// is a number of indirections. It may not affect performance in real-life |
1634 | | /// code, though. |
1635 | | static std::pair<SmallVector<SVal, 2>, const MemRegion *> |
1636 | 9.12k | getElementRegionOffsetsWithBase(const ElementRegion *ER) { |
1637 | 9.12k | assert(ER && "ConstantArrayType should not be null"); |
1638 | 9.12k | const MemRegion *Base; |
1639 | 9.12k | SmallVector<SVal, 2> SValOffsets; |
1640 | 10.0k | do { |
1641 | 10.0k | SValOffsets.push_back(ER->getIndex()); |
1642 | 10.0k | Base = ER->getSuperRegion(); |
1643 | 10.0k | ER = dyn_cast<ElementRegion>(Base); |
1644 | 10.0k | } while (ER); |
1645 | 9.12k | return {SValOffsets, Base}; |
1646 | 9.12k | } |
1647 | | |
1648 | | /// This is a helper function for `getConstantValFromConstArrayInitializer`. |
1649 | | /// |
1650 | | /// Convert array of offsets from `SVal` to `uint64_t` in consideration of |
1651 | | /// respective array extents. |
1652 | | /// \param SrcOffsets [in] The array of offsets of type `SVal` in reversed |
1653 | | /// order (expectedly received from `getElementRegionOffsetsWithBase`). |
1654 | | /// \param ArrayExtents [in] The array of extents. |
1655 | | /// \param DstOffsets [out] The array of offsets of type `uint64_t`. |
1656 | | /// \returns: |
1657 | | /// - `std::nullopt` for successful convertion. |
1658 | | /// - `UndefinedVal` or `UnknownVal` otherwise. It's expected that this SVal |
1659 | | /// will be returned as a suitable value of the access operation. |
1660 | | /// which should be returned as a correct |
1661 | | /// |
1662 | | /// \example: |
1663 | | /// const int arr[10][20][30] = {}; // ArrayExtents { 10, 20, 30 } |
1664 | | /// int x1 = arr[4][5][6]; // SrcOffsets { NonLoc(6), NonLoc(5), NonLoc(4) } |
1665 | | /// // DstOffsets { 4, 5, 6 } |
1666 | | /// // returns std::nullopt |
1667 | | /// int x2 = arr[42][5][-6]; // returns UndefinedVal |
1668 | | /// int x3 = arr[4][5][x2]; // returns UnknownVal |
1669 | | static std::optional<SVal> |
1670 | | convertOffsetsFromSvalToUnsigneds(const SmallVector<SVal, 2> &SrcOffsets, |
1671 | | const SmallVector<uint64_t, 2> ArrayExtents, |
1672 | 1.04k | SmallVector<uint64_t, 2> &DstOffsets) { |
1673 | | // Check offsets for being out of bounds. |
1674 | | // C++20 [expr.add] 7.6.6.4 (excerpt): |
1675 | | // If P points to an array element i of an array object x with n |
1676 | | // elements, where i < 0 or i > n, the behavior is undefined. |
1677 | | // Dereferencing is not allowed on the "one past the last |
1678 | | // element", when i == n. |
1679 | | // Example: |
1680 | | // const int arr[3][2] = {{1, 2}, {3, 4}}; |
1681 | | // arr[0][0]; // 1 |
1682 | | // arr[0][1]; // 2 |
1683 | | // arr[0][2]; // UB |
1684 | | // arr[1][0]; // 3 |
1685 | | // arr[1][1]; // 4 |
1686 | | // arr[1][-1]; // UB |
1687 | | // arr[2][0]; // 0 |
1688 | | // arr[2][1]; // 0 |
1689 | | // arr[-2][0]; // UB |
1690 | 1.04k | DstOffsets.resize(SrcOffsets.size()); |
1691 | 1.04k | auto ExtentIt = ArrayExtents.begin(); |
1692 | 1.04k | auto OffsetIt = DstOffsets.begin(); |
1693 | | // Reverse `SValOffsets` to make it consistent with `ArrayExtents`. |
1694 | 1.31k | for (SVal V : llvm::reverse(SrcOffsets)) { |
1695 | 1.31k | if (auto CI = V.getAs<nonloc::ConcreteInt>()) { |
1696 | | // When offset is out of array's bounds, result is UB. |
1697 | 1.30k | const llvm::APSInt &Offset = CI->getValue(); |
1698 | 1.30k | if (Offset.isNegative() || Offset.uge(*(ExtentIt++))825 ) |
1699 | 899 | return UndefinedVal(); |
1700 | | // Store index in a reversive order. |
1701 | 405 | *(OffsetIt++) = Offset.getZExtValue(); |
1702 | 405 | continue; |
1703 | 1.30k | } |
1704 | | // Symbolic index presented. Return Unknown value. |
1705 | | // FIXME: We also need to take ElementRegions with symbolic indexes into |
1706 | | // account. |
1707 | 13 | return UnknownVal(); |
1708 | 1.31k | } |
1709 | 137 | return std::nullopt; |
1710 | 1.04k | } |
1711 | | |
1712 | | std::optional<SVal> RegionStoreManager::getConstantValFromConstArrayInitializer( |
1713 | 9.12k | RegionBindingsConstRef B, const ElementRegion *R) { |
1714 | 9.12k | assert(R && "ElementRegion should not be null"); |
1715 | | |
1716 | | // Treat an n-dimensional array. |
1717 | 9.12k | SmallVector<SVal, 2> SValOffsets; |
1718 | 9.12k | const MemRegion *Base; |
1719 | 9.12k | std::tie(SValOffsets, Base) = getElementRegionOffsetsWithBase(R); |
1720 | 9.12k | const VarRegion *VR = dyn_cast<VarRegion>(Base); |
1721 | 9.12k | if (!VR) |
1722 | 33 | return std::nullopt; |
1723 | | |
1724 | 9.08k | assert(!SValOffsets.empty() && "getElementRegionOffsets guarantees the " |
1725 | 9.08k | "offsets vector is not empty."); |
1726 | | |
1727 | | // Check if the containing array has an initialized value that we can trust. |
1728 | | // We can trust a const value or a value of a global initializer in main(). |
1729 | 9.08k | const VarDecl *VD = VR->getDecl(); |
1730 | 9.08k | if (!VD->getType().isConstQualified() && |
1731 | 9.08k | !R->getElementType().isConstQualified()8.04k && |
1732 | 9.08k | (8.04k !B.isMainAnalysis()8.04k || !VD->hasGlobalStorage()11 )) |
1733 | 8.03k | return std::nullopt; |
1734 | | |
1735 | | // Array's declaration should have `ConstantArrayType` type, because only this |
1736 | | // type contains an array extent. It may happen that array type can be of |
1737 | | // `IncompleteArrayType` type. To get the declaration of `ConstantArrayType` |
1738 | | // type, we should find the declaration in the redeclarations chain that has |
1739 | | // the initialization expression. |
1740 | | // NOTE: `getAnyInitializer` has an out-parameter, which returns a new `VD` |
1741 | | // from which an initializer is obtained. We replace current `VD` with the new |
1742 | | // `VD`. If the return value of the function is null than `VD` won't be |
1743 | | // replaced. |
1744 | 1.05k | const Expr *Init = VD->getAnyInitializer(VD); |
1745 | | // NOTE: If `Init` is non-null, then a new `VD` is non-null for sure. So check |
1746 | | // `Init` for null only and don't worry about the replaced `VD`. |
1747 | 1.05k | if (!Init) |
1748 | 3 | return std::nullopt; |
1749 | | |
1750 | | // Array's declaration should have ConstantArrayType type, because only this |
1751 | | // type contains an array extent. |
1752 | 1.04k | const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(VD->getType()); |
1753 | 1.04k | if (!CAT) |
1754 | 0 | return std::nullopt; |
1755 | | |
1756 | | // Get array extents. |
1757 | 1.04k | SmallVector<uint64_t, 2> Extents = getConstantArrayExtents(CAT); |
1758 | | |
1759 | | // The number of offsets should equal to the numbers of extents, |
1760 | | // otherwise wrong type punning occurred. For instance: |
1761 | | // int arr[1][2][3]; |
1762 | | // auto ptr = (int(*)[42])arr; |
1763 | | // auto x = ptr[4][2]; // UB |
1764 | | // FIXME: Should return UndefinedVal. |
1765 | 1.04k | if (SValOffsets.size() != Extents.size()) |
1766 | 0 | return std::nullopt; |
1767 | | |
1768 | 1.04k | SmallVector<uint64_t, 2> ConcreteOffsets; |
1769 | 1.04k | if (std::optional<SVal> V = convertOffsetsFromSvalToUnsigneds( |
1770 | 1.04k | SValOffsets, Extents, ConcreteOffsets)) |
1771 | 912 | return *V; |
1772 | | |
1773 | | // Handle InitListExpr. |
1774 | | // Example: |
1775 | | // const char arr[4][2] = { { 1, 2 }, { 3 }, 4, 5 }; |
1776 | 137 | if (const auto *ILE = dyn_cast<InitListExpr>(Init)) |
1777 | 127 | return getSValFromInitListExpr(ILE, ConcreteOffsets, R->getElementType()); |
1778 | | |
1779 | | // Handle StringLiteral. |
1780 | | // Example: |
1781 | | // const char arr[] = "abc"; |
1782 | 10 | if (const auto *SL = dyn_cast<StringLiteral>(Init)) |
1783 | 10 | return getSValFromStringLiteral(SL, ConcreteOffsets.front(), |
1784 | 10 | R->getElementType()); |
1785 | | |
1786 | | // FIXME: Handle CompoundLiteralExpr. |
1787 | | |
1788 | 0 | return std::nullopt; |
1789 | 10 | } |
1790 | | |
1791 | | /// Returns an SVal, if possible, for the specified position of an |
1792 | | /// initialization list. |
1793 | | /// |
1794 | | /// \param ILE The given initialization list. |
1795 | | /// \param Offsets The array of unsigned offsets. E.g. for the expression |
1796 | | /// `int x = arr[1][2][3];` an array should be { 1, 2, 3 }. |
1797 | | /// \param ElemT The type of the result SVal expression. |
1798 | | /// \return Optional SVal for the particular position in the initialization |
1799 | | /// list. E.g. for the list `{{1, 2},[3, 4],{5, 6}, {}}` offsets: |
1800 | | /// - {1, 1} returns SVal{4}, because it's the second position in the second |
1801 | | /// sublist; |
1802 | | /// - {3, 0} returns SVal{0}, because there's no explicit value at this |
1803 | | /// position in the sublist. |
1804 | | /// |
1805 | | /// NOTE: Inorder to get a valid SVal, a caller shall guarantee valid offsets |
1806 | | /// for the given initialization list. Otherwise SVal can be an equivalent to 0 |
1807 | | /// or lead to assertion. |
1808 | | std::optional<SVal> RegionStoreManager::getSValFromInitListExpr( |
1809 | | const InitListExpr *ILE, const SmallVector<uint64_t, 2> &Offsets, |
1810 | 127 | QualType ElemT) { |
1811 | 127 | assert(ILE && "InitListExpr should not be null"); |
1812 | | |
1813 | 158 | for (uint64_t Offset : Offsets)127 { |
1814 | | // C++20 [dcl.init.string] 9.4.2.1: |
1815 | | // An array of ordinary character type [...] can be initialized by [...] |
1816 | | // an appropriately-typed string-literal enclosed in braces. |
1817 | | // Example: |
1818 | | // const char arr[] = { "abc" }; |
1819 | 158 | if (ILE->isStringLiteralInit()) |
1820 | 5 | if (const auto *SL = dyn_cast<StringLiteral>(ILE->getInit(0))) |
1821 | 5 | return getSValFromStringLiteral(SL, Offset, ElemT); |
1822 | | |
1823 | | // C++20 [expr.add] 9.4.17.5 (excerpt): |
1824 | | // i-th array element is value-initialized for each k < i ≤ n, |
1825 | | // where k is an expression-list size and n is an array extent. |
1826 | 153 | if (Offset >= ILE->getNumInits()) |
1827 | 29 | return svalBuilder.makeZeroVal(ElemT); |
1828 | | |
1829 | 124 | const Expr *E = ILE->getInit(Offset); |
1830 | 124 | const auto *IL = dyn_cast<InitListExpr>(E); |
1831 | 124 | if (!IL) |
1832 | | // Return a constant value, if it is presented. |
1833 | | // FIXME: Support other SVals. |
1834 | 92 | return svalBuilder.getConstantVal(E); |
1835 | | |
1836 | | // Go to the nested initializer list. |
1837 | 32 | ILE = IL; |
1838 | 32 | } |
1839 | | |
1840 | 1 | assert(ILE); |
1841 | | |
1842 | | // FIXME: Unhandeled InitListExpr sub-expression, possibly constructing an |
1843 | | // enum? |
1844 | 1 | return std::nullopt; |
1845 | 1 | } |
1846 | | |
1847 | | /// Returns an SVal, if possible, for the specified position in a string |
1848 | | /// literal. |
1849 | | /// |
1850 | | /// \param SL The given string literal. |
1851 | | /// \param Offset The unsigned offset. E.g. for the expression |
1852 | | /// `char x = str[42];` an offset should be 42. |
1853 | | /// E.g. for the string "abc" offset: |
1854 | | /// - 1 returns SVal{b}, because it's the second position in the string. |
1855 | | /// - 42 returns SVal{0}, because there's no explicit value at this |
1856 | | /// position in the string. |
1857 | | /// \param ElemT The type of the result SVal expression. |
1858 | | /// |
1859 | | /// NOTE: We return `0` for every offset >= the literal length for array |
1860 | | /// declarations, like: |
1861 | | /// const char str[42] = "123"; // Literal length is 4. |
1862 | | /// char c = str[41]; // Offset is 41. |
1863 | | /// FIXME: Nevertheless, we can't do the same for pointer declaraions, like: |
1864 | | /// const char * const str = "123"; // Literal length is 4. |
1865 | | /// char c = str[41]; // Offset is 41. Returns `0`, but Undef |
1866 | | /// // expected. |
1867 | | /// It should be properly handled before reaching this point. |
1868 | | /// The main problem is that we can't distinguish between these declarations, |
1869 | | /// because in case of array we can get the Decl from VarRegion, but in case |
1870 | | /// of pointer the region is a StringRegion, which doesn't contain a Decl. |
1871 | | /// Possible solution could be passing an array extent along with the offset. |
1872 | | SVal RegionStoreManager::getSValFromStringLiteral(const StringLiteral *SL, |
1873 | | uint64_t Offset, |
1874 | 1.54k | QualType ElemT) { |
1875 | 1.54k | assert(SL && "StringLiteral should not be null"); |
1876 | | // C++20 [dcl.init.string] 9.4.2.3: |
1877 | | // If there are fewer initializers than there are array elements, each |
1878 | | // element not explicitly initialized shall be zero-initialized [dcl.init]. |
1879 | 1.54k | uint32_t Code = (Offset >= SL->getLength()) ? 033 : SL->getCodeUnit(Offset)1.50k ; |
1880 | 1.54k | return svalBuilder.makeIntVal(Code, ElemT); |
1881 | 1.54k | } |
1882 | | |
1883 | | static std::optional<SVal> getDerivedSymbolForBinding( |
1884 | | RegionBindingsConstRef B, const TypedValueRegion *BaseRegion, |
1885 | 34.8k | const TypedValueRegion *SubReg, const ASTContext &Ctx, SValBuilder &SVB) { |
1886 | 34.8k | assert(BaseRegion); |
1887 | 34.8k | QualType BaseTy = BaseRegion->getValueType(); |
1888 | 34.8k | QualType Ty = SubReg->getValueType(); |
1889 | 34.8k | if (BaseTy->isScalarType() && Ty->isScalarType()87 ) { |
1890 | 87 | if (Ctx.getTypeSizeInChars(BaseTy) >= Ctx.getTypeSizeInChars(Ty)) { |
1891 | 86 | if (const std::optional<SVal> &ParentValue = |
1892 | 86 | B.getDirectBinding(BaseRegion)) { |
1893 | 9 | if (SymbolRef ParentValueAsSym = ParentValue->getAsSymbol()) |
1894 | 4 | return SVB.getDerivedRegionValueSymbolVal(ParentValueAsSym, SubReg); |
1895 | | |
1896 | 5 | if (ParentValue->isUndef()) |
1897 | 0 | return UndefinedVal(); |
1898 | | |
1899 | | // Other cases: give up. We are indexing into a larger object |
1900 | | // that has some value, but we don't know how to handle that yet. |
1901 | 5 | return UnknownVal(); |
1902 | 5 | } |
1903 | 86 | } |
1904 | 87 | } |
1905 | 34.8k | return std::nullopt; |
1906 | 34.8k | } |
1907 | | |
1908 | | SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B, |
1909 | 34.4k | const ElementRegion* R) { |
1910 | | // Check if the region has a binding. |
1911 | 34.4k | if (const std::optional<SVal> &V = B.getDirectBinding(R)) |
1912 | 5.11k | return *V; |
1913 | | |
1914 | 29.3k | const MemRegion* superR = R->getSuperRegion(); |
1915 | | |
1916 | | // Check if the region is an element region of a string literal. |
1917 | 29.3k | if (const StringRegion *StrR = dyn_cast<StringRegion>(superR)) { |
1918 | | // FIXME: Handle loads from strings where the literal is treated as |
1919 | | // an integer, e.g., *((unsigned int*)"hello"). Such loads are UB according |
1920 | | // to C++20 7.2.1.11 [basic.lval]. |
1921 | 1.57k | QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType(); |
1922 | 1.57k | if (!Ctx.hasSameUnqualifiedType(T, R->getElementType())) |
1923 | 2 | return UnknownVal(); |
1924 | 1.56k | if (const auto CI = R->getIndex().getAs<nonloc::ConcreteInt>()) { |
1925 | 1.56k | const llvm::APSInt &Idx = CI->getValue(); |
1926 | 1.56k | if (Idx < 0) |
1927 | 42 | return UndefinedVal(); |
1928 | 1.52k | const StringLiteral *SL = StrR->getStringLiteral(); |
1929 | 1.52k | return getSValFromStringLiteral(SL, Idx.getZExtValue(), T); |
1930 | 1.56k | } |
1931 | 27.7k | } else if (isa<ElementRegion, VarRegion>(superR)) { |
1932 | 9.12k | if (std::optional<SVal> V = getConstantValFromConstArrayInitializer(B, R)) |
1933 | 1.04k | return *V; |
1934 | 9.12k | } |
1935 | | |
1936 | | // Check for loads from a code text region. For such loads, just give up. |
1937 | 26.7k | if (isa<CodeTextRegion>(superR)) |
1938 | 89 | return UnknownVal(); |
1939 | | |
1940 | | // Handle the case where we are indexing into a larger scalar object. |
1941 | | // For example, this handles: |
1942 | | // int x = ... |
1943 | | // char *y = &x; |
1944 | | // return *y; |
1945 | | // FIXME: This is a hack, and doesn't do anything really intelligent yet. |
1946 | 26.6k | const RegionRawOffset &O = R->getAsArrayOffset(); |
1947 | | |
1948 | | // If we cannot reason about the offset, return an unknown value. |
1949 | 26.6k | if (!O.getRegion()) |
1950 | 9.05k | return UnknownVal(); |
1951 | | |
1952 | 17.5k | if (const TypedValueRegion *baseR = dyn_cast<TypedValueRegion>(O.getRegion())) |
1953 | 8.71k | if (auto V = getDerivedSymbolForBinding(B, baseR, R, Ctx, svalBuilder)) |
1954 | 5 | return *V; |
1955 | | |
1956 | 17.5k | return getBindingForFieldOrElementCommon(B, R, R->getElementType()); |
1957 | 17.5k | } |
1958 | | |
1959 | | SVal RegionStoreManager::getBindingForField(RegionBindingsConstRef B, |
1960 | 100k | const FieldRegion* R) { |
1961 | | |
1962 | | // Check if the region has a binding. |
1963 | 100k | if (const std::optional<SVal> &V = B.getDirectBinding(R)) |
1964 | 33.8k | return *V; |
1965 | | |
1966 | | // If the containing record was initialized, try to get its constant value. |
1967 | 66.9k | const FieldDecl *FD = R->getDecl(); |
1968 | 66.9k | QualType Ty = FD->getType(); |
1969 | 66.9k | const MemRegion* superR = R->getSuperRegion(); |
1970 | 66.9k | if (const auto *VR = dyn_cast<VarRegion>(superR)) { |
1971 | 16.6k | const VarDecl *VD = VR->getDecl(); |
1972 | 16.6k | QualType RecordVarTy = VD->getType(); |
1973 | 16.6k | unsigned Index = FD->getFieldIndex(); |
1974 | | // Either the record variable or the field has an initializer that we can |
1975 | | // trust. We trust initializers of constants and, additionally, respect |
1976 | | // initializers of globals when analyzing main(). |
1977 | 16.6k | if (RecordVarTy.isConstQualified() || Ty.isConstQualified()16.3k || |
1978 | 16.6k | (16.2k B.isMainAnalysis()16.2k && VD->hasGlobalStorage()3 )) |
1979 | 405 | if (const Expr *Init = VD->getAnyInitializer()) |
1980 | 182 | if (const auto *InitList = dyn_cast<InitListExpr>(Init)) { |
1981 | 119 | if (Index < InitList->getNumInits()) { |
1982 | 118 | if (const Expr *FieldInit = InitList->getInit(Index)) |
1983 | 118 | if (std::optional<SVal> V = svalBuilder.getConstantVal(FieldInit)) |
1984 | 118 | return *V; |
1985 | 118 | } else { |
1986 | 1 | return svalBuilder.makeZeroVal(Ty); |
1987 | 1 | } |
1988 | 119 | } |
1989 | 16.6k | } |
1990 | | |
1991 | | // Handle the case where we are accessing into a larger scalar object. |
1992 | | // For example, this handles: |
1993 | | // struct header { |
1994 | | // unsigned a : 1; |
1995 | | // unsigned b : 1; |
1996 | | // }; |
1997 | | // struct parse_t { |
1998 | | // unsigned bits0 : 1; |
1999 | | // unsigned bits2 : 2; // <-- header |
2000 | | // unsigned bits4 : 4; |
2001 | | // }; |
2002 | | // int parse(parse_t *p) { |
2003 | | // unsigned copy = p->bits2; |
2004 | | // header *bits = (header *)© |
2005 | | // return bits->b; <-- here |
2006 | | // } |
2007 | 66.7k | if (const auto *Base = dyn_cast<TypedValueRegion>(R->getBaseRegion())) |
2008 | 26.1k | if (auto V = getDerivedSymbolForBinding(B, Base, R, Ctx, svalBuilder)) |
2009 | 4 | return *V; |
2010 | | |
2011 | 66.7k | return getBindingForFieldOrElementCommon(B, R, Ty); |
2012 | 66.7k | } |
2013 | | |
2014 | | std::optional<SVal> RegionStoreManager::getBindingForDerivedDefaultValue( |
2015 | | RegionBindingsConstRef B, const MemRegion *superR, |
2016 | 213k | const TypedValueRegion *R, QualType Ty) { |
2017 | | |
2018 | 213k | if (const std::optional<SVal> &D = B.getDefaultBinding(superR)) { |
2019 | 17.6k | const SVal &val = *D; |
2020 | 17.6k | if (SymbolRef parentSym = val.getAsSymbol()) |
2021 | 15.8k | return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); |
2022 | | |
2023 | 1.77k | if (val.isZeroConstant()) |
2024 | 412 | return svalBuilder.makeZeroVal(Ty); |
2025 | | |
2026 | 1.36k | if (val.isUnknownOrUndef()) |
2027 | 1.32k | return val; |
2028 | | |
2029 | | // Lazy bindings are usually handled through getExistingLazyBinding(). |
2030 | | // We should unify these two code paths at some point. |
2031 | 34 | if (isa<nonloc::LazyCompoundVal, nonloc::CompoundVal>(val)) |
2032 | 34 | return val; |
2033 | | |
2034 | 0 | llvm_unreachable("Unknown default value"); |
2035 | 0 | } |
2036 | | |
2037 | 195k | return std::nullopt; |
2038 | 213k | } |
2039 | | |
2040 | | SVal RegionStoreManager::getLazyBinding(const SubRegion *LazyBindingRegion, |
2041 | 779 | RegionBindingsRef LazyBinding) { |
2042 | 779 | SVal Result; |
2043 | 779 | if (const ElementRegion *ER = dyn_cast<ElementRegion>(LazyBindingRegion)) |
2044 | 339 | Result = getBindingForElement(LazyBinding, ER); |
2045 | 440 | else |
2046 | 440 | Result = getBindingForField(LazyBinding, |
2047 | 440 | cast<FieldRegion>(LazyBindingRegion)); |
2048 | | |
2049 | | // FIXME: This is a hack to deal with RegionStore's inability to distinguish a |
2050 | | // default value for /part/ of an aggregate from a default value for the |
2051 | | // /entire/ aggregate. The most common case of this is when struct Outer |
2052 | | // has as its first member a struct Inner, which is copied in from a stack |
2053 | | // variable. In this case, even if the Outer's default value is symbolic, 0, |
2054 | | // or unknown, it gets overridden by the Inner's default value of undefined. |
2055 | | // |
2056 | | // This is a general problem -- if the Inner is zero-initialized, the Outer |
2057 | | // will now look zero-initialized. The proper way to solve this is with a |
2058 | | // new version of RegionStore that tracks the extent of a binding as well |
2059 | | // as the offset. |
2060 | | // |
2061 | | // This hack only takes care of the undefined case because that can very |
2062 | | // quickly result in a warning. |
2063 | 779 | if (Result.isUndef()) |
2064 | 30 | Result = UnknownVal(); |
2065 | | |
2066 | 779 | return Result; |
2067 | 779 | } |
2068 | | |
2069 | | SVal |
2070 | | RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B, |
2071 | | const TypedValueRegion *R, |
2072 | 84.3k | QualType Ty) { |
2073 | | |
2074 | | // At this point we have already checked in either getBindingForElement or |
2075 | | // getBindingForField if 'R' has a direct binding. |
2076 | | |
2077 | | // Lazy binding? |
2078 | 84.3k | Store lazyBindingStore = nullptr; |
2079 | 84.3k | const SubRegion *lazyBindingRegion = nullptr; |
2080 | 84.3k | std::tie(lazyBindingStore, lazyBindingRegion) = findLazyBinding(B, R, R); |
2081 | 84.3k | if (lazyBindingRegion) |
2082 | 779 | return getLazyBinding(lazyBindingRegion, |
2083 | 779 | getRegionBindings(lazyBindingStore)); |
2084 | | |
2085 | | // Record whether or not we see a symbolic index. That can completely |
2086 | | // be out of scope of our lookup. |
2087 | 83.5k | bool hasSymbolicIndex = false; |
2088 | | |
2089 | | // FIXME: This is a hack to deal with RegionStore's inability to distinguish a |
2090 | | // default value for /part/ of an aggregate from a default value for the |
2091 | | // /entire/ aggregate. The most common case of this is when struct Outer |
2092 | | // has as its first member a struct Inner, which is copied in from a stack |
2093 | | // variable. In this case, even if the Outer's default value is symbolic, 0, |
2094 | | // or unknown, it gets overridden by the Inner's default value of undefined. |
2095 | | // |
2096 | | // This is a general problem -- if the Inner is zero-initialized, the Outer |
2097 | | // will now look zero-initialized. The proper way to solve this is with a |
2098 | | // new version of RegionStore that tracks the extent of a binding as well |
2099 | | // as the offset. |
2100 | | // |
2101 | | // This hack only takes care of the undefined case because that can very |
2102 | | // quickly result in a warning. |
2103 | 83.5k | bool hasPartialLazyBinding = false; |
2104 | | |
2105 | 83.5k | const SubRegion *SR = R; |
2106 | 277k | while (SR) { |
2107 | 205k | const MemRegion *Base = SR->getSuperRegion(); |
2108 | 205k | if (std::optional<SVal> D = |
2109 | 205k | getBindingForDerivedDefaultValue(B, Base, R, Ty)) { |
2110 | 12.1k | if (D->getAs<nonloc::LazyCompoundVal>()) { |
2111 | 21 | hasPartialLazyBinding = true; |
2112 | 21 | break; |
2113 | 21 | } |
2114 | | |
2115 | 12.1k | return *D; |
2116 | 12.1k | } |
2117 | | |
2118 | 193k | if (const ElementRegion *ER = dyn_cast<ElementRegion>(Base)) { |
2119 | 44.8k | NonLoc index = ER->getIndex(); |
2120 | 44.8k | if (!index.isConstant()) |
2121 | 27.0k | hasSymbolicIndex = true; |
2122 | 44.8k | } |
2123 | | |
2124 | | // If our super region is a field or element itself, walk up the region |
2125 | | // hierarchy to see if there is a default value installed in an ancestor. |
2126 | 193k | SR = dyn_cast<SubRegion>(Base); |
2127 | 193k | } |
2128 | | |
2129 | 71.4k | if (R->hasStackNonParametersStorage()) { |
2130 | 23.2k | if (isa<ElementRegion>(R)) { |
2131 | | // Currently we don't reason specially about Clang-style vectors. Check |
2132 | | // if superR is a vector and if so return Unknown. |
2133 | 4.61k | if (const TypedValueRegion *typedSuperR = |
2134 | 4.61k | dyn_cast<TypedValueRegion>(R->getSuperRegion())) { |
2135 | 4.59k | if (typedSuperR->getValueType()->isVectorType()) |
2136 | 6 | return UnknownVal(); |
2137 | 4.59k | } |
2138 | 4.61k | } |
2139 | | |
2140 | | // FIXME: We also need to take ElementRegions with symbolic indexes into |
2141 | | // account. This case handles both directly accessing an ElementRegion |
2142 | | // with a symbolic offset, but also fields within an element with |
2143 | | // a symbolic offset. |
2144 | 23.2k | if (hasSymbolicIndex) |
2145 | 11 | return UnknownVal(); |
2146 | | |
2147 | | // Additionally allow introspection of a block's internal layout. |
2148 | | // Try to get direct binding if all other attempts failed thus far. |
2149 | | // Else, return UndefinedVal() |
2150 | 23.2k | if (!hasPartialLazyBinding && !isa<BlockDataRegion>(R->getBaseRegion())23.2k ) { |
2151 | 23.2k | if (const std::optional<SVal> &V = B.getDefaultBinding(R)) |
2152 | 2 | return *V; |
2153 | 23.2k | return UndefinedVal(); |
2154 | 23.2k | } |
2155 | 23.2k | } |
2156 | | |
2157 | | // All other values are symbolic. |
2158 | 48.2k | return svalBuilder.getRegionValueSymbolVal(R); |
2159 | 71.4k | } |
2160 | | |
2161 | | SVal RegionStoreManager::getBindingForObjCIvar(RegionBindingsConstRef B, |
2162 | 2.71k | const ObjCIvarRegion* R) { |
2163 | | // Check if the region has a binding. |
2164 | 2.71k | if (const std::optional<SVal> &V = B.getDirectBinding(R)) |
2165 | 1.28k | return *V; |
2166 | | |
2167 | 1.43k | const MemRegion *superR = R->getSuperRegion(); |
2168 | | |
2169 | | // Check if the super region has a default binding. |
2170 | 1.43k | if (const std::optional<SVal> &V = B.getDefaultBinding(superR)) { |
2171 | 66 | if (SymbolRef parentSym = V->getAsSymbol()) |
2172 | 66 | return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R); |
2173 | | |
2174 | | // Other cases: give up. |
2175 | 0 | return UnknownVal(); |
2176 | 66 | } |
2177 | | |
2178 | 1.36k | return getBindingForLazySymbol(R); |
2179 | 1.43k | } |
2180 | | |
2181 | | SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B, |
2182 | 457k | const VarRegion *R) { |
2183 | | |
2184 | | // Check if the region has a binding. |
2185 | 457k | if (std::optional<SVal> V = B.getDirectBinding(R)) |
2186 | 257k | return *V; |
2187 | | |
2188 | 199k | if (std::optional<SVal> V = B.getDefaultBinding(R)) |
2189 | 13 | return *V; |
2190 | | |
2191 | | // Lazily derive a value for the VarRegion. |
2192 | 199k | const VarDecl *VD = R->getDecl(); |
2193 | 199k | const MemSpaceRegion *MS = R->getMemorySpace(); |
2194 | | |
2195 | | // Arguments are always symbolic. |
2196 | 199k | if (isa<StackArgumentsSpaceRegion>(MS)) |
2197 | 111k | return svalBuilder.getRegionValueSymbolVal(R); |
2198 | | |
2199 | | // Is 'VD' declared constant? If so, retrieve the constant value. |
2200 | 87.6k | if (VD->getType().isConstQualified()) { |
2201 | 976 | if (const Expr *Init = VD->getAnyInitializer()) { |
2202 | 726 | if (std::optional<SVal> V = svalBuilder.getConstantVal(Init)) |
2203 | 687 | return *V; |
2204 | | |
2205 | | // If the variable is const qualified and has an initializer but |
2206 | | // we couldn't evaluate initializer to a value, treat the value as |
2207 | | // unknown. |
2208 | 39 | return UnknownVal(); |
2209 | 726 | } |
2210 | 976 | } |
2211 | | |
2212 | | // This must come after the check for constants because closure-captured |
2213 | | // constant variables may appear in UnknownSpaceRegion. |
2214 | 86.9k | if (isa<UnknownSpaceRegion>(MS)) |
2215 | 140 | return svalBuilder.getRegionValueSymbolVal(R); |
2216 | | |
2217 | 86.7k | if (isa<GlobalsSpaceRegion>(MS)) { |
2218 | 8.18k | QualType T = VD->getType(); |
2219 | | |
2220 | | // If we're in main(), then global initializers have not become stale yet. |
2221 | 8.18k | if (B.isMainAnalysis()) |
2222 | 3 | if (const Expr *Init = VD->getAnyInitializer()) |
2223 | 1 | if (std::optional<SVal> V = svalBuilder.getConstantVal(Init)) |
2224 | 1 | return *V; |
2225 | | |
2226 | | // Function-scoped static variables are default-initialized to 0; if they |
2227 | | // have an initializer, it would have been processed by now. |
2228 | | // FIXME: This is only true when we're starting analysis from main(). |
2229 | | // We're losing a lot of coverage here. |
2230 | 8.17k | if (isa<StaticGlobalSpaceRegion>(MS)) |
2231 | 840 | return svalBuilder.makeZeroVal(T); |
2232 | | |
2233 | 7.33k | if (std::optional<SVal> V = getBindingForDerivedDefaultValue(B, MS, R, T)) { |
2234 | 5.48k | assert(!V->getAs<nonloc::LazyCompoundVal>()); |
2235 | 5.48k | return *V; |
2236 | 5.48k | } |
2237 | | |
2238 | 1.85k | return svalBuilder.getRegionValueSymbolVal(R); |
2239 | 7.33k | } |
2240 | | |
2241 | 78.6k | return UndefinedVal(); |
2242 | 86.7k | } |
2243 | | |
2244 | 1.36k | SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) { |
2245 | | // All other values are symbolic. |
2246 | 1.36k | return svalBuilder.getRegionValueSymbolVal(R); |
2247 | 1.36k | } |
2248 | | |
2249 | | const RegionStoreManager::SValListTy & |
2250 | 14.6k | RegionStoreManager::getInterestingValues(nonloc::LazyCompoundVal LCV) { |
2251 | | // First, check the cache. |
2252 | 14.6k | LazyBindingsMapTy::iterator I = LazyBindingsMap.find(LCV.getCVData()); |
2253 | 14.6k | if (I != LazyBindingsMap.end()) |
2254 | 13.4k | return I->second; |
2255 | | |
2256 | | // If we don't have a list of values cached, start constructing it. |
2257 | 1.16k | SValListTy List; |
2258 | | |
2259 | 1.16k | const SubRegion *LazyR = LCV.getRegion(); |
2260 | 1.16k | RegionBindingsRef B = getRegionBindings(LCV.getStore()); |
2261 | | |
2262 | | // If this region had /no/ bindings at the time, there are no interesting |
2263 | | // values to return. |
2264 | 1.16k | const ClusterBindings *Cluster = B.lookup(LazyR->getBaseRegion()); |
2265 | 1.16k | if (!Cluster) |
2266 | 287 | return (LazyBindingsMap[LCV.getCVData()] = std::move(List)); |
2267 | | |
2268 | 881 | SmallVector<BindingPair, 32> Bindings; |
2269 | 881 | collectSubRegionBindings(Bindings, svalBuilder, *Cluster, LazyR, |
2270 | 881 | /*IncludeAllDefaultBindings=*/true); |
2271 | 1.19k | for (SVal V : llvm::make_second_range(Bindings)) { |
2272 | 1.19k | if (V.isUnknownOrUndef() || V.isConstant()1.08k ) |
2273 | 480 | continue; |
2274 | | |
2275 | 717 | if (auto InnerLCV = V.getAs<nonloc::LazyCompoundVal>()) { |
2276 | 16 | const SValListTy &InnerList = getInterestingValues(*InnerLCV); |
2277 | 16 | List.insert(List.end(), InnerList.begin(), InnerList.end()); |
2278 | 16 | } |
2279 | | |
2280 | 717 | List.push_back(V); |
2281 | 717 | } |
2282 | | |
2283 | 881 | return (LazyBindingsMap[LCV.getCVData()] = std::move(List)); |
2284 | 1.16k | } |
2285 | | |
2286 | | NonLoc RegionStoreManager::createLazyBinding(RegionBindingsConstRef B, |
2287 | 59.1k | const TypedValueRegion *R) { |
2288 | 59.1k | if (std::optional<nonloc::LazyCompoundVal> V = |
2289 | 59.1k | getExistingLazyBinding(svalBuilder, B, R, false)) |
2290 | 179 | return *V; |
2291 | | |
2292 | 58.9k | return svalBuilder.makeLazyCompoundVal(StoreRef(B.asStore(), *this), R); |
2293 | 59.1k | } |
2294 | | |
2295 | 63.3k | static bool isRecordEmpty(const RecordDecl *RD) { |
2296 | 63.3k | if (!RD->field_empty()) |
2297 | 53.5k | return false; |
2298 | 9.80k | if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) |
2299 | 9.67k | return CRD->getNumBases() == 0; |
2300 | 134 | return true; |
2301 | 9.80k | } |
2302 | | |
2303 | | SVal RegionStoreManager::getBindingForStruct(RegionBindingsConstRef B, |
2304 | 64.6k | const TypedValueRegion *R) { |
2305 | 64.6k | const RecordDecl *RD = R->getValueType()->castAs<RecordType>()->getDecl(); |
2306 | 64.6k | if (!RD->getDefinition() || isRecordEmpty(RD)63.3k ) |
2307 | 8.86k | return UnknownVal(); |
2308 | | |
2309 | 55.7k | return createLazyBinding(B, R); |
2310 | 64.6k | } |
2311 | | |
2312 | | SVal RegionStoreManager::getBindingForArray(RegionBindingsConstRef B, |
2313 | 3.19k | const TypedValueRegion *R) { |
2314 | 3.19k | assert(Ctx.getAsConstantArrayType(R->getValueType()) && |
2315 | 3.19k | "Only constant array types can have compound bindings."); |
2316 | | |
2317 | 3.19k | return createLazyBinding(B, R); |
2318 | 3.19k | } |
2319 | | |
2320 | | bool RegionStoreManager::includedInBindings(Store store, |
2321 | 16.2k | const MemRegion *region) const { |
2322 | 16.2k | RegionBindingsRef B = getRegionBindings(store); |
2323 | 16.2k | region = region->getBaseRegion(); |
2324 | | |
2325 | | // Quick path: if the base is the head of a cluster, the region is live. |
2326 | 16.2k | if (B.lookup(region)) |
2327 | 128 | return true; |
2328 | | |
2329 | | // Slow path: if the region is the VALUE of any binding, it is live. |
2330 | 64.6k | for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); 16.0k RI != RE; ++RI48.5k ) { |
2331 | 48.5k | const ClusterBindings &Cluster = RI.getData(); |
2332 | 48.5k | for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end(); |
2333 | 97.6k | CI != CE; ++CI49.0k ) { |
2334 | 49.0k | const SVal &D = CI.getData(); |
2335 | 49.0k | if (const MemRegion *R = D.getAsRegion()) |
2336 | 9.96k | if (R->getBaseRegion() == region) |
2337 | 11 | return true; |
2338 | 49.0k | } |
2339 | 48.5k | } |
2340 | | |
2341 | 16.0k | return false; |
2342 | 16.0k | } |
2343 | | |
2344 | | //===----------------------------------------------------------------------===// |
2345 | | // Binding values to regions. |
2346 | | //===----------------------------------------------------------------------===// |
2347 | | |
2348 | 177 | StoreRef RegionStoreManager::killBinding(Store ST, Loc L) { |
2349 | 177 | if (std::optional<loc::MemRegionVal> LV = L.getAs<loc::MemRegionVal>()) |
2350 | 171 | if (const MemRegion* R = LV->getRegion()) |
2351 | 171 | return StoreRef(getRegionBindings(ST).removeBinding(R) |
2352 | 171 | .asImmutableMap() |
2353 | 171 | .getRootWithoutRetain(), |
2354 | 171 | *this); |
2355 | | |
2356 | 6 | return StoreRef(ST, *this); |
2357 | 177 | } |
2358 | | |
2359 | | RegionBindingsRef |
2360 | 232k | RegionStoreManager::bind(RegionBindingsConstRef B, Loc L, SVal V) { |
2361 | 232k | if (L.getAs<loc::ConcreteInt>()) |
2362 | 5 | return B; |
2363 | | |
2364 | | // If we get here, the location should be a region. |
2365 | 232k | const MemRegion *R = L.castAs<loc::MemRegionVal>().getRegion(); |
2366 | | |
2367 | | // Check if the region is a struct region. |
2368 | 232k | if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) { |
2369 | 231k | QualType Ty = TR->getValueType(); |
2370 | 231k | if (Ty->isArrayType()) |
2371 | 1.86k | return bindArray(B, TR, V); |
2372 | 230k | if (Ty->isStructureOrClassType()) |
2373 | 23.8k | return bindStruct(B, TR, V); |
2374 | 206k | if (Ty->isVectorType()) |
2375 | 11 | return bindVector(B, TR, V); |
2376 | 206k | if (Ty->isUnionType()) |
2377 | 165 | return bindAggregate(B, TR, V); |
2378 | 206k | } |
2379 | | |
2380 | | // Binding directly to a symbolic region should be treated as binding |
2381 | | // to element 0. |
2382 | 206k | if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) |
2383 | 677 | R = GetElementZeroRegion(SR, SR->getPointeeStaticType()); |
2384 | | |
2385 | 206k | assert((!isa<CXXThisRegion>(R) || !B.lookup(R)) && |
2386 | 206k | "'this' pointer is not an l-value and is not assignable"); |
2387 | | |
2388 | | // Clear out bindings that may overlap with this binding. |
2389 | 206k | RegionBindingsRef NewB = removeSubRegionBindings(B, cast<SubRegion>(R)); |
2390 | | |
2391 | | // LazyCompoundVals should be always bound as 'default' bindings. |
2392 | 206k | auto KeyKind = isa<nonloc::LazyCompoundVal>(V) ? BindingKey::Default27 |
2393 | 206k | : BindingKey::Direct206k ; |
2394 | 206k | return NewB.addBinding(BindingKey::Make(R, KeyKind), V); |
2395 | 206k | } |
2396 | | |
2397 | | RegionBindingsRef |
2398 | | RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B, |
2399 | | const MemRegion *R, |
2400 | 586 | QualType T) { |
2401 | 586 | SVal V; |
2402 | | |
2403 | 586 | if (Loc::isLocType(T)) |
2404 | 10 | V = svalBuilder.makeNullWithType(T); |
2405 | 576 | else if (T->isIntegralOrEnumerationType()) |
2406 | 515 | V = svalBuilder.makeZeroVal(T); |
2407 | 61 | else if (T->isStructureOrClassType() || T->isArrayType()14 ) { |
2408 | | // Set the default value to a zero constant when it is a structure |
2409 | | // or array. The type doesn't really matter. |
2410 | 47 | V = svalBuilder.makeZeroVal(Ctx.IntTy); |
2411 | 47 | } |
2412 | 14 | else { |
2413 | | // We can't represent values of this type, but we still need to set a value |
2414 | | // to record that the region has been initialized. |
2415 | | // If this assertion ever fires, a new case should be added above -- we |
2416 | | // should know how to default-initialize any value we can symbolicate. |
2417 | 14 | assert(!SymbolManager::canSymbolicate(T) && "This type is representable"); |
2418 | 14 | V = UnknownVal(); |
2419 | 14 | } |
2420 | | |
2421 | 586 | return B.addBinding(R, BindingKey::Default, V); |
2422 | 586 | } |
2423 | | |
2424 | | std::optional<RegionBindingsRef> RegionStoreManager::tryBindSmallArray( |
2425 | | RegionBindingsConstRef B, const TypedValueRegion *R, const ArrayType *AT, |
2426 | 51 | nonloc::LazyCompoundVal LCV) { |
2427 | | |
2428 | 51 | auto CAT = dyn_cast<ConstantArrayType>(AT); |
2429 | | |
2430 | | // If we don't know the size, create a lazyCompoundVal instead. |
2431 | 51 | if (!CAT) |
2432 | 0 | return std::nullopt; |
2433 | | |
2434 | 51 | QualType Ty = CAT->getElementType(); |
2435 | 51 | if (!(Ty->isScalarType() || Ty->isReferenceType()10 )) |
2436 | 10 | return std::nullopt; |
2437 | | |
2438 | | // If the array is too big, create a LCV instead. |
2439 | 41 | uint64_t ArrSize = CAT->getSize().getLimitedValue(); |
2440 | 41 | if (ArrSize > SmallArrayLimit) |
2441 | 3 | return std::nullopt; |
2442 | | |
2443 | 38 | RegionBindingsRef NewB = B; |
2444 | | |
2445 | 182 | for (uint64_t i = 0; i < ArrSize; ++i144 ) { |
2446 | 144 | auto Idx = svalBuilder.makeArrayIndex(i); |
2447 | 144 | const ElementRegion *SrcER = |
2448 | 144 | MRMgr.getElementRegion(Ty, Idx, LCV.getRegion(), Ctx); |
2449 | 144 | SVal V = getBindingForElement(getRegionBindings(LCV.getStore()), SrcER); |
2450 | | |
2451 | 144 | const ElementRegion *DstER = MRMgr.getElementRegion(Ty, Idx, R, Ctx); |
2452 | 144 | NewB = bind(NewB, loc::MemRegionVal(DstER), V); |
2453 | 144 | } |
2454 | | |
2455 | 38 | return NewB; |
2456 | 41 | } |
2457 | | |
2458 | | RegionBindingsRef |
2459 | | RegionStoreManager::bindArray(RegionBindingsConstRef B, |
2460 | | const TypedValueRegion* R, |
2461 | 2.13k | SVal Init) { |
2462 | | |
2463 | 2.13k | const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType())); |
2464 | 2.13k | QualType ElementTy = AT->getElementType(); |
2465 | 2.13k | std::optional<uint64_t> Size; |
2466 | | |
2467 | 2.13k | if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT)) |
2468 | 2.12k | Size = CAT->getSize().getZExtValue(); |
2469 | | |
2470 | | // Check if the init expr is a literal. If so, bind the rvalue instead. |
2471 | | // FIXME: It's not responsibility of the Store to transform this lvalue |
2472 | | // to rvalue. ExprEngine or maybe even CFG should do this before binding. |
2473 | 2.13k | if (std::optional<loc::MemRegionVal> MRV = Init.getAs<loc::MemRegionVal>()) { |
2474 | 502 | SVal V = getBinding(B.asStore(), *MRV, R->getValueType()); |
2475 | 502 | return bindAggregate(B, R, V); |
2476 | 502 | } |
2477 | | |
2478 | | // Handle lazy compound values. |
2479 | 1.63k | if (std::optional<nonloc::LazyCompoundVal> LCV = |
2480 | 1.63k | Init.getAs<nonloc::LazyCompoundVal>()) { |
2481 | 51 | if (std::optional<RegionBindingsRef> NewB = |
2482 | 51 | tryBindSmallArray(B, R, AT, *LCV)) |
2483 | 38 | return *NewB; |
2484 | | |
2485 | 13 | return bindAggregate(B, R, Init); |
2486 | 51 | } |
2487 | | |
2488 | 1.58k | if (Init.isUnknown()) |
2489 | 65 | return bindAggregate(B, R, UnknownVal()); |
2490 | | |
2491 | | // Remaining case: explicit compound values. |
2492 | 1.52k | const nonloc::CompoundVal& CV = Init.castAs<nonloc::CompoundVal>(); |
2493 | 1.52k | nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); |
2494 | 1.52k | uint64_t i = 0; |
2495 | | |
2496 | 1.52k | RegionBindingsRef NewB(B); |
2497 | | |
2498 | 5.37k | for (; Size ? i < *Size5.35k : true20 ; ++i, ++VI3.85k ) { |
2499 | | // The init list might be shorter than the array length. |
2500 | 4.43k | if (VI == VE) |
2501 | 586 | break; |
2502 | | |
2503 | 3.85k | const NonLoc &Idx = svalBuilder.makeArrayIndex(i); |
2504 | 3.85k | const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx); |
2505 | | |
2506 | 3.85k | if (ElementTy->isStructureOrClassType()) |
2507 | 220 | NewB = bindStruct(NewB, ER, *VI); |
2508 | 3.63k | else if (ElementTy->isArrayType()) |
2509 | 89 | NewB = bindArray(NewB, ER, *VI); |
2510 | 3.54k | else |
2511 | 3.54k | NewB = bind(NewB, loc::MemRegionVal(ER), *VI); |
2512 | 3.85k | } |
2513 | | |
2514 | | // If the init list is shorter than the array length (or the array has |
2515 | | // variable length), set the array default value. Values that are already set |
2516 | | // are not overwritten. |
2517 | 1.52k | if (!Size || i < *Size1.50k ) |
2518 | 586 | NewB = setImplicitDefaultValue(NewB, R, ElementTy); |
2519 | | |
2520 | 1.52k | return NewB; |
2521 | 1.58k | } |
2522 | | |
2523 | | RegionBindingsRef RegionStoreManager::bindVector(RegionBindingsConstRef B, |
2524 | | const TypedValueRegion* R, |
2525 | 11 | SVal V) { |
2526 | 11 | QualType T = R->getValueType(); |
2527 | 11 | const VectorType *VT = T->castAs<VectorType>(); // Use castAs for typedefs. |
2528 | | |
2529 | | // Handle lazy compound values and symbolic values. |
2530 | 11 | if (isa<nonloc::LazyCompoundVal, nonloc::SymbolVal>(V)) |
2531 | 0 | return bindAggregate(B, R, V); |
2532 | | |
2533 | | // We may get non-CompoundVal accidentally due to imprecise cast logic or |
2534 | | // that we are binding symbolic struct value. Kill the field values, and if |
2535 | | // the value is symbolic go and bind it as a "default" binding. |
2536 | 11 | if (!isa<nonloc::CompoundVal>(V)) { |
2537 | 3 | return bindAggregate(B, R, UnknownVal()); |
2538 | 3 | } |
2539 | | |
2540 | 8 | QualType ElemType = VT->getElementType(); |
2541 | 8 | nonloc::CompoundVal CV = V.castAs<nonloc::CompoundVal>(); |
2542 | 8 | nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); |
2543 | 8 | unsigned index = 0, numElements = VT->getNumElements(); |
2544 | 8 | RegionBindingsRef NewB(B); |
2545 | | |
2546 | 28 | for ( ; index != numElements ; ++index20 ) { |
2547 | 20 | if (VI == VE) |
2548 | 0 | break; |
2549 | | |
2550 | 20 | NonLoc Idx = svalBuilder.makeArrayIndex(index); |
2551 | 20 | const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx); |
2552 | | |
2553 | 20 | if (ElemType->isArrayType()) |
2554 | 0 | NewB = bindArray(NewB, ER, *VI); |
2555 | 20 | else if (ElemType->isStructureOrClassType()) |
2556 | 0 | NewB = bindStruct(NewB, ER, *VI); |
2557 | 20 | else |
2558 | 20 | NewB = bind(NewB, loc::MemRegionVal(ER), *VI); |
2559 | 20 | } |
2560 | 8 | return NewB; |
2561 | 11 | } |
2562 | | |
2563 | | std::optional<RegionBindingsRef> RegionStoreManager::tryBindSmallStruct( |
2564 | | RegionBindingsConstRef B, const TypedValueRegion *R, const RecordDecl *RD, |
2565 | 22.3k | nonloc::LazyCompoundVal LCV) { |
2566 | 22.3k | FieldVector Fields; |
2567 | | |
2568 | 22.3k | if (const CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(RD)) |
2569 | 22.1k | if (Class->getNumBases() != 0 || Class->getNumVBases() != 022.0k ) |
2570 | 80 | return std::nullopt; |
2571 | | |
2572 | 22.9k | for (const auto *FD : RD->fields())22.2k { |
2573 | 22.9k | if (FD->isUnnamedBitfield()) |
2574 | 8 | continue; |
2575 | | |
2576 | | // If there are too many fields, or if any of the fields are aggregates, |
2577 | | // just use the LCV as a default binding. |
2578 | 22.9k | if (Fields.size() == SmallStructLimit) |
2579 | 113 | return std::nullopt; |
2580 | | |
2581 | 22.8k | QualType Ty = FD->getType(); |
2582 | | |
2583 | | // Zero length arrays are basically no-ops, so we also ignore them here. |
2584 | 22.8k | if (Ty->isConstantArrayType() && |
2585 | 22.8k | Ctx.getConstantArrayElementCount(Ctx.getAsConstantArrayType(Ty)) == 0145 ) |
2586 | 20 | continue; |
2587 | | |
2588 | 22.7k | if (!(Ty->isScalarType() || Ty->isReferenceType()576 )) |
2589 | 233 | return std::nullopt; |
2590 | | |
2591 | 22.5k | Fields.push_back(FD); |
2592 | 22.5k | } |
2593 | | |
2594 | 21.9k | RegionBindingsRef NewB = B; |
2595 | | |
2596 | 22.3k | for (const FieldDecl *Field : Fields) { |
2597 | 22.3k | const FieldRegion *SourceFR = MRMgr.getFieldRegion(Field, LCV.getRegion()); |
2598 | 22.3k | SVal V = getBindingForField(getRegionBindings(LCV.getStore()), SourceFR); |
2599 | | |
2600 | 22.3k | const FieldRegion *DestFR = MRMgr.getFieldRegion(Field, R); |
2601 | 22.3k | NewB = bind(NewB, loc::MemRegionVal(DestFR), V); |
2602 | 22.3k | } |
2603 | | |
2604 | 21.9k | return NewB; |
2605 | 22.2k | } |
2606 | | |
2607 | | RegionBindingsRef RegionStoreManager::bindStruct(RegionBindingsConstRef B, |
2608 | | const TypedValueRegion *R, |
2609 | 24.2k | SVal V) { |
2610 | 24.2k | QualType T = R->getValueType(); |
2611 | 24.2k | assert(T->isStructureOrClassType()); |
2612 | | |
2613 | 24.2k | const RecordType* RT = T->castAs<RecordType>(); |
2614 | 24.2k | const RecordDecl *RD = RT->getDecl(); |
2615 | | |
2616 | 24.2k | if (!RD->isCompleteDefinition()) |
2617 | 0 | return B; |
2618 | | |
2619 | | // Handle lazy compound values and symbolic values. |
2620 | 24.2k | if (std::optional<nonloc::LazyCompoundVal> LCV = |
2621 | 24.2k | V.getAs<nonloc::LazyCompoundVal>()) { |
2622 | 22.3k | if (std::optional<RegionBindingsRef> NewB = |
2623 | 22.3k | tryBindSmallStruct(B, R, RD, *LCV)) |
2624 | 21.9k | return *NewB; |
2625 | 426 | return bindAggregate(B, R, V); |
2626 | 22.3k | } |
2627 | 1.93k | if (isa<nonloc::SymbolVal>(V)) |
2628 | 520 | return bindAggregate(B, R, V); |
2629 | | |
2630 | | // We may get non-CompoundVal accidentally due to imprecise cast logic or |
2631 | | // that we are binding symbolic struct value. Kill the field values, and if |
2632 | | // the value is symbolic go and bind it as a "default" binding. |
2633 | 1.41k | if (V.isUnknown() || !isa<nonloc::CompoundVal>(V)1.34k ) |
2634 | 78 | return bindAggregate(B, R, UnknownVal()); |
2635 | | |
2636 | | // The raw CompoundVal is essentially a symbolic InitListExpr: an (immutable) |
2637 | | // list of other values. It appears pretty much only when there's an actual |
2638 | | // initializer list expression in the program, and the analyzer tries to |
2639 | | // unwrap it as soon as possible. |
2640 | | // This code is where such unwrap happens: when the compound value is put into |
2641 | | // the object that it was supposed to initialize (it's an *initializer* list, |
2642 | | // after all), instead of binding the whole value to the whole object, we bind |
2643 | | // sub-values to sub-objects. Sub-values may themselves be compound values, |
2644 | | // and in this case the procedure becomes recursive. |
2645 | | // FIXME: The annoying part about compound values is that they don't carry |
2646 | | // any sort of information about which value corresponds to which sub-object. |
2647 | | // It's simply a list of values in the middle of nowhere; we expect to match |
2648 | | // them to sub-objects, essentially, "by index": first value binds to |
2649 | | // the first field, second value binds to the second field, etc. |
2650 | | // It would have been much safer to organize non-lazy compound values as |
2651 | | // a mapping from fields/bases to values. |
2652 | 1.34k | const nonloc::CompoundVal& CV = V.castAs<nonloc::CompoundVal>(); |
2653 | 1.34k | nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end(); |
2654 | | |
2655 | 1.34k | RegionBindingsRef NewB(B); |
2656 | | |
2657 | | // In C++17 aggregates may have base classes, handle those as well. |
2658 | | // They appear before fields in the initializer list / compound value. |
2659 | 1.34k | if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) { |
2660 | | // If the object was constructed with a constructor, its value is a |
2661 | | // LazyCompoundVal. If it's a raw CompoundVal, it means that we're |
2662 | | // performing aggregate initialization. The only exception from this |
2663 | | // rule is sending an Objective-C++ message that returns a C++ object |
2664 | | // to a nil receiver; in this case the semantics is to return a |
2665 | | // zero-initialized object even if it's a C++ object that doesn't have |
2666 | | // this sort of constructor; the CompoundVal is empty in this case. |
2667 | 1.06k | assert((CRD->isAggregate() || (Ctx.getLangOpts().ObjC && VI == VE)) && |
2668 | 1.06k | "Non-aggregates are constructed with a constructor!"); |
2669 | | |
2670 | 1.06k | for (const auto &B : CRD->bases()) { |
2671 | | // (Multiple inheritance is fine though.) |
2672 | 67 | assert(!B.isVirtual() && "Aggregates cannot have virtual base classes!"); |
2673 | | |
2674 | 67 | if (VI == VE) |
2675 | 0 | break; |
2676 | | |
2677 | 67 | QualType BTy = B.getType(); |
2678 | 67 | assert(BTy->isStructureOrClassType() && "Base classes must be classes!"); |
2679 | | |
2680 | 67 | const CXXRecordDecl *BRD = BTy->getAsCXXRecordDecl(); |
2681 | 67 | assert(BRD && "Base classes must be C++ classes!"); |
2682 | | |
2683 | 67 | const CXXBaseObjectRegion *BR = |
2684 | 67 | MRMgr.getCXXBaseObjectRegion(BRD, R, /*IsVirtual=*/false); |
2685 | | |
2686 | 67 | NewB = bindStruct(NewB, BR, *VI); |
2687 | | |
2688 | 67 | ++VI; |
2689 | 67 | } |
2690 | 1.06k | } |
2691 | | |
2692 | 1.34k | RecordDecl::field_iterator FI, FE; |
2693 | | |
2694 | 2.86k | for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI1.52k ) { |
2695 | | |
2696 | 1.53k | if (VI == VE) |
2697 | 8 | break; |
2698 | | |
2699 | | // Skip any unnamed bitfields to stay in sync with the initializers. |
2700 | 1.52k | if (FI->isUnnamedBitfield()) |
2701 | 4 | continue; |
2702 | | |
2703 | 1.52k | QualType FTy = FI->getType(); |
2704 | 1.52k | const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R); |
2705 | | |
2706 | 1.52k | if (FTy->isArrayType()) |
2707 | 188 | NewB = bindArray(NewB, FR, *VI); |
2708 | 1.33k | else if (FTy->isStructureOrClassType()) |
2709 | 101 | NewB = bindStruct(NewB, FR, *VI); |
2710 | 1.23k | else |
2711 | 1.23k | NewB = bind(NewB, loc::MemRegionVal(FR), *VI); |
2712 | 1.52k | ++VI; |
2713 | 1.52k | } |
2714 | | |
2715 | | // There may be fewer values in the initialize list than the fields of struct. |
2716 | 1.34k | if (FI != FE) { |
2717 | 8 | NewB = NewB.addBinding(R, BindingKey::Default, |
2718 | 8 | svalBuilder.makeIntVal(0, false)); |
2719 | 8 | } |
2720 | | |
2721 | 1.34k | return NewB; |
2722 | 1.34k | } |
2723 | | |
2724 | | RegionBindingsRef |
2725 | | RegionStoreManager::bindAggregate(RegionBindingsConstRef B, |
2726 | | const TypedRegion *R, |
2727 | 1.77k | SVal Val) { |
2728 | | // Remove the old bindings, using 'R' as the root of all regions |
2729 | | // we will invalidate. Then add the new binding. |
2730 | 1.77k | return removeSubRegionBindings(B, R).addBinding(R, BindingKey::Default, Val); |
2731 | 1.77k | } |
2732 | | |
2733 | | //===----------------------------------------------------------------------===// |
2734 | | // State pruning. |
2735 | | //===----------------------------------------------------------------------===// |
2736 | | |
2737 | | namespace { |
2738 | | class RemoveDeadBindingsWorker |
2739 | | : public ClusterAnalysis<RemoveDeadBindingsWorker> { |
2740 | | SmallVector<const SymbolicRegion *, 12> Postponed; |
2741 | | SymbolReaper &SymReaper; |
2742 | | const StackFrameContext *CurrentLCtx; |
2743 | | |
2744 | | public: |
2745 | | RemoveDeadBindingsWorker(RegionStoreManager &rm, |
2746 | | ProgramStateManager &stateMgr, |
2747 | | RegionBindingsRef b, SymbolReaper &symReaper, |
2748 | | const StackFrameContext *LCtx) |
2749 | 427k | : ClusterAnalysis<RemoveDeadBindingsWorker>(rm, stateMgr, b), |
2750 | 427k | SymReaper(symReaper), CurrentLCtx(LCtx) {} |
2751 | | |
2752 | | // Called by ClusterAnalysis. |
2753 | | void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C); |
2754 | | void VisitCluster(const MemRegion *baseR, const ClusterBindings *C); |
2755 | | using ClusterAnalysis<RemoveDeadBindingsWorker>::VisitCluster; |
2756 | | |
2757 | | using ClusterAnalysis::AddToWorkList; |
2758 | | |
2759 | | bool AddToWorkList(const MemRegion *R); |
2760 | | |
2761 | | bool UpdatePostponed(); |
2762 | | void VisitBinding(SVal V); |
2763 | | }; |
2764 | | } |
2765 | | |
2766 | 1.21M | bool RemoveDeadBindingsWorker::AddToWorkList(const MemRegion *R) { |
2767 | 1.21M | const MemRegion *BaseR = R->getBaseRegion(); |
2768 | 1.21M | return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR)); |
2769 | 1.21M | } |
2770 | | |
2771 | | void RemoveDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR, |
2772 | 1.51M | const ClusterBindings &C) { |
2773 | | |
2774 | 1.51M | if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) { |
2775 | 795k | if (SymReaper.isLive(VR)) |
2776 | 656k | AddToWorkList(baseR, &C); |
2777 | | |
2778 | 795k | return; |
2779 | 795k | } |
2780 | | |
2781 | 719k | if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) { |
2782 | 82.2k | if (SymReaper.isLive(SR->getSymbol())) |
2783 | 66.7k | AddToWorkList(SR, &C); |
2784 | 15.5k | else |
2785 | 15.5k | Postponed.push_back(SR); |
2786 | | |
2787 | 82.2k | return; |
2788 | 82.2k | } |
2789 | | |
2790 | 637k | if (isa<NonStaticGlobalSpaceRegion>(baseR)) { |
2791 | 478k | AddToWorkList(baseR, &C); |
2792 | 478k | return; |
2793 | 478k | } |
2794 | | |
2795 | | // CXXThisRegion in the current or parent location context is live. |
2796 | 158k | if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) { |
2797 | 133k | const auto *StackReg = |
2798 | 133k | cast<StackArgumentsSpaceRegion>(TR->getSuperRegion()); |
2799 | 133k | const StackFrameContext *RegCtx = StackReg->getStackFrame(); |
2800 | 133k | if (CurrentLCtx && |
2801 | 133k | (133k RegCtx == CurrentLCtx133k || RegCtx->isParentOf(CurrentLCtx)82.2k )) |
2802 | 116k | AddToWorkList(TR, &C); |
2803 | 133k | } |
2804 | 158k | } |
2805 | | |
2806 | | void RemoveDeadBindingsWorker::VisitCluster(const MemRegion *baseR, |
2807 | 2.10M | const ClusterBindings *C) { |
2808 | 2.10M | if (!C) |
2809 | 715k | return; |
2810 | | |
2811 | | // Mark the symbol for any SymbolicRegion with live bindings as live itself. |
2812 | | // This means we should continue to track that symbol. |
2813 | 1.38M | if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(baseR)) |
2814 | 73.7k | SymReaper.markLive(SymR->getSymbol()); |
2815 | | |
2816 | 1.71M | for (const auto &[Key, Val] : *C) { |
2817 | | // Element index of a binding key is live. |
2818 | 1.71M | SymReaper.markElementIndicesLive(Key.getRegion()); |
2819 | | |
2820 | 1.71M | VisitBinding(Val); |
2821 | 1.71M | } |
2822 | 1.38M | } |
2823 | | |
2824 | 1.71M | void RemoveDeadBindingsWorker::VisitBinding(SVal V) { |
2825 | | // Is it a LazyCompoundVal? All referenced regions are live as well. |
2826 | | // The LazyCompoundVal itself is not live but should be readable. |
2827 | 1.71M | if (auto LCS = V.getAs<nonloc::LazyCompoundVal>()) { |
2828 | 4.77k | SymReaper.markLazilyCopied(LCS->getRegion()); |
2829 | | |
2830 | 4.77k | for (SVal V : RM.getInterestingValues(*LCS)) { |
2831 | 496 | if (auto DepLCS = V.getAs<nonloc::LazyCompoundVal>()) |
2832 | 83 | SymReaper.markLazilyCopied(DepLCS->getRegion()); |
2833 | 413 | else |
2834 | 413 | VisitBinding(V); |
2835 | 496 | } |
2836 | | |
2837 | 4.77k | return; |
2838 | 4.77k | } |
2839 | | |
2840 | | // If V is a region, then add it to the worklist. |
2841 | 1.70M | if (const MemRegion *R = V.getAsRegion()) { |
2842 | 389k | AddToWorkList(R); |
2843 | 389k | SymReaper.markLive(R); |
2844 | | |
2845 | | // All regions captured by a block are also live. |
2846 | 389k | if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) { |
2847 | 656 | for (auto Var : BR->referenced_vars()) |
2848 | 584 | AddToWorkList(Var.getCapturedRegion()); |
2849 | 656 | } |
2850 | 389k | } |
2851 | | |
2852 | | |
2853 | | // Update the set of live symbols. |
2854 | 1.70M | for (SymbolRef Sym : V.symbols()) |
2855 | 1.51M | SymReaper.markLive(Sym); |
2856 | 1.70M | } |
2857 | | |
2858 | 428k | bool RemoveDeadBindingsWorker::UpdatePostponed() { |
2859 | | // See if any postponed SymbolicRegions are actually live now, after |
2860 | | // having done a scan. |
2861 | 428k | bool Changed = false; |
2862 | | |
2863 | 428k | for (const SymbolicRegion *SR : Postponed) { |
2864 | 17.7k | if (SymReaper.isLive(SR->getSymbol())) { |
2865 | 9.08k | Changed |= AddToWorkList(SR); |
2866 | 9.08k | SR = nullptr; |
2867 | 9.08k | } |
2868 | 17.7k | } |
2869 | | |
2870 | 428k | return Changed; |
2871 | 428k | } |
2872 | | |
2873 | | StoreRef RegionStoreManager::removeDeadBindings(Store store, |
2874 | | const StackFrameContext *LCtx, |
2875 | 427k | SymbolReaper& SymReaper) { |
2876 | 427k | RegionBindingsRef B = getRegionBindings(store); |
2877 | 427k | RemoveDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx); |
2878 | 427k | W.GenerateClusters(); |
2879 | | |
2880 | | // Enqueue the region roots onto the worklist. |
2881 | 812k | for (const MemRegion *Reg : SymReaper.regions()) { |
2882 | 812k | W.AddToWorkList(Reg); |
2883 | 812k | } |
2884 | | |
2885 | 428k | do W.RunWorkList(); while (W.UpdatePostponed()); |
2886 | | |
2887 | | // We have now scanned the store, marking reachable regions and symbols |
2888 | | // as live. We now remove all the regions that are dead from the store |
2889 | | // as well as update DSymbols with the set symbols that are now dead. |
2890 | 1.51M | for (const MemRegion *Base : llvm::make_first_range(B)) { |
2891 | | // If the cluster has been visited, we know the region has been marked. |
2892 | | // Otherwise, remove the dead entry. |
2893 | 1.51M | if (!W.isVisited(Base)) |
2894 | 127k | B = B.remove(Base); |
2895 | 1.51M | } |
2896 | | |
2897 | 427k | return StoreRef(B.asStore(), *this); |
2898 | 427k | } |
2899 | | |
2900 | | //===----------------------------------------------------------------------===// |
2901 | | // Utility methods. |
2902 | | //===----------------------------------------------------------------------===// |
2903 | | |
2904 | | void RegionStoreManager::printJson(raw_ostream &Out, Store S, const char *NL, |
2905 | 158 | unsigned int Space, bool IsDot) const { |
2906 | 158 | RegionBindingsRef Bindings = getRegionBindings(S); |
2907 | | |
2908 | 158 | Indent(Out, Space, IsDot) << "\"store\": "; |
2909 | | |
2910 | 158 | if (Bindings.isEmpty()) { |
2911 | 50 | Out << "null," << NL; |
2912 | 50 | return; |
2913 | 50 | } |
2914 | | |
2915 | 108 | Out << "{ \"pointer\": \"" << Bindings.asStore() << "\", \"items\": [" << NL; |
2916 | 108 | Bindings.printJson(Out, NL, Space + 1, IsDot); |
2917 | 108 | Indent(Out, Space, IsDot) << "]}," << NL; |
2918 | 108 | } |