Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
Warning:line 957, column 36
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name MemRegion.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/StaticAnalyzer/Core -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/StaticAnalyzer/Core -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/StaticAnalyzer/Core/MemRegion.cpp
1//===- MemRegion.cpp - Abstract memory regions for static analysis --------===//
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 MemRegion and its subclasses. MemRegion defines a
10// partially-typed abstraction of memory useful for path-sensitive dataflow
11// analyses.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/PrettyPrinter.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/AST/Type.h"
26#include "clang/Analysis/AnalysisDeclContext.h"
27#include "clang/Analysis/Support/BumpVector.h"
28#include "clang/Basic/IdentifierTable.h"
29#include "clang/Basic/LLVM.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
32#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
33#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
34#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
35#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
36#include "llvm/ADT/APInt.h"
37#include "llvm/ADT/FoldingSet.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/SmallString.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/Twine.h"
43#include "llvm/Support/Allocator.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/CheckedArithmetic.h"
46#include "llvm/Support/Compiler.h"
47#include "llvm/Support/Debug.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/raw_ostream.h"
50#include <cassert>
51#include <cstdint>
52#include <functional>
53#include <iterator>
54#include <string>
55#include <tuple>
56#include <utility>
57
58using namespace clang;
59using namespace ento;
60
61#define DEBUG_TYPE"MemRegion" "MemRegion"
62
63//===----------------------------------------------------------------------===//
64// MemRegion Construction.
65//===----------------------------------------------------------------------===//
66
67template <typename RegionTy, typename SuperTy, typename Arg1Ty>
68RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
69 const SuperTy *superRegion) {
70 llvm::FoldingSetNodeID ID;
71 RegionTy::ProfileRegion(ID, arg1, superRegion);
72 void *InsertPos;
73 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
74
75 if (!R) {
76 R = A.Allocate<RegionTy>();
77 new (R) RegionTy(arg1, superRegion);
78 Regions.InsertNode(R, InsertPos);
79 }
80
81 return R;
82}
83
84template <typename RegionTy, typename SuperTy, typename Arg1Ty, typename Arg2Ty>
85RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
86 const SuperTy *superRegion) {
87 llvm::FoldingSetNodeID ID;
88 RegionTy::ProfileRegion(ID, arg1, arg2, superRegion);
89 void *InsertPos;
90 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
91
92 if (!R) {
93 R = A.Allocate<RegionTy>();
94 new (R) RegionTy(arg1, arg2, superRegion);
95 Regions.InsertNode(R, InsertPos);
96 }
97
98 return R;
99}
100
101template <typename RegionTy, typename SuperTy,
102 typename Arg1Ty, typename Arg2Ty, typename Arg3Ty>
103RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
104 const Arg3Ty arg3,
105 const SuperTy *superRegion) {
106 llvm::FoldingSetNodeID ID;
107 RegionTy::ProfileRegion(ID, arg1, arg2, arg3, superRegion);
108 void *InsertPos;
109 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
110
111 if (!R) {
112 R = A.Allocate<RegionTy>();
113 new (R) RegionTy(arg1, arg2, arg3, superRegion);
114 Regions.InsertNode(R, InsertPos);
115 }
116
117 return R;
118}
119
120//===----------------------------------------------------------------------===//
121// Object destruction.
122//===----------------------------------------------------------------------===//
123
124MemRegion::~MemRegion() = default;
125
126// All regions and their data are BumpPtrAllocated. No need to call their
127// destructors.
128MemRegionManager::~MemRegionManager() = default;
129
130//===----------------------------------------------------------------------===//
131// Basic methods.
132//===----------------------------------------------------------------------===//
133
134bool SubRegion::isSubRegionOf(const MemRegion* R) const {
135 const MemRegion* r = this;
136 do {
137 if (r == R)
138 return true;
139 if (const auto *sr = dyn_cast<SubRegion>(r))
140 r = sr->getSuperRegion();
141 else
142 break;
143 } while (r != nullptr);
144 return false;
145}
146
147MemRegionManager &SubRegion::getMemRegionManager() const {
148 const SubRegion* r = this;
149 do {
150 const MemRegion *superRegion = r->getSuperRegion();
151 if (const auto *sr = dyn_cast<SubRegion>(superRegion)) {
152 r = sr;
153 continue;
154 }
155 return superRegion->getMemRegionManager();
156 } while (true);
157}
158
159const StackFrameContext *VarRegion::getStackFrame() const {
160 const auto *SSR = dyn_cast<StackSpaceRegion>(getMemorySpace());
161 return SSR ? SSR->getStackFrame() : nullptr;
162}
163
164ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, const SubRegion *sReg)
165 : DeclRegion(sReg, ObjCIvarRegionKind), IVD(ivd) {
166 assert(IVD)(static_cast <bool> (IVD) ? void (0) : __assert_fail ("IVD"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 166, __extension__
__PRETTY_FUNCTION__))
;
167}
168
169const ObjCIvarDecl *ObjCIvarRegion::getDecl() const { return IVD; }
170
171QualType ObjCIvarRegion::getValueType() const {
172 return getDecl()->getType();
173}
174
175QualType CXXBaseObjectRegion::getValueType() const {
176 return QualType(getDecl()->getTypeForDecl(), 0);
177}
178
179QualType CXXDerivedObjectRegion::getValueType() const {
180 return QualType(getDecl()->getTypeForDecl(), 0);
181}
182
183QualType ParamVarRegion::getValueType() const {
184 assert(getDecl() &&(static_cast <bool> (getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 186, __extension__
__PRETTY_FUNCTION__))
185 "`ParamVarRegion` support functions without `Decl` not implemented"(static_cast <bool> (getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 186, __extension__
__PRETTY_FUNCTION__))
186 " yet.")(static_cast <bool> (getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 186, __extension__
__PRETTY_FUNCTION__))
;
187 return getDecl()->getType();
188}
189
190const ParmVarDecl *ParamVarRegion::getDecl() const {
191 const Decl *D = getStackFrame()->getDecl();
192
193 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
194 assert(Index < FD->param_size())(static_cast <bool> (Index < FD->param_size()) ? void
(0) : __assert_fail ("Index < FD->param_size()", "clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 194, __extension__ __PRETTY_FUNCTION__))
;
195 return FD->parameters()[Index];
196 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
197 assert(Index < BD->param_size())(static_cast <bool> (Index < BD->param_size()) ? void
(0) : __assert_fail ("Index < BD->param_size()", "clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 197, __extension__ __PRETTY_FUNCTION__))
;
198 return BD->parameters()[Index];
199 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
200 assert(Index < MD->param_size())(static_cast <bool> (Index < MD->param_size()) ? void
(0) : __assert_fail ("Index < MD->param_size()", "clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 200, __extension__ __PRETTY_FUNCTION__))
;
201 return MD->parameters()[Index];
202 } else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
203 assert(Index < CD->param_size())(static_cast <bool> (Index < CD->param_size()) ? void
(0) : __assert_fail ("Index < CD->param_size()", "clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 203, __extension__ __PRETTY_FUNCTION__))
;
204 return CD->parameters()[Index];
205 } else {
206 llvm_unreachable("Unexpected Decl kind!")::llvm::llvm_unreachable_internal("Unexpected Decl kind!", "clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 206)
;
207 }
208}
209
210//===----------------------------------------------------------------------===//
211// FoldingSet profiling.
212//===----------------------------------------------------------------------===//
213
214void MemSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
215 ID.AddInteger(static_cast<unsigned>(getKind()));
216}
217
218void StackSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
219 ID.AddInteger(static_cast<unsigned>(getKind()));
220 ID.AddPointer(getStackFrame());
221}
222
223void StaticGlobalSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
224 ID.AddInteger(static_cast<unsigned>(getKind()));
225 ID.AddPointer(getCodeRegion());
226}
227
228void StringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
229 const StringLiteral *Str,
230 const MemRegion *superRegion) {
231 ID.AddInteger(static_cast<unsigned>(StringRegionKind));
232 ID.AddPointer(Str);
233 ID.AddPointer(superRegion);
234}
235
236void ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
237 const ObjCStringLiteral *Str,
238 const MemRegion *superRegion) {
239 ID.AddInteger(static_cast<unsigned>(ObjCStringRegionKind));
240 ID.AddPointer(Str);
241 ID.AddPointer(superRegion);
242}
243
244void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
245 const Expr *Ex, unsigned cnt,
246 const MemRegion *superRegion) {
247 ID.AddInteger(static_cast<unsigned>(AllocaRegionKind));
248 ID.AddPointer(Ex);
249 ID.AddInteger(cnt);
250 ID.AddPointer(superRegion);
251}
252
253void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
254 ProfileRegion(ID, Ex, Cnt, superRegion);
255}
256
257void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
258 CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
259}
260
261void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
262 const CompoundLiteralExpr *CL,
263 const MemRegion* superRegion) {
264 ID.AddInteger(static_cast<unsigned>(CompoundLiteralRegionKind));
265 ID.AddPointer(CL);
266 ID.AddPointer(superRegion);
267}
268
269void CXXThisRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
270 const PointerType *PT,
271 const MemRegion *sRegion) {
272 ID.AddInteger(static_cast<unsigned>(CXXThisRegionKind));
273 ID.AddPointer(PT);
274 ID.AddPointer(sRegion);
275}
276
277void CXXThisRegion::Profile(llvm::FoldingSetNodeID &ID) const {
278 CXXThisRegion::ProfileRegion(ID, ThisPointerTy, superRegion);
279}
280
281void FieldRegion::Profile(llvm::FoldingSetNodeID &ID) const {
282 ProfileRegion(ID, getDecl(), superRegion);
283}
284
285void ObjCIvarRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
286 const ObjCIvarDecl *ivd,
287 const MemRegion* superRegion) {
288 ID.AddInteger(static_cast<unsigned>(ObjCIvarRegionKind));
289 ID.AddPointer(ivd);
290 ID.AddPointer(superRegion);
291}
292
293void ObjCIvarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
294 ProfileRegion(ID, getDecl(), superRegion);
295}
296
297void NonParamVarRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
298 const VarDecl *VD,
299 const MemRegion *superRegion) {
300 ID.AddInteger(static_cast<unsigned>(NonParamVarRegionKind));
301 ID.AddPointer(VD);
302 ID.AddPointer(superRegion);
303}
304
305void NonParamVarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
306 ProfileRegion(ID, getDecl(), superRegion);
307}
308
309void ParamVarRegion::ProfileRegion(llvm::FoldingSetNodeID &ID, const Expr *OE,
310 unsigned Idx, const MemRegion *SReg) {
311 ID.AddInteger(static_cast<unsigned>(ParamVarRegionKind));
312 ID.AddPointer(OE);
313 ID.AddInteger(Idx);
314 ID.AddPointer(SReg);
315}
316
317void ParamVarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
318 ProfileRegion(ID, getOriginExpr(), getIndex(), superRegion);
319}
320
321void SymbolicRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym,
322 const MemRegion *sreg) {
323 ID.AddInteger(static_cast<unsigned>(MemRegion::SymbolicRegionKind));
324 ID.Add(sym);
325 ID.AddPointer(sreg);
326}
327
328void SymbolicRegion::Profile(llvm::FoldingSetNodeID& ID) const {
329 SymbolicRegion::ProfileRegion(ID, sym, getSuperRegion());
330}
331
332void ElementRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
333 QualType ElementType, SVal Idx,
334 const MemRegion* superRegion) {
335 ID.AddInteger(MemRegion::ElementRegionKind);
336 ID.Add(ElementType);
337 ID.AddPointer(superRegion);
338 Idx.Profile(ID);
339}
340
341void ElementRegion::Profile(llvm::FoldingSetNodeID& ID) const {
342 ElementRegion::ProfileRegion(ID, ElementType, Index, superRegion);
343}
344
345void FunctionCodeRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
346 const NamedDecl *FD,
347 const MemRegion*) {
348 ID.AddInteger(MemRegion::FunctionCodeRegionKind);
349 ID.AddPointer(FD);
350}
351
352void FunctionCodeRegion::Profile(llvm::FoldingSetNodeID& ID) const {
353 FunctionCodeRegion::ProfileRegion(ID, FD, superRegion);
354}
355
356void BlockCodeRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
357 const BlockDecl *BD, CanQualType,
358 const AnalysisDeclContext *AC,
359 const MemRegion*) {
360 ID.AddInteger(MemRegion::BlockCodeRegionKind);
361 ID.AddPointer(BD);
362}
363
364void BlockCodeRegion::Profile(llvm::FoldingSetNodeID& ID) const {
365 BlockCodeRegion::ProfileRegion(ID, BD, locTy, AC, superRegion);
366}
367
368void BlockDataRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
369 const BlockCodeRegion *BC,
370 const LocationContext *LC,
371 unsigned BlkCount,
372 const MemRegion *sReg) {
373 ID.AddInteger(MemRegion::BlockDataRegionKind);
374 ID.AddPointer(BC);
375 ID.AddPointer(LC);
376 ID.AddInteger(BlkCount);
377 ID.AddPointer(sReg);
378}
379
380void BlockDataRegion::Profile(llvm::FoldingSetNodeID& ID) const {
381 BlockDataRegion::ProfileRegion(ID, BC, LC, BlockCount, getSuperRegion());
382}
383
384void CXXTempObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
385 Expr const *Ex,
386 const MemRegion *sReg) {
387 ID.AddPointer(Ex);
388 ID.AddPointer(sReg);
389}
390
391void CXXTempObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
392 ProfileRegion(ID, Ex, getSuperRegion());
393}
394
395void CXXBaseObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
396 const CXXRecordDecl *RD,
397 bool IsVirtual,
398 const MemRegion *SReg) {
399 ID.AddPointer(RD);
400 ID.AddBoolean(IsVirtual);
401 ID.AddPointer(SReg);
402}
403
404void CXXBaseObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
405 ProfileRegion(ID, getDecl(), isVirtual(), superRegion);
406}
407
408void CXXDerivedObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
409 const CXXRecordDecl *RD,
410 const MemRegion *SReg) {
411 ID.AddPointer(RD);
412 ID.AddPointer(SReg);
413}
414
415void CXXDerivedObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
416 ProfileRegion(ID, getDecl(), superRegion);
417}
418
419//===----------------------------------------------------------------------===//
420// Region anchors.
421//===----------------------------------------------------------------------===//
422
423void GlobalsSpaceRegion::anchor() {}
424
425void NonStaticGlobalSpaceRegion::anchor() {}
426
427void StackSpaceRegion::anchor() {}
428
429void TypedRegion::anchor() {}
430
431void TypedValueRegion::anchor() {}
432
433void CodeTextRegion::anchor() {}
434
435void SubRegion::anchor() {}
436
437//===----------------------------------------------------------------------===//
438// Region pretty-printing.
439//===----------------------------------------------------------------------===//
440
441LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void MemRegion::dump() const {
442 dumpToStream(llvm::errs());
443}
444
445std::string MemRegion::getString() const {
446 std::string s;
447 llvm::raw_string_ostream os(s);
448 dumpToStream(os);
449 return s;
450}
451
452void MemRegion::dumpToStream(raw_ostream &os) const {
453 os << "<Unknown Region>";
454}
455
456void AllocaRegion::dumpToStream(raw_ostream &os) const {
457 os << "alloca{S" << Ex->getID(getContext()) << ',' << Cnt << '}';
458}
459
460void FunctionCodeRegion::dumpToStream(raw_ostream &os) const {
461 os << "code{" << getDecl()->getDeclName().getAsString() << '}';
462}
463
464void BlockCodeRegion::dumpToStream(raw_ostream &os) const {
465 os << "block_code{" << static_cast<const void *>(this) << '}';
466}
467
468void BlockDataRegion::dumpToStream(raw_ostream &os) const {
469 os << "block_data{" << BC;
470 os << "; ";
471 for (BlockDataRegion::referenced_vars_iterator
472 I = referenced_vars_begin(),
473 E = referenced_vars_end(); I != E; ++I)
474 os << "(" << I.getCapturedRegion() << "<-" <<
475 I.getOriginalRegion() << ") ";
476 os << '}';
477}
478
479void CompoundLiteralRegion::dumpToStream(raw_ostream &os) const {
480 // FIXME: More elaborate pretty-printing.
481 os << "{ S" << CL->getID(getContext()) << " }";
482}
483
484void CXXTempObjectRegion::dumpToStream(raw_ostream &os) const {
485 os << "temp_object{" << getValueType() << ", "
486 << "S" << Ex->getID(getContext()) << '}';
487}
488
489void CXXBaseObjectRegion::dumpToStream(raw_ostream &os) const {
490 os << "Base{" << superRegion << ',' << getDecl()->getName() << '}';
491}
492
493void CXXDerivedObjectRegion::dumpToStream(raw_ostream &os) const {
494 os << "Derived{" << superRegion << ',' << getDecl()->getName() << '}';
495}
496
497void CXXThisRegion::dumpToStream(raw_ostream &os) const {
498 os << "this";
499}
500
501void ElementRegion::dumpToStream(raw_ostream &os) const {
502 os << "Element{" << superRegion << ',' << Index << ',' << getElementType()
503 << '}';
504}
505
506void FieldRegion::dumpToStream(raw_ostream &os) const {
507 os << superRegion << "." << *getDecl();
508}
509
510void ObjCIvarRegion::dumpToStream(raw_ostream &os) const {
511 os << "Ivar{" << superRegion << ',' << *getDecl() << '}';
512}
513
514void StringRegion::dumpToStream(raw_ostream &os) const {
515 assert(Str != nullptr && "Expecting non-null StringLiteral")(static_cast <bool> (Str != nullptr && "Expecting non-null StringLiteral"
) ? void (0) : __assert_fail ("Str != nullptr && \"Expecting non-null StringLiteral\""
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 515, __extension__
__PRETTY_FUNCTION__))
;
516 Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts()));
517}
518
519void ObjCStringRegion::dumpToStream(raw_ostream &os) const {
520 assert(Str != nullptr && "Expecting non-null ObjCStringLiteral")(static_cast <bool> (Str != nullptr && "Expecting non-null ObjCStringLiteral"
) ? void (0) : __assert_fail ("Str != nullptr && \"Expecting non-null ObjCStringLiteral\""
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 520, __extension__
__PRETTY_FUNCTION__))
;
521 Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts()));
522}
523
524void SymbolicRegion::dumpToStream(raw_ostream &os) const {
525 if (isa<HeapSpaceRegion>(getSuperRegion()))
526 os << "Heap";
527 os << "SymRegion{" << sym << '}';
528}
529
530void NonParamVarRegion::dumpToStream(raw_ostream &os) const {
531 if (const IdentifierInfo *ID = VD->getIdentifier())
532 os << ID->getName();
533 else
534 os << "NonParamVarRegion{D" << VD->getID() << '}';
535}
536
537LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RegionRawOffset::dump() const {
538 dumpToStream(llvm::errs());
539}
540
541void RegionRawOffset::dumpToStream(raw_ostream &os) const {
542 os << "raw_offset{" << getRegion() << ',' << getOffset().getQuantity() << '}';
543}
544
545void CodeSpaceRegion::dumpToStream(raw_ostream &os) const {
546 os << "CodeSpaceRegion";
547}
548
549void StaticGlobalSpaceRegion::dumpToStream(raw_ostream &os) const {
550 os << "StaticGlobalsMemSpace{" << CR << '}';
551}
552
553void GlobalInternalSpaceRegion::dumpToStream(raw_ostream &os) const {
554 os << "GlobalInternalSpaceRegion";
555}
556
557void GlobalSystemSpaceRegion::dumpToStream(raw_ostream &os) const {
558 os << "GlobalSystemSpaceRegion";
559}
560
561void GlobalImmutableSpaceRegion::dumpToStream(raw_ostream &os) const {
562 os << "GlobalImmutableSpaceRegion";
563}
564
565void HeapSpaceRegion::dumpToStream(raw_ostream &os) const {
566 os << "HeapSpaceRegion";
567}
568
569void UnknownSpaceRegion::dumpToStream(raw_ostream &os) const {
570 os << "UnknownSpaceRegion";
571}
572
573void StackArgumentsSpaceRegion::dumpToStream(raw_ostream &os) const {
574 os << "StackArgumentsSpaceRegion";
575}
576
577void StackLocalsSpaceRegion::dumpToStream(raw_ostream &os) const {
578 os << "StackLocalsSpaceRegion";
579}
580
581void ParamVarRegion::dumpToStream(raw_ostream &os) const {
582 const ParmVarDecl *PVD = getDecl();
583 assert(PVD &&(static_cast <bool> (PVD && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("PVD && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 585, __extension__
__PRETTY_FUNCTION__))
584 "`ParamVarRegion` support functions without `Decl` not implemented"(static_cast <bool> (PVD && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("PVD && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 585, __extension__
__PRETTY_FUNCTION__))
585 " yet.")(static_cast <bool> (PVD && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("PVD && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 585, __extension__
__PRETTY_FUNCTION__))
;
586 if (const IdentifierInfo *ID = PVD->getIdentifier()) {
587 os << ID->getName();
588 } else {
589 os << "ParamVarRegion{P" << PVD->getID() << '}';
590 }
591}
592
593bool MemRegion::canPrintPretty() const {
594 return canPrintPrettyAsExpr();
595}
596
597bool MemRegion::canPrintPrettyAsExpr() const {
598 return false;
599}
600
601void MemRegion::printPretty(raw_ostream &os) const {
602 assert(canPrintPretty() && "This region cannot be printed pretty.")(static_cast <bool> (canPrintPretty() && "This region cannot be printed pretty."
) ? void (0) : __assert_fail ("canPrintPretty() && \"This region cannot be printed pretty.\""
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 602, __extension__
__PRETTY_FUNCTION__))
;
603 os << "'";
604 printPrettyAsExpr(os);
605 os << "'";
606}
607
608void MemRegion::printPrettyAsExpr(raw_ostream &) const {
609 llvm_unreachable("This region cannot be printed pretty.")::llvm::llvm_unreachable_internal("This region cannot be printed pretty."
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 609)
;
610}
611
612bool NonParamVarRegion::canPrintPrettyAsExpr() const { return true; }
613
614void NonParamVarRegion::printPrettyAsExpr(raw_ostream &os) const {
615 os << getDecl()->getName();
616}
617
618bool ParamVarRegion::canPrintPrettyAsExpr() const { return true; }
619
620void ParamVarRegion::printPrettyAsExpr(raw_ostream &os) const {
621 assert(getDecl() &&(static_cast <bool> (getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 623, __extension__
__PRETTY_FUNCTION__))
622 "`ParamVarRegion` support functions without `Decl` not implemented"(static_cast <bool> (getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 623, __extension__
__PRETTY_FUNCTION__))
623 " yet.")(static_cast <bool> (getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 623, __extension__
__PRETTY_FUNCTION__))
;
624 os << getDecl()->getName();
625}
626
627bool ObjCIvarRegion::canPrintPrettyAsExpr() const {
628 return true;
629}
630
631void ObjCIvarRegion::printPrettyAsExpr(raw_ostream &os) const {
632 os << getDecl()->getName();
633}
634
635bool FieldRegion::canPrintPretty() const {
636 return true;
637}
638
639bool FieldRegion::canPrintPrettyAsExpr() const {
640 return superRegion->canPrintPrettyAsExpr();
641}
642
643void FieldRegion::printPrettyAsExpr(raw_ostream &os) const {
644 assert(canPrintPrettyAsExpr())(static_cast <bool> (canPrintPrettyAsExpr()) ? void (0)
: __assert_fail ("canPrintPrettyAsExpr()", "clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 644, __extension__ __PRETTY_FUNCTION__))
;
645 superRegion->printPrettyAsExpr(os);
646 os << "." << getDecl()->getName();
647}
648
649void FieldRegion::printPretty(raw_ostream &os) const {
650 if (canPrintPrettyAsExpr()) {
651 os << "\'";
652 printPrettyAsExpr(os);
653 os << "'";
654 } else {
655 os << "field " << "\'" << getDecl()->getName() << "'";
656 }
657}
658
659bool CXXBaseObjectRegion::canPrintPrettyAsExpr() const {
660 return superRegion->canPrintPrettyAsExpr();
661}
662
663void CXXBaseObjectRegion::printPrettyAsExpr(raw_ostream &os) const {
664 superRegion->printPrettyAsExpr(os);
665}
666
667bool CXXDerivedObjectRegion::canPrintPrettyAsExpr() const {
668 return superRegion->canPrintPrettyAsExpr();
669}
670
671void CXXDerivedObjectRegion::printPrettyAsExpr(raw_ostream &os) const {
672 superRegion->printPrettyAsExpr(os);
673}
674
675std::string MemRegion::getDescriptiveName(bool UseQuotes) const {
676 std::string VariableName;
677 std::string ArrayIndices;
678 const MemRegion *R = this;
679 SmallString<50> buf;
680 llvm::raw_svector_ostream os(buf);
681
682 // Obtain array indices to add them to the variable name.
683 const ElementRegion *ER = nullptr;
684 while ((ER = R->getAs<ElementRegion>())) {
685 // Index is a ConcreteInt.
686 if (auto CI = ER->getIndex().getAs<nonloc::ConcreteInt>()) {
687 llvm::SmallString<2> Idx;
688 CI->getValue().toString(Idx);
689 ArrayIndices = (llvm::Twine("[") + Idx.str() + "]" + ArrayIndices).str();
690 }
691 // If not a ConcreteInt, try to obtain the variable
692 // name by calling 'getDescriptiveName' recursively.
693 else {
694 std::string Idx = ER->getDescriptiveName(false);
695 if (!Idx.empty()) {
696 ArrayIndices = (llvm::Twine("[") + Idx + "]" + ArrayIndices).str();
697 }
698 }
699 R = ER->getSuperRegion();
700 }
701
702 // Get variable name.
703 if (R && R->canPrintPrettyAsExpr()) {
704 R->printPrettyAsExpr(os);
705 if (UseQuotes)
706 return (llvm::Twine("'") + os.str() + ArrayIndices + "'").str();
707 else
708 return (llvm::Twine(os.str()) + ArrayIndices).str();
709 }
710
711 return VariableName;
712}
713
714SourceRange MemRegion::sourceRange() const {
715 const auto *const VR = dyn_cast<VarRegion>(this->getBaseRegion());
716 const auto *const FR = dyn_cast<FieldRegion>(this);
717
718 // Check for more specific regions first.
719 // FieldRegion
720 if (FR) {
721 return FR->getDecl()->getSourceRange();
722 }
723 // VarRegion
724 else if (VR) {
725 return VR->getDecl()->getSourceRange();
726 }
727 // Return invalid source range (can be checked by client).
728 else
729 return {};
730}
731
732//===----------------------------------------------------------------------===//
733// MemRegionManager methods.
734//===----------------------------------------------------------------------===//
735
736DefinedOrUnknownSVal MemRegionManager::getStaticSize(const MemRegion *MR,
737 SValBuilder &SVB) const {
738 const auto *SR = cast<SubRegion>(MR);
739 SymbolManager &SymMgr = SVB.getSymbolManager();
740
741 switch (SR->getKind()) {
742 case MemRegion::AllocaRegionKind:
743 case MemRegion::SymbolicRegionKind:
744 return nonloc::SymbolVal(SymMgr.getExtentSymbol(SR));
745 case MemRegion::StringRegionKind:
746 return SVB.makeIntVal(
747 cast<StringRegion>(SR)->getStringLiteral()->getByteLength() + 1,
748 SVB.getArrayIndexType());
749 case MemRegion::CompoundLiteralRegionKind:
750 case MemRegion::CXXBaseObjectRegionKind:
751 case MemRegion::CXXDerivedObjectRegionKind:
752 case MemRegion::CXXTempObjectRegionKind:
753 case MemRegion::CXXThisRegionKind:
754 case MemRegion::ObjCIvarRegionKind:
755 case MemRegion::NonParamVarRegionKind:
756 case MemRegion::ParamVarRegionKind:
757 case MemRegion::ElementRegionKind:
758 case MemRegion::ObjCStringRegionKind: {
759 QualType Ty = cast<TypedValueRegion>(SR)->getDesugaredValueType(Ctx);
760 if (isa<VariableArrayType>(Ty))
761 return nonloc::SymbolVal(SymMgr.getExtentSymbol(SR));
762
763 if (Ty->isIncompleteType())
764 return UnknownVal();
765
766 return getElementExtent(Ty, SVB);
767 }
768 case MemRegion::FieldRegionKind: {
769 // Force callers to deal with bitfields explicitly.
770 if (cast<FieldRegion>(SR)->getDecl()->isBitField())
771 return UnknownVal();
772
773 QualType Ty = cast<TypedValueRegion>(SR)->getDesugaredValueType(Ctx);
774 const DefinedOrUnknownSVal Size = getElementExtent(Ty, SVB);
775
776 // We currently don't model flexible array members (FAMs), which are:
777 // - int array[]; of IncompleteArrayType
778 // - int array[0]; of ConstantArrayType with size 0
779 // - int array[1]; of ConstantArrayType with size 1 (*)
780 // (*): Consider single element array object members as FAM candidates only
781 // if the consider-single-element-arrays-as-flexible-array-members
782 // analyzer option is true.
783 // https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
784 const auto isFlexibleArrayMemberCandidate = [this,
785 &SVB](QualType Ty) -> bool {
786 const ArrayType *AT = Ctx.getAsArrayType(Ty);
787 if (!AT)
788 return false;
789 if (isa<IncompleteArrayType>(AT))
790 return true;
791
792 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
793 const llvm::APInt &Size = CAT->getSize();
794 if (Size.isZero())
795 return true;
796
797 if (getContext().getLangOpts().StrictFlexArrays >= 2)
798 return false;
799
800 const AnalyzerOptions &Opts = SVB.getAnalyzerOptions();
801 // FIXME: this option is probably redundant with -fstrict-flex-arrays=1.
802 if (Opts.ShouldConsiderSingleElementArraysAsFlexibleArrayMembers &&
803 Size.isOne())
804 return true;
805 }
806 return false;
807 };
808
809 if (isFlexibleArrayMemberCandidate(Ty))
810 return UnknownVal();
811
812 return Size;
813 }
814 // FIXME: The following are being used in 'SimpleSValBuilder' and in
815 // 'ArrayBoundChecker::checkLocation' because there is no symbol to
816 // represent the regions more appropriately.
817 case MemRegion::BlockDataRegionKind:
818 case MemRegion::BlockCodeRegionKind:
819 case MemRegion::FunctionCodeRegionKind:
820 return nonloc::SymbolVal(SymMgr.getExtentSymbol(SR));
821 default:
822 llvm_unreachable("Unhandled region")::llvm::llvm_unreachable_internal("Unhandled region", "clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 822)
;
823 }
824}
825
826template <typename REG>
827const REG *MemRegionManager::LazyAllocate(REG*& region) {
828 if (!region) {
829 region = A.Allocate<REG>();
830 new (region) REG(*this);
831 }
832
833 return region;
834}
835
836template <typename REG, typename ARG>
837const REG *MemRegionManager::LazyAllocate(REG*& region, ARG a) {
838 if (!region) {
839 region = A.Allocate<REG>();
840 new (region) REG(this, a);
841 }
842
843 return region;
844}
845
846const StackLocalsSpaceRegion*
847MemRegionManager::getStackLocalsRegion(const StackFrameContext *STC) {
848 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 848, __extension__
__PRETTY_FUNCTION__))
;
849 StackLocalsSpaceRegion *&R = StackLocalsSpaceRegions[STC];
850
851 if (R)
852 return R;
853
854 R = A.Allocate<StackLocalsSpaceRegion>();
855 new (R) StackLocalsSpaceRegion(*this, STC);
856 return R;
857}
858
859const StackArgumentsSpaceRegion *
860MemRegionManager::getStackArgumentsRegion(const StackFrameContext *STC) {
861 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 861, __extension__
__PRETTY_FUNCTION__))
;
862 StackArgumentsSpaceRegion *&R = StackArgumentsSpaceRegions[STC];
863
864 if (R)
865 return R;
866
867 R = A.Allocate<StackArgumentsSpaceRegion>();
868 new (R) StackArgumentsSpaceRegion(*this, STC);
869 return R;
870}
871
872const GlobalsSpaceRegion
873*MemRegionManager::getGlobalsRegion(MemRegion::Kind K,
874 const CodeTextRegion *CR) {
875 if (!CR) {
876 if (K == MemRegion::GlobalSystemSpaceRegionKind)
877 return LazyAllocate(SystemGlobals);
878 if (K == MemRegion::GlobalImmutableSpaceRegionKind)
879 return LazyAllocate(ImmutableGlobals);
880 assert(K == MemRegion::GlobalInternalSpaceRegionKind)(static_cast <bool> (K == MemRegion::GlobalInternalSpaceRegionKind
) ? void (0) : __assert_fail ("K == MemRegion::GlobalInternalSpaceRegionKind"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 880, __extension__
__PRETTY_FUNCTION__))
;
881 return LazyAllocate(InternalGlobals);
882 }
883
884 assert(K == MemRegion::StaticGlobalSpaceRegionKind)(static_cast <bool> (K == MemRegion::StaticGlobalSpaceRegionKind
) ? void (0) : __assert_fail ("K == MemRegion::StaticGlobalSpaceRegionKind"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 884, __extension__
__PRETTY_FUNCTION__))
;
885 StaticGlobalSpaceRegion *&R = StaticsGlobalSpaceRegions[CR];
886 if (R)
887 return R;
888
889 R = A.Allocate<StaticGlobalSpaceRegion>();
890 new (R) StaticGlobalSpaceRegion(*this, CR);
891 return R;
892}
893
894const HeapSpaceRegion *MemRegionManager::getHeapRegion() {
895 return LazyAllocate(heap);
896}
897
898const UnknownSpaceRegion *MemRegionManager::getUnknownRegion() {
899 return LazyAllocate(unknown);
900}
901
902const CodeSpaceRegion *MemRegionManager::getCodeRegion() {
903 return LazyAllocate(code);
904}
905
906//===----------------------------------------------------------------------===//
907// Constructing regions.
908//===----------------------------------------------------------------------===//
909
910const StringRegion *MemRegionManager::getStringRegion(const StringLiteral *Str){
911 return getSubRegion<StringRegion>(
912 Str, cast<GlobalInternalSpaceRegion>(getGlobalsRegion()));
913}
914
915const ObjCStringRegion *
916MemRegionManager::getObjCStringRegion(const ObjCStringLiteral *Str){
917 return getSubRegion<ObjCStringRegion>(
918 Str, cast<GlobalInternalSpaceRegion>(getGlobalsRegion()));
919}
920
921/// Look through a chain of LocationContexts to either find the
922/// StackFrameContext that matches a DeclContext, or find a VarRegion
923/// for a variable captured by a block.
924static llvm::PointerUnion<const StackFrameContext *, const VarRegion *>
925getStackOrCaptureRegionForDeclContext(const LocationContext *LC,
926 const DeclContext *DC,
927 const VarDecl *VD) {
928 while (LC) {
929 if (const auto *SFC = dyn_cast<StackFrameContext>(LC)) {
930 if (cast<DeclContext>(SFC->getDecl()) == DC)
931 return SFC;
932 }
933 if (const auto *BC = dyn_cast<BlockInvocationContext>(LC)) {
934 const auto *BR = static_cast<const BlockDataRegion *>(BC->getData());
935 // FIXME: This can be made more efficient.
936 for (BlockDataRegion::referenced_vars_iterator
937 I = BR->referenced_vars_begin(),
938 E = BR->referenced_vars_end(); I != E; ++I) {
939 const TypedValueRegion *OrigR = I.getOriginalRegion();
940 if (const auto *VR = dyn_cast<VarRegion>(OrigR)) {
941 if (VR->getDecl() == VD)
942 return cast<VarRegion>(I.getCapturedRegion());
943 }
944 }
945 }
946
947 LC = LC->getParent();
948 }
949 return (const StackFrameContext *)nullptr;
950}
951
952const VarRegion *MemRegionManager::getVarRegion(const VarDecl *D,
953 const LocationContext *LC) {
954 const auto *PVD = dyn_cast<ParmVarDecl>(D);
15
Assuming 'D' is a 'CastReturnType'
955 if (PVD
15.1
'PVD' is non-null
) {
16
Taking true branch
956 unsigned Index = PVD->getFunctionScopeIndex();
957 const StackFrameContext *SFC = LC->getStackFrame();
17
Called C++ object pointer is null
958 const Stmt *CallSite = SFC->getCallSite();
959 if (CallSite) {
960 const Decl *D = SFC->getDecl();
961 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
962 if (Index < FD->param_size() && FD->parameters()[Index] == PVD)
963 return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
964 getStackArgumentsRegion(SFC));
965 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
966 if (Index < BD->param_size() && BD->parameters()[Index] == PVD)
967 return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
968 getStackArgumentsRegion(SFC));
969 } else {
970 return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
971 getStackArgumentsRegion(SFC));
972 }
973 }
974 }
975
976 D = D->getCanonicalDecl();
977 const MemRegion *sReg = nullptr;
978
979 if (D->hasGlobalStorage() && !D->isStaticLocal()) {
980 QualType Ty = D->getType();
981 assert(!Ty.isNull())(static_cast <bool> (!Ty.isNull()) ? void (0) : __assert_fail
("!Ty.isNull()", "clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 981, __extension__ __PRETTY_FUNCTION__))
;
982 if (Ty.isConstQualified()) {
983 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
984 } else if (Ctx.getSourceManager().isInSystemHeader(D->getLocation())) {
985 sReg = getGlobalsRegion(MemRegion::GlobalSystemSpaceRegionKind);
986 } else {
987 sReg = getGlobalsRegion(MemRegion::GlobalInternalSpaceRegionKind);
988 }
989
990 // Finally handle static locals.
991 } else {
992 // FIXME: Once we implement scope handling, we will need to properly lookup
993 // 'D' to the proper LocationContext.
994 const DeclContext *DC = D->getDeclContext();
995 llvm::PointerUnion<const StackFrameContext *, const VarRegion *> V =
996 getStackOrCaptureRegionForDeclContext(LC, DC, D);
997
998 if (V.is<const VarRegion*>())
999 return V.get<const VarRegion*>();
1000
1001 const auto *STC = V.get<const StackFrameContext *>();
1002
1003 if (!STC) {
1004 // FIXME: Assign a more sensible memory space to static locals
1005 // we see from within blocks that we analyze as top-level declarations.
1006 sReg = getUnknownRegion();
1007 } else {
1008 if (D->hasLocalStorage()) {
1009 sReg =
1010 isa<ParmVarDecl, ImplicitParamDecl>(D)
1011 ? static_cast<const MemRegion *>(getStackArgumentsRegion(STC))
1012 : static_cast<const MemRegion *>(getStackLocalsRegion(STC));
1013 }
1014 else {
1015 assert(D->isStaticLocal())(static_cast <bool> (D->isStaticLocal()) ? void (0) :
__assert_fail ("D->isStaticLocal()", "clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1015, __extension__ __PRETTY_FUNCTION__))
;
1016 const Decl *STCD = STC->getDecl();
1017 if (isa<FunctionDecl, ObjCMethodDecl>(STCD))
1018 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
1019 getFunctionCodeRegion(cast<NamedDecl>(STCD)));
1020 else if (const auto *BD = dyn_cast<BlockDecl>(STCD)) {
1021 // FIXME: The fallback type here is totally bogus -- though it should
1022 // never be queried, it will prevent uniquing with the real
1023 // BlockCodeRegion. Ideally we'd fix the AST so that we always had a
1024 // signature.
1025 QualType T;
1026 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten())
1027 T = TSI->getType();
1028 if (T.isNull())
1029 T = getContext().VoidTy;
1030 if (!T->getAs<FunctionType>()) {
1031 FunctionProtoType::ExtProtoInfo Ext;
1032 T = getContext().getFunctionType(T, None, Ext);
1033 }
1034 T = getContext().getBlockPointerType(T);
1035
1036 const BlockCodeRegion *BTR =
1037 getBlockCodeRegion(BD, Ctx.getCanonicalType(T),
1038 STC->getAnalysisDeclContext());
1039 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
1040 BTR);
1041 }
1042 else {
1043 sReg = getGlobalsRegion();
1044 }
1045 }
1046 }
1047 }
1048
1049 return getSubRegion<NonParamVarRegion>(D, sReg);
1050}
1051
1052const NonParamVarRegion *
1053MemRegionManager::getNonParamVarRegion(const VarDecl *D,
1054 const MemRegion *superR) {
1055 D = D->getCanonicalDecl();
1056 return getSubRegion<NonParamVarRegion>(D, superR);
1057}
1058
1059const ParamVarRegion *
1060MemRegionManager::getParamVarRegion(const Expr *OriginExpr, unsigned Index,
1061 const LocationContext *LC) {
1062 const StackFrameContext *SFC = LC->getStackFrame();
1063 assert(SFC)(static_cast <bool> (SFC) ? void (0) : __assert_fail ("SFC"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1063, __extension__
__PRETTY_FUNCTION__))
;
1064 return getSubRegion<ParamVarRegion>(OriginExpr, Index,
1065 getStackArgumentsRegion(SFC));
1066}
1067
1068const BlockDataRegion *
1069MemRegionManager::getBlockDataRegion(const BlockCodeRegion *BC,
1070 const LocationContext *LC,
1071 unsigned blockCount) {
1072 const MemSpaceRegion *sReg = nullptr;
1073 const BlockDecl *BD = BC->getDecl();
1074 if (!BD->hasCaptures()) {
1075 // This handles 'static' blocks.
1076 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
1077 }
1078 else {
1079 bool IsArcManagedBlock = Ctx.getLangOpts().ObjCAutoRefCount;
1080
1081 // ARC managed blocks can be initialized on stack or directly in heap
1082 // depending on the implementations. So we initialize them with
1083 // UnknownRegion.
1084 if (!IsArcManagedBlock && LC) {
1085 // FIXME: Once we implement scope handling, we want the parent region
1086 // to be the scope.
1087 const StackFrameContext *STC = LC->getStackFrame();
1088 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1088, __extension__
__PRETTY_FUNCTION__))
;
1089 sReg = getStackLocalsRegion(STC);
1090 } else {
1091 // We allow 'LC' to be NULL for cases where want BlockDataRegions
1092 // without context-sensitivity.
1093 sReg = getUnknownRegion();
1094 }
1095 }
1096
1097 return getSubRegion<BlockDataRegion>(BC, LC, blockCount, sReg);
1098}
1099
1100const CXXTempObjectRegion *
1101MemRegionManager::getCXXStaticTempObjectRegion(const Expr *Ex) {
1102 return getSubRegion<CXXTempObjectRegion>(
1103 Ex, getGlobalsRegion(MemRegion::GlobalInternalSpaceRegionKind, nullptr));
1104}
1105
1106const CompoundLiteralRegion*
1107MemRegionManager::getCompoundLiteralRegion(const CompoundLiteralExpr *CL,
1108 const LocationContext *LC) {
1109 const MemSpaceRegion *sReg = nullptr;
1110
1111 if (CL->isFileScope())
1112 sReg = getGlobalsRegion();
1113 else {
1114 const StackFrameContext *STC = LC->getStackFrame();
1115 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1115, __extension__
__PRETTY_FUNCTION__))
;
1116 sReg = getStackLocalsRegion(STC);
1117 }
1118
1119 return getSubRegion<CompoundLiteralRegion>(CL, sReg);
1120}
1121
1122const ElementRegion*
1123MemRegionManager::getElementRegion(QualType elementType, NonLoc Idx,
1124 const SubRegion* superRegion,
1125 ASTContext &Ctx){
1126 QualType T = Ctx.getCanonicalType(elementType).getUnqualifiedType();
1127
1128 llvm::FoldingSetNodeID ID;
1129 ElementRegion::ProfileRegion(ID, T, Idx, superRegion);
1130
1131 void *InsertPos;
1132 MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos);
1133 auto *R = cast_or_null<ElementRegion>(data);
1134
1135 if (!R) {
1136 R = A.Allocate<ElementRegion>();
1137 new (R) ElementRegion(T, Idx, superRegion);
1138 Regions.InsertNode(R, InsertPos);
1139 }
1140
1141 return R;
1142}
1143
1144const FunctionCodeRegion *
1145MemRegionManager::getFunctionCodeRegion(const NamedDecl *FD) {
1146 // To think: should we canonicalize the declaration here?
1147 return getSubRegion<FunctionCodeRegion>(FD, getCodeRegion());
1148}
1149
1150const BlockCodeRegion *
1151MemRegionManager::getBlockCodeRegion(const BlockDecl *BD, CanQualType locTy,
1152 AnalysisDeclContext *AC) {
1153 return getSubRegion<BlockCodeRegion>(BD, locTy, AC, getCodeRegion());
1154}
1155
1156const SymbolicRegion *
1157MemRegionManager::getSymbolicRegion(SymbolRef sym,
1158 const MemSpaceRegion *MemSpace) {
1159 if (MemSpace == nullptr)
1160 MemSpace = getUnknownRegion();
1161 return getSubRegion<SymbolicRegion>(sym, MemSpace);
1162}
1163
1164const SymbolicRegion *MemRegionManager::getSymbolicHeapRegion(SymbolRef Sym) {
1165 return getSubRegion<SymbolicRegion>(Sym, getHeapRegion());
1166}
1167
1168const FieldRegion*
1169MemRegionManager::getFieldRegion(const FieldDecl *d,
1170 const SubRegion* superRegion){
1171 return getSubRegion<FieldRegion>(d, superRegion);
1172}
1173
1174const ObjCIvarRegion*
1175MemRegionManager::getObjCIvarRegion(const ObjCIvarDecl *d,
1176 const SubRegion* superRegion) {
1177 return getSubRegion<ObjCIvarRegion>(d, superRegion);
1178}
1179
1180const CXXTempObjectRegion*
1181MemRegionManager::getCXXTempObjectRegion(Expr const *E,
1182 LocationContext const *LC) {
1183 const StackFrameContext *SFC = LC->getStackFrame();
1184 assert(SFC)(static_cast <bool> (SFC) ? void (0) : __assert_fail ("SFC"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1184, __extension__
__PRETTY_FUNCTION__))
;
1185 return getSubRegion<CXXTempObjectRegion>(E, getStackLocalsRegion(SFC));
1186}
1187
1188/// Checks whether \p BaseClass is a valid virtual or direct non-virtual base
1189/// class of the type of \p Super.
1190static bool isValidBaseClass(const CXXRecordDecl *BaseClass,
1191 const TypedValueRegion *Super,
1192 bool IsVirtual) {
1193 BaseClass = BaseClass->getCanonicalDecl();
1194
1195 const CXXRecordDecl *Class = Super->getValueType()->getAsCXXRecordDecl();
1196 if (!Class)
1197 return true;
1198
1199 if (IsVirtual)
1200 return Class->isVirtuallyDerivedFrom(BaseClass);
1201
1202 for (const auto &I : Class->bases()) {
1203 if (I.getType()->getAsCXXRecordDecl()->getCanonicalDecl() == BaseClass)
1204 return true;
1205 }
1206
1207 return false;
1208}
1209
1210const CXXBaseObjectRegion *
1211MemRegionManager::getCXXBaseObjectRegion(const CXXRecordDecl *RD,
1212 const SubRegion *Super,
1213 bool IsVirtual) {
1214 if (isa<TypedValueRegion>(Super)) {
1215 assert(isValidBaseClass(RD, cast<TypedValueRegion>(Super), IsVirtual))(static_cast <bool> (isValidBaseClass(RD, cast<TypedValueRegion
>(Super), IsVirtual)) ? void (0) : __assert_fail ("isValidBaseClass(RD, cast<TypedValueRegion>(Super), IsVirtual)"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1215, __extension__
__PRETTY_FUNCTION__))
;
1216 (void)&isValidBaseClass;
1217
1218 if (IsVirtual) {
1219 // Virtual base regions should not be layered, since the layout rules
1220 // are different.
1221 while (const auto *Base = dyn_cast<CXXBaseObjectRegion>(Super))
1222 Super = cast<SubRegion>(Base->getSuperRegion());
1223 assert(Super && !isa<MemSpaceRegion>(Super))(static_cast <bool> (Super && !isa<MemSpaceRegion
>(Super)) ? void (0) : __assert_fail ("Super && !isa<MemSpaceRegion>(Super)"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1223, __extension__
__PRETTY_FUNCTION__))
;
1224 }
1225 }
1226
1227 return getSubRegion<CXXBaseObjectRegion>(RD, IsVirtual, Super);
1228}
1229
1230const CXXDerivedObjectRegion *
1231MemRegionManager::getCXXDerivedObjectRegion(const CXXRecordDecl *RD,
1232 const SubRegion *Super) {
1233 return getSubRegion<CXXDerivedObjectRegion>(RD, Super);
1234}
1235
1236const CXXThisRegion*
1237MemRegionManager::getCXXThisRegion(QualType thisPointerTy,
1238 const LocationContext *LC) {
1239 const auto *PT = thisPointerTy->getAs<PointerType>();
1240 assert(PT)(static_cast <bool> (PT) ? void (0) : __assert_fail ("PT"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1240, __extension__
__PRETTY_FUNCTION__))
;
1241 // Inside the body of the operator() of a lambda a this expr might refer to an
1242 // object in one of the parent location contexts.
1243 const auto *D = dyn_cast<CXXMethodDecl>(LC->getDecl());
1244 // FIXME: when operator() of lambda is analyzed as a top level function and
1245 // 'this' refers to a this to the enclosing scope, there is no right region to
1246 // return.
1247 while (!LC->inTopFrame() && (!D || D->isStatic() ||
1248 PT != D->getThisType()->getAs<PointerType>())) {
1249 LC = LC->getParent();
1250 D = dyn_cast<CXXMethodDecl>(LC->getDecl());
1251 }
1252 const StackFrameContext *STC = LC->getStackFrame();
1253 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1253, __extension__
__PRETTY_FUNCTION__))
;
1254 return getSubRegion<CXXThisRegion>(PT, getStackArgumentsRegion(STC));
1255}
1256
1257const AllocaRegion*
1258MemRegionManager::getAllocaRegion(const Expr *E, unsigned cnt,
1259 const LocationContext *LC) {
1260 const StackFrameContext *STC = LC->getStackFrame();
1261 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1261, __extension__
__PRETTY_FUNCTION__))
;
1262 return getSubRegion<AllocaRegion>(E, cnt, getStackLocalsRegion(STC));
1263}
1264
1265const MemSpaceRegion *MemRegion::getMemorySpace() const {
1266 const MemRegion *R = this;
1267 const auto *SR = dyn_cast<SubRegion>(this);
1268
1269 while (SR) {
1270 R = SR->getSuperRegion();
1271 SR = dyn_cast<SubRegion>(R);
1272 }
1273
1274 return dyn_cast<MemSpaceRegion>(R);
1275}
1276
1277bool MemRegion::hasStackStorage() const {
1278 return isa<StackSpaceRegion>(getMemorySpace());
1279}
1280
1281bool MemRegion::hasStackNonParametersStorage() const {
1282 return isa<StackLocalsSpaceRegion>(getMemorySpace());
1283}
1284
1285bool MemRegion::hasStackParametersStorage() const {
1286 return isa<StackArgumentsSpaceRegion>(getMemorySpace());
1287}
1288
1289bool MemRegion::hasGlobalsOrParametersStorage() const {
1290 return isa<StackArgumentsSpaceRegion, GlobalsSpaceRegion>(getMemorySpace());
1291}
1292
1293// Strips away all elements and fields.
1294// Returns the base region of them.
1295const MemRegion *MemRegion::getBaseRegion() const {
1296 const MemRegion *R = this;
1297 while (true) {
1298 switch (R->getKind()) {
1299 case MemRegion::ElementRegionKind:
1300 case MemRegion::FieldRegionKind:
1301 case MemRegion::ObjCIvarRegionKind:
1302 case MemRegion::CXXBaseObjectRegionKind:
1303 case MemRegion::CXXDerivedObjectRegionKind:
1304 R = cast<SubRegion>(R)->getSuperRegion();
1305 continue;
1306 default:
1307 break;
1308 }
1309 break;
1310 }
1311 return R;
1312}
1313
1314// Returns the region of the root class of a C++ class hierarchy.
1315const MemRegion *MemRegion::getMostDerivedObjectRegion() const {
1316 const MemRegion *R = this;
1317 while (const auto *BR = dyn_cast<CXXBaseObjectRegion>(R))
1318 R = BR->getSuperRegion();
1319 return R;
1320}
1321
1322bool MemRegion::isSubRegionOf(const MemRegion *) const {
1323 return false;
1324}
1325
1326//===----------------------------------------------------------------------===//
1327// View handling.
1328//===----------------------------------------------------------------------===//
1329
1330const MemRegion *MemRegion::StripCasts(bool StripBaseAndDerivedCasts) const {
1331 const MemRegion *R = this;
1332 while (true) {
1333 switch (R->getKind()) {
1334 case ElementRegionKind: {
1335 const auto *ER = cast<ElementRegion>(R);
1336 if (!ER->getIndex().isZeroConstant())
1337 return R;
1338 R = ER->getSuperRegion();
1339 break;
1340 }
1341 case CXXBaseObjectRegionKind:
1342 case CXXDerivedObjectRegionKind:
1343 if (!StripBaseAndDerivedCasts)
1344 return R;
1345 R = cast<TypedValueRegion>(R)->getSuperRegion();
1346 break;
1347 default:
1348 return R;
1349 }
1350 }
1351}
1352
1353const SymbolicRegion *MemRegion::getSymbolicBase() const {
1354 const auto *SubR = dyn_cast<SubRegion>(this);
1355
1356 while (SubR) {
1357 if (const auto *SymR = dyn_cast<SymbolicRegion>(SubR))
1358 return SymR;
1359 SubR = dyn_cast<SubRegion>(SubR->getSuperRegion());
1360 }
1361 return nullptr;
1362}
1363
1364RegionRawOffset ElementRegion::getAsArrayOffset() const {
1365 int64_t offset = 0;
1366 const ElementRegion *ER = this;
1367 const MemRegion *superR = nullptr;
1368 ASTContext &C = getContext();
1369
1370 // FIXME: Handle multi-dimensional arrays.
1371
1372 while (ER) {
1373 superR = ER->getSuperRegion();
1374
1375 // FIXME: generalize to symbolic offsets.
1376 SVal index = ER->getIndex();
1377 if (auto CI = index.getAs<nonloc::ConcreteInt>()) {
1378 // Update the offset.
1379 int64_t i = CI->getValue().getSExtValue();
1380
1381 if (i != 0) {
1382 QualType elemType = ER->getElementType();
1383
1384 // If we are pointing to an incomplete type, go no further.
1385 if (elemType->isIncompleteType()) {
1386 superR = ER;
1387 break;
1388 }
1389
1390 int64_t size = C.getTypeSizeInChars(elemType).getQuantity();
1391 if (auto NewOffset = llvm::checkedMulAdd(i, size, offset)) {
1392 offset = *NewOffset;
1393 } else {
1394 LLVM_DEBUG(llvm::dbgs() << "MemRegion::getAsArrayOffset: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("MemRegion")) { llvm::dbgs() << "MemRegion::getAsArrayOffset: "
<< "offset overflowing, returning unknown\n"; } } while
(false)
1395 << "offset overflowing, returning unknown\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("MemRegion")) { llvm::dbgs() << "MemRegion::getAsArrayOffset: "
<< "offset overflowing, returning unknown\n"; } } while
(false)
;
1396
1397 return nullptr;
1398 }
1399 }
1400
1401 // Go to the next ElementRegion (if any).
1402 ER = dyn_cast<ElementRegion>(superR);
1403 continue;
1404 }
1405
1406 return nullptr;
1407 }
1408
1409 assert(superR && "super region cannot be NULL")(static_cast <bool> (superR && "super region cannot be NULL"
) ? void (0) : __assert_fail ("superR && \"super region cannot be NULL\""
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1409, __extension__
__PRETTY_FUNCTION__))
;
1410 return RegionRawOffset(superR, CharUnits::fromQuantity(offset));
1411}
1412
1413/// Returns true if \p Base is an immediate base class of \p Child
1414static bool isImmediateBase(const CXXRecordDecl *Child,
1415 const CXXRecordDecl *Base) {
1416 assert(Child && "Child must not be null")(static_cast <bool> (Child && "Child must not be null"
) ? void (0) : __assert_fail ("Child && \"Child must not be null\""
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1416, __extension__
__PRETTY_FUNCTION__))
;
1417 // Note that we do NOT canonicalize the base class here, because
1418 // ASTRecordLayout doesn't either. If that leads us down the wrong path,
1419 // so be it; at least we won't crash.
1420 for (const auto &I : Child->bases()) {
1421 if (I.getType()->getAsCXXRecordDecl() == Base)
1422 return true;
1423 }
1424
1425 return false;
1426}
1427
1428static RegionOffset calculateOffset(const MemRegion *R) {
1429 const MemRegion *SymbolicOffsetBase = nullptr;
1430 int64_t Offset = 0;
1431
1432 while (true) {
1433 switch (R->getKind()) {
1434 case MemRegion::CodeSpaceRegionKind:
1435 case MemRegion::StackLocalsSpaceRegionKind:
1436 case MemRegion::StackArgumentsSpaceRegionKind:
1437 case MemRegion::HeapSpaceRegionKind:
1438 case MemRegion::UnknownSpaceRegionKind:
1439 case MemRegion::StaticGlobalSpaceRegionKind:
1440 case MemRegion::GlobalInternalSpaceRegionKind:
1441 case MemRegion::GlobalSystemSpaceRegionKind:
1442 case MemRegion::GlobalImmutableSpaceRegionKind:
1443 // Stores can bind directly to a region space to set a default value.
1444 assert(Offset == 0 && !SymbolicOffsetBase)(static_cast <bool> (Offset == 0 && !SymbolicOffsetBase
) ? void (0) : __assert_fail ("Offset == 0 && !SymbolicOffsetBase"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1444, __extension__
__PRETTY_FUNCTION__))
;
1445 goto Finish;
1446
1447 case MemRegion::FunctionCodeRegionKind:
1448 case MemRegion::BlockCodeRegionKind:
1449 case MemRegion::BlockDataRegionKind:
1450 // These will never have bindings, but may end up having values requested
1451 // if the user does some strange casting.
1452 if (Offset != 0)
1453 SymbolicOffsetBase = R;
1454 goto Finish;
1455
1456 case MemRegion::SymbolicRegionKind:
1457 case MemRegion::AllocaRegionKind:
1458 case MemRegion::CompoundLiteralRegionKind:
1459 case MemRegion::CXXThisRegionKind:
1460 case MemRegion::StringRegionKind:
1461 case MemRegion::ObjCStringRegionKind:
1462 case MemRegion::NonParamVarRegionKind:
1463 case MemRegion::ParamVarRegionKind:
1464 case MemRegion::CXXTempObjectRegionKind:
1465 // Usual base regions.
1466 goto Finish;
1467
1468 case MemRegion::ObjCIvarRegionKind:
1469 // This is a little strange, but it's a compromise between
1470 // ObjCIvarRegions having unknown compile-time offsets (when using the
1471 // non-fragile runtime) and yet still being distinct, non-overlapping
1472 // regions. Thus we treat them as "like" base regions for the purposes
1473 // of computing offsets.
1474 goto Finish;
1475
1476 case MemRegion::CXXBaseObjectRegionKind: {
1477 const auto *BOR = cast<CXXBaseObjectRegion>(R);
1478 R = BOR->getSuperRegion();
1479
1480 QualType Ty;
1481 bool RootIsSymbolic = false;
1482 if (const auto *TVR = dyn_cast<TypedValueRegion>(R)) {
1483 Ty = TVR->getDesugaredValueType(R->getContext());
1484 } else if (const auto *SR = dyn_cast<SymbolicRegion>(R)) {
1485 // If our base region is symbolic, we don't know what type it really is.
1486 // Pretend the type of the symbol is the true dynamic type.
1487 // (This will at least be self-consistent for the life of the symbol.)
1488 Ty = SR->getSymbol()->getType()->getPointeeType();
1489 RootIsSymbolic = true;
1490 }
1491
1492 const CXXRecordDecl *Child = Ty->getAsCXXRecordDecl();
1493 if (!Child) {
1494 // We cannot compute the offset of the base class.
1495 SymbolicOffsetBase = R;
1496 } else {
1497 if (RootIsSymbolic) {
1498 // Base layers on symbolic regions may not be type-correct.
1499 // Double-check the inheritance here, and revert to a symbolic offset
1500 // if it's invalid (e.g. due to a reinterpret_cast).
1501 if (BOR->isVirtual()) {
1502 if (!Child->isVirtuallyDerivedFrom(BOR->getDecl()))
1503 SymbolicOffsetBase = R;
1504 } else {
1505 if (!isImmediateBase(Child, BOR->getDecl()))
1506 SymbolicOffsetBase = R;
1507 }
1508 }
1509 }
1510
1511 // Don't bother calculating precise offsets if we already have a
1512 // symbolic offset somewhere in the chain.
1513 if (SymbolicOffsetBase)
1514 continue;
1515
1516 CharUnits BaseOffset;
1517 const ASTRecordLayout &Layout = R->getContext().getASTRecordLayout(Child);
1518 if (BOR->isVirtual())
1519 BaseOffset = Layout.getVBaseClassOffset(BOR->getDecl());
1520 else
1521 BaseOffset = Layout.getBaseClassOffset(BOR->getDecl());
1522
1523 // The base offset is in chars, not in bits.
1524 Offset += BaseOffset.getQuantity() * R->getContext().getCharWidth();
1525 break;
1526 }
1527
1528 case MemRegion::CXXDerivedObjectRegionKind: {
1529 // TODO: Store the base type in the CXXDerivedObjectRegion and use it.
1530 goto Finish;
1531 }
1532
1533 case MemRegion::ElementRegionKind: {
1534 const auto *ER = cast<ElementRegion>(R);
1535 R = ER->getSuperRegion();
1536
1537 QualType EleTy = ER->getValueType();
1538 if (EleTy->isIncompleteType()) {
1539 // We cannot compute the offset of the base class.
1540 SymbolicOffsetBase = R;
1541 continue;
1542 }
1543
1544 SVal Index = ER->getIndex();
1545 if (Optional<nonloc::ConcreteInt> CI =
1546 Index.getAs<nonloc::ConcreteInt>()) {
1547 // Don't bother calculating precise offsets if we already have a
1548 // symbolic offset somewhere in the chain.
1549 if (SymbolicOffsetBase)
1550 continue;
1551
1552 int64_t i = CI->getValue().getSExtValue();
1553 // This type size is in bits.
1554 Offset += i * R->getContext().getTypeSize(EleTy);
1555 } else {
1556 // We cannot compute offset for non-concrete index.
1557 SymbolicOffsetBase = R;
1558 }
1559 break;
1560 }
1561 case MemRegion::FieldRegionKind: {
1562 const auto *FR = cast<FieldRegion>(R);
1563 R = FR->getSuperRegion();
1564 assert(R)(static_cast <bool> (R) ? void (0) : __assert_fail ("R"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1564, __extension__
__PRETTY_FUNCTION__))
;
1565
1566 const RecordDecl *RD = FR->getDecl()->getParent();
1567 if (RD->isUnion() || !RD->isCompleteDefinition()) {
1568 // We cannot compute offset for incomplete type.
1569 // For unions, we could treat everything as offset 0, but we'd rather
1570 // treat each field as a symbolic offset so they aren't stored on top
1571 // of each other, since we depend on things in typed regions actually
1572 // matching their types.
1573 SymbolicOffsetBase = R;
1574 }
1575
1576 // Don't bother calculating precise offsets if we already have a
1577 // symbolic offset somewhere in the chain.
1578 if (SymbolicOffsetBase)
1579 continue;
1580
1581 // Get the field number.
1582 unsigned idx = 0;
1583 for (RecordDecl::field_iterator FI = RD->field_begin(),
1584 FE = RD->field_end(); FI != FE; ++FI, ++idx) {
1585 if (FR->getDecl() == *FI)
1586 break;
1587 }
1588 const ASTRecordLayout &Layout = R->getContext().getASTRecordLayout(RD);
1589 // This is offset in bits.
1590 Offset += Layout.getFieldOffset(idx);
1591 break;
1592 }
1593 }
1594 }
1595
1596 Finish:
1597 if (SymbolicOffsetBase)
1598 return RegionOffset(SymbolicOffsetBase, RegionOffset::Symbolic);
1599 return RegionOffset(R, Offset);
1600}
1601
1602RegionOffset MemRegion::getAsOffset() const {
1603 if (!cachedOffset)
1604 cachedOffset = calculateOffset(this);
1605 return *cachedOffset;
1606}
1607
1608//===----------------------------------------------------------------------===//
1609// BlockDataRegion
1610//===----------------------------------------------------------------------===//
1611
1612std::pair<const VarRegion *, const VarRegion *>
1613BlockDataRegion::getCaptureRegions(const VarDecl *VD) {
1614 MemRegionManager &MemMgr = getMemRegionManager();
9
Value assigned to field 'LC'
1615 const VarRegion *VR = nullptr;
1616 const VarRegion *OriginalVR = nullptr;
1617
1618 if (!VD->hasAttr<BlocksAttr>() && VD->hasLocalStorage()) {
10
Taking false branch
1619 VR = MemMgr.getNonParamVarRegion(VD, this);
1620 OriginalVR = MemMgr.getVarRegion(VD, LC);
1621 }
1622 else {
1623 if (LC) {
11
Assuming field 'LC' is null
12
Taking false branch
1624 VR = MemMgr.getVarRegion(VD, LC);
1625 OriginalVR = VR;
1626 }
1627 else {
1628 VR = MemMgr.getNonParamVarRegion(VD, MemMgr.getUnknownRegion());
1629 OriginalVR = MemMgr.getVarRegion(VD, LC);
13
Passing null pointer value via 2nd parameter 'LC'
14
Calling 'MemRegionManager::getVarRegion'
1630 }
1631 }
1632 return std::make_pair(VR, OriginalVR);
1633}
1634
1635void BlockDataRegion::LazyInitializeReferencedVars() {
1636 if (ReferencedVars)
3
Assuming field 'ReferencedVars' is null
4
Taking false branch
1637 return;
1638
1639 AnalysisDeclContext *AC = getCodeRegion()->getAnalysisDeclContext();
1640 const auto &ReferencedBlockVars = AC->getReferencedBlockVars(BC->getDecl());
1641 auto NumBlockVars =
1642 std::distance(ReferencedBlockVars.begin(), ReferencedBlockVars.end());
1643
1644 if (NumBlockVars == 0) {
5
Assuming 'NumBlockVars' is not equal to 0
6
Taking false branch
1645 ReferencedVars = (void*) 0x1;
1646 return;
1647 }
1648
1649 MemRegionManager &MemMgr = getMemRegionManager();
1650 llvm::BumpPtrAllocator &A = MemMgr.getAllocator();
1651 BumpVectorContext BC(A);
1652
1653 using VarVec = BumpVector<const MemRegion *>;
1654
1655 auto *BV = A.Allocate<VarVec>();
1656 new (BV) VarVec(BC, NumBlockVars);
1657 auto *BVOriginal = A.Allocate<VarVec>();
1658 new (BVOriginal) VarVec(BC, NumBlockVars);
1659
1660 for (const auto *VD : ReferencedBlockVars) {
7
Assuming '__begin1' is not equal to '__end1'
1661 const VarRegion *VR = nullptr;
1662 const VarRegion *OriginalVR = nullptr;
1663 std::tie(VR, OriginalVR) = getCaptureRegions(VD);
8
Calling 'BlockDataRegion::getCaptureRegions'
1664 assert(VR)(static_cast <bool> (VR) ? void (0) : __assert_fail ("VR"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1664, __extension__
__PRETTY_FUNCTION__))
;
1665 assert(OriginalVR)(static_cast <bool> (OriginalVR) ? void (0) : __assert_fail
("OriginalVR", "clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1665, __extension__ __PRETTY_FUNCTION__))
;
1666 BV->push_back(VR, BC);
1667 BVOriginal->push_back(OriginalVR, BC);
1668 }
1669
1670 ReferencedVars = BV;
1671 OriginalVars = BVOriginal;
1672}
1673
1674BlockDataRegion::referenced_vars_iterator
1675BlockDataRegion::referenced_vars_begin() const {
1676 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
2
Calling 'BlockDataRegion::LazyInitializeReferencedVars'
1677
1678 auto *Vec = static_cast<BumpVector<const MemRegion *> *>(ReferencedVars);
1679
1680 if (Vec == (void*) 0x1)
1681 return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1682
1683 auto *VecOriginal =
1684 static_cast<BumpVector<const MemRegion *> *>(OriginalVars);
1685
1686 return BlockDataRegion::referenced_vars_iterator(Vec->begin(),
1687 VecOriginal->begin());
1688}
1689
1690BlockDataRegion::referenced_vars_iterator
1691BlockDataRegion::referenced_vars_end() const {
1692 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1693
1694 auto *Vec = static_cast<BumpVector<const MemRegion *> *>(ReferencedVars);
1695
1696 if (Vec == (void*) 0x1)
1697 return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1698
1699 auto *VecOriginal =
1700 static_cast<BumpVector<const MemRegion *> *>(OriginalVars);
1701
1702 return BlockDataRegion::referenced_vars_iterator(Vec->end(),
1703 VecOriginal->end());
1704}
1705
1706const VarRegion *BlockDataRegion::getOriginalRegion(const VarRegion *R) const {
1707 for (referenced_vars_iterator I = referenced_vars_begin(),
1
Calling 'BlockDataRegion::referenced_vars_begin'
1708 E = referenced_vars_end();
1709 I != E; ++I) {
1710 if (I.getCapturedRegion() == R)
1711 return I.getOriginalRegion();
1712 }
1713 return nullptr;
1714}
1715
1716//===----------------------------------------------------------------------===//
1717// RegionAndSymbolInvalidationTraits
1718//===----------------------------------------------------------------------===//
1719
1720void RegionAndSymbolInvalidationTraits::setTrait(SymbolRef Sym,
1721 InvalidationKinds IK) {
1722 SymTraitsMap[Sym] |= IK;
1723}
1724
1725void RegionAndSymbolInvalidationTraits::setTrait(const MemRegion *MR,
1726 InvalidationKinds IK) {
1727 assert(MR)(static_cast <bool> (MR) ? void (0) : __assert_fail ("MR"
, "clang/lib/StaticAnalyzer/Core/MemRegion.cpp", 1727, __extension__
__PRETTY_FUNCTION__))
;
1728 if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1729 setTrait(SR->getSymbol(), IK);
1730 else
1731 MRTraitsMap[MR] |= IK;
1732}
1733
1734bool RegionAndSymbolInvalidationTraits::hasTrait(SymbolRef Sym,
1735 InvalidationKinds IK) const {
1736 const_symbol_iterator I = SymTraitsMap.find(Sym);
1737 if (I != SymTraitsMap.end())
1738 return I->second & IK;
1739
1740 return false;
1741}
1742
1743bool RegionAndSymbolInvalidationTraits::hasTrait(const MemRegion *MR,
1744 InvalidationKinds IK) const {
1745 if (!MR)
1746 return false;
1747
1748 if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1749 return hasTrait(SR->getSymbol(), IK);
1750
1751 const_region_iterator I = MRTraitsMap.find(MR);
1752 if (I != MRTraitsMap.end())
1753 return I->second & IK;
1754
1755 return false;
1756}