Coverage Report

Created: 2020-02-18 08:44

/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/DynamicSize.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 "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
31
#include "llvm/ADT/ImmutableMap.h"
32
#include "llvm/ADT/Optional.h"
33
#include "llvm/Support/raw_ostream.h"
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
91.9k
    : P(r, k | Symbolic), Data(reinterpret_cast<uintptr_t>(Base)) {
57
91.9k
    assert(r && Base && "Must have known regions.");
58
91.9k
    assert(getConcreteOffsetRegion() == Base && "Failed to store base region");
59
91.9k
  }
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.70M
    : P(r, k), Data(offset) {
64
1.70M
    assert(r && "Must have known regions.");
65
1.70M
    assert(getOffset() == offset && "Failed to store offset");
66
1.70M
    assert((r == r->getBaseRegion() || isa<ObjCIvarRegion>(r) ||
67
1.70M
            isa <CXXDerivedObjectRegion>(r)) &&
68
1.70M
           "Not a base");
69
1.70M
  }
70
public:
71
72
645k
  bool isDirect() const { return P.getInt() & Direct; }
73
4.12M
  bool hasSymbolicOffset() const { return P.getInt() & Symbolic; }
74
75
4.49M
  const MemRegion *getRegion() const { return P.getPointer(); }
76
2.03M
  uint64_t getOffset() const {
77
2.03M
    assert(!hasSymbolicOffset());
78
2.03M
    return Data;
79
2.03M
  }
80
81
184k
  const SubRegion *getConcreteOffsetRegion() const {
82
184k
    assert(hasSymbolicOffset());
83
184k
    return reinterpret_cast<const SubRegion *>(static_cast<uintptr_t>(Data));
84
184k
  }
85
86
1.79M
  const MemRegion *getBaseRegion() const {
87
1.79M
    if (hasSymbolicOffset())
88
91.9k
      return getConcreteOffsetRegion()->getBaseRegion();
89
1.70M
    return getRegion()->getBaseRegion();
90
1.70M
  }
91
92
403k
  void Profile(llvm::FoldingSetNodeID& ID) const {
93
403k
    ID.AddPointer(P.getOpaqueValue());
94
403k
    ID.AddInteger(Data);
95
403k
  }
96
97
  static BindingKey Make(const MemRegion *R, Kind k);
98
99
157k
  bool operator<(const BindingKey &X) const {
100
157k
    if (P.getOpaqueValue() < X.P.getOpaqueValue())
101
57.7k
      return true;
102
99.8k
    if (P.getOpaqueValue() > X.P.getOpaqueValue())
103
36.9k
      return false;
104
62.9k
    return Data < X.Data;
105
62.9k
  }
106
107
899k
  bool operator==(const BindingKey &X) const {
108
899k
    return P.getOpaqueValue() == X.P.getOpaqueValue() &&
109
899k
           
Data == X.Data804k
;
110
899k
  }
111
112
  LLVM_DUMP_METHOD void dump() const;
113
};
114
} // end anonymous namespace
115
116
1.79M
BindingKey BindingKey::Make(const MemRegion *R, Kind k) {
117
1.79M
  const RegionOffset &RO = R->getAsOffset();
118
1.79M
  if (RO.hasSymbolicOffset())
119
91.9k
    return BindingKey(cast<SubRegion>(R), cast<SubRegion>(RO.getRegion()), k);
120
1.70M
121
1.70M
  return BindingKey(RO.getRegion(), RO.getOffset(), k);
122
1.70M
}
123
124
namespace llvm {
125
135
static inline raw_ostream &operator<<(raw_ostream &Out, BindingKey K) {
126
135
  Out << "\"kind\": \"" << (K.isDirect() ? 
"Direct"84
:
"Default"51
)
127
135
      << "\", \"offset\": ";
128
135
129
135
  if (!K.hasSymbolicOffset())
130
135
    Out << K.getOffset();
131
0
  else
132
0
    Out << "null";
133
135
134
135
  return Out;
135
135
}
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
      : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(T, F),
179
15.3M
        CBFactory(&CBFactory), IsMainAnalysis(IsMainAnalysis) {}
180
181
  RegionBindingsRef(const ParentTy &P,
182
                    ClusterBindings::Factory &CBFactory,
183
                    bool IsMainAnalysis)
184
      : llvm::ImmutableMapRef<const MemRegion *, ClusterBindings>(P),
185
794k
        CBFactory(&CBFactory), IsMainAnalysis(IsMainAnalysis) {}
186
187
362k
  RegionBindingsRef add(key_type_ref K, data_type_ref D) const {
188
362k
    return RegionBindingsRef(static_cast<const ParentTy *>(this)->add(K, D),
189
362k
                             *CBFactory, IsMainAnalysis);
190
362k
  }
191
192
419k
  RegionBindingsRef remove(key_type_ref K) const {
193
419k
    return RegionBindingsRef(static_cast<const ParentTy *>(this)->remove(K),
194
419k
                             *CBFactory, IsMainAnalysis);
195
419k
  }
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
65.0k
  RegionBindingsRef removeBinding(const MemRegion *R) {
212
65.0k
    return removeBinding(R, BindingKey::Direct).
213
65.0k
           removeBinding(R, BindingKey::Default);
214
65.0k
  }
215
216
  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
  Optional<SVal> getDefaultBinding(const MemRegion *R) const;
221
222
  /// Return the internal tree as a Store.
223
831k
  Store asStore() const {
224
831k
    llvm::PointerIntPair<Store, 1, bool> Ptr = {
225
831k
        asImmutableMap().getRootWithoutRetain(), IsMainAnalysis};
226
831k
    return reinterpret_cast<Store>(Ptr.getOpaqueValue());
227
831k
  }
228
229
30.9k
  bool isMainAnalysis() const {
230
30.9k
    return IsMainAnalysis;
231
30.9k
  }
232
233
  void printJson(raw_ostream &Out, const char *NL = "\n",
234
75
                 unsigned int Space = 0, bool IsDot = false) const {
235
206
    for (iterator I = begin(); I != end(); 
++I131
) {
236
131
      // TODO: We might need a .printJson for I.getKey() as well.
237
131
      Indent(Out, Space, IsDot)
238
131
          << "{ \"cluster\": \"" << I.getKey() << "\", \"pointer\": \""
239
131
          << (const void *)I.getKey() << "\", \"items\": [" << NL;
240
131
241
131
      ++Space;
242
131
      const ClusterBindings &CB = I.getData();
243
266
      for (ClusterBindings::iterator CI = CB.begin(); CI != CB.end(); 
++CI135
) {
244
135
        Indent(Out, Space, IsDot) << "{ " << CI.getKey() << ", \"value\": ";
245
135
        CI.getData().printJson(Out, /*AddQuotes=*/true);
246
135
        Out << " }";
247
135
        if (std::next(CI) != CB.end())
248
4
          Out << ',';
249
135
        Out << NL;
250
135
      }
251
131
252
131
      --Space;
253
131
      Indent(Out, Space, IsDot) << "]}";
254
131
      if (std::next(I) != end())
255
56
        Out << ',';
256
131
      Out << NL;
257
131
    }
258
75
  }
259
260
0
  LLVM_DUMP_METHOD void dump() const { printJson(llvm::errs()); }
261
};
262
} // end anonymous namespace
263
264
typedef const RegionBindingsRef& RegionBindingsConstRef;
265
266
464k
Optional<SVal> RegionBindingsRef::getDirectBinding(const MemRegion *R) const {
267
464k
  return Optional<SVal>::create(lookup(R, BindingKey::Direct));
268
464k
}
269
270
507k
Optional<SVal> RegionBindingsRef::getDefaultBinding(const MemRegion *R) const {
271
507k
  return Optional<SVal>::create(lookup(R, BindingKey::Default));
272
507k
}
273
274
336k
RegionBindingsRef RegionBindingsRef::addBinding(BindingKey K, SVal V) const {
275
336k
  const MemRegion *Base = K.getBaseRegion();
276
336k
277
336k
  const ClusterBindings *ExistingCluster = lookup(Base);
278
336k
  ClusterBindings Cluster =
279
336k
      (ExistingCluster ? 
*ExistingCluster26.6k
:
CBFactory->getEmptyMap()309k
);
280
336k
281
336k
  ClusterBindings NewCluster = CBFactory->add(Cluster, K, V);
282
336k
  return add(Base, NewCluster);
283
336k
}
284
285
286
RegionBindingsRef RegionBindingsRef::addBinding(const MemRegion *R,
287
                                                BindingKey::Kind k,
288
25.2k
                                                SVal V) const {
289
25.2k
  return addBinding(BindingKey::Make(R, k), V);
290
25.2k
}
291
292
1.08M
const SVal *RegionBindingsRef::lookup(BindingKey K) const {
293
1.08M
  const ClusterBindings *Cluster = lookup(K.getBaseRegion());
294
1.08M
  if (!Cluster)
295
594k
    return nullptr;
296
486k
  return Cluster->lookup(K);
297
486k
}
298
299
const SVal *RegionBindingsRef::lookup(const MemRegion *R,
300
1.08M
                                      BindingKey::Kind k) const {
301
1.08M
  return lookup(BindingKey::Make(R, k));
302
1.08M
}
303
304
130k
RegionBindingsRef RegionBindingsRef::removeBinding(BindingKey K) {
305
130k
  const MemRegion *Base = K.getBaseRegion();
306
130k
  const ClusterBindings *Cluster = lookup(Base);
307
130k
  if (!Cluster)
308
130k
    return *this;
309
89
310
89
  ClusterBindings NewCluster = CBFactory->remove(*Cluster, K);
311
89
  if (NewCluster.isEmpty())
312
4
    return remove(Base);
313
85
  return add(Base, NewCluster);
314
85
}
315
316
RegionBindingsRef RegionBindingsRef::removeBinding(const MemRegion *R,
317
130k
                                                BindingKey::Kind k){
318
130k
  return removeBinding(BindingKey::Make(R, k));
319
130k
}
320
321
//===----------------------------------------------------------------------===//
322
// Fine-grained control of RegionStoreManager.
323
//===----------------------------------------------------------------------===//
324
325
namespace {
326
struct minimal_features_tag {};
327
struct maximal_features_tag {};
328
329
class RegionStoreFeatures {
330
  bool SupportsFields;
331
public:
332
  RegionStoreFeatures(minimal_features_tag) :
333
0
    SupportsFields(false) {}
334
335
  RegionStoreFeatures(maximal_features_tag) :
336
12.6k
    SupportsFields(true) {}
337
338
0
  void enableFields(bool t) { SupportsFields = t; }
339
340
34.2k
  bool supportsFields() const { return SupportsFields; }
341
};
342
}
343
344
//===----------------------------------------------------------------------===//
345
// Main RegionStore logic.
346
//===----------------------------------------------------------------------===//
347
348
namespace {
349
class InvalidateRegionsWorker;
350
351
class RegionStoreManager : public StoreManager {
352
public:
353
  const RegionStoreFeatures Features;
354
355
  RegionBindings::Factory RBFactory;
356
  mutable ClusterBindings::Factory CBFactory;
357
358
  typedef std::vector<SVal> SValListTy;
359
private:
360
  typedef llvm::DenseMap<const LazyCompoundValData *,
361
                         SValListTy> LazyBindingsMapTy;
362
  LazyBindingsMapTy LazyBindingsMap;
363
364
  /// The largest number of fields a struct can have and still be
365
  /// considered "small".
366
  ///
367
  /// This is currently used to decide whether or not it is worth "forcing" a
368
  /// LazyCompoundVal on bind.
369
  ///
370
  /// This is controlled by 'region-store-small-struct-limit' option.
371
  /// To disable all small-struct-dependent behavior, set the option to "0".
372
  unsigned SmallStructLimit;
373
374
  /// A helper used to populate the work list with the given set of
375
  /// regions.
376
  void populateWorkList(InvalidateRegionsWorker &W,
377
                        ArrayRef<SVal> Values,
378
                        InvalidatedRegions *TopLevelRegions);
379
380
public:
381
  RegionStoreManager(ProgramStateManager& mgr, const RegionStoreFeatures &f)
382
    : StoreManager(mgr), Features(f),
383
      RBFactory(mgr.getAllocator()), CBFactory(mgr.getAllocator()),
384
12.6k
      SmallStructLimit(0) {
385
12.6k
    SubEngine &Eng = StateMgr.getOwningEngine();
386
12.6k
    AnalyzerOptions &Options = Eng.getAnalysisManager().options;
387
12.6k
    SmallStructLimit = Options.RegionStoreSmallStructLimit;
388
12.6k
  }
389
390
391
  /// setImplicitDefaultValue - Set the default binding for the provided
392
  ///  MemRegion to the value implicitly defined for compound literals when
393
  ///  the value is not specified.
394
  RegionBindingsRef setImplicitDefaultValue(RegionBindingsConstRef B,
395
                                            const MemRegion *R, QualType T);
396
397
  /// ArrayToPointer - Emulates the "decay" of an array to a pointer
398
  ///  type.  'Array' represents the lvalue of the array being decayed
399
  ///  to a pointer, and the returned SVal represents the decayed
400
  ///  version of that lvalue (i.e., a pointer to the first element of
401
  ///  the array).  This is called by ExprEngine when evaluating
402
  ///  casts from arrays to pointers.
403
  SVal ArrayToPointer(Loc Array, QualType ElementTy) override;
404
405
  /// Creates the Store that correctly represents memory contents before
406
  /// the beginning of the analysis of the given top-level stack frame.
407
12.6k
  StoreRef getInitialStore(const LocationContext *InitLoc) override {
408
12.6k
    bool IsMainAnalysis = false;
409
12.6k
    if (const auto *FD = dyn_cast<FunctionDecl>(InitLoc->getDecl()))
410
11.4k
      IsMainAnalysis = FD->isMain() && 
!Ctx.getLangOpts().CPlusPlus59
;
411
12.6k
    return StoreRef(RegionBindingsRef(
412
12.6k
        RegionBindingsRef::ParentTy(RBFactory.getEmptyMap(), RBFactory),
413
12.6k
        CBFactory, IsMainAnalysis).asStore(), *this);
414
12.6k
  }
415
416
  //===-------------------------------------------------------------------===//
417
  // Binding values to regions.
418
  //===-------------------------------------------------------------------===//
419
  RegionBindingsRef invalidateGlobalRegion(MemRegion::Kind K,
420
                                           const Expr *Ex,
421
                                           unsigned Count,
422
                                           const LocationContext *LCtx,
423
                                           RegionBindingsRef B,
424
                                           InvalidatedRegions *Invalidated);
425
426
  StoreRef invalidateRegions(Store store,
427
                             ArrayRef<SVal> Values,
428
                             const Expr *E, unsigned Count,
429
                             const LocationContext *LCtx,
430
                             const CallEvent *Call,
431
                             InvalidatedSymbols &IS,
432
                             RegionAndSymbolInvalidationTraits &ITraits,
433
                             InvalidatedRegions *Invalidated,
434
                             InvalidatedRegions *InvalidatedTopLevel) override;
435
436
  bool scanReachableSymbols(Store S, const MemRegion *R,
437
                            ScanReachableSymbols &Callbacks) override;
438
439
  RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B,
440
                                            const SubRegion *R);
441
442
public: // Part of public interface to class.
443
444
244k
  StoreRef Bind(Store store, Loc LV, SVal V) override {
445
244k
    return StoreRef(bind(getRegionBindings(store), LV, V).asStore(), *this);
446
244k
  }
447
448
  RegionBindingsRef bind(RegionBindingsConstRef B, Loc LV, SVal V);
449
450
  // BindDefaultInitial is only used to initialize a region with
451
  // a default value.
452
  StoreRef BindDefaultInitial(Store store, const MemRegion *R,
453
778
                              SVal V) override {
454
778
    RegionBindingsRef B = getRegionBindings(store);
455
778
    // Use other APIs when you have to wipe the region that was initialized
456
778
    // earlier.
457
778
    assert(!(B.getDefaultBinding(R) || B.getDirectBinding(R)) &&
458
778
           "Double initialization!");
459
778
    B = B.addBinding(BindingKey::Make(R, BindingKey::Default), V);
460
778
    return StoreRef(B.asImmutableMap().getRootWithoutRetain(), *this);
461
778
  }
462
463
  // BindDefaultZero is used for zeroing constructors that may accidentally
464
  // overwrite existing bindings.
465
1.90k
  StoreRef BindDefaultZero(Store store, const MemRegion *R) override {
466
1.90k
    // FIXME: The offsets of empty bases can be tricky because of
467
1.90k
    // of the so called "empty base class optimization".
468
1.90k
    // If a base class has been optimized out
469
1.90k
    // we should not try to create a binding, otherwise we should.
470
1.90k
    // Unfortunately, at the moment ASTRecordLayout doesn't expose
471
1.90k
    // the actual sizes of the empty bases
472
1.90k
    // and trying to infer them from offsets/alignments
473
1.90k
    // seems to be error-prone and non-trivial because of the trailing padding.
474
1.90k
    // As a temporary mitigation we don't create bindings for empty bases.
475
1.90k
    if (const auto *BR = dyn_cast<CXXBaseObjectRegion>(R))
476
16
      if (BR->getDecl()->isEmpty())
477
4
        return StoreRef(store, *this);
478
1.90k
479
1.90k
    RegionBindingsRef B = getRegionBindings(store);
480
1.90k
    SVal V = svalBuilder.makeZeroVal(Ctx.CharTy);
481
1.90k
    B = removeSubRegionBindings(B, cast<SubRegion>(R));
482
1.90k
    B = B.addBinding(BindingKey::Make(R, BindingKey::Default), V);
483
1.90k
    return StoreRef(B.asImmutableMap().getRootWithoutRetain(), *this);
484
1.90k
  }
485
486
  /// Attempt to extract the fields of \p LCV and bind them to the struct region
487
  /// \p R.
488
  ///
489
  /// This path is used when it seems advantageous to "force" loading the values
490
  /// within a LazyCompoundVal to bind memberwise to the struct region, rather
491
  /// than using a Default binding at the base of the entire region. This is a
492
  /// heuristic attempting to avoid building long chains of LazyCompoundVals.
493
  ///
494
  /// \returns The updated store bindings, or \c None if binding non-lazily
495
  ///          would be too expensive.
496
  Optional<RegionBindingsRef> tryBindSmallStruct(RegionBindingsConstRef B,
497
                                                 const TypedValueRegion *R,
498
                                                 const RecordDecl *RD,
499
                                                 nonloc::LazyCompoundVal LCV);
500
501
  /// BindStruct - Bind a compound value to a structure.
502
  RegionBindingsRef bindStruct(RegionBindingsConstRef B,
503
                               const TypedValueRegion* R, SVal V);
504
505
  /// BindVector - Bind a compound value to a vector.
506
  RegionBindingsRef bindVector(RegionBindingsConstRef B,
507
                               const TypedValueRegion* R, SVal V);
508
509
  RegionBindingsRef bindArray(RegionBindingsConstRef B,
510
                              const TypedValueRegion* R,
511
                              SVal V);
512
513
  /// Clears out all bindings in the given region and assigns a new value
514
  /// as a Default binding.
515
  RegionBindingsRef bindAggregate(RegionBindingsConstRef B,
516
                                  const TypedRegion *R,
517
                                  SVal DefaultVal);
518
519
  /// Create a new store with the specified binding removed.
520
  /// \param ST the original store, that is the basis for the new store.
521
  /// \param L the location whose binding should be removed.
522
  StoreRef killBinding(Store ST, Loc L) override;
523
524
6.81M
  void incrementReferenceCount(Store store) override {
525
6.81M
    getRegionBindings(store).manualRetain();
526
6.81M
  }
527
528
  /// If the StoreManager supports it, decrement the reference count of
529
  /// the specified Store object.  If the reference count hits 0, the memory
530
  /// associated with the object is recycled.
531
5.69M
  void decrementReferenceCount(Store store) override {
532
5.69M
    getRegionBindings(store).manualRelease();
533
5.69M
  }
534
535
  bool includedInBindings(Store store, const MemRegion *region) const override;
536
537
  /// Return the value bound to specified location in a given state.
538
  ///
539
  /// The high level logic for this method is this:
540
  /// getBinding (L)
541
  ///   if L has binding
542
  ///     return L's binding
543
  ///   else if L is in killset
544
  ///     return unknown
545
  ///   else
546
  ///     if L is on stack or heap
547
  ///       return undefined
548
  ///     else
549
  ///       return symbolic
550
623k
  SVal getBinding(Store S, Loc L, QualType T) override {
551
623k
    return getBinding(getRegionBindings(S), L, T);
552
623k
  }
553
554
15
  Optional<SVal> getDefaultBinding(Store S, const MemRegion *R) override {
555
15
    RegionBindingsRef B = getRegionBindings(S);
556
15
    // Default bindings are always applied over a base region so look up the
557
15
    // base region's default binding, otherwise the lookup will fail when R
558
15
    // is at an offset from R->getBaseRegion().
559
15
    return B.getDefaultBinding(R->getBaseRegion());
560
15
  }
561
562
  SVal getBinding(RegionBindingsConstRef B, Loc L, QualType T = QualType());
563
564
  SVal getBindingForElement(RegionBindingsConstRef B, const ElementRegion *R);
565
566
  SVal getBindingForField(RegionBindingsConstRef B, const FieldRegion *R);
567
568
  SVal getBindingForObjCIvar(RegionBindingsConstRef B, const ObjCIvarRegion *R);
569
570
  SVal getBindingForVar(RegionBindingsConstRef B, const VarRegion *R);
571
572
  SVal getBindingForLazySymbol(const TypedValueRegion *R);
573
574
  SVal getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
575
                                         const TypedValueRegion *R,
576
                                         QualType Ty);
577
578
  SVal getLazyBinding(const SubRegion *LazyBindingRegion,
579
                      RegionBindingsRef LazyBinding);
580
581
  /// Get bindings for the values in a struct and return a CompoundVal, used
582
  /// when doing struct copy:
583
  /// struct s x, y;
584
  /// x = y;
585
  /// y's value is retrieved by this method.
586
  SVal getBindingForStruct(RegionBindingsConstRef B, const TypedValueRegion *R);
587
  SVal getBindingForArray(RegionBindingsConstRef B, const TypedValueRegion *R);
588
  NonLoc createLazyBinding(RegionBindingsConstRef B, const TypedValueRegion *R);
589
590
  /// Used to lazily generate derived symbols for bindings that are defined
591
  /// implicitly by default bindings in a super region.
592
  ///
593
  /// Note that callers may need to specially handle LazyCompoundVals, which
594
  /// are returned as is in case the caller needs to treat them differently.
595
  Optional<SVal> getBindingForDerivedDefaultValue(RegionBindingsConstRef B,
596
                                                  const MemRegion *superR,
597
                                                  const TypedValueRegion *R,
598
                                                  QualType Ty);
599
600
  /// Get the state and region whose binding this region \p R corresponds to.
601
  ///
602
  /// If there is no lazy binding for \p R, the returned value will have a null
603
  /// \c second. Note that a null pointer can represents a valid Store.
604
  std::pair<Store, const SubRegion *>
605
  findLazyBinding(RegionBindingsConstRef B, const SubRegion *R,
606
                  const SubRegion *originalRegion);
607
608
  /// Returns the cached set of interesting SVals contained within a lazy
609
  /// binding.
610
  ///
611
  /// The precise value of "interesting" is determined for the purposes of
612
  /// RegionStore's internal analysis. It must always contain all regions and
613
  /// symbols, but may omit constants and other kinds of SVal.
614
  const SValListTy &getInterestingValues(nonloc::LazyCompoundVal LCV);
615
616
  //===------------------------------------------------------------------===//
617
  // State pruning.
618
  //===------------------------------------------------------------------===//
619
620
  /// removeDeadBindings - Scans the RegionStore of 'state' for dead values.
621
  ///  It returns a new Store with these values removed.
622
  StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
623
                              SymbolReaper& SymReaper) override;
624
625
  //===------------------------------------------------------------------===//
626
  // Utility methods.
627
  //===------------------------------------------------------------------===//
628
629
15.3M
  RegionBindingsRef getRegionBindings(Store store) const {
630
15.3M
    llvm::PointerIntPair<Store, 1, bool> Ptr;
631
15.3M
    Ptr.setFromOpaqueValue(const_cast<void *>(store));
632
15.3M
    return RegionBindingsRef(
633
15.3M
        CBFactory,
634
15.3M
        static_cast<const RegionBindings::TreeTy *>(Ptr.getPointer()),
635
15.3M
        RBFactory.getTreeFactory(),
636
15.3M
        Ptr.getInt());
637
15.3M
  }
638
639
  void printJson(raw_ostream &Out, Store S, const char *NL = "\n",
640
                 unsigned int Space = 0, bool IsDot = false) const override;
641
642
113k
  void iterBindings(Store store, BindingsHandler& f) override {
643
113k
    RegionBindingsRef B = getRegionBindings(store);
644
659k
    for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; 
++I545k
) {
645
545k
      const ClusterBindings &Cluster = I.getData();
646
545k
      for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
647
1.17M
           CI != CE; 
++CI629k
) {
648
629k
        const BindingKey &K = CI.getKey();
649
629k
        if (!K.isDirect())
650
254k
          continue;
651
375k
        if (const SubRegion *R = dyn_cast<SubRegion>(K.getRegion())) {
652
375k
          // FIXME: Possibly incorporate the offset?
653
375k
          if (!f.HandleBinding(*this, store, R, CI.getData()))
654
544
            return;
655
375k
        }
656
375k
      }
657
545k
    }
658
113k
  }
659
};
660
661
} // end anonymous namespace
662
663
//===----------------------------------------------------------------------===//
664
// RegionStore creation.
665
//===----------------------------------------------------------------------===//
666
667
std::unique_ptr<StoreManager>
668
12.6k
ento::CreateRegionStoreManager(ProgramStateManager &StMgr) {
669
12.6k
  RegionStoreFeatures F = maximal_features_tag();
670
12.6k
  return std::make_unique<RegionStoreManager>(StMgr, F);
671
12.6k
}
672
673
std::unique_ptr<StoreManager>
674
0
ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) {
675
0
  RegionStoreFeatures F = minimal_features_tag();
676
0
  F.enableFields(true);
677
0
  return std::make_unique<RegionStoreManager>(StMgr, F);
678
0
}
679
680
681
//===----------------------------------------------------------------------===//
682
// Region Cluster analysis.
683
//===----------------------------------------------------------------------===//
684
685
namespace {
686
/// Used to determine which global regions are automatically included in the
687
/// initial worklist of a ClusterAnalysis.
688
enum GlobalsFilterKind {
689
  /// Don't include any global regions.
690
  GFK_None,
691
  /// Only include system globals.
692
  GFK_SystemOnly,
693
  /// Include all global regions.
694
  GFK_All
695
};
696
697
template <typename DERIVED>
698
class ClusterAnalysis  {
699
protected:
700
  typedef llvm::DenseMap<const MemRegion *, const ClusterBindings *> ClusterMap;
701
  typedef const MemRegion * WorkListElement;
702
  typedef SmallVector<WorkListElement, 10> WorkList;
703
704
  llvm::SmallPtrSet<const ClusterBindings *, 16> Visited;
705
706
  WorkList WL;
707
708
  RegionStoreManager &RM;
709
  ASTContext &Ctx;
710
  SValBuilder &svalBuilder;
711
712
  RegionBindingsRef B;
713
714
715
protected:
716
7.32M
  const ClusterBindings *getCluster(const MemRegion *R) {
717
7.32M
    return B.lookup(R);
718
7.32M
  }
RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::RemoveDeadBindingsWorker>::getCluster(clang::ento::MemRegion const*)
Line
Count
Source
716
7.21M
  const ClusterBindings *getCluster(const MemRegion *R) {
717
7.21M
    return B.lookup(R);
718
7.21M
  }
RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::InvalidateRegionsWorker>::getCluster(clang::ento::MemRegion const*)
Line
Count
Source
716
109k
  const ClusterBindings *getCluster(const MemRegion *R) {
717
109k
    return B.lookup(R);
718
109k
  }
719
720
  /// Returns true if all clusters in the given memspace should be initially
721
  /// included in the cluster analysis. Subclasses may provide their
722
  /// own implementation.
723
2.11M
  bool includeEntireMemorySpace(const MemRegion *Base) {
724
2.11M
    return false;
725
2.11M
  }
726
727
public:
728
  ClusterAnalysis(RegionStoreManager &rm, ProgramStateManager &StateMgr,
729
                  RegionBindingsRef b)
730
      : RM(rm), Ctx(StateMgr.getContext()),
731
506k
        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
731
470k
        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
731
36.1k
        svalBuilder(StateMgr.getSValBuilder()), B(std::move(b)) {}
732
733
36.1k
  RegionBindingsRef getRegionBindings() const { return B; }
734
735
2.11M
  bool isVisited(const MemRegion *R) {
736
2.11M
    return Visited.count(getCluster(R));
737
2.11M
  }
738
739
506k
  void GenerateClusters() {
740
506k
    // Scan the entire set of bindings and record the region clusters.
741
506k
    for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end();
742
2.74M
         RI != RE; 
++RI2.23M
){
743
2.23M
      const MemRegion *Base = RI.getKey();
744
2.23M
745
2.23M
      const ClusterBindings &Cluster = RI.getData();
746
2.23M
      assert(!Cluster.isEmpty() && "Empty clusters should be removed");
747
2.23M
      static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster);
748
2.23M
749
2.23M
      // If the base's memspace should be entirely invalidated, add the cluster
750
2.23M
      // to the workspace up front.
751
2.23M
      if (static_cast<DERIVED*>(this)->includeEntireMemorySpace(Base))
752
53.5k
        AddToWorkList(WorkListElement(Base), &Cluster);
753
2.23M
    }
754
506k
  }
RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::RemoveDeadBindingsWorker>::GenerateClusters()
Line
Count
Source
739
470k
  void GenerateClusters() {
740
470k
    // Scan the entire set of bindings and record the region clusters.
741
470k
    for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end();
742
2.58M
         RI != RE; 
++RI2.11M
){
743
2.11M
      const MemRegion *Base = RI.getKey();
744
2.11M
745
2.11M
      const ClusterBindings &Cluster = RI.getData();
746
2.11M
      assert(!Cluster.isEmpty() && "Empty clusters should be removed");
747
2.11M
      static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster);
748
2.11M
749
2.11M
      // If the base's memspace should be entirely invalidated, add the cluster
750
2.11M
      // to the workspace up front.
751
2.11M
      if (static_cast<DERIVED*>(this)->includeEntireMemorySpace(Base))
752
0
        AddToWorkList(WorkListElement(Base), &Cluster);
753
2.11M
    }
754
470k
  }
RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::InvalidateRegionsWorker>::GenerateClusters()
Line
Count
Source
739
36.1k
  void GenerateClusters() {
740
36.1k
    // Scan the entire set of bindings and record the region clusters.
741
36.1k
    for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end();
742
153k
         RI != RE; 
++RI117k
){
743
117k
      const MemRegion *Base = RI.getKey();
744
117k
745
117k
      const ClusterBindings &Cluster = RI.getData();
746
117k
      assert(!Cluster.isEmpty() && "Empty clusters should be removed");
747
117k
      static_cast<DERIVED*>(this)->VisitAddedToCluster(Base, Cluster);
748
117k
749
117k
      // If the base's memspace should be entirely invalidated, add the cluster
750
117k
      // to the workspace up front.
751
117k
      if (static_cast<DERIVED*>(this)->includeEntireMemorySpace(Base))
752
53.5k
        AddToWorkList(WorkListElement(Base), &Cluster);
753
117k
    }
754
36.1k
  }
755
756
3.91M
  bool AddToWorkList(WorkListElement E, const ClusterBindings *C) {
757
3.91M
    if (C && 
!Visited.insert(C).second2.74M
)
758
751k
      return false;
759
3.16M
    WL.push_back(E);
760
3.16M
    return true;
761
3.16M
  }
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
756
3.83M
  bool AddToWorkList(WorkListElement E, const ClusterBindings *C) {
757
3.83M
    if (C && 
!Visited.insert(C).second2.68M
)
758
751k
      return false;
759
3.08M
    WL.push_back(E);
760
3.08M
    return true;
761
3.08M
  }
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
756
81.3k
  bool AddToWorkList(WorkListElement E, const ClusterBindings *C) {
757
81.3k
    if (C && 
!Visited.insert(C).second65.0k
)
758
51
      return false;
759
81.3k
    WL.push_back(E);
760
81.3k
    return true;
761
81.3k
  }
762
763
  bool AddToWorkList(const MemRegion *R) {
764
    return static_cast<DERIVED*>(this)->AddToWorkList(R);
765
  }
766
767
507k
  void RunWorkList() {
768
3.66M
    while (!WL.empty()) {
769
3.16M
      WorkListElement E = WL.pop_back_val();
770
3.16M
      const MemRegion *BaseR = E;
771
3.16M
772
3.16M
      static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR));
773
3.16M
    }
774
507k
  }
RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::RemoveDeadBindingsWorker>::RunWorkList()
Line
Count
Source
767
471k
  void RunWorkList() {
768
3.55M
    while (!WL.empty()) {
769
3.08M
      WorkListElement E = WL.pop_back_val();
770
3.08M
      const MemRegion *BaseR = E;
771
3.08M
772
3.08M
      static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR));
773
3.08M
    }
774
471k
  }
RegionStore.cpp:(anonymous namespace)::ClusterAnalysis<(anonymous namespace)::InvalidateRegionsWorker>::RunWorkList()
Line
Count
Source
767
36.1k
  void RunWorkList() {
768
117k
    while (!WL.empty()) {
769
81.3k
      WorkListElement E = WL.pop_back_val();
770
81.3k
      const MemRegion *BaseR = E;
771
81.3k
772
81.3k
      static_cast<DERIVED*>(this)->VisitCluster(BaseR, getCluster(BaseR));
773
81.3k
    }
774
36.1k
  }
775
776
117k
  void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C) {}
777
  void VisitCluster(const MemRegion *baseR, const ClusterBindings *C) {}
778
779
  void VisitCluster(const MemRegion *BaseR, const ClusterBindings *C,
780
                    bool Flag) {
781
    static_cast<DERIVED*>(this)->VisitCluster(BaseR, C);
782
  }
783
};
784
}
785
786
//===----------------------------------------------------------------------===//
787
// Binding invalidation.
788
//===----------------------------------------------------------------------===//
789
790
bool RegionStoreManager::scanReachableSymbols(Store S, const MemRegion *R,
791
1.30M
                                              ScanReachableSymbols &Callbacks) {
792
1.30M
  assert(R == R->getBaseRegion() && "Should only be called for base regions");
793
1.30M
  RegionBindingsRef B = getRegionBindings(S);
794
1.30M
  const ClusterBindings *Cluster = B.lookup(R);
795
1.30M
796
1.30M
  if (!Cluster)
797
811k
    return true;
798
497k
799
497k
  for (ClusterBindings::iterator RI = Cluster->begin(), RE = Cluster->end();
800
1.27M
       RI != RE; 
++RI776k
) {
801
776k
    if (!Callbacks.scan(RI.getData()))
802
0
      return false;
803
776k
  }
804
497k
805
497k
  return true;
806
497k
}
807
808
151
static inline bool isUnionField(const FieldRegion *FR) {
809
151
  return FR->getDecl()->getParent()->isUnion();
810
151
}
811
812
typedef SmallVector<const FieldDecl *, 8> FieldVector;
813
814
150
static void getSymbolicOffsetFields(BindingKey K, FieldVector &Fields) {
815
150
  assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys");
816
150
817
150
  const MemRegion *Base = K.getConcreteOffsetRegion();
818
150
  const MemRegion *R = K.getRegion();
819
150
820
482
  while (R != Base) {
821
332
    if (const FieldRegion *FR = dyn_cast<FieldRegion>(R))
822
151
      if (!isUnionField(FR))
823
133
        Fields.push_back(FR->getDecl());
824
332
825
332
    R = cast<SubRegion>(R)->getSuperRegion();
826
332
  }
827
150
}
828
829
105
static bool isCompatibleWithFields(BindingKey K, const FieldVector &Fields) {
830
105
  assert(K.hasSymbolicOffset() && "Not implemented for concrete offset keys");
831
105
832
105
  if (Fields.empty())
833
50
    return true;
834
55
835
55
  FieldVector FieldsInBindingKey;
836
55
  getSymbolicOffsetFields(K, FieldsInBindingKey);
837
55
838
55
  ptrdiff_t Delta = FieldsInBindingKey.size() - Fields.size();
839
55
  if (Delta >= 0)
840
51
    return std::equal(FieldsInBindingKey.begin() + Delta,
841
51
                      FieldsInBindingKey.end(),
842
51
                      Fields.begin());
843
4
  else
844
4
    return std::equal(FieldsInBindingKey.begin(), FieldsInBindingKey.end(),
845
4
                      Fields.begin() - Delta);
846
55
}
847
848
/// Collects all bindings in \p Cluster that may refer to bindings within
849
/// \p Top.
850
///
851
/// Each binding is a pair whose \c first is the key (a BindingKey) and whose
852
/// \c second is the value (an SVal).
853
///
854
/// The \p IncludeAllDefaultBindings parameter specifies whether to include
855
/// default bindings that may extend beyond \p Top itself, e.g. if \p Top is
856
/// an aggregate within a larger aggregate with a default binding.
857
static void
858
collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
859
                         SValBuilder &SVB, const ClusterBindings &Cluster,
860
                         const SubRegion *Top, BindingKey TopKey,
861
27.6k
                         bool IncludeAllDefaultBindings) {
862
27.6k
  FieldVector FieldsInSymbolicSubregions;
863
27.6k
  if (TopKey.hasSymbolicOffset()) {
864
95
    getSymbolicOffsetFields(TopKey, FieldsInSymbolicSubregions);
865
95
    Top = TopKey.getConcreteOffsetRegion();
866
95
    TopKey = BindingKey::Make(Top, BindingKey::Default);
867
95
  }
868
27.6k
869
27.6k
  // Find the length (in bits) of the region being invalidated.
870
27.6k
  uint64_t Length = UINT64_MAX;
871
27.6k
  SVal Extent = Top->getMemRegionManager().getStaticSize(Top, SVB);
872
27.6k
  if (Optional<nonloc::ConcreteInt> ExtentCI =
873
27.6k
          Extent.getAs<nonloc::ConcreteInt>()) {
874
27.6k
    const llvm::APSInt &ExtentInt = ExtentCI->getValue();
875
27.6k
    assert(ExtentInt.isNonNegative() || ExtentInt.isUnsigned());
876
27.6k
    // Extents are in bytes but region offsets are in bits. Be careful!
877
27.6k
    Length = ExtentInt.getLimitedValue() * SVB.getContext().getCharWidth();
878
27.6k
  } else 
if (const FieldRegion *58
FR58
= dyn_cast<FieldRegion>(Top)) {
879
37
    if (FR->getDecl()->isBitField())
880
37
      Length = FR->getDecl()->getBitWidthValue(SVB.getContext());
881
37
  }
882
27.6k
883
27.6k
  for (ClusterBindings::iterator I = Cluster.begin(), E = Cluster.end();
884
102k
       I != E; 
++I74.7k
) {
885
74.7k
    BindingKey NextKey = I.getKey();
886
74.7k
    if (NextKey.getRegion() == TopKey.getRegion()) {
887
74.5k
      // FIXME: This doesn't catch the case where we're really invalidating a
888
74.5k
      // region with a symbolic offset. Example:
889
74.5k
      //      R: points[i].y
890
74.5k
      //   Next: points[0].x
891
74.5k
892
74.5k
      if (NextKey.getOffset() > TopKey.getOffset() &&
893
74.5k
          
NextKey.getOffset() - TopKey.getOffset() < Length14.8k
) {
894
286
        // Case 1: The next binding is inside the region we're invalidating.
895
286
        // Include it.
896
286
        Bindings.push_back(*I);
897
286
898
74.2k
      } else if (NextKey.getOffset() == TopKey.getOffset()) {
899
16.4k
        // Case 2: The next binding is at the same offset as the region we're
900
16.4k
        // invalidating. In this case, we need to leave default bindings alone,
901
16.4k
        // since they may be providing a default value for a regions beyond what
902
16.4k
        // we're invalidating.
903
16.4k
        // FIXME: This is probably incorrect; consider invalidating an outer
904
16.4k
        // struct whose first field is bound to a LazyCompoundVal.
905
16.4k
        if (IncludeAllDefaultBindings || 
NextKey.isDirect()15.7k
)
906
16.0k
          Bindings.push_back(*I);
907
16.4k
      }
908
74.5k
909
74.5k
    } else 
if (212
NextKey.hasSymbolicOffset()212
) {
910
141
      const MemRegion *Base = NextKey.getConcreteOffsetRegion();
911
141
      if (Top->isSubRegionOf(Base) && 
Top != Base105
) {
912
28
        // Case 3: The next key is symbolic and we just changed something within
913
28
        // its concrete region. We don't know if the binding is still valid, so
914
28
        // we'll be conservative and include it.
915
28
        if (IncludeAllDefaultBindings || NextKey.isDirect())
916
28
          if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
917
28
            Bindings.push_back(*I);
918
113
      } else if (const SubRegion *BaseSR = dyn_cast<SubRegion>(Base)) {
919
113
        // Case 4: The next key is symbolic, but we changed a known
920
113
        // super-region. In this case the binding is certainly included.
921
113
        if (BaseSR->isSubRegionOf(Top))
922
77
          if (isCompatibleWithFields(NextKey, FieldsInSymbolicSubregions))
923
35
            Bindings.push_back(*I);
924
113
      }
925
141
    }
926
74.7k
  }
927
27.6k
}
928
929
static void
930
collectSubRegionBindings(SmallVectorImpl<BindingPair> &Bindings,
931
                         SValBuilder &SVB, const ClusterBindings &Cluster,
932
770
                         const SubRegion *Top, bool IncludeAllDefaultBindings) {
933
770
  collectSubRegionBindings(Bindings, SVB, Cluster, Top,
934
770
                           BindingKey::Make(Top, BindingKey::Default),
935
770
                           IncludeAllDefaultBindings);
936
770
}
937
938
RegionBindingsRef
939
RegionStoreManager::removeSubRegionBindings(RegionBindingsConstRef B,
940
248k
                                            const SubRegion *Top) {
941
248k
  BindingKey TopKey = BindingKey::Make(Top, BindingKey::Default);
942
248k
  const MemRegion *ClusterHead = TopKey.getBaseRegion();
943
248k
944
248k
  if (Top == ClusterHead) {
945
169k
    // We can remove an entire cluster's bindings all in one go.
946
169k
    return B.remove(Top);
947
169k
  }
948
79.6k
949
79.6k
  const ClusterBindings *Cluster = B.lookup(ClusterHead);
950
79.6k
  if (!Cluster) {
951
52.7k
    // If we're invalidating a region with a symbolic offset, we need to make
952
52.7k
    // sure we don't treat the base region as uninitialized anymore.
953
52.7k
    if (TopKey.hasSymbolicOffset()) {
954
146
      const SubRegion *Concrete = TopKey.getConcreteOffsetRegion();
955
146
      return B.addBinding(Concrete, BindingKey::Default, UnknownVal());
956
146
    }
957
52.5k
    return B;
958
52.5k
  }
959
26.8k
960
26.8k
  SmallVector<BindingPair, 32> Bindings;
961
26.8k
  collectSubRegionBindings(Bindings, svalBuilder, *Cluster, Top, TopKey,
962
26.8k
                           /*IncludeAllDefaultBindings=*/false);
963
26.8k
964
26.8k
  ClusterBindingsRef Result(*Cluster, CBFactory);
965
26.8k
  for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(),
966
26.8k
                                                    E = Bindings.end();
967
42.3k
       I != E; 
++I15.4k
)
968
15.4k
    Result = Result.remove(I->first);
969
26.8k
970
26.8k
  // If we're invalidating a region with a symbolic offset, we need to make sure
971
26.8k
  // we don't treat the base region as uninitialized anymore.
972
26.8k
  // FIXME: This isn't very precise; see the example in
973
26.8k
  // collectSubRegionBindings.
974
26.8k
  if (TopKey.hasSymbolicOffset()) {
975
95
    const SubRegion *Concrete = TopKey.getConcreteOffsetRegion();
976
95
    Result = Result.add(BindingKey::Make(Concrete, BindingKey::Default),
977
95
                        UnknownVal());
978
95
  }
979
26.8k
980
26.8k
  if (Result.isEmpty())
981
788
    return B.remove(ClusterHead);
982
26.1k
  return B.add(ClusterHead, Result.asImmutableMap());
983
26.1k
}
984
985
namespace {
986
class InvalidateRegionsWorker : public ClusterAnalysis<InvalidateRegionsWorker>
987
{
988
  const Expr *Ex;
989
  unsigned Count;
990
  const LocationContext *LCtx;
991
  InvalidatedSymbols &IS;
992
  RegionAndSymbolInvalidationTraits &ITraits;
993
  StoreManager::InvalidatedRegions *Regions;
994
  GlobalsFilterKind GlobalsFilter;
995
public:
996
  InvalidateRegionsWorker(RegionStoreManager &rm,
997
                          ProgramStateManager &stateMgr,
998
                          RegionBindingsRef b,
999
                          const Expr *ex, unsigned count,
1000
                          const LocationContext *lctx,
1001
                          InvalidatedSymbols &is,
1002
                          RegionAndSymbolInvalidationTraits &ITraitsIn,
1003
                          StoreManager::InvalidatedRegions *r,
1004
                          GlobalsFilterKind GFK)
1005
     : ClusterAnalysis<InvalidateRegionsWorker>(rm, stateMgr, b),
1006
       Ex(ex), Count(count), LCtx(lctx), IS(is), ITraits(ITraitsIn), Regions(r),
1007
36.1k
       GlobalsFilter(GFK) {}
1008
1009
  void VisitCluster(const MemRegion *baseR, const ClusterBindings *C);
1010
  void VisitBinding(SVal V);
1011
1012
  using ClusterAnalysis::AddToWorkList;
1013
1014
  bool AddToWorkList(const MemRegion *R);
1015
1016
  /// Returns true if all clusters in the memory space for \p Base should be
1017
  /// be invalidated.
1018
  bool includeEntireMemorySpace(const MemRegion *Base);
1019
1020
  /// Returns true if the memory space of the given region is one of the global
1021
  /// regions specially included at the start of invalidation.
1022
  bool isInitiallyIncludedGlobalRegion(const MemRegion *R);
1023
};
1024
}
1025
1026
27.8k
bool InvalidateRegionsWorker::AddToWorkList(const MemRegion *R) {
1027
27.8k
  bool doNotInvalidateSuperRegion = ITraits.hasTrait(
1028
27.8k
      R, RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
1029
27.8k
  const MemRegion *BaseR = doNotInvalidateSuperRegion ? 
R1.78k
:
R->getBaseRegion()26.0k
;
1030
27.8k
  return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR));
1031
27.8k
}
1032
1033
69.4k
void InvalidateRegionsWorker::VisitBinding(SVal V) {
1034
69.4k
  // A symbol?  Mark it touched by the invalidation.
1035
69.4k
  if (SymbolRef Sym = V.getAsSymbol())
1036
63.9k
    IS.insert(Sym);
1037
69.4k
1038
69.4k
  if (const MemRegion *R = V.getAsRegion()) {
1039
900
    AddToWorkList(R);
1040
900
    return;
1041
900
  }
1042
68.5k
1043
68.5k
  // Is it a LazyCompoundVal?  All references get invalidated as well.
1044
68.5k
  if (Optional<nonloc::LazyCompoundVal> LCS =
1045
138
          V.getAs<nonloc::LazyCompoundVal>()) {
1046
138
1047
138
    const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS);
1048
138
1049
138
    for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(),
1050
138
                                                        E = Vals.end();
1051
148
         I != E; 
++I10
)
1052
10
      VisitBinding(*I);
1053
138
1054
138
    return;
1055
138
  }
1056
68.5k
}
1057
1058
void InvalidateRegionsWorker::VisitCluster(const MemRegion *baseR,
1059
81.3k
                                           const ClusterBindings *C) {
1060
81.3k
1061
81.3k
  bool PreserveRegionsContents =
1062
81.3k
      ITraits.hasTrait(baseR,
1063
81.3k
                       RegionAndSymbolInvalidationTraits::TK_PreserveContents);
1064
81.3k
1065
81.3k
  if (C) {
1066
134k
    for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; 
++I69.4k
)
1067
69.4k
      VisitBinding(I.getData());
1068
65.0k
1069
65.0k
    // Invalidate regions contents.
1070
65.0k
    if (!PreserveRegionsContents)
1071
61.8k
      B = B.remove(baseR);
1072
65.0k
  }
1073
81.3k
1074
81.3k
  if (const auto *TO = dyn_cast<TypedValueRegion>(baseR)) {
1075
19.1k
    if (const auto *RD = TO->getValueType()->getAsCXXRecordDecl()) {
1076
12.0k
1077
12.0k
      // Lambdas can affect all static local variables without explicitly
1078
12.0k
      // capturing those.
1079
12.0k
      // We invalidate all static locals referenced inside the lambda body.
1080
12.0k
      if (RD->isLambda() && 
RD->getLambdaCallOperator()->getBody()4
) {
1081
4
        using namespace ast_matchers;
1082
4
1083
4
        const char *DeclBind = "DeclBind";
1084
4
        StatementMatcher RefToStatic = stmt(hasDescendant(declRefExpr(
1085
4
              to(varDecl(hasStaticStorageDuration()).bind(DeclBind)))));
1086
4
        auto Matches =
1087
4
            match(RefToStatic, *RD->getLambdaCallOperator()->getBody(),
1088
4
                  RD->getASTContext());
1089
4
1090
4
        for (BoundNodes &Match : Matches) {
1091
2
          auto *VD = Match.getNodeAs<VarDecl>(DeclBind);
1092
2
          const VarRegion *ToInvalidate =
1093
2
              RM.getRegionManager().getVarRegion(VD, LCtx);
1094
2
          AddToWorkList(ToInvalidate);
1095
2
        }
1096
4
      }
1097
12.0k
    }
1098
19.1k
  }
1099
81.3k
1100
81.3k
  // BlockDataRegion?  If so, invalidate captured variables that are passed
1101
81.3k
  // by reference.
1102
81.3k
  if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(baseR)) {
1103
137
    for (BlockDataRegion::referenced_vars_iterator
1104
137
         BI = BR->referenced_vars_begin(), BE = BR->referenced_vars_end() ;
1105
266
         BI != BE; 
++BI129
) {
1106
129
      const VarRegion *VR = BI.getCapturedRegion();
1107
129
      const VarDecl *VD = VR->getDecl();
1108
129
      if (VD->hasAttr<BlocksAttr>() || 
!VD->hasLocalStorage()113
) {
1109
32
        AddToWorkList(VR);
1110
32
      }
1111
97
      else if (Loc::isLocType(VR->getValueType())) {
1112
58
        // Map the current bindings to a Store to retrieve the value
1113
58
        // of the binding.  If that binding itself is a region, we should
1114
58
        // invalidate that region.  This is because a block may capture
1115
58
        // a pointer value, but the thing pointed by that pointer may
1116
58
        // get invalidated.
1117
58
        SVal V = RM.getBinding(B, loc::MemRegionVal(VR));
1118
58
        if (Optional<Loc> L = V.getAs<Loc>()) {
1119
58
          if (const MemRegion *LR = L->getAsRegion())
1120
58
            AddToWorkList(LR);
1121
58
        }
1122
58
      }
1123
129
    }
1124
137
    return;
1125
137
  }
1126
81.1k
1127
81.1k
  // Symbolic region?
1128
81.1k
  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR))
1129
8.56k
    IS.insert(SR->getSymbol());
1130
81.1k
1131
81.1k
  // Nothing else should be done in the case when we preserve regions context.
1132
81.1k
  if (PreserveRegionsContents)
1133
6.42k
    return;
1134
74.7k
1135
74.7k
  // Otherwise, we have a normal data region. Record that we touched the region.
1136
74.7k
  if (Regions)
1137
74.7k
    Regions->push_back(baseR);
1138
74.7k
1139
74.7k
  if (isa<AllocaRegion>(baseR) || 
isa<SymbolicRegion>(baseR)74.7k
) {
1140
6.84k
    // Invalidate the region by setting its default value to
1141
6.84k
    // conjured symbol. The type of the symbol is irrelevant.
1142
6.84k
    DefinedOrUnknownSVal V =
1143
6.84k
      svalBuilder.conjureSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count);
1144
6.84k
    B = B.addBinding(baseR, BindingKey::Default, V);
1145
6.84k
    return;
1146
6.84k
  }
1147
67.8k
1148
67.8k
  if (!baseR->isBoundable())
1149
53.7k
    return;
1150
14.1k
1151
14.1k
  const TypedValueRegion *TR = cast<TypedValueRegion>(baseR);
1152
14.1k
  QualType T = TR->getValueType();
1153
14.1k
1154
14.1k
  if (isInitiallyIncludedGlobalRegion(baseR)) {
1155
255
    // If the region is a global and we are invalidating all globals,
1156
255
    // erasing the entry is good enough.  This causes all globals to be lazily
1157
255
    // symbolicated from the same base symbol.
1158
255
    return;
1159
255
  }
1160
13.8k
1161
13.8k
  if (T->isRecordType()) {
1162
10.9k
    // Invalidate the region by setting its default value to
1163
10.9k
    // conjured symbol. The type of the symbol is irrelevant.
1164
10.9k
    DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1165
10.9k
                                                          Ctx.IntTy, Count);
1166
10.9k
    B = B.addBinding(baseR, BindingKey::Default, V);
1167
10.9k
    return;
1168
10.9k
  }
1169
2.92k
1170
2.92k
  if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
1171
775
    bool doNotInvalidateSuperRegion = ITraits.hasTrait(
1172
775
        baseR,
1173
775
        RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
1174
775
1175
775
    if (doNotInvalidateSuperRegion) {
1176
35
      // We are not doing blank invalidation of the whole array region so we
1177
35
      // have to manually invalidate each elements.
1178
35
      Optional<uint64_t> NumElements;
1179
35
1180
35
      // Compute lower and upper offsets for region within array.
1181
35
      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1182
35
        NumElements = CAT->getSize().getZExtValue();
1183
35
      if (!NumElements) // We are not dealing with a constant size array
1184
0
        goto conjure_default;
1185
35
      QualType ElementTy = AT->getElementType();
1186
35
      uint64_t ElemSize = Ctx.getTypeSize(ElementTy);
1187
35
      const RegionOffset &RO = baseR->getAsOffset();
1188
35
      const MemRegion *SuperR = baseR->getBaseRegion();
1189
35
      if (RO.hasSymbolicOffset()) {
1190
4
        // If base region has a symbolic offset,
1191
4
        // we revert to invalidating the super region.
1192
4
        if (SuperR)
1193
4
          AddToWorkList(SuperR);
1194
4
        goto conjure_default;
1195
4
      }
1196
31
1197
31
      uint64_t LowerOffset = RO.getOffset();
1198
31
      uint64_t UpperOffset = LowerOffset + *NumElements * ElemSize;
1199
31
      bool UpperOverflow = UpperOffset < LowerOffset;
1200
31
1201
31
      // Invalidate regions which are within array boundaries,
1202
31
      // or have a symbolic offset.
1203
31
      if (!SuperR)
1204
0
        goto conjure_default;
1205
31
1206
31
      const ClusterBindings *C = B.lookup(SuperR);
1207
31
      if (!C)
1208
0
        goto conjure_default;
1209
31
1210
159
      
for (ClusterBindings::iterator I = C->begin(), E = C->end(); 31
I != E;
1211
128
           ++I) {
1212
128
        const BindingKey &BK = I.getKey();
1213
128
        Optional<uint64_t> ROffset =
1214
128
            BK.hasSymbolicOffset() ? 
Optional<uint64_t>()5
:
BK.getOffset()123
;
1215
128
1216
128
        // Check offset is not symbolic and within array's boundaries.
1217
128
        // Handles arrays of 0 elements and of 0-sized elements as well.
1218
128
        if (!ROffset ||
1219
128
            
(123
(123
*ROffset >= LowerOffset123
&&
*ROffset < UpperOffset110
) ||
1220
123
             
(50
UpperOverflow50
&&
1221
50
              
(11
*ROffset >= LowerOffset11
||
*ROffset < UpperOffset5
)) ||
1222
123
             
(42
LowerOffset == UpperOffset42
&&
*ROffset == LowerOffset3
))) {
1223
89
          B = B.removeBinding(I.getKey());
1224
89
          // Bound symbolic regions need to be invalidated for dead symbol
1225
89
          // detection.
1226
89
          SVal V = I.getData();
1227
89
          const MemRegion *R = V.getAsRegion();
1228
89
          if (R && 
isa<SymbolicRegion>(R)3
)
1229
3
            VisitBinding(V);
1230
89
        }
1231
128
      }
1232
31
    }
1233
775
  conjure_default:
1234
775
      // Set the default value of the array to conjured symbol.
1235
775
    DefinedOrUnknownSVal V =
1236
775
    svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1237
775
                                     AT->getElementType(), Count);
1238
775
    B = B.addBinding(baseR, BindingKey::Default, V);
1239
775
    return;
1240
2.14k
  }
1241
2.14k
1242
2.14k
  DefinedOrUnknownSVal V = svalBuilder.conjureSymbolVal(baseR, Ex, LCtx,
1243
2.14k
                                                        T,Count);
1244
2.14k
  assert(SymbolManager::canSymbolicate(T) || V.isUnknown());
1245
2.14k
  B = B.addBinding(baseR, BindingKey::Direct, V);
1246
2.14k
}
1247
1248
bool InvalidateRegionsWorker::isInitiallyIncludedGlobalRegion(
1249
131k
    const MemRegion *R) {
1250
131k
  switch (GlobalsFilter) {
1251
2.77k
  case GFK_None:
1252
2.77k
    return false;
1253
15.8k
  case GFK_SystemOnly:
1254
15.8k
    return isa<GlobalSystemSpaceRegion>(R->getMemorySpace());
1255
112k
  case GFK_All:
1256
112k
    return isa<NonStaticGlobalSpaceRegion>(R->getMemorySpace());
1257
0
  }
1258
0
1259
0
  llvm_unreachable("unknown globals filter");
1260
0
}
1261
1262
117k
bool InvalidateRegionsWorker::includeEntireMemorySpace(const MemRegion *Base) {
1263
117k
  if (isInitiallyIncludedGlobalRegion(Base))
1264
53.4k
    return true;
1265
63.5k
1266
63.5k
  const MemSpaceRegion *MemSpace = Base->getMemorySpace();
1267
63.5k
  return ITraits.hasTrait(MemSpace,
1268
63.5k
                          RegionAndSymbolInvalidationTraits::TK_EntireMemSpace);
1269
63.5k
}
1270
1271
RegionBindingsRef
1272
RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind K,
1273
                                           const Expr *Ex,
1274
                                           unsigned Count,
1275
                                           const LocationContext *LCtx,
1276
                                           RegionBindingsRef B,
1277
65.0k
                                           InvalidatedRegions *Invalidated) {
1278
65.0k
  // Bind the globals memory space to a new symbol that we will use to derive
1279
65.0k
  // the bindings for all globals.
1280
65.0k
  const GlobalsSpaceRegion *GS = MRMgr.getGlobalsRegion(K);
1281
65.0k
  SVal V = svalBuilder.conjureSymbolVal(/* symbolTag = */ (const void*) GS, Ex, LCtx,
1282
65.0k
                                        /* type does not matter */ Ctx.IntTy,
1283
65.0k
                                        Count);
1284
65.0k
1285
65.0k
  B = B.removeBinding(GS)
1286
65.0k
       .addBinding(BindingKey::Make(GS, BindingKey::Default), V);
1287
65.0k
1288
65.0k
  // Even if there are no bindings in the global scope, we still need to
1289
65.0k
  // record that we touched it.
1290
65.0k
  if (Invalidated)
1291
65.0k
    Invalidated->push_back(GS);
1292
65.0k
1293
65.0k
  return B;
1294
65.0k
}
1295
1296
void RegionStoreManager::populateWorkList(InvalidateRegionsWorker &W,
1297
                                          ArrayRef<SVal> Values,
1298
36.1k
                                          InvalidatedRegions *TopLevelRegions) {
1299
36.1k
  for (ArrayRef<SVal>::iterator I = Values.begin(),
1300
80.1k
                                E = Values.end(); I != E; 
++I43.9k
) {
1301
43.9k
    SVal V = *I;
1302
43.9k
    if (Optional<nonloc::LazyCompoundVal> LCS =
1303
9.43k
        V.getAs<nonloc::LazyCompoundVal>()) {
1304
9.43k
1305
9.43k
      const SValListTy &Vals = getInterestingValues(*LCS);
1306
9.43k
1307
9.43k
      for (SValListTy::const_iterator I = Vals.begin(),
1308
18.8k
                                      E = Vals.end(); I != E; 
++I9.37k
) {
1309
9.37k
        // Note: the last argument is false here because these are
1310
9.37k
        // non-top-level regions.
1311
9.37k
        if (const MemRegion *R = (*I).getAsRegion())
1312
305
          W.AddToWorkList(R);
1313
9.37k
      }
1314
9.43k
      continue;
1315
9.43k
    }
1316
34.5k
1317
34.5k
    if (const MemRegion *R = V.getAsRegion()) {
1318
26.5k
      if (TopLevelRegions)
1319
26.5k
        TopLevelRegions->push_back(R);
1320
26.5k
      W.AddToWorkList(R);
1321
26.5k
      continue;
1322
26.5k
    }
1323
34.5k
  }
1324
36.1k
}
1325
1326
StoreRef
1327
RegionStoreManager::invalidateRegions(Store store,
1328
                                     ArrayRef<SVal> Values,
1329
                                     const Expr *Ex, unsigned Count,
1330
                                     const LocationContext *LCtx,
1331
                                     const CallEvent *Call,
1332
                                     InvalidatedSymbols &IS,
1333
                                     RegionAndSymbolInvalidationTraits &ITraits,
1334
                                     InvalidatedRegions *TopLevelRegions,
1335
36.1k
                                     InvalidatedRegions *Invalidated) {
1336
36.1k
  GlobalsFilterKind GlobalsFilter;
1337
36.1k
  if (Call) {
1338
35.2k
    if (Call->isInSystemHeader())
1339
5.38k
      GlobalsFilter = GFK_SystemOnly;
1340
29.8k
    else
1341
29.8k
      GlobalsFilter = GFK_All;
1342
35.2k
  } else {
1343
957
    GlobalsFilter = GFK_None;
1344
957
  }
1345
36.1k
1346
36.1k
  RegionBindingsRef B = getRegionBindings(store);
1347
36.1k
  InvalidateRegionsWorker W(*this, StateMgr, B, Ex, Count, LCtx, IS, ITraits,
1348
36.1k
                            Invalidated, GlobalsFilter);
1349
36.1k
1350
36.1k
  // Scan the bindings and generate the clusters.
1351
36.1k
  W.GenerateClusters();
1352
36.1k
1353
36.1k
  // Add the regions to the worklist.
1354
36.1k
  populateWorkList(W, Values, TopLevelRegions);
1355
36.1k
1356
36.1k
  W.RunWorkList();
1357
36.1k
1358
36.1k
  // Return the new bindings.
1359
36.1k
  B = W.getRegionBindings();
1360
36.1k
1361
36.1k
  // For calls, determine which global regions should be invalidated and
1362
36.1k
  // invalidate them. (Note that function-static and immutable globals are never
1363
36.1k
  // invalidated by this.)
1364
36.1k
  // TODO: This could possibly be more precise with modules.
1365
36.1k
  switch (GlobalsFilter) {
1366
29.8k
  case GFK_All:
1367
29.8k
    B = invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind,
1368
29.8k
                               Ex, Count, LCtx, B, Invalidated);
1369
29.8k
    LLVM_FALLTHROUGH;
1370
35.2k
  case GFK_SystemOnly:
1371
35.2k
    B = invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
1372
35.2k
                               Ex, Count, LCtx, B, Invalidated);
1373
35.2k
    LLVM_FALLTHROUGH;
1374
36.1k
  case GFK_None:
1375
36.1k
    break;
1376
36.1k
  }
1377
36.1k
1378
36.1k
  return StoreRef(B.asStore(), *this);
1379
36.1k
}
1380
1381
//===----------------------------------------------------------------------===//
1382
// Location and region casting.
1383
//===----------------------------------------------------------------------===//
1384
1385
/// ArrayToPointer - Emulates the "decay" of an array to a pointer
1386
///  type.  'Array' represents the lvalue of the array being decayed
1387
///  to a pointer, and the returned SVal represents the decayed
1388
///  version of that lvalue (i.e., a pointer to the first element of
1389
///  the array).  This is called by ExprEngine when evaluating casts
1390
///  from arrays to pointers.
1391
8.04k
SVal RegionStoreManager::ArrayToPointer(Loc Array, QualType T) {
1392
8.04k
  if (Array.getAs<loc::ConcreteInt>())
1393
7
    return Array;
1394
8.03k
1395
8.03k
  if (!Array.getAs<loc::MemRegionVal>())
1396
0
    return UnknownVal();
1397
8.03k
1398
8.03k
  const SubRegion *R =
1399
8.03k
      cast<SubRegion>(Array.castAs<loc::MemRegionVal>().getRegion());
1400
8.03k
  NonLoc ZeroIdx = svalBuilder.makeZeroArrayIndex();
1401
8.03k
  return loc::MemRegionVal(MRMgr.getElementRegion(T, ZeroIdx, R, Ctx));
1402
8.03k
}
1403
1404
//===----------------------------------------------------------------------===//
1405
// Loading values from regions.
1406
//===----------------------------------------------------------------------===//
1407
1408
623k
SVal RegionStoreManager::getBinding(RegionBindingsConstRef B, Loc L, QualType T) {
1409
623k
  assert(!L.getAs<UnknownVal>() && "location unknown");
1410
623k
  assert(!L.getAs<UndefinedVal>() && "location undefined");
1411
623k
1412
623k
  // For access to concrete addresses, return UnknownVal.  Checks
1413
623k
  // for null dereferences (and similar errors) are done by checkers, not
1414
623k
  // the Store.
1415
623k
  // FIXME: We can consider lazily symbolicating such memory, but we really
1416
623k
  // should defer this when we can reason easily about symbolicating arrays
1417
623k
  // of bytes.
1418
623k
  if (L.getAs<loc::ConcreteInt>()) {
1419
12
    return UnknownVal();
1420
12
  }
1421
623k
  if (!L.getAs<loc::MemRegionVal>()) {
1422
0
    return UnknownVal();
1423
0
  }
1424
623k
1425
623k
  const MemRegion *MR = L.castAs<loc::MemRegionVal>().getRegion();
1426
623k
1427
623k
  if (isa<BlockDataRegion>(MR)) {
1428
1
    return UnknownVal();
1429
1
  }
1430
623k
1431
623k
  if (!isa<TypedValueRegion>(MR)) {
1432
7.05k
    if (T.isNull()) {
1433
5.01k
      if (const TypedRegion *TR = dyn_cast<TypedRegion>(MR))
1434
0
        T = TR->getLocationType()->getPointeeType();
1435
5.01k
      else if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(MR))
1436
5.01k
        T = SR->getSymbol()->getType()->getPointeeType();
1437
5.01k
    }
1438
7.05k
    assert(!T.isNull() && "Unable to auto-detect binding type!");
1439
7.05k
    assert(!T->isVoidType() && "Attempting to dereference a void pointer!");
1440
7.05k
    MR = GetElementZeroRegion(cast<SubRegion>(MR), T);
1441
616k
  } else {
1442
616k
    T = cast<TypedValueRegion>(MR)->getValueType();
1443
616k
  }
1444
623k
1445
623k
  // FIXME: Perhaps this method should just take a 'const MemRegion*' argument
1446
623k
  //  instead of 'Loc', and have the other Loc cases handled at a higher level.
1447
623k
  const TypedValueRegion *R = cast<TypedValueRegion>(MR);
1448
623k
  QualType RTy = R->getValueType();
1449
623k
1450
623k
  // FIXME: we do not yet model the parts of a complex type, so treat the
1451
623k
  // whole thing as "unknown".
1452
623k
  if (RTy->isAnyComplexType())
1453
89
    return UnknownVal();
1454
623k
1455
623k
  // FIXME: We should eventually handle funny addressing.  e.g.:
1456
623k
  //
1457
623k
  //   int x = ...;
1458
623k
  //   int *p = &x;
1459
623k
  //   char *q = (char*) p;
1460
623k
  //   char c = *q;  // returns the first byte of 'x'.
1461
623k
  //
1462
623k
  // Such funny addressing will occur due to layering of regions.
1463
623k
  if (RTy->isStructureOrClassType())
1464
79.3k
    return getBindingForStruct(B, R);
1465
543k
1466
543k
  // FIXME: Handle unions.
1467
543k
  if (RTy->isUnionType())
1468
85
    return createLazyBinding(B, R);
1469
543k
1470
543k
  if (RTy->isArrayType()) {
1471
1.52k
    if (RTy->isConstantArrayType())
1472
1.52k
      return getBindingForArray(B, R);
1473
2
    else
1474
2
      return UnknownVal();
1475
542k
  }
1476
542k
1477
542k
  // FIXME: handle Vector types.
1478
542k
  if (RTy->isVectorType())
1479
21
    return UnknownVal();
1480
542k
1481
542k
  if (const FieldRegion* FR = dyn_cast<FieldRegion>(R))
1482
80.3k
    return CastRetrievedVal(getBindingForField(B, FR), FR, T);
1483
461k
1484
461k
  if (const ElementRegion* ER = dyn_cast<ElementRegion>(R)) {
1485
24.8k
    // FIXME: Here we actually perform an implicit conversion from the loaded
1486
24.8k
    // value to the element type.  Eventually we want to compose these values
1487
24.8k
    // more intelligently.  For example, an 'element' can encompass multiple
1488
24.8k
    // bound regions (e.g., several bound bytes), or could be a subset of
1489
24.8k
    // a larger value.
1490
24.8k
    return CastRetrievedVal(getBindingForElement(B, ER), ER, T);
1491
24.8k
  }
1492
437k
1493
437k
  if (const ObjCIvarRegion *IVR = dyn_cast<ObjCIvarRegion>(R)) {
1494
2.47k
    // FIXME: Here we actually perform an implicit conversion from the loaded
1495
2.47k
    // value to the ivar type.  What we should model is stores to ivars
1496
2.47k
    // that blow past the extent of the ivar.  If the address of the ivar is
1497
2.47k
    // reinterpretted, it is possible we stored a different value that could
1498
2.47k
    // fit within the ivar.  Either we need to cast these when storing them
1499
2.47k
    // or reinterpret them lazily (as we do here).
1500
2.47k
    return CastRetrievedVal(getBindingForObjCIvar(B, IVR), IVR, T);
1501
2.47k
  }
1502
434k
1503
434k
  if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
1504
325k
    // FIXME: Here we actually perform an implicit conversion from the loaded
1505
325k
    // value to the variable type.  What we should model is stores to variables
1506
325k
    // that blow past the extent of the variable.  If the address of the
1507
325k
    // variable is reinterpretted, it is possible we stored a different value
1508
325k
    // that could fit within the variable.  Either we need to cast these when
1509
325k
    // storing them or reinterpret them lazily (as we do here).
1510
325k
    return CastRetrievedVal(getBindingForVar(B, VR), VR, T);
1511
325k
  }
1512
109k
1513
109k
  const SVal *V = B.lookup(R, BindingKey::Direct);
1514
109k
1515
109k
  // Check if the region has a binding.
1516
109k
  if (V)
1517
105k
    return *V;
1518
3.61k
1519
3.61k
  // The location does not have a bound value.  This means that it has
1520
3.61k
  // the value it had upon its creation and/or entry to the analyzed
1521
3.61k
  // function/method.  These are either symbolic values or 'undefined'.
1522
3.61k
  if (R->hasStackNonParametersStorage()) {
1523
42
    // All stack variables are considered to have undefined values
1524
42
    // upon creation.  All heap allocated blocks are considered to
1525
42
    // have undefined values as well unless they are explicitly bound
1526
42
    // to specific values.
1527
42
    return UndefinedVal();
1528
42
  }
1529
3.57k
1530
3.57k
  // All other values are symbolic.
1531
3.57k
  return svalBuilder.getRegionValueSymbolVal(R);
1532
3.57k
}
1533
1534
805
static QualType getUnderlyingType(const SubRegion *R) {
1535
805
  QualType RegionTy;
1536
805
  if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R))
1537
798
    RegionTy = TVR->getValueType();
1538
805
1539
805
  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
1540
7
    RegionTy = SR->getSymbol()->getType();
1541
805
1542
805
  return RegionTy;
1543
805
}
1544
1545
/// Checks to see if store \p B has a lazy binding for region \p R.
1546
///
1547
/// If \p AllowSubregionBindings is \c false, a lazy binding will be rejected
1548
/// if there are additional bindings within \p R.
1549
///
1550
/// Note that unlike RegionStoreManager::findLazyBinding, this will not search
1551
/// for lazy bindings for super-regions of \p R.
1552
static Optional<nonloc::LazyCompoundVal>
1553
getExistingLazyBinding(SValBuilder &SVB, RegionBindingsConstRef B,
1554
192k
                       const SubRegion *R, bool AllowSubregionBindings) {
1555
192k
  Optional<SVal> V = B.getDefaultBinding(R);
1556
192k
  if (!V)
1557
165k
    return None;
1558
26.6k
1559
26.6k
  Optional<nonloc::LazyCompoundVal> LCV = V->getAs<nonloc::LazyCompoundVal>();
1560
26.6k
  if (!LCV)
1561
25.8k
    return None;
1562
805
1563
805
  // If the LCV is for a subregion, the types might not match, and we shouldn't
1564
805
  // reuse the binding.
1565
805
  QualType RegionTy = getUnderlyingType(R);
1566
805
  if (!RegionTy.isNull() &&
1567
805
      !RegionTy->isVoidPointerType()) {
1568
801
    QualType SourceRegionTy = LCV->getRegion()->getValueType();
1569
801
    if (!SVB.getContext().hasSameUnqualifiedType(RegionTy, SourceRegionTy))
1570
222
      return None;
1571
583
  }
1572
583
1573
583
  if (!AllowSubregionBindings) {
1574
140
    // If there are any other bindings within this region, we shouldn't reuse
1575
140
    // the top-level binding.
1576
140
    SmallVector<BindingPair, 16> Bindings;
1577
140
    collectSubRegionBindings(Bindings, SVB, *B.lookup(R->getBaseRegion()), R,
1578
140
                             /*IncludeAllDefaultBindings=*/true);
1579
140
    if (Bindings.size() > 1)
1580
2
      return None;
1581
581
  }
1582
581
1583
581
  return *LCV;
1584
581
}
1585
1586
1587
std::pair<Store, const SubRegion *>
1588
RegionStoreManager::findLazyBinding(RegionBindingsConstRef B,
1589
                                   const SubRegion *R,
1590
205k
                                   const SubRegion *originalRegion) {
1591
205k
  if (originalRegion != R) {
1592
125k
    if (Optional<nonloc::LazyCompoundVal> V =
1593
443
          getExistingLazyBinding(svalBuilder, B, R, true))
1594
443
      return std::make_pair(V->getStore(), V->getRegion());
1595
205k
  }
1596
205k
1597
205k
  typedef std::pair<Store, const SubRegion *> StoreRegionPair;
1598
205k
  StoreRegionPair Result = StoreRegionPair();
1599
205k
1600
205k
  if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
1601
55.3k
    Result = findLazyBinding(B, cast<SubRegion>(ER->getSuperRegion()),
1602
55.3k
                             originalRegion);
1603
55.3k
1604
55.3k
    if (Result.second)
1605
252
      Result.second = MRMgr.getElementRegionWithSuper(ER, Result.second);
1606
55.3k
1607
150k
  } else if (const FieldRegion *FR = dyn_cast<FieldRegion>(R)) {
1608
69.0k
    Result = findLazyBinding(B, cast<SubRegion>(FR->getSuperRegion()),
1609
69.0k
                                       originalRegion);
1610
69.0k
1611
69.0k
    if (Result.second)
1612
450
      Result.second = MRMgr.getFieldRegionWithSuper(FR, Result.second);
1613
69.0k
1614
81.1k
  } else if (const CXXBaseObjectRegion *BaseReg =
1615
1.08k
               dyn_cast<CXXBaseObjectRegion>(R)) {
1616
1.08k
    // C++ base object region is another kind of region that we should blast
1617
1.08k
    // through to look for lazy compound value. It is like a field region.
1618
1.08k
    Result = findLazyBinding(B, cast<SubRegion>(BaseReg->getSuperRegion()),
1619
1.08k
                             originalRegion);
1620
1.08k
1621
1.08k
    if (Result.second)
1622
40
      Result.second = MRMgr.getCXXBaseObjectRegionWithSuper(BaseReg,
1623
40
                                                            Result.second);
1624
1.08k
  }
1625
205k
1626
205k
  return Result;
1627
205k
}
1628
1629
SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B,
1630
24.9k
                                              const ElementRegion* R) {
1631
24.9k
  // We do not currently model bindings of the CompoundLiteralregion.
1632
24.9k
  if (isa<CompoundLiteralRegion>(R->getBaseRegion()))
1633
5
    return UnknownVal();
1634
24.9k
1635
24.9k
  // Check if the region has a binding.
1636
24.9k
  if (const Optional<SVal> &V = B.getDirectBinding(R))
1637
6.20k
    return *V;
1638
18.7k
1639
18.7k
  const MemRegion* superR = R->getSuperRegion();
1640
18.7k
1641
18.7k
  // Check if the region is an element region of a string literal.
1642
18.7k
  if (const StringRegion *StrR = dyn_cast<StringRegion>(superR)) {
1643
216
    // FIXME: Handle loads from strings where the literal is treated as
1644
216
    // an integer, e.g., *((unsigned int*)"hello")
1645
216
    QualType T = Ctx.getAsArrayType(StrR->getValueType())->getElementType();
1646
216
    if (!Ctx.hasSameUnqualifiedType(T, R->getElementType()))
1647
2
      return UnknownVal();
1648
214
1649
214
    const StringLiteral *Str = StrR->getStringLiteral();
1650
214
    SVal Idx = R->getIndex();
1651
214
    if (Optional<nonloc::ConcreteInt> CI = Idx.getAs<nonloc::ConcreteInt>()) {
1652
214
      int64_t i = CI->getValue().getSExtValue();
1653
214
      // Abort on string underrun.  This can be possible by arbitrary
1654
214
      // clients of getBindingForElement().
1655
214
      if (i < 0)
1656
0
        return UndefinedVal();
1657
214
      int64_t length = Str->getLength();
1658
214
      // Technically, only i == length is guaranteed to be null.
1659
214
      // However, such overflows should be caught before reaching this point;
1660
214
      // the only time such an access would be made is if a string literal was
1661
214
      // used to initialize a larger array.
1662
214
      char c = (i >= length) ? 
'\0'6
:
Str->getCodeUnit(i)208
;
1663
214
      return svalBuilder.makeIntVal(c, T);
1664
214
    }
1665
18.5k
  } else if (const VarRegion *VR = dyn_cast<VarRegion>(superR)) {
1666
7.15k
    // Check if the containing array has an initialized value that we can trust.
1667
7.15k
    // We can trust a const value or a value of a global initializer in main().
1668
7.15k
    const VarDecl *VD = VR->getDecl();
1669
7.15k
    if (VD->getType().isConstQualified() ||
1670
7.15k
        
R->getElementType().isConstQualified()7.11k
||
1671
7.15k
        
(7.11k
B.isMainAnalysis()7.11k
&&
VD->hasGlobalStorage()7
)) {
1672
44
      if (const Expr *Init = VD->getAnyInitializer()) {
1673
44
        if (const auto *InitList = dyn_cast<InitListExpr>(Init)) {
1674
44
          // The array index has to be known.
1675
44
          if (auto CI = R->getIndex().getAs<nonloc::ConcreteInt>()) {
1676
44
            int64_t i = CI->getValue().getSExtValue();
1677
44
            // If it is known that the index is out of bounds, we can return
1678
44
            // an undefined value.
1679
44
            if (i < 0)
1680
1
              return UndefinedVal();
1681
43
1682
43
            if (auto CAT = Ctx.getAsConstantArrayType(VD->getType()))
1683
43
              if (CAT->getSize().sle(i))
1684
1
                return UndefinedVal();
1685
42
1686
42
            // If there is a list, but no init, it must be zero.
1687
42
            if (i >= InitList->getNumInits())
1688
1
              return svalBuilder.makeZeroVal(R->getElementType());
1689
41
1690
41
            if (const Expr *ElemInit = InitList->getInit(i))
1691
41
              if (Optional<SVal> V = svalBuilder.getConstantVal(ElemInit))
1692
41
                return *V;
1693
18.5k
          }
1694
44
        }
1695
44
      }
1696
44
    }
1697
7.15k
  }
1698
18.5k
1699
18.5k
  // Check for loads from a code text region.  For such loads, just give up.
1700
18.5k
  if (isa<CodeTextRegion>(superR))
1701
90
    return UnknownVal();
1702
18.4k
1703
18.4k
  // Handle the case where we are indexing into a larger scalar object.
1704
18.4k
  // For example, this handles:
1705
18.4k
  //   int x = ...
1706
18.4k
  //   char *y = &x;
1707
18.4k
  //   return *y;
1708
18.4k
  // FIXME: This is a hack, and doesn't do anything really intelligent yet.
1709
18.4k
  const RegionRawOffset &O = R->getAsArrayOffset();
1710
18.4k
1711
18.4k
  // If we cannot reason about the offset, return an unknown value.
1712
18.4k
  if (!O.getRegion())
1713
3.08k
    return UnknownVal();
1714
15.3k
1715
15.3k
  if (const TypedValueRegion *baseR =
1716
9.24k
        dyn_cast_or_null<TypedValueRegion>(O.getRegion())) {
1717
9.24k
    QualType baseT = baseR->getValueType();
1718
9.24k
    if (baseT->isScalarType()) {
1719
80
      QualType elemT = R->getElementType();
1720
80
      if (elemT->isScalarType()) {
1721
80
        if (Ctx.getTypeSizeInChars(baseT) >= Ctx.getTypeSizeInChars(elemT)) {
1722
79
          if (const Optional<SVal> &V = B.getDirectBinding(superR)) {
1723
4
            if (SymbolRef parentSym = V->getAsSymbol())
1724
0
              return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1725
4
1726
4
            if (V->isUnknownOrUndef())
1727
0
              return *V;
1728
4
            // Other cases: give up.  We are indexing into a larger object
1729
4
            // that has some value, but we don't know how to handle that yet.
1730
4
            return UnknownVal();
1731
4
          }
1732
79
        }
1733
80
      }
1734
80
    }
1735
9.24k
  }
1736
15.3k
  return getBindingForFieldOrElementCommon(B, R, R->getElementType());
1737
15.3k
}
1738
1739
SVal RegionStoreManager::getBindingForField(RegionBindingsConstRef B,
1740
110k
                                            const FieldRegion* R) {
1741
110k
1742
110k
  // Check if the region has a binding.
1743
110k
  if (const Optional<SVal> &V = B.getDirectBinding(R))
1744
45.4k
    return *V;
1745
65.2k
1746
65.2k
  // Is the field declared constant and has an in-class initializer?
1747
65.2k
  const FieldDecl *FD = R->getDecl();
1748
65.2k
  QualType Ty = FD->getType();
1749
65.2k
  if (Ty.isConstQualified())
1750
49
    if (const Expr *Init = FD->getInClassInitializer())
1751
0
      if (Optional<SVal> V = svalBuilder.getConstantVal(Init))
1752
0
        return *V;
1753
65.2k
1754
65.2k
  // If the containing record was initialized, try to get its constant value.
1755
65.2k
  const MemRegion* superR = R->getSuperRegion();
1756
65.2k
  if (const auto *VR = dyn_cast<VarRegion>(superR)) {
1757
17.5k
    const VarDecl *VD = VR->getDecl();
1758
17.5k
    QualType RecordVarTy = VD->getType();
1759
17.5k
    unsigned Index = FD->getFieldIndex();
1760
17.5k
    // Either the record variable or the field has an initializer that we can
1761
17.5k
    // trust. We trust initializers of constants and, additionally, respect
1762
17.5k
    // initializers of globals when analyzing main().
1763
17.5k
    if (RecordVarTy.isConstQualified() || 
Ty.isConstQualified()17.2k
||
1764
17.5k
        
(17.1k
B.isMainAnalysis()17.1k
&&
VD->hasGlobalStorage()3
))
1765
339
      if (const Expr *Init = VD->getAnyInitializer())
1766
126
        if (const auto *InitList = dyn_cast<InitListExpr>(Init)) {
1767
97
          if (Index < InitList->getNumInits()) {
1768
96
            if (const Expr *FieldInit = InitList->getInit(Index))
1769
96
              if (Optional<SVal> V = svalBuilder.getConstantVal(FieldInit))
1770
96
                return *V;
1771
1
          } else {
1772
1
            return svalBuilder.makeZeroVal(Ty);
1773
1
          }
1774
65.1k
        }
1775
17.5k
  }
1776
65.1k
1777
65.1k
  return getBindingForFieldOrElementCommon(B, R, Ty);
1778
65.1k
}
1779
1780
Optional<SVal>
1781
RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindingsConstRef B,
1782
                                                     const MemRegion *superR,
1783
                                                     const TypedValueRegion *R,
1784
194k
                                                     QualType Ty) {
1785
194k
1786
194k
  if (const Optional<SVal> &D = B.getDefaultBinding(superR)) {
1787
18.9k
    const SVal &val = D.getValue();
1788
18.9k
    if (SymbolRef parentSym = val.getAsSymbol())
1789
18.0k
      return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1790
870
1791
870
    if (val.isZeroConstant())
1792
349
      return svalBuilder.makeZeroVal(Ty);
1793
521
1794
521
    if (val.isUnknownOrUndef())
1795
499
      return val;
1796
22
1797
22
    // Lazy bindings are usually handled through getExistingLazyBinding().
1798
22
    // We should unify these two code paths at some point.
1799
22
    if (val.getAs<nonloc::LazyCompoundVal>() ||
1800
22
        
val.getAs<nonloc::CompoundVal>()10
)
1801
22
      return val;
1802
0
1803
0
    llvm_unreachable("Unknown default value");
1804
0
  }
1805
175k
1806
175k
  return None;
1807
175k
}
1808
1809
SVal RegionStoreManager::getLazyBinding(const SubRegion *LazyBindingRegion,
1810
443
                                        RegionBindingsRef LazyBinding) {
1811
443
  SVal Result;
1812
443
  if (const ElementRegion *ER = dyn_cast<ElementRegion>(LazyBindingRegion))
1813
152
    Result = getBindingForElement(LazyBinding, ER);
1814
291
  else
1815
291
    Result = getBindingForField(LazyBinding,
1816
291
                                cast<FieldRegion>(LazyBindingRegion));
1817
443
1818
443
  // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
1819
443
  // default value for /part/ of an aggregate from a default value for the
1820
443
  // /entire/ aggregate. The most common case of this is when struct Outer
1821
443
  // has as its first member a struct Inner, which is copied in from a stack
1822
443
  // variable. In this case, even if the Outer's default value is symbolic, 0,
1823
443
  // or unknown, it gets overridden by the Inner's default value of undefined.
1824
443
  //
1825
443
  // This is a general problem -- if the Inner is zero-initialized, the Outer
1826
443
  // will now look zero-initialized. The proper way to solve this is with a
1827
443
  // new version of RegionStore that tracks the extent of a binding as well
1828
443
  // as the offset.
1829
443
  //
1830
443
  // This hack only takes care of the undefined case because that can very
1831
443
  // quickly result in a warning.
1832
443
  if (Result.isUndef())
1833
7
    Result = UnknownVal();
1834
443
1835
443
  return Result;
1836
443
}
1837
1838
SVal
1839
RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
1840
                                                      const TypedValueRegion *R,
1841
80.4k
                                                      QualType Ty) {
1842
80.4k
1843
80.4k
  // At this point we have already checked in either getBindingForElement or
1844
80.4k
  // getBindingForField if 'R' has a direct binding.
1845
80.4k
1846
80.4k
  // Lazy binding?
1847
80.4k
  Store lazyBindingStore = nullptr;
1848
80.4k
  const SubRegion *lazyBindingRegion = nullptr;
1849
80.4k
  std::tie(lazyBindingStore, lazyBindingRegion) = findLazyBinding(B, R, R);
1850
80.4k
  if (lazyBindingRegion)
1851
443
    return getLazyBinding(lazyBindingRegion,
1852
443
                          getRegionBindings(lazyBindingStore));
1853
80.0k
1854
80.0k
  // Record whether or not we see a symbolic index.  That can completely
1855
80.0k
  // be out of scope of our lookup.
1856
80.0k
  bool hasSymbolicIndex = false;
1857
80.0k
1858
80.0k
  // FIXME: This is a hack to deal with RegionStore's inability to distinguish a
1859
80.0k
  // default value for /part/ of an aggregate from a default value for the
1860
80.0k
  // /entire/ aggregate. The most common case of this is when struct Outer
1861
80.0k
  // has as its first member a struct Inner, which is copied in from a stack
1862
80.0k
  // variable. In this case, even if the Outer's default value is symbolic, 0,
1863
80.0k
  // or unknown, it gets overridden by the Inner's default value of undefined.
1864
80.0k
  //
1865
80.0k
  // This is a general problem -- if the Inner is zero-initialized, the Outer
1866
80.0k
  // will now look zero-initialized. The proper way to solve this is with a
1867
80.0k
  // new version of RegionStore that tracks the extent of a binding as well
1868
80.0k
  // as the offset.
1869
80.0k
  //
1870
80.0k
  // This hack only takes care of the undefined case because that can very
1871
80.0k
  // quickly result in a warning.
1872
80.0k
  bool hasPartialLazyBinding = false;
1873
80.0k
1874
80.0k
  const SubRegion *SR = R;
1875
253k
  while (SR) {
1876
187k
    const MemRegion *Base = SR->getSuperRegion();
1877
187k
    if (Optional<SVal> D = getBindingForDerivedDefaultValue(B, Base, R, Ty)) {
1878
13.9k
      if (D->getAs<nonloc::LazyCompoundVal>()) {
1879
12
        hasPartialLazyBinding = true;
1880
12
        break;
1881
12
      }
1882
13.8k
1883
13.8k
      return *D;
1884
13.8k
    }
1885
173k
1886
173k
    if (const ElementRegion *ER = dyn_cast<ElementRegion>(Base)) {
1887
37.2k
      NonLoc index = ER->getIndex();
1888
37.2k
      if (!index.isConstant())
1889
27.0k
        hasSymbolicIndex = true;
1890
37.2k
    }
1891
173k
1892
173k
    // If our super region is a field or element itself, walk up the region
1893
173k
    // hierarchy to see if there is a default value installed in an ancestor.
1894
173k
    SR = dyn_cast<SubRegion>(Base);
1895
173k
  }
1896
80.0k
1897
80.0k
  
if (66.1k
R->hasStackNonParametersStorage()66.1k
) {
1898
18.4k
    if (isa<ElementRegion>(R)) {
1899
5.26k
      // Currently we don't reason specially about Clang-style vectors.  Check
1900
5.26k
      // if superR is a vector and if so return Unknown.
1901
5.26k
      if (const TypedValueRegion *typedSuperR =
1902
5.24k
            dyn_cast<TypedValueRegion>(R->getSuperRegion())) {
1903
5.24k
        if (typedSuperR->getValueType()->isVectorType())
1904
6
          return UnknownVal();
1905
18.4k
      }
1906
5.26k
    }
1907
18.4k
1908
18.4k
    // FIXME: We also need to take ElementRegions with symbolic indexes into
1909
18.4k
    // account.  This case handles both directly accessing an ElementRegion
1910
18.4k
    // with a symbolic offset, but also fields within an element with
1911
18.4k
    // a symbolic offset.
1912
18.4k
    if (hasSymbolicIndex)
1913
11
      return UnknownVal();
1914
18.4k
1915
18.4k
    // Additionally allow introspection of a block's internal layout.
1916
18.4k
    if (!hasPartialLazyBinding && 
!isa<BlockDataRegion>(R->getBaseRegion())18.4k
)
1917
18.4k
      return UndefinedVal();
1918
47.7k
  }
1919
47.7k
1920
47.7k
  // All other values are symbolic.
1921
47.7k
  return svalBuilder.getRegionValueSymbolVal(R);
1922
47.7k
}
1923
1924
SVal RegionStoreManager::getBindingForObjCIvar(RegionBindingsConstRef B,
1925
2.47k
                                               const ObjCIvarRegion* R) {
1926
2.47k
  // Check if the region has a binding.
1927
2.47k
  if (const Optional<SVal> &V = B.getDirectBinding(R))
1928
1.10k
    return *V;
1929
1.36k
1930
1.36k
  const MemRegion *superR = R->getSuperRegion();
1931
1.36k
1932
1.36k
  // Check if the super region has a default binding.
1933
1.36k
  if (const Optional<SVal> &V = B.getDefaultBinding(superR)) {
1934
65
    if (SymbolRef parentSym = V->getAsSymbol())
1935
65
      return svalBuilder.getDerivedRegionValueSymbolVal(parentSym, R);
1936
0
1937
0
    // Other cases: give up.
1938
0
    return UnknownVal();
1939
0
  }
1940
1.30k
1941
1.30k
  return getBindingForLazySymbol(R);
1942
1.30k
}
1943
1944
SVal RegionStoreManager::getBindingForVar(RegionBindingsConstRef B,
1945
325k
                                          const VarRegion *R) {
1946
325k
1947
325k
  // Check if the region has a binding.
1948
325k
  if (Optional<SVal> V = B.getDirectBinding(R))
1949
206k
    return *V;
1950
118k
1951
118k
  if (Optional<SVal> V = B.getDefaultBinding(R))
1952
13
    return *V;
1953
118k
1954
118k
  // Lazily derive a value for the VarRegion.
1955
118k
  const VarDecl *VD = R->getDecl();
1956
118k
  const MemSpaceRegion *MS = R->getMemorySpace();
1957
118k
1958
118k
  // Arguments are always symbolic.
1959
118k
  if (isa<StackArgumentsSpaceRegion>(MS))
1960
49.6k
    return svalBuilder.getRegionValueSymbolVal(R);
1961
68.9k
1962
68.9k
  // Is 'VD' declared constant?  If so, retrieve the constant value.
1963
68.9k
  if (VD->getType().isConstQualified()) {
1964
769
    if (const Expr *Init = VD->getAnyInitializer()) {
1965
533
      if (Optional<SVal> V = svalBuilder.getConstantVal(Init))
1966
509
        return *V;
1967
24
1968
24
      // If the variable is const qualified and has an initializer but
1969
24
      // we couldn't evaluate initializer to a value, treat the value as
1970
24
      // unknown.
1971
24
      return UnknownVal();
1972
24
    }
1973
769
  }
1974
68.4k
1975
68.4k
  // This must come after the check for constants because closure-captured
1976
68.4k
  // constant variables may appear in UnknownSpaceRegion.
1977
68.4k
  if (isa<UnknownSpaceRegion>(MS))
1978
136
    return svalBuilder.getRegionValueSymbolVal(R);
1979
68.3k
1980
68.3k
  if (isa<GlobalsSpaceRegion>(MS)) {
1981
6.63k
    QualType T = VD->getType();
1982
6.63k
1983
6.63k
    // If we're in main(), then global initializers have not become stale yet.
1984
6.63k
    if (B.isMainAnalysis())
1985
3
      if (const Expr *Init = VD->getAnyInitializer())
1986
1
        if (Optional<SVal> V = svalBuilder.getConstantVal(Init))
1987
1
          return *V;
1988
6.63k
1989
6.63k
    // Function-scoped static variables are default-initialized to 0; if they
1990
6.63k
    // have an initializer, it would have been processed by now.
1991
6.63k
    // FIXME: This is only true when we're starting analysis from main().
1992
6.63k
    // We're losing a lot of coverage here.
1993
6.63k
    if (isa<StaticGlobalSpaceRegion>(MS))
1994
202
      return svalBuilder.makeZeroVal(T);
1995
6.43k
1996
6.43k
    if (Optional<SVal> V = getBindingForDerivedDefaultValue(B, MS, R, T)) {
1997
5.04k
      assert(!V->getAs<nonloc::LazyCompoundVal>());
1998
5.04k
      return V.getValue();
1999
5.04k
    }
2000
1.39k
2001
1.39k
    return svalBuilder.getRegionValueSymbolVal(R);
2002
1.39k
  }
2003
61.6k
2004
61.6k
  return UndefinedVal();
2005
61.6k
}
2006
2007
1.30k
SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R) {
2008
1.30k
  // All other values are symbolic.
2009
1.30k
  return svalBuilder.getRegionValueSymbolVal(R);
2010
1.30k
}
2011
2012
const RegionStoreManager::SValListTy &
2013
14.0k
RegionStoreManager::getInterestingValues(nonloc::LazyCompoundVal LCV) {
2014
14.0k
  // First, check the cache.
2015
14.0k
  LazyBindingsMapTy::iterator I = LazyBindingsMap.find(LCV.getCVData());
2016
14.0k
  if (I != LazyBindingsMap.end())
2017
13.1k
    return I->second;
2018
885
2019
885
  // If we don't have a list of values cached, start constructing it.
2020
885
  SValListTy List;
2021
885
2022
885
  const SubRegion *LazyR = LCV.getRegion();
2023
885
  RegionBindingsRef B = getRegionBindings(LCV.getStore());
2024
885
2025
885
  // If this region had /no/ bindings at the time, there are no interesting
2026
885
  // values to return.
2027
885
  const ClusterBindings *Cluster = B.lookup(LazyR->getBaseRegion());
2028
885
  if (!Cluster)
2029
255
    return (LazyBindingsMap[LCV.getCVData()] = std::move(List));
2030
630
2031
630
  SmallVector<BindingPair, 32> Bindings;
2032
630
  collectSubRegionBindings(Bindings, svalBuilder, *Cluster, LazyR,
2033
630
                           /*IncludeAllDefaultBindings=*/true);
2034
630
  for (SmallVectorImpl<BindingPair>::const_iterator I = Bindings.begin(),
2035
630
                                                    E = Bindings.end();
2036
1.47k
       I != E; 
++I843
) {
2037
843
    SVal V = I->second;
2038
843
    if (V.isUnknownOrUndef() || 
V.isConstant()754
)
2039
341
      continue;
2040
502
2041
502
    if (Optional<nonloc::LazyCompoundVal> InnerLCV =
2042
6
            V.getAs<nonloc::LazyCompoundVal>()) {
2043
6
      const SValListTy &InnerList = getInterestingValues(*InnerLCV);
2044
6
      List.insert(List.end(), InnerList.begin(), InnerList.end());
2045
6
      continue;
2046
6
    }
2047
496
2048
496
    List.push_back(V);
2049
496
  }
2050
630
2051
630
  return (LazyBindingsMap[LCV.getCVData()] = std::move(List));
2052
630
}
2053
2054
NonLoc RegionStoreManager::createLazyBinding(RegionBindingsConstRef B,
2055
66.8k
                                             const TypedValueRegion *R) {
2056
66.8k
  if (Optional<nonloc::LazyCompoundVal> V =
2057
138
        getExistingLazyBinding(svalBuilder, B, R, false))
2058
138
    return *V;
2059
66.7k
2060
66.7k
  return svalBuilder.makeLazyCompoundVal(StoreRef(B.asStore(), *this), R);
2061
66.7k
}
2062
2063
78.9k
static bool isRecordEmpty(const RecordDecl *RD) {
2064
78.9k
  if (!RD->field_empty())
2065
64.3k
    return false;
2066
14.5k
  if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD))
2067
14.4k
    return CRD->getNumBases() == 0;
2068
135
  return true;
2069
135
}
2070
2071
SVal RegionStoreManager::getBindingForStruct(RegionBindingsConstRef B,
2072
79.3k
                                             const TypedValueRegion *R) {
2073
79.3k
  const RecordDecl *RD = R->getValueType()->castAs<RecordType>()->getDecl();
2074
79.3k
  if (!RD->getDefinition() || 
isRecordEmpty(RD)78.9k
)
2075
14.0k
    return UnknownVal();
2076
65.2k
2077
65.2k
  return createLazyBinding(B, R);
2078
65.2k
}
2079
2080
SVal RegionStoreManager::getBindingForArray(RegionBindingsConstRef B,
2081
1.52k
                                            const TypedValueRegion *R) {
2082
1.52k
  assert(Ctx.getAsConstantArrayType(R->getValueType()) &&
2083
1.52k
         "Only constant array types can have compound bindings.");
2084
1.52k
2085
1.52k
  return createLazyBinding(B, R);
2086
1.52k
}
2087
2088
bool RegionStoreManager::includedInBindings(Store store,
2089
25.6k
                                            const MemRegion *region) const {
2090
25.6k
  RegionBindingsRef B = getRegionBindings(store);
2091
25.6k
  region = region->getBaseRegion();
2092
25.6k
2093
25.6k
  // Quick path: if the base is the head of a cluster, the region is live.
2094
25.6k
  if (B.lookup(region))
2095
0
    return true;
2096
25.6k
2097
25.6k
  // Slow path: if the region is the VALUE of any binding, it is live.
2098
105k
  
for (RegionBindingsRef::iterator RI = B.begin(), RE = B.end(); 25.6k
RI != RE;
++RI79.6k
) {
2099
79.6k
    const ClusterBindings &Cluster = RI.getData();
2100
79.6k
    for (ClusterBindings::iterator CI = Cluster.begin(), CE = Cluster.end();
2101
159k
         CI != CE; 
++CI80.2k
) {
2102
80.2k
      const SVal &D = CI.getData();
2103
80.2k
      if (const MemRegion *R = D.getAsRegion())
2104
6.95k
        if (R->getBaseRegion() == region)
2105
0
          return true;
2106
80.2k
    }
2107
79.6k
  }
2108
25.6k
2109
25.6k
  return false;
2110
25.6k
}
2111
2112
//===----------------------------------------------------------------------===//
2113
// Binding values to regions.
2114
//===----------------------------------------------------------------------===//
2115
2116
6
StoreRef RegionStoreManager::killBinding(Store ST, Loc L) {
2117
6
  if (Optional<loc::MemRegionVal> LV = L.getAs<loc::MemRegionVal>())
2118
0
    if (const MemRegion* R = LV->getRegion())
2119
0
      return StoreRef(getRegionBindings(ST).removeBinding(R)
2120
0
                                           .asImmutableMap()
2121
0
                                           .getRootWithoutRetain(),
2122
0
                      *this);
2123
6
2124
6
  return StoreRef(ST, *this);
2125
6
}
2126
2127
RegionBindingsRef
2128
278k
RegionStoreManager::bind(RegionBindingsConstRef B, Loc L, SVal V) {
2129
278k
  if (L.getAs<loc::ConcreteInt>())
2130
5
    return B;
2131
278k
2132
278k
  // If we get here, the location should be a region.
2133
278k
  const MemRegion *R = L.castAs<loc::MemRegionVal>().getRegion();
2134
278k
2135
278k
  // Check if the region is a struct region.
2136
278k
  if (const TypedValueRegion* TR = dyn_cast<TypedValueRegion>(R)) {
2137
277k
    QualType Ty = TR->getValueType();
2138
277k
    if (Ty->isArrayType())
2139
1.28k
      return bindArray(B, TR, V);
2140
276k
    if (Ty->isStructureOrClassType())
2141
33.9k
      return bindStruct(B, TR, V);
2142
242k
    if (Ty->isVectorType())
2143
11
      return bindVector(B, TR, V);
2144
242k
    if (Ty->isUnionType())
2145
71
      return bindAggregate(B, TR, V);
2146
243k
  }
2147
243k
2148
243k
  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
2149
548
    // Binding directly to a symbolic region should be treated as binding
2150
548
    // to element 0.
2151
548
    QualType T = SR->getSymbol()->getType();
2152
548
    if (T->isAnyPointerType() || 
T->isReferenceType()120
)
2153
548
      T = T->getPointeeType();
2154
548
2155
548
    R = GetElementZeroRegion(SR, T);
2156
548
  }
2157
243k
2158
243k
  assert((!isa<CXXThisRegion>(R) || !B.lookup(R)) &&
2159
243k
         "'this' pointer is not an l-value and is not assignable");
2160
243k
2161
243k
  // Clear out bindings that may overlap with this binding.
2162
243k
  RegionBindingsRef NewB = removeSubRegionBindings(B, cast<SubRegion>(R));
2163
243k
  return NewB.addBinding(BindingKey::Make(R, BindingKey::Direct), V);
2164
243k
}
2165
2166
RegionBindingsRef
2167
RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B,
2168
                                            const MemRegion *R,
2169
320
                                            QualType T) {
2170
320
  SVal V;
2171
320
2172
320
  if (Loc::isLocType(T))
2173
10
    V = svalBuilder.makeNull();
2174
310
  else if (T->isIntegralOrEnumerationType())
2175
262
    V = svalBuilder.makeZeroVal(T);
2176
48
  else if (T->isStructureOrClassType() || 
T->isArrayType()14
) {
2177
34
    // Set the default value to a zero constant when it is a structure
2178
34
    // or array.  The type doesn't really matter.
2179
34
    V = svalBuilder.makeZeroVal(Ctx.IntTy);
2180
34
  }
2181
14
  else {
2182
14
    // We can't represent values of this type, but we still need to set a value
2183
14
    // to record that the region has been initialized.
2184
14
    // If this assertion ever fires, a new case should be added above -- we
2185
14
    // should know how to default-initialize any value we can symbolicate.
2186
14
    assert(!SymbolManager::canSymbolicate(T) && "This type is representable");
2187
14
    V = UnknownVal();
2188
14
  }
2189
320
2190
320
  return B.addBinding(R, BindingKey::Default, V);
2191
320
}
2192
2193
RegionBindingsRef
2194
RegionStoreManager::bindArray(RegionBindingsConstRef B,
2195
                              const TypedValueRegion* R,
2196
1.51k
                              SVal Init) {
2197
1.51k
2198
1.51k
  const ArrayType *AT =cast<ArrayType>(Ctx.getCanonicalType(R->getValueType()));
2199
1.51k
  QualType ElementTy = AT->getElementType();
2200
1.51k
  Optional<uint64_t> Size;
2201
1.51k
2202
1.51k
  if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(AT))
2203
1.49k
    Size = CAT->getSize().getZExtValue();
2204
1.51k
2205
1.51k
  // Check if the init expr is a literal. If so, bind the rvalue instead.
2206
1.51k
  // FIXME: It's not responsibility of the Store to transform this lvalue
2207
1.51k
  // to rvalue. ExprEngine or maybe even CFG should do this before binding.
2208
1.51k
  if (Optional<loc::MemRegionVal> MRV = Init.getAs<loc::MemRegionVal>()) {
2209
446
    SVal V = getBinding(B.asStore(), *MRV, R->getValueType());
2210
446
    return bindAggregate(B, R, V);
2211
446
  }
2212
1.06k
2213
1.06k
  // Handle lazy compound values.
2214
1.06k
  if (Init.getAs<nonloc::LazyCompoundVal>())
2215
8
    return bindAggregate(B, R, Init);
2216
1.05k
2217
1.05k
  if (Init.isUnknown())
2218
47
    return bindAggregate(B, R, UnknownVal());
2219
1.00k
2220
1.00k
  // Remaining case: explicit compound values.
2221
1.00k
  const nonloc::CompoundVal& CV = Init.castAs<nonloc::CompoundVal>();
2222
1.00k
  nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2223
1.00k
  uint64_t i = 0;
2224
1.00k
2225
1.00k
  RegionBindingsRef NewB(B);
2226
1.00k
2227
3.86k
  for (; Size.hasValue() ? 
i < Size.getValue()3.85k
:
true14
;
++i, ++VI2.86k
) {
2228
3.18k
    // The init list might be shorter than the array length.
2229
3.18k
    if (VI == VE)
2230
320
      break;
2231
2.86k
2232
2.86k
    const NonLoc &Idx = svalBuilder.makeArrayIndex(i);
2233
2.86k
    const ElementRegion *ER = MRMgr.getElementRegion(ElementTy, Idx, R, Ctx);
2234
2.86k
2235
2.86k
    if (ElementTy->isStructureOrClassType())
2236
190
      NewB = bindStruct(NewB, ER, *VI);
2237
2.67k
    else if (ElementTy->isArrayType())
2238
81
      NewB = bindArray(NewB, ER, *VI);
2239
2.58k
    else
2240
2.58k
      NewB = bind(NewB, loc::MemRegionVal(ER), *VI);
2241
2.86k
  }
2242
1.00k
2243
1.00k
  // If the init list is shorter than the array length (or the array has
2244
1.00k
  // variable length), set the array default value. Values that are already set
2245
1.00k
  // are not overwritten.
2246
1.00k
  if (!Size.hasValue() || 
i < Size.getValue()999
)
2247
320
    NewB = setImplicitDefaultValue(NewB, R, ElementTy);
2248
1.00k
2249
1.00k
  return NewB;
2250
1.00k
}
2251
2252
RegionBindingsRef RegionStoreManager::bindVector(RegionBindingsConstRef B,
2253
                                                 const TypedValueRegion* R,
2254
11
                                                 SVal V) {
2255
11
  QualType T = R->getValueType();
2256
11
  const VectorType *VT = T->castAs<VectorType>(); // Use castAs for typedefs.
2257
11
2258
11
  // Handle lazy compound values and symbolic values.
2259
11
  if (V.getAs<nonloc::LazyCompoundVal>() || V.getAs<nonloc::SymbolVal>())
2260
0
    return bindAggregate(B, R, V);
2261
11
2262
11
  // We may get non-CompoundVal accidentally due to imprecise cast logic or
2263
11
  // that we are binding symbolic struct value. Kill the field values, and if
2264
11
  // the value is symbolic go and bind it as a "default" binding.
2265
11
  if (!V.getAs<nonloc::CompoundVal>()) {
2266
3
    return bindAggregate(B, R, UnknownVal());
2267
3
  }
2268
8
2269
8
  QualType ElemType = VT->getElementType();
2270
8
  nonloc::CompoundVal CV = V.castAs<nonloc::CompoundVal>();
2271
8
  nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2272
8
  unsigned index = 0, numElements = VT->getNumElements();
2273
8
  RegionBindingsRef NewB(B);
2274
8
2275
28
  for ( ; index != numElements ; 
++index20
) {
2276
20
    if (VI == VE)
2277
0
      break;
2278
20
2279
20
    NonLoc Idx = svalBuilder.makeArrayIndex(index);
2280
20
    const ElementRegion *ER = MRMgr.getElementRegion(ElemType, Idx, R, Ctx);
2281
20
2282
20
    if (ElemType->isArrayType())
2283
0
      NewB = bindArray(NewB, ER, *VI);
2284
20
    else if (ElemType->isStructureOrClassType())
2285
0
      NewB = bindStruct(NewB, ER, *VI);
2286
20
    else
2287
20
      NewB = bind(NewB, loc::MemRegionVal(ER), *VI);
2288
20
  }
2289
8
  return NewB;
2290
8
}
2291
2292
Optional<RegionBindingsRef>
2293
RegionStoreManager::tryBindSmallStruct(RegionBindingsConstRef B,
2294
                                       const TypedValueRegion *R,
2295
                                       const RecordDecl *RD,
2296
30.1k
                                       nonloc::LazyCompoundVal LCV) {
2297
30.1k
  FieldVector Fields;
2298
30.1k
2299
30.1k
  if (const CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(RD))
2300
29.9k
    if (Class->getNumBases() != 0 || 
Class->getNumVBases() != 029.9k
)
2301
75
      return None;
2302
30.0k
2303
30.5k
  
for (const auto *FD : RD->fields())30.0k
{
2304
30.5k
    if (FD->isUnnamedBitfield())
2305
8
      continue;
2306
30.5k
2307
30.5k
    // If there are too many fields, or if any of the fields are aggregates,
2308
30.5k
    // just use the LCV as a default binding.
2309
30.5k
    if (Fields.size() == SmallStructLimit)
2310
106
      return None;
2311
30.4k
2312
30.4k
    QualType Ty = FD->getType();
2313
30.4k
    if (!(Ty->isScalarType() || 
Ty->isReferenceType()507
))
2314
198
      return None;
2315
30.2k
2316
30.2k
    Fields.push_back(FD);
2317
30.2k
  }
2318
30.0k
2319
30.0k
  RegionBindingsRef NewB = B;
2320
29.7k
2321
59.7k
  for (FieldVector::iterator I = Fields.begin(), E = Fields.end(); I != E; 
++I30.0k
){
2322
30.0k
    const FieldRegion *SourceFR = MRMgr.getFieldRegion(*I, LCV.getRegion());
2323
30.0k
    SVal V = getBindingForField(getRegionBindings(LCV.getStore()), SourceFR);
2324
30.0k
2325
30.0k
    const FieldRegion *DestFR = MRMgr.getFieldRegion(*I, R);
2326
30.0k
    NewB = bind(NewB, loc::MemRegionVal(DestFR), V);
2327
30.0k
  }
2328
29.7k
2329
29.7k
  return NewB;
2330
30.0k
}
2331
2332
RegionBindingsRef RegionStoreManager::bindStruct(RegionBindingsConstRef B,
2333
                                                 const TypedValueRegion* R,
2334
34.2k
                                                 SVal V) {
2335
34.2k
  if (!Features.supportsFields())
2336
0
    return B;
2337
34.2k
2338
34.2k
  QualType T = R->getValueType();
2339
34.2k
  assert(T->isStructureOrClassType());
2340
34.2k
2341
34.2k
  const RecordType* RT = T->castAs<RecordType>();
2342
34.2k
  const RecordDecl *RD = RT->getDecl();
2343
34.2k
2344
34.2k
  if (!RD->isCompleteDefinition())
2345
0
    return B;
2346
34.2k
2347
34.2k
  // Handle lazy compound values and symbolic values.
2348
34.2k
  if (Optional<nonloc::LazyCompoundVal> LCV =
2349
30.1k
        V.getAs<nonloc::LazyCompoundVal>()) {
2350
30.1k
    if (Optional<RegionBindingsRef> NewB = tryBindSmallStruct(B, R, RD, *LCV))
2351
29.7k
      return *NewB;
2352
379
    return bindAggregate(B, R, V);
2353
379
  }
2354
4.08k
  if (V.getAs<nonloc::SymbolVal>())
2355
3.01k
    return bindAggregate(B, R, V);
2356
1.07k
2357
1.07k
  // We may get non-CompoundVal accidentally due to imprecise cast logic or
2358
1.07k
  // that we are binding symbolic struct value. Kill the field values, and if
2359
1.07k
  // the value is symbolic go and bind it as a "default" binding.
2360
1.07k
  if (V.isUnknown() || 
!V.getAs<nonloc::CompoundVal>()996
)
2361
78
    return bindAggregate(B, R, UnknownVal());
2362
994
2363
994
  // The raw CompoundVal is essentially a symbolic InitListExpr: an (immutable)
2364
994
  // list of other values. It appears pretty much only when there's an actual
2365
994
  // initializer list expression in the program, and the analyzer tries to
2366
994
  // unwrap it as soon as possible.
2367
994
  // This code is where such unwrap happens: when the compound value is put into
2368
994
  // the object that it was supposed to initialize (it's an *initializer* list,
2369
994
  // after all), instead of binding the whole value to the whole object, we bind
2370
994
  // sub-values to sub-objects. Sub-values may themselves be compound values,
2371
994
  // and in this case the procedure becomes recursive.
2372
994
  // FIXME: The annoying part about compound values is that they don't carry
2373
994
  // any sort of information about which value corresponds to which sub-object.
2374
994
  // It's simply a list of values in the middle of nowhere; we expect to match
2375
994
  // them to sub-objects, essentially, "by index": first value binds to
2376
994
  // the first field, second value binds to the second field, etc.
2377
994
  // It would have been much safer to organize non-lazy compound values as
2378
994
  // a mapping from fields/bases to values.
2379
994
  const nonloc::CompoundVal& CV = V.castAs<nonloc::CompoundVal>();
2380
994
  nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
2381
994
2382
994
  RegionBindingsRef NewB(B);
2383
994
2384
994
  // In C++17 aggregates may have base classes, handle those as well.
2385
994
  // They appear before fields in the initializer list / compound value.
2386
994
  if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
2387
768
    // If the object was constructed with a constructor, its value is a
2388
768
    // LazyCompoundVal. If it's a raw CompoundVal, it means that we're
2389
768
    // performing aggregate initialization. The only exception from this
2390
768
    // rule is sending an Objective-C++ message that returns a C++ object
2391
768
    // to a nil receiver; in this case the semantics is to return a
2392
768
    // zero-initialized object even if it's a C++ object that doesn't have
2393
768
    // this sort of constructor; the CompoundVal is empty in this case.
2394
768
    assert((CRD->isAggregate() || (Ctx.getLangOpts().ObjC && VI == VE)) &&
2395
768
           "Non-aggregates are constructed with a constructor!");
2396
768
2397
768
    for (const auto &B : CRD->bases()) {
2398
66
      // (Multiple inheritance is fine though.)
2399
66
      assert(!B.isVirtual() && "Aggregates cannot have virtual base classes!");
2400
66
2401
66
      if (VI == VE)
2402
0
        break;
2403
66
2404
66
      QualType BTy = B.getType();
2405
66
      assert(BTy->isStructureOrClassType() && "Base classes must be classes!");
2406
66
2407
66
      const CXXRecordDecl *BRD = BTy->getAsCXXRecordDecl();
2408
66
      assert(BRD && "Base classes must be C++ classes!");
2409
66
2410
66
      const CXXBaseObjectRegion *BR =
2411
66
          MRMgr.getCXXBaseObjectRegion(BRD, R, /*IsVirtual=*/false);
2412
66
2413
66
      NewB = bindStruct(NewB, BR, *VI);
2414
66
2415
66
      ++VI;
2416
66
    }
2417
768
  }
2418
994
2419
994
  RecordDecl::field_iterator FI, FE;
2420
994
2421
1.92k
  for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; 
++FI930
) {
2422
937
2423
937
    if (VI == VE)
2424
7
      break;
2425
930
2426
930
    // Skip any unnamed bitfields to stay in sync with the initializers.
2427
930
    if (FI->isUnnamedBitfield())
2428
4
      continue;
2429
926
2430
926
    QualType FTy = FI->getType();
2431
926
    const FieldRegion* FR = MRMgr.getFieldRegion(*FI, R);
2432
926
2433
926
    if (FTy->isArrayType())
2434
140
      NewB = bindArray(NewB, FR, *VI);
2435
786
    else if (FTy->isStructureOrClassType())
2436
45
      NewB = bindStruct(NewB, FR, *VI);
2437
741
    else
2438
741
      NewB = bind(NewB, loc::MemRegionVal(FR), *VI);
2439
926
    ++VI;
2440
926
  }
2441
994
2442
994
  // There may be fewer values in the initialize list than the fields of struct.
2443
994
  if (FI != FE) {
2444
7
    NewB = NewB.addBinding(R, BindingKey::Default,
2445
7
                           svalBuilder.makeIntVal(0, false));
2446
7
  }
2447
994
2448
994
  return NewB;
2449
994
}
2450
2451
RegionBindingsRef
2452
RegionStoreManager::bindAggregate(RegionBindingsConstRef B,
2453
                                  const TypedRegion *R,
2454
4.04k
                                  SVal Val) {
2455
4.04k
  // Remove the old bindings, using 'R' as the root of all regions
2456
4.04k
  // we will invalidate. Then add the new binding.
2457
4.04k
  return removeSubRegionBindings(B, R).addBinding(R, BindingKey::Default, Val);
2458
4.04k
}
2459
2460
//===----------------------------------------------------------------------===//
2461
// State pruning.
2462
//===----------------------------------------------------------------------===//
2463
2464
namespace {
2465
class RemoveDeadBindingsWorker
2466
    : public ClusterAnalysis<RemoveDeadBindingsWorker> {
2467
  SmallVector<const SymbolicRegion *, 12> Postponed;
2468
  SymbolReaper &SymReaper;
2469
  const StackFrameContext *CurrentLCtx;
2470
2471
public:
2472
  RemoveDeadBindingsWorker(RegionStoreManager &rm,
2473
                           ProgramStateManager &stateMgr,
2474
                           RegionBindingsRef b, SymbolReaper &symReaper,
2475
                           const StackFrameContext *LCtx)
2476
    : ClusterAnalysis<RemoveDeadBindingsWorker>(rm, stateMgr, b),
2477
470k
      SymReaper(symReaper), CurrentLCtx(LCtx) {}
2478
2479
  // Called by ClusterAnalysis.
2480
  void VisitAddedToCluster(const MemRegion *baseR, const ClusterBindings &C);
2481
  void VisitCluster(const MemRegion *baseR, const ClusterBindings *C);
2482
  using ClusterAnalysis<RemoveDeadBindingsWorker>::VisitCluster;
2483
2484
  using ClusterAnalysis::AddToWorkList;
2485
2486
  bool AddToWorkList(const MemRegion *R);
2487
2488
  bool UpdatePostponed();
2489
  void VisitBinding(SVal V);
2490
};
2491
}
2492
2493
2.01M
bool RemoveDeadBindingsWorker::AddToWorkList(const MemRegion *R) {
2494
2.01M
  const MemRegion *BaseR = R->getBaseRegion();
2495
2.01M
  return AddToWorkList(WorkListElement(BaseR), getCluster(BaseR));
2496
2.01M
}
2497
2498
void RemoveDeadBindingsWorker::VisitAddedToCluster(const MemRegion *baseR,
2499
2.11M
                                                   const ClusterBindings &C) {
2500
2.11M
2501
2.11M
  if (const VarRegion *VR = dyn_cast<VarRegion>(baseR)) {
2502
919k
    if (SymReaper.isLive(VR))
2503
751k
      AddToWorkList(baseR, &C);
2504
919k
2505
919k
    return;
2506
919k
  }
2507
1.19M
2508
1.19M
  if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(baseR)) {
2509
53.8k
    if (SymReaper.isLive(SR->getSymbol()))
2510
43.6k
      AddToWorkList(SR, &C);
2511
10.2k
    else
2512
10.2k
      Postponed.push_back(SR);
2513
53.8k
2514
53.8k
    return;
2515
53.8k
  }
2516
1.14M
2517
1.14M
  if (isa<NonStaticGlobalSpaceRegion>(baseR)) {
2518
723k
    AddToWorkList(baseR, &C);
2519
723k
    return;
2520
723k
  }
2521
420k
2522
420k
  // CXXThisRegion in the current or parent location context is live.
2523
420k
  if (const CXXThisRegion *TR = dyn_cast<CXXThisRegion>(baseR)) {
2524
346k
    const auto *StackReg =
2525
346k
        cast<StackArgumentsSpaceRegion>(TR->getSuperRegion());
2526
346k
    const StackFrameContext *RegCtx = StackReg->getStackFrame();
2527
346k
    if (CurrentLCtx &&
2528
346k
        
(346k
RegCtx == CurrentLCtx346k
||
RegCtx->isParentOf(CurrentLCtx)217k
))
2529
295k
      AddToWorkList(TR, &C);
2530
346k
  }
2531
420k
}
2532
2533
void RemoveDeadBindingsWorker::VisitCluster(const MemRegion *baseR,
2534
3.08M
                                            const ClusterBindings *C) {
2535
3.08M
  if (!C)
2536
1.15M
    return;
2537
1.93M
2538
1.93M
  // Mark the symbol for any SymbolicRegion with live bindings as live itself.
2539
1.93M
  // This means we should continue to track that symbol.
2540
1.93M
  if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(baseR))
2541
47.4k
    SymReaper.markLive(SymR->getSymbol());
2542
1.93M
2543
4.19M
  for (ClusterBindings::iterator I = C->begin(), E = C->end(); I != E; 
++I2.26M
) {
2544
2.26M
    // Element index of a binding key is live.
2545
2.26M
    SymReaper.markElementIndicesLive(I.getKey().getRegion());
2546
2.26M
2547
2.26M
    VisitBinding(I.getData());
2548
2.26M
  }
2549
1.93M
}
2550
2551
2.26M
void RemoveDeadBindingsWorker::VisitBinding(SVal V) {
2552
2.26M
  // Is it a LazyCompoundVal?  All referenced regions are live as well.
2553
2.26M
  if (Optional<nonloc::LazyCompoundVal> LCS =
2554
4.43k
          V.getAs<nonloc::LazyCompoundVal>()) {
2555
4.43k
2556
4.43k
    const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS);
2557
4.43k
2558
4.43k
    for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(),
2559
4.43k
                                                        E = Vals.end();
2560
4.82k
         I != E; 
++I395
)
2561
395
      VisitBinding(*I);
2562
4.43k
2563
4.43k
    return;
2564
4.43k
  }
2565
2.26M
2566
2.26M
  // If V is a region, then add it to the worklist.
2567
2.26M
  if (const MemRegion *R = V.getAsRegion()) {
2568
717k
    AddToWorkList(R);
2569
717k
    SymReaper.markLive(R);
2570
717k
2571
717k
    // All regions captured by a block are also live.
2572
717k
    if (const BlockDataRegion *BR = dyn_cast<BlockDataRegion>(R)) {
2573
605
      BlockDataRegion::referenced_vars_iterator I = BR->referenced_vars_begin(),
2574
605
                                                E = BR->referenced_vars_end();
2575
1.16k
      for ( ; I != E; 
++I563
)
2576
563
        AddToWorkList(I.getCapturedRegion());
2577
605
    }
2578
717k
  }
2579
2.26M
2580
2.26M
2581
2.26M
  // Update the set of live symbols.
2582
3.55M
  for (auto SI = V.symbol_begin(), SE = V.symbol_end(); SI!=SE; 
++SI1.28M
)
2583
1.28M
    SymReaper.markLive(*SI);
2584
2.26M
}
2585
2586
471k
bool RemoveDeadBindingsWorker::UpdatePostponed() {
2587
471k
  // See if any postponed SymbolicRegions are actually live now, after
2588
471k
  // having done a scan.
2589
471k
  bool Changed = false;
2590
471k
2591
483k
  for (auto I = Postponed.begin(), E = Postponed.end(); I != E; 
++I12.1k
) {
2592
12.1k
    if (const SymbolicRegion *SR = *I) {
2593
10.4k
      if (SymReaper.isLive(SR->getSymbol())) {
2594
3.84k
        Changed |= AddToWorkList(SR);
2595
3.84k
        *I = nullptr;
2596
3.84k
      }
2597
10.4k
    }
2598
12.1k
  }
2599
471k
2600
471k
  return Changed;
2601
471k
}
2602
2603
StoreRef RegionStoreManager::removeDeadBindings(Store store,
2604
                                                const StackFrameContext *LCtx,
2605
470k
                                                SymbolReaper& SymReaper) {
2606
470k
  RegionBindingsRef B = getRegionBindings(store);
2607
470k
  RemoveDeadBindingsWorker W(*this, StateMgr, B, SymReaper, LCtx);
2608
470k
  W.GenerateClusters();
2609
470k
2610
470k
  // Enqueue the region roots onto the worklist.
2611
470k
  for (SymbolReaper::region_iterator I = SymReaper.region_begin(),
2612
1.76M
       E = SymReaper.region_end(); I != E; 
++I1.29M
) {
2613
1.29M
    W.AddToWorkList(*I);
2614
1.29M
  }
2615
470k
2616
471k
  do W.RunWorkList(); while (W.UpdatePostponed());
2617
470k
2618
470k
  // We have now scanned the store, marking reachable regions and symbols
2619
470k
  // as live.  We now remove all the regions that are dead from the store
2620
470k
  // as well as update DSymbols with the set symbols that are now dead.
2621
2.58M
  for (RegionBindingsRef::iterator I = B.begin(), E = B.end(); I != E; 
++I2.11M
) {
2622
2.11M
    const MemRegion *Base = I.getKey();
2623
2.11M
2624
2.11M
    // If the cluster has been visited, we know the region has been marked.
2625
2.11M
    // Otherwise, remove the dead entry.
2626
2.11M
    if (!W.isVisited(Base))
2627
187k
      B = B.remove(Base);
2628
2.11M
  }
2629
470k
2630
470k
  return StoreRef(B.asStore(), *this);
2631
470k
}
2632
2633
//===----------------------------------------------------------------------===//
2634
// Utility methods.
2635
//===----------------------------------------------------------------------===//
2636
2637
void RegionStoreManager::printJson(raw_ostream &Out, Store S, const char *NL,
2638
107
                                   unsigned int Space, bool IsDot) const {
2639
107
  RegionBindingsRef Bindings = getRegionBindings(S);
2640
107
2641
107
  Indent(Out, Space, IsDot) << "\"store\": ";
2642
107
2643
107
  if (Bindings.isEmpty()) {
2644
32
    Out << "null," << NL;
2645
32
    return;
2646
32
  }
2647
75
2648
75
  Out << "{ \"pointer\": \"" << Bindings.asStore() << "\", \"items\": [" << NL;
2649
75
  Bindings.printJson(Out, NL, Space + 1, IsDot);
2650
75
  Indent(Out, Space, IsDot) << "]}," << NL;
2651
75
}