clang 23.0.0git
MemRegion.cpp
Go to the documentation of this file.
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
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"
25#include "clang/AST/Type.h"
29#include "clang/Basic/LLVM.h"
35#include "llvm/ADT/APInt.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/PointerUnion.h"
38#include "llvm/ADT/SmallString.h"
39#include "llvm/ADT/StringRef.h"
40#include "llvm/ADT/Twine.h"
41#include "llvm/ADT/iterator_range.h"
42#include "llvm/Support/Allocator.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/CheckedArithmetic.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/raw_ostream.h"
49#include <cassert>
50#include <cstdint>
51#include <iterator>
52#include <optional>
53#include <string>
54#include <tuple>
55#include <utility>
56
57using namespace clang;
58using namespace ento;
59
60#define DEBUG_TYPE "MemRegion"
61
63 const MemSpaceRegion *)
64
65//===----------------------------------------------------------------------===//
66// MemRegion Construction.
67//===----------------------------------------------------------------------===//
68
69[[maybe_unused]] static bool isAReferenceTypedValueRegion(const MemRegion *R) {
70 const auto *TyReg = llvm::dyn_cast<TypedValueRegion>(R);
71 return TyReg && TyReg->getValueType()->isReferenceType();
72}
73
74template <typename RegionTy, typename SuperTy, typename Arg1Ty>
75RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
76 const SuperTy *superRegion) {
77 llvm::FoldingSetNodeID ID;
78 RegionTy::ProfileRegion(ID, arg1, superRegion);
79 void *InsertPos;
80 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
81
82 if (!R) {
83 R = new (A) RegionTy(arg1, superRegion);
84 Regions.InsertNode(R, InsertPos);
85 assert(!isAReferenceTypedValueRegion(superRegion));
86 }
87
88 return R;
89}
90
91template <typename RegionTy, typename SuperTy, typename Arg1Ty, typename Arg2Ty>
92RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
93 const SuperTy *superRegion) {
94 llvm::FoldingSetNodeID ID;
95 RegionTy::ProfileRegion(ID, arg1, arg2, superRegion);
96 void *InsertPos;
97 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
98
99 if (!R) {
100 R = new (A) RegionTy(arg1, arg2, superRegion);
101 Regions.InsertNode(R, InsertPos);
102 assert(!isAReferenceTypedValueRegion(superRegion));
103 }
104
105 return R;
106}
107
108template <typename RegionTy, typename SuperTy,
109 typename Arg1Ty, typename Arg2Ty, typename Arg3Ty>
110RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
111 const Arg3Ty arg3,
112 const SuperTy *superRegion) {
113 llvm::FoldingSetNodeID ID;
114 RegionTy::ProfileRegion(ID, arg1, arg2, arg3, superRegion);
115 void *InsertPos;
116 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
117
118 if (!R) {
119 R = new (A) RegionTy(arg1, arg2, arg3, superRegion);
120 Regions.InsertNode(R, InsertPos);
121 assert(!isAReferenceTypedValueRegion(superRegion));
122 }
123
124 return R;
125}
126
127//===----------------------------------------------------------------------===//
128// Object destruction.
129//===----------------------------------------------------------------------===//
130
131MemRegion::~MemRegion() = default;
132
133// All regions and their data are BumpPtrAllocated. No need to call their
134// destructors.
136
137//===----------------------------------------------------------------------===//
138// Basic methods.
139//===----------------------------------------------------------------------===//
140
142 const MemRegion* r = this;
143 do {
144 if (r == R)
145 return true;
146 if (const auto *sr = dyn_cast<SubRegion>(r))
147 r = sr->getSuperRegion();
148 else
149 break;
150 } while (r != nullptr);
151 return false;
152}
153
155 const SubRegion* r = this;
156 do {
158 if (const auto *sr = dyn_cast<SubRegion>(superRegion)) {
159 r = sr;
160 continue;
161 }
162 return superRegion->getMemRegionManager();
163 } while (true);
164}
165
167 const auto *SSR = dyn_cast<StackSpaceRegion>(getRawMemorySpace());
168 return SSR ? SSR->getStackFrame() : nullptr;
169}
170
172 const auto *SSR = dyn_cast<StackSpaceRegion>(getRawMemorySpace());
173 return SSR ? SSR->getStackFrame() : nullptr;
174}
175
178 "A temporary object can only be allocated on the stack");
179 return cast<StackSpaceRegion>(getRawMemorySpace())->getStackFrame();
180}
181
182ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, const SubRegion *sReg)
183 : DeclRegion(sReg, ObjCIvarRegionKind), IVD(ivd) {
184 assert(IVD);
185}
186
187const ObjCIvarDecl *ObjCIvarRegion::getDecl() const { return IVD; }
188
190 return getDecl()->getType();
191}
192
196
200
202 assert(getDecl() &&
203 "`ParamVarRegion` support functions without `Decl` not implemented"
204 " yet.");
205 return getDecl()->getType();
206}
207
209 const Decl *D = getStackFrame()->getDecl();
210
211 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
212 assert(Index < FD->param_size());
213 return FD->parameters()[Index];
214 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
215 assert(Index < BD->param_size());
216 return BD->parameters()[Index];
217 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
218 assert(Index < MD->param_size());
219 return MD->parameters()[Index];
220 } else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
221 assert(Index < CD->param_size());
222 return CD->parameters()[Index];
223 } else {
224 llvm_unreachable("Unexpected Decl kind!");
225 }
226}
227
228//===----------------------------------------------------------------------===//
229// FoldingSet profiling.
230//===----------------------------------------------------------------------===//
231
232void MemSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
233 ID.AddInteger(static_cast<unsigned>(getKind()));
234}
235
236void StackSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
237 ID.AddInteger(static_cast<unsigned>(getKind()));
238 ID.AddPointer(getStackFrame());
239}
240
241void StaticGlobalSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
242 ID.AddInteger(static_cast<unsigned>(getKind()));
243 ID.AddPointer(getCodeRegion());
244}
245
246void StringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
247 const StringLiteral *Str,
248 const MemRegion *superRegion) {
249 ID.AddInteger(static_cast<unsigned>(StringRegionKind));
250 ID.AddPointer(Str);
251 ID.AddPointer(superRegion);
252}
253
254void ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
255 const ObjCStringLiteral *Str,
256 const MemRegion *superRegion) {
257 ID.AddInteger(static_cast<unsigned>(ObjCStringRegionKind));
258 ID.AddPointer(Str);
259 ID.AddPointer(superRegion);
260}
261
262void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
263 const Expr *Ex, unsigned cnt,
264 const MemRegion *superRegion) {
265 ID.AddInteger(static_cast<unsigned>(AllocaRegionKind));
266 ID.AddPointer(Ex);
267 ID.AddInteger(cnt);
268 ID.AddPointer(superRegion);
269}
270
271void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
272 ProfileRegion(ID, Ex, Cnt, superRegion);
273}
274
275void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
276 CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
277}
278
279void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
280 const CompoundLiteralExpr *CL,
281 const MemRegion* superRegion) {
282 ID.AddInteger(static_cast<unsigned>(CompoundLiteralRegionKind));
283 ID.AddPointer(CL);
284 ID.AddPointer(superRegion);
285}
286
287void CXXThisRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
288 const PointerType *PT,
289 const MemRegion *sRegion) {
290 ID.AddInteger(static_cast<unsigned>(CXXThisRegionKind));
291 ID.AddPointer(PT);
292 ID.AddPointer(sRegion);
293}
294
295void CXXThisRegion::Profile(llvm::FoldingSetNodeID &ID) const {
296 CXXThisRegion::ProfileRegion(ID, ThisPointerTy, superRegion);
297}
298
299void FieldRegion::Profile(llvm::FoldingSetNodeID &ID) const {
300 ProfileRegion(ID, getDecl(), superRegion);
301}
302
303void ObjCIvarRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
304 const ObjCIvarDecl *ivd,
305 const MemRegion* superRegion) {
306 ID.AddInteger(static_cast<unsigned>(ObjCIvarRegionKind));
307 ID.AddPointer(ivd);
308 ID.AddPointer(superRegion);
309}
310
311void ObjCIvarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
312 ProfileRegion(ID, getDecl(), superRegion);
313}
314
315void NonParamVarRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
316 const VarDecl *VD,
317 const MemRegion *superRegion) {
318 ID.AddInteger(static_cast<unsigned>(NonParamVarRegionKind));
319 ID.AddPointer(VD);
320 ID.AddPointer(superRegion);
321}
322
323void NonParamVarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
324 ProfileRegion(ID, getDecl(), superRegion);
325}
326
327void ParamVarRegion::ProfileRegion(llvm::FoldingSetNodeID &ID, const Expr *OE,
328 unsigned Idx, const MemRegion *SReg) {
329 ID.AddInteger(static_cast<unsigned>(ParamVarRegionKind));
330 ID.AddPointer(OE);
331 ID.AddInteger(Idx);
332 ID.AddPointer(SReg);
333}
334
335void ParamVarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
336 ProfileRegion(ID, getOriginExpr(), getIndex(), superRegion);
337}
338
339void SymbolicRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym,
340 const MemRegion *sreg) {
341 ID.AddInteger(static_cast<unsigned>(MemRegion::SymbolicRegionKind));
342 ID.Add(sym);
343 ID.AddPointer(sreg);
344}
345
346void SymbolicRegion::Profile(llvm::FoldingSetNodeID& ID) const {
348}
349
350void ElementRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
351 QualType ElementType, SVal Idx,
352 const MemRegion* superRegion) {
353 ID.AddInteger(MemRegion::ElementRegionKind);
354 ID.Add(ElementType);
355 ID.AddPointer(superRegion);
356 Idx.Profile(ID);
357}
358
359void ElementRegion::Profile(llvm::FoldingSetNodeID& ID) const {
360 ElementRegion::ProfileRegion(ID, ElementType, Index, superRegion);
361}
362
363void FunctionCodeRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
364 const NamedDecl *FD,
365 const MemRegion*) {
366 ID.AddInteger(MemRegion::FunctionCodeRegionKind);
367 ID.AddPointer(FD);
368}
369
370void FunctionCodeRegion::Profile(llvm::FoldingSetNodeID& ID) const {
371 FunctionCodeRegion::ProfileRegion(ID, FD, superRegion);
372}
373
374void BlockCodeRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
375 const BlockDecl *BD, CanQualType,
376 const AnalysisDeclContext *AC,
377 const MemRegion*) {
378 ID.AddInteger(MemRegion::BlockCodeRegionKind);
379 ID.AddPointer(BD);
380}
381
382void BlockCodeRegion::Profile(llvm::FoldingSetNodeID& ID) const {
383 BlockCodeRegion::ProfileRegion(ID, BD, locTy, AC, superRegion);
384}
385
386void BlockDataRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
387 const BlockCodeRegion *BC,
388 const StackFrame *SF, unsigned BlkCount,
389 const MemRegion *sReg) {
390 ID.AddInteger(MemRegion::BlockDataRegionKind);
391 ID.AddPointer(BC);
392 ID.AddPointer(SF);
393 ID.AddInteger(BlkCount);
394 ID.AddPointer(sReg);
395}
396
397void BlockDataRegion::Profile(llvm::FoldingSetNodeID& ID) const {
398 BlockDataRegion::ProfileRegion(ID, BC, SF, BlockCount, getSuperRegion());
399}
400
401void CXXTempObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
402 Expr const *Ex,
403 const MemRegion *sReg) {
404 ID.AddPointer(Ex);
405 ID.AddPointer(sReg);
406}
407
408void CXXTempObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
409 ProfileRegion(ID, Ex, getSuperRegion());
410}
411
412void CXXLifetimeExtendedObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
413 const Expr *E,
414 const ValueDecl *D,
415 const MemRegion *sReg) {
416 ID.AddPointer(E);
417 ID.AddPointer(D);
418 ID.AddPointer(sReg);
419}
420
422 llvm::FoldingSetNodeID &ID) const {
423 ProfileRegion(ID, Ex, ExD, getSuperRegion());
424}
425
426void CXXBaseObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
427 const CXXRecordDecl *RD,
428 bool IsVirtual,
429 const MemRegion *SReg) {
430 ID.AddPointer(RD);
431 ID.AddBoolean(IsVirtual);
432 ID.AddPointer(SReg);
433}
434
435void CXXBaseObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
436 ProfileRegion(ID, getDecl(), isVirtual(), superRegion);
437}
438
439void CXXDerivedObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
440 const CXXRecordDecl *RD,
441 const MemRegion *SReg) {
442 ID.AddPointer(RD);
443 ID.AddPointer(SReg);
444}
445
446void CXXDerivedObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
447 ProfileRegion(ID, getDecl(), superRegion);
448}
449
450//===----------------------------------------------------------------------===//
451// Region anchors.
452//===----------------------------------------------------------------------===//
453
454void GlobalsSpaceRegion::anchor() {}
455
456void NonStaticGlobalSpaceRegion::anchor() {}
457
458void StackSpaceRegion::anchor() {}
459
460void TypedRegion::anchor() {}
461
462void TypedValueRegion::anchor() {}
463
464void CodeTextRegion::anchor() {}
465
466void SubRegion::anchor() {}
467
468//===----------------------------------------------------------------------===//
469// Region pretty-printing.
470//===----------------------------------------------------------------------===//
471
472LLVM_DUMP_METHOD void MemRegion::dump() const {
473 dumpToStream(llvm::errs());
474}
475
476std::string MemRegion::getString() const {
477 std::string s;
478 llvm::raw_string_ostream os(s);
479 dumpToStream(os);
480 return s;
481}
482
483void MemRegion::dumpToStream(raw_ostream &os) const {
484 os << "<Unknown Region>";
485}
486
487void AllocaRegion::dumpToStream(raw_ostream &os) const {
488 os << "alloca{S" << Ex->getID(getContext()) << ',' << Cnt << '}';
489}
490
491void FunctionCodeRegion::dumpToStream(raw_ostream &os) const {
492 os << "code{" << getDecl()->getDeclName().getAsString() << '}';
493}
494
495void BlockCodeRegion::dumpToStream(raw_ostream &os) const {
496 os << "block_code{" << static_cast<const void *>(this) << '}';
497}
498
499void BlockDataRegion::dumpToStream(raw_ostream &os) const {
500 os << "block_data{" << BC;
501 os << "; ";
502 for (auto Var : referenced_vars())
503 os << "(" << Var.getCapturedRegion() << "<-" << Var.getOriginalRegion()
504 << ") ";
505 os << '}';
506}
507
508void CompoundLiteralRegion::dumpToStream(raw_ostream &os) const {
509 // FIXME: More elaborate pretty-printing.
510 os << "{ S" << CL->getID(getContext()) << " }";
511}
512
513void CXXTempObjectRegion::dumpToStream(raw_ostream &os) const {
514 os << "temp_object{" << getValueType() << ", "
515 << "S" << Ex->getID(getContext()) << '}';
516}
517
519 os << "lifetime_extended_object{" << getValueType() << ", ";
520 if (const IdentifierInfo *ID = ExD->getIdentifier())
521 os << ID->getName();
522 else
523 os << "D" << ExD->getID();
524 os << ", "
525 << "S" << Ex->getID(getContext()) << '}';
526}
527
528void CXXBaseObjectRegion::dumpToStream(raw_ostream &os) const {
529 os << "Base{" << superRegion << ',' << getDecl()->getName() << '}';
530}
531
532void CXXDerivedObjectRegion::dumpToStream(raw_ostream &os) const {
533 os << "Derived{" << superRegion << ',' << getDecl()->getName() << '}';
534}
535
536void CXXThisRegion::dumpToStream(raw_ostream &os) const {
537 os << "this";
538}
539
540void ElementRegion::dumpToStream(raw_ostream &os) const {
541 os << "Element{" << superRegion << ',' << Index << ',' << getElementType()
542 << '}';
543}
544
545void FieldRegion::dumpToStream(raw_ostream &os) const {
546 os << superRegion << "." << *getDecl();
547}
548
549void ObjCIvarRegion::dumpToStream(raw_ostream &os) const {
550 os << "Ivar{" << superRegion << ',' << *getDecl() << '}';
551}
552
553void StringRegion::dumpToStream(raw_ostream &os) const {
554 assert(Str != nullptr && "Expecting non-null StringLiteral");
555 Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts()));
556}
557
558void ObjCStringRegion::dumpToStream(raw_ostream &os) const {
559 assert(Str != nullptr && "Expecting non-null ObjCStringLiteral");
560 Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts()));
561}
562
563void SymbolicRegion::dumpToStream(raw_ostream &os) const {
565 os << "Heap";
566 os << "SymRegion{" << sym << '}';
567}
568
569void NonParamVarRegion::dumpToStream(raw_ostream &os) const {
570 if (const IdentifierInfo *ID = VD->getIdentifier())
571 os << ID->getName();
572 else
573 os << "NonParamVarRegion{D" << VD->getID() << '}';
574}
575
576LLVM_DUMP_METHOD void RegionRawOffset::dump() const {
577 dumpToStream(llvm::errs());
578}
579
580void RegionRawOffset::dumpToStream(raw_ostream &os) const {
581 os << "raw_offset{" << getRegion() << ',' << getOffset().getQuantity() << '}';
582}
583
584void CodeSpaceRegion::dumpToStream(raw_ostream &os) const {
585 os << "CodeSpaceRegion";
586}
587
588void StaticGlobalSpaceRegion::dumpToStream(raw_ostream &os) const {
589 os << "StaticGlobalsMemSpace{" << CR << '}';
590}
591
592void GlobalInternalSpaceRegion::dumpToStream(raw_ostream &os) const {
593 os << "GlobalInternalSpaceRegion";
594}
595
596void GlobalSystemSpaceRegion::dumpToStream(raw_ostream &os) const {
597 os << "GlobalSystemSpaceRegion";
598}
599
600void GlobalImmutableSpaceRegion::dumpToStream(raw_ostream &os) const {
601 os << "GlobalImmutableSpaceRegion";
602}
603
604void HeapSpaceRegion::dumpToStream(raw_ostream &os) const {
605 os << "HeapSpaceRegion";
606}
607
608void UnknownSpaceRegion::dumpToStream(raw_ostream &os) const {
609 os << "UnknownSpaceRegion";
610}
611
612void StackArgumentsSpaceRegion::dumpToStream(raw_ostream &os) const {
613 os << "StackArgumentsSpaceRegion";
614}
615
616void StackLocalsSpaceRegion::dumpToStream(raw_ostream &os) const {
617 os << "StackLocalsSpaceRegion";
618}
619
620void ParamVarRegion::dumpToStream(raw_ostream &os) const {
621 const ParmVarDecl *PVD = getDecl();
622 assert(PVD &&
623 "`ParamVarRegion` support functions without `Decl` not implemented"
624 " yet.");
625 if (const IdentifierInfo *ID = PVD->getIdentifier()) {
626 os << ID->getName();
627 } else {
628 os << "ParamVarRegion{P" << PVD->getID() << '}';
629 }
630}
631
633 return canPrintPrettyAsExpr();
634}
635
637 return false;
638}
639
640StringRef MemRegion::getKindStr() const {
641 switch (getKind()) {
642#define REGION(Id, Parent) \
643 case Id##Kind: \
644 return #Id;
645#include "clang/StaticAnalyzer/Core/PathSensitive/Regions.def"
646#undef REGION
647 }
648 llvm_unreachable("Unkown kind!");
649}
650
651void MemRegion::printPretty(raw_ostream &os) const {
652 assert(canPrintPretty() && "This region cannot be printed pretty.");
653 os << "'";
655 os << "'";
656}
657
658void MemRegion::printPrettyAsExpr(raw_ostream &) const {
659 llvm_unreachable("This region cannot be printed pretty.");
660}
661
662bool NonParamVarRegion::canPrintPrettyAsExpr() const { return true; }
663
664void NonParamVarRegion::printPrettyAsExpr(raw_ostream &os) const {
665 os << getDecl()->getName();
666}
667
668bool ParamVarRegion::canPrintPrettyAsExpr() const { return true; }
669
670void ParamVarRegion::printPrettyAsExpr(raw_ostream &os) const {
671 assert(getDecl() &&
672 "`ParamVarRegion` support functions without `Decl` not implemented"
673 " yet.");
674 os << getDecl()->getName();
675}
676
678 return true;
679}
680
681void ObjCIvarRegion::printPrettyAsExpr(raw_ostream &os) const {
682 os << getDecl()->getName();
683}
684
686 return true;
687}
688
690 return superRegion->canPrintPrettyAsExpr();
691}
692
693void FieldRegion::printPrettyAsExpr(raw_ostream &os) const {
694 assert(canPrintPrettyAsExpr());
695 superRegion->printPrettyAsExpr(os);
696 os << "." << getDecl()->getName();
697}
698
699void FieldRegion::printPretty(raw_ostream &os) const {
700 if (canPrintPrettyAsExpr()) {
701 os << "\'";
703 os << "'";
704 } else {
705 os << "field " << "\'" << getDecl()->getName() << "'";
706 }
707}
708
710 return superRegion->canPrintPrettyAsExpr();
711}
712
713void CXXBaseObjectRegion::printPrettyAsExpr(raw_ostream &os) const {
714 superRegion->printPrettyAsExpr(os);
715}
716
718 return superRegion->canPrintPrettyAsExpr();
719}
720
721void CXXDerivedObjectRegion::printPrettyAsExpr(raw_ostream &os) const {
722 superRegion->printPrettyAsExpr(os);
723}
724
725std::string MemRegion::getDescriptiveName(bool UseQuotes) const {
726 std::string VariableName;
727 std::string ArrayIndices;
728 const MemRegion *R = this;
729 SmallString<50> buf;
730 llvm::raw_svector_ostream os(buf);
731
732 // Enclose subject with single quotes if needed.
733 auto QuoteIfNeeded = [UseQuotes](const Twine &Subject) -> std::string {
734 if (UseQuotes)
735 return ("'" + Subject + "'").str();
736 return Subject.str();
737 };
738
739 // Obtain array indices to add them to the variable name.
740 const ElementRegion *ER = nullptr;
741 while ((ER = R->getAs<ElementRegion>())) {
742 // Index is a ConcreteInt.
743 if (auto CI = ER->getIndex().getAs<nonloc::ConcreteInt>()) {
745 CI->getValue()->toString(Idx);
746 ArrayIndices = (llvm::Twine("[") + Idx.str() + "]" + ArrayIndices).str();
747 }
748 // Index is symbolic, but may have a descriptive name.
749 else {
750 auto SI = ER->getIndex().getAs<nonloc::SymbolVal>();
751 if (!SI)
752 return "";
753
754 const MemRegion *OR = SI->getAsSymbol()->getOriginRegion();
755 if (!OR)
756 return "";
757
758 std::string Idx = OR->getDescriptiveName(false);
759 if (Idx.empty())
760 return "";
761
762 ArrayIndices = (llvm::Twine("[") + Idx + "]" + ArrayIndices).str();
763 }
764 R = ER->getSuperRegion();
765 }
766
767 // Get variable name.
768 if (R) {
769 // MemRegion can be pretty printed.
770 if (R->canPrintPrettyAsExpr()) {
771 R->printPrettyAsExpr(os);
772 return QuoteIfNeeded(llvm::Twine(os.str()) + ArrayIndices);
773 }
774
775 // FieldRegion may have ElementRegion as SuperRegion.
776 if (const auto *FR = R->getAs<FieldRegion>()) {
777 std::string Super = FR->getSuperRegion()->getDescriptiveName(false);
778 if (Super.empty())
779 return "";
780 return QuoteIfNeeded(Super + "." + FR->getDecl()->getName());
781 }
782 }
783
784 return VariableName;
785}
786
788 // Check for more specific regions first.
789 if (auto *FR = dyn_cast<FieldRegion>(this)) {
790 return FR->getDecl()->getSourceRange();
791 }
792
793 if (auto *VR = dyn_cast<VarRegion>(this->getBaseRegion())) {
794 return VR->getDecl()->getSourceRange();
795 }
796
797 // Return invalid source range (can be checked by client).
798 return {};
799}
800
801//===----------------------------------------------------------------------===//
802// MemRegionManager methods.
803//===----------------------------------------------------------------------===//
804
806 SValBuilder &SVB) const {
807 const auto *SR = cast<SubRegion>(MR);
808 SymbolManager &SymMgr = SVB.getSymbolManager();
809
810 switch (SR->getKind()) {
811 case MemRegion::AllocaRegionKind:
812 case MemRegion::SymbolicRegionKind:
813 return nonloc::SymbolVal(SymMgr.acquire<SymbolExtent>(SR));
814 case MemRegion::StringRegionKind:
815 return SVB.makeIntVal(
816 cast<StringRegion>(SR)->getStringLiteral()->getByteLength() + 1,
817 SVB.getArrayIndexType());
818 case MemRegion::CompoundLiteralRegionKind:
819 case MemRegion::CXXBaseObjectRegionKind:
820 case MemRegion::CXXDerivedObjectRegionKind:
821 case MemRegion::CXXTempObjectRegionKind:
822 case MemRegion::CXXLifetimeExtendedObjectRegionKind:
823 case MemRegion::CXXThisRegionKind:
824 case MemRegion::ObjCIvarRegionKind:
825 case MemRegion::NonParamVarRegionKind:
826 case MemRegion::ParamVarRegionKind:
827 case MemRegion::ElementRegionKind:
828 case MemRegion::ObjCStringRegionKind: {
829 QualType Ty = cast<TypedValueRegion>(SR)->getDesugaredValueType(Ctx);
831 return nonloc::SymbolVal(SymMgr.acquire<SymbolExtent>(SR));
832
833 if (Ty->isIncompleteType())
834 return UnknownVal();
835
836 return getElementExtent(Ty, SVB);
837 }
838 case MemRegion::FieldRegionKind: {
839 // Force callers to deal with bitfields explicitly.
840 if (cast<FieldRegion>(SR)->getDecl()->isBitField())
841 return UnknownVal();
842
843 QualType Ty = cast<TypedValueRegion>(SR)->getDesugaredValueType(Ctx);
844 const DefinedOrUnknownSVal Size = getElementExtent(Ty, SVB);
845
846 // We currently don't model flexible array members (FAMs), which are:
847 // - int array[]; of IncompleteArrayType
848 // - int array[0]; of ConstantArrayType with size 0
849 // - int array[1]; of ConstantArrayType with size 1
850 // https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
851 const auto isFlexibleArrayMemberCandidate =
852 [this](const ArrayType *AT) -> bool {
853 if (!AT)
854 return false;
855
856 auto IsIncompleteArray = [](const ArrayType *AT) {
857 return isa<IncompleteArrayType>(AT);
858 };
859 auto IsArrayOfZero = [](const ArrayType *AT) {
860 const auto *CAT = dyn_cast<ConstantArrayType>(AT);
861 return CAT && CAT->isZeroSize();
862 };
863 auto IsArrayOfOne = [](const ArrayType *AT) {
864 const auto *CAT = dyn_cast<ConstantArrayType>(AT);
865 return CAT && CAT->getSize() == 1;
866 };
867
869 const FAMKind StrictFlexArraysLevel =
870 Ctx.getLangOpts().getStrictFlexArraysLevel();
871
872 // "Default": Any trailing array member is a FAM.
873 // Since we cannot tell at this point if this array is a trailing member
874 // or not, let's just do the same as for "OneZeroOrIncomplete".
875 if (StrictFlexArraysLevel == FAMKind::Default)
876 return IsArrayOfOne(AT) || IsArrayOfZero(AT) || IsIncompleteArray(AT);
877
878 if (StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
879 return IsArrayOfOne(AT) || IsArrayOfZero(AT) || IsIncompleteArray(AT);
880
881 if (StrictFlexArraysLevel == FAMKind::ZeroOrIncomplete)
882 return IsArrayOfZero(AT) || IsIncompleteArray(AT);
883
884 assert(StrictFlexArraysLevel == FAMKind::IncompleteOnly);
885 return IsIncompleteArray(AT);
886 };
887
888 if (isFlexibleArrayMemberCandidate(Ctx.getAsArrayType(Ty)))
889 return UnknownVal();
890
891 return Size;
892 }
893 // FIXME: The following are being used in 'SimpleSValBuilder' because there
894 // is no symbol to represent the regions more appropriately.
895 case MemRegion::BlockDataRegionKind:
896 case MemRegion::BlockCodeRegionKind:
897 case MemRegion::FunctionCodeRegionKind:
898 return nonloc::SymbolVal(SymMgr.acquire<SymbolExtent>(SR));
899 default:
900 llvm_unreachable("Unhandled region");
901 }
902}
903
904template <typename REG>
905const REG *MemRegionManager::LazyAllocate(REG*& region) {
906 if (!region) {
907 region = new (A) REG(*this);
908 }
909
910 return region;
911}
912
913template <typename REG, typename ARG>
914const REG *MemRegionManager::LazyAllocate(REG*& region, ARG a) {
915 if (!region) {
916 region = new (A) REG(this, a);
917 }
918
919 return region;
920}
921
924 assert(SF);
925 StackLocalsSpaceRegion *&R = StackLocalsSpaceRegions[SF];
926
927 if (R)
928 return R;
929
930 R = new (A) StackLocalsSpaceRegion(*this, SF);
931 return R;
932}
933
936 assert(SF);
937 StackArgumentsSpaceRegion *&R = StackArgumentsSpaceRegions[SF];
938
939 if (R)
940 return R;
941
942 R = new (A) StackArgumentsSpaceRegion(*this, SF);
943 return R;
944}
945
948 const CodeTextRegion *CR) {
949 if (!CR) {
950 if (K == MemRegion::GlobalSystemSpaceRegionKind)
951 return LazyAllocate(SystemGlobals);
952 if (K == MemRegion::GlobalImmutableSpaceRegionKind)
953 return LazyAllocate(ImmutableGlobals);
954 assert(K == MemRegion::GlobalInternalSpaceRegionKind);
955 return LazyAllocate(InternalGlobals);
956 }
957
958 assert(K == MemRegion::StaticGlobalSpaceRegionKind);
959 StaticGlobalSpaceRegion *&R = StaticsGlobalSpaceRegions[CR];
960 if (R)
961 return R;
962
963 R = new (A) StaticGlobalSpaceRegion(*this, CR);
964 return R;
965}
966
968 return LazyAllocate(heap);
969}
970
972 return LazyAllocate(unknown);
973}
974
976 return LazyAllocate(code);
977}
978
979//===----------------------------------------------------------------------===//
980// Constructing regions.
981//===----------------------------------------------------------------------===//
982
984 return getSubRegion<StringRegion>(
986}
987
988const ObjCStringRegion *
990 return getSubRegion<ObjCStringRegion>(
992}
993
994/// Look through a chain of StackFrames to either find the
995/// StackFrame that matches a DeclContext, or find a VarRegion
996/// for a variable captured by a block.
997static llvm::PointerUnion<const StackFrame *, const VarRegion *>
999 const DeclContext *DC,
1000 const VarDecl *VD) {
1001 while (SF) {
1002 if (cast<DeclContext>(SF->getDecl()) == DC)
1003 return SF;
1004 if (SF->getData()) {
1005 // FIXME: This can be made more efficient.
1006 for (auto Var : static_cast<const BlockDataRegion *>(SF->getData())
1007 ->referenced_vars()) {
1008 const TypedValueRegion *OrigR = Var.getOriginalRegion();
1009 if (const auto *VR = dyn_cast<VarRegion>(OrigR)) {
1010 if (VR->getDecl() == VD)
1011 return cast<VarRegion>(Var.getCapturedRegion());
1012 }
1013 }
1014 }
1015
1016 SF = SF->getParent();
1017 }
1018 return (const StackFrame *)nullptr;
1019}
1020
1021static bool isStdStreamVar(const VarDecl *D) {
1022 const IdentifierInfo *II = D->getIdentifier();
1023 if (!II)
1024 return false;
1025 if (!D->getDeclContext()->isTranslationUnit())
1026 return false;
1027 StringRef N = II->getName();
1028 QualType FILETy = D->getASTContext().getFILEType();
1029 if (FILETy.isNull())
1030 return false;
1031 FILETy = FILETy.getCanonicalType();
1032 QualType Ty = D->getType().getCanonicalType();
1033 return Ty->isPointerType() && Ty->getPointeeType() == FILETy &&
1034 (N == "stdin" || N == "stdout" || N == "stderr");
1035}
1036
1038 const StackFrame *SF) {
1039 const auto *PVD = dyn_cast<ParmVarDecl>(D);
1040 if (PVD) {
1041 unsigned Index = PVD->getFunctionScopeIndex();
1042 const Expr *CallSite = SF->getCallSite();
1043 if (CallSite) {
1044 const Decl *CalleeDecl = SF->getDecl();
1045 bool CurrentParam = true;
1046 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl)) {
1047 CurrentParam =
1048 (Index < FD->param_size() && FD->getParamDecl(Index) == PVD);
1049 } else if (const auto *BD = dyn_cast<BlockDecl>(CalleeDecl)) {
1050 CurrentParam =
1051 (Index < BD->param_size() && BD->getParamDecl(Index) == PVD);
1052 }
1053
1054 if (CurrentParam) {
1055 // If this is a parameter of the *current* stack frame, we can
1056 // represent it with a `ParamVarRegion`.
1057 return getSubRegion<ParamVarRegion>(CallSite, Index,
1059 } else {
1060 // TODO: Parameters of other stack frames (which may have been be
1061 // captured by a lambda or a block) are currently represented by
1062 // `NonParamVarRegion`s. This behavior is present since commit
1063 // 98db1f990fc273adc1ae36d4ce97ce66fd27ac30 which introduced
1064 // `ParamVarRegion` in 2020; and appears to work (at least to some
1065 // extent); but it would be nice to clean this up (if somebody has time
1066 // and knowledge for a proper investigation).
1067 }
1068 } else {
1069 // TODO: Parameters of the entrypoint stack frame (where `CallSite` is
1070 // null) are currently represented by `NonParamVarRegion`s. This behavior
1071 // is also present since 98db1f990fc273adc1ae36d4ce97ce66fd27ac30 which
1072 // introduced `ParamVarRegion` in 2020, but it would be nice to clean it
1073 // up for the sake of clarity and consistency.
1074 }
1075 }
1076
1077 D = D->getCanonicalDecl();
1078 const MemRegion *sReg = nullptr;
1079
1080 if (D->hasGlobalStorage() && !D->isStaticLocal()) {
1081 QualType Ty = D->getType();
1082 assert(!Ty.isNull());
1083 if (Ty.isConstQualified()) {
1084 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
1085 } else {
1086 // Pointer value of C standard streams is usually not modified by calls
1087 // to functions declared in system headers. This means that they should
1088 // not get invalidated by calls to functions declared in system headers,
1089 // so they are placed in the global internal space, which is not
1090 // invalidated by calls to functions declared in system headers.
1091 if (Ctx.getSourceManager().isInSystemHeader(D->getLocation()) &&
1092 !isStdStreamVar(D)) {
1093 sReg = getGlobalsRegion(MemRegion::GlobalSystemSpaceRegionKind);
1094 } else {
1095 sReg = getGlobalsRegion(MemRegion::GlobalInternalSpaceRegionKind);
1096 }
1097 }
1098
1099 // Finally handle static locals.
1100 } else {
1101 // FIXME: Once we implement scope handling, we will need to properly lookup
1102 // 'D' to the proper StackFrame.
1103 const DeclContext *DC = D->getDeclContext();
1104 llvm::PointerUnion<const StackFrame *, const VarRegion *> V =
1106
1107 if (const auto *VR = dyn_cast_if_present<const VarRegion *>(V))
1108 return VR;
1109
1110 const auto *SF = cast<const StackFrame *>(V);
1111
1112 if (!SF) {
1113 // FIXME: Assign a more sensible memory space to static locals
1114 // we see from within blocks that we analyze as top-level declarations.
1115 sReg = getUnknownRegion();
1116 } else {
1117 if (D->hasLocalStorage()) {
1119 ? static_cast<const MemRegion *>(getStackArgumentsRegion(SF))
1120 : static_cast<const MemRegion *>(getStackLocalsRegion(SF));
1121 }
1122 else {
1123 assert(D->isStaticLocal());
1124 const Decl *STCD = SF->getDecl();
1126 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
1128 else if (const auto *BD = dyn_cast<BlockDecl>(STCD)) {
1129 // FIXME: The fallback type here is totally bogus -- though it should
1130 // never be queried, it will prevent uniquing with the real
1131 // BlockCodeRegion. Ideally we'd fix the AST so that we always had a
1132 // signature.
1133 QualType T;
1134 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten())
1135 T = TSI->getType();
1136 if (T.isNull())
1137 T = getContext().VoidTy;
1138 if (!T->getAs<FunctionType>()) {
1140 T = getContext().getFunctionType(T, {}, Ext);
1141 }
1143
1145 BD, Ctx.getCanonicalType(T), SF->getAnalysisDeclContext());
1146 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
1147 BTR);
1148 }
1149 else {
1150 sReg = getGlobalsRegion();
1151 }
1152 }
1153 }
1154 }
1155
1156 return getNonParamVarRegion(D, sReg);
1157}
1158
1159const NonParamVarRegion *
1161 const MemRegion *superR) {
1162 // Prefer the definition over the canonical decl as the canonical form.
1163 D = D->getCanonicalDecl();
1164 if (const VarDecl *Def = D->getDefinition())
1165 D = Def;
1166 return getSubRegion<NonParamVarRegion>(D, superR);
1167}
1168
1169const ParamVarRegion *
1170MemRegionManager::getParamVarRegion(const Expr *OriginExpr, unsigned Index,
1171 const StackFrame *SF) {
1172 assert(SF);
1173 return getSubRegion<ParamVarRegion>(OriginExpr, Index,
1175}
1176
1178 const BlockCodeRegion *BC, const StackFrame *SF, unsigned blockCount) {
1179 const MemSpaceRegion *sReg = nullptr;
1180 const BlockDecl *BD = BC->getDecl();
1181 if (!BD->hasCaptures()) {
1182 // This handles 'static' blocks.
1183 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
1184 }
1185 else {
1186 bool IsArcManagedBlock = Ctx.getLangOpts().ObjCAutoRefCount;
1187
1188 // ARC managed blocks can be initialized on stack or directly in heap
1189 // depending on the implementations. So we initialize them with
1190 // UnknownRegion.
1191 if (!IsArcManagedBlock && SF) {
1192 // FIXME: Once we implement scope handling, we want the parent region
1193 // to be the scope.
1194 assert(SF);
1195 sReg = getStackLocalsRegion(SF);
1196 } else {
1197 // We allow 'SF' to be NULL for cases where want BlockDataRegions
1198 // without context-sensitivity.
1199 sReg = getUnknownRegion();
1200 }
1201 }
1202
1203 return getSubRegion<BlockDataRegion>(BC, SF, blockCount, sReg);
1204}
1205
1208 const StackFrame *SF) {
1209 const MemSpaceRegion *sReg = nullptr;
1210
1211 if (CL->isFileScope())
1212 sReg = getGlobalsRegion();
1213 else {
1214 assert(SF);
1215 sReg = getStackLocalsRegion(SF);
1216 }
1217
1218 return getSubRegion<CompoundLiteralRegion>(CL, sReg);
1219}
1220
1221const ElementRegion *
1223 const SubRegion *superRegion,
1224 const ASTContext &Ctx) {
1225 QualType T = Ctx.getCanonicalType(elementType).getUnqualifiedType();
1226
1227 // The address space must be preserved because some target-specific address
1228 // spaces influence the size of the pointer value which is represented by the
1229 // element region.
1230 LangAS AS = elementType.getAddressSpace();
1231 if (AS != LangAS::Default) {
1232 Qualifiers Quals;
1233 Quals.setAddressSpace(AS);
1234 T = Ctx.getQualifiedType(T, Quals);
1235 }
1236
1237 llvm::FoldingSetNodeID ID;
1238 ElementRegion::ProfileRegion(ID, T, Idx, superRegion);
1239
1240 void *InsertPos;
1241 MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos);
1242 auto *R = cast_or_null<ElementRegion>(data);
1243
1244 if (!R) {
1245 R = new (A) ElementRegion(T, Idx, superRegion);
1246 Regions.InsertNode(R, InsertPos);
1247 }
1248
1249 return R;
1250}
1251
1252const FunctionCodeRegion *
1254 // To think: should we canonicalize the declaration here?
1255 return getSubRegion<FunctionCodeRegion>(FD, getCodeRegion());
1256}
1257
1258const BlockCodeRegion *
1260 AnalysisDeclContext *AC) {
1261 return getSubRegion<BlockCodeRegion>(BD, locTy, AC, getCodeRegion());
1262}
1263
1264const SymbolicRegion *
1266 const MemSpaceRegion *MemSpace) {
1267 if (MemSpace == nullptr)
1268 MemSpace = getUnknownRegion();
1269 return getSubRegion<SymbolicRegion>(sym, MemSpace);
1270}
1271
1273 return getSubRegion<SymbolicRegion>(Sym, getHeapRegion());
1274}
1275
1276const FieldRegion *
1278 const SubRegion *SuperRegion) {
1279 return getSubRegion<FieldRegion>(FD->getCanonicalDecl(), SuperRegion);
1280}
1281
1282const ObjCIvarRegion*
1284 const SubRegion* superRegion) {
1285 return getSubRegion<ObjCIvarRegion>(d, superRegion);
1286}
1287
1288const CXXTempObjectRegion *
1290 assert(SF);
1291 return getSubRegion<CXXTempObjectRegion>(E, getStackLocalsRegion(SF));
1292}
1293
1296 const ValueDecl *VD,
1297 const StackFrame *SF) {
1298 assert(SF);
1299 return getSubRegion<CXXLifetimeExtendedObjectRegion>(
1300 Ex, VD, getStackLocalsRegion(SF));
1301}
1302
1305 const Expr *Ex, const ValueDecl *VD) {
1306 return getSubRegion<CXXLifetimeExtendedObjectRegion>(
1307 Ex, VD,
1308 getGlobalsRegion(MemRegion::GlobalInternalSpaceRegionKind, nullptr));
1309}
1310
1311/// Checks whether \p BaseClass is a valid virtual or direct non-virtual base
1312/// class of the type of \p Super.
1313static bool isValidBaseClass(const CXXRecordDecl *BaseClass,
1314 const TypedValueRegion *Super,
1315 bool IsVirtual) {
1316 BaseClass = BaseClass->getCanonicalDecl();
1317
1318 const CXXRecordDecl *Class = Super->getValueType()->getAsCXXRecordDecl();
1319 if (!Class)
1320 return true;
1321
1322 if (IsVirtual)
1323 return Class->isVirtuallyDerivedFrom(BaseClass);
1324
1325 for (const auto &I : Class->bases()) {
1326 if (I.getType()->getAsCXXRecordDecl()->getCanonicalDecl() == BaseClass)
1327 return true;
1328 }
1329
1330 return false;
1331}
1332
1333const CXXBaseObjectRegion *
1335 const SubRegion *Super,
1336 bool IsVirtual) {
1337 if (isa<TypedValueRegion>(Super)) {
1338 assert(isValidBaseClass(RD, cast<TypedValueRegion>(Super), IsVirtual));
1339 (void)&isValidBaseClass;
1340
1341 if (IsVirtual) {
1342 // Virtual base regions should not be layered, since the layout rules
1343 // are different.
1344 while (const auto *Base = dyn_cast<CXXBaseObjectRegion>(Super))
1345 Super = cast<SubRegion>(Base->getSuperRegion());
1346 assert(Super && !isa<MemSpaceRegion>(Super));
1347 }
1348 }
1349
1350 return getSubRegion<CXXBaseObjectRegion>(RD, IsVirtual, Super);
1351}
1352
1355 const SubRegion *Super) {
1356 return getSubRegion<CXXDerivedObjectRegion>(RD, Super);
1357}
1358
1360 const StackFrame *SF) {
1361 const auto *PT = thisPointerTy->getAs<PointerType>();
1362 assert(PT);
1363 // Inside the body of the operator() of a lambda a this expr might refer to an
1364 // object in one of the parent stack frames.
1365 const auto *D = dyn_cast<CXXMethodDecl>(SF->getDecl());
1366 // FIXME: when operator() of lambda is analyzed as a top level function and
1367 // 'this' refers to a this to the enclosing scope, there is no right region to
1368 // return.
1369 while (!SF->inTopFrame() && (!D || D->isStatic() ||
1370 PT != D->getThisType()->getAs<PointerType>())) {
1371 SF = SF->getParent();
1372 D = dyn_cast<CXXMethodDecl>(SF->getDecl());
1373 }
1374 assert(SF);
1375 return getSubRegion<CXXThisRegion>(PT, getStackArgumentsRegion(SF));
1376}
1377
1379 unsigned cnt,
1380 const StackFrame *SF) {
1381 assert(SF);
1382 return getSubRegion<AllocaRegion>(E, cnt, getStackLocalsRegion(SF));
1383}
1384
1386 const MemRegion *R = this;
1387 const auto *SR = dyn_cast<SubRegion>(this);
1388
1389 while (SR) {
1390 R = SR->getSuperRegion();
1391 SR = dyn_cast<SubRegion>(R);
1392 }
1393
1394 return cast<MemSpaceRegion>(R);
1395}
1396
1398 const MemRegion *MR = getBaseRegion();
1399
1400 const MemSpaceRegion *RawSpace = MR->getRawMemorySpace();
1401 if (!isa<UnknownSpaceRegion>(RawSpace))
1402 return RawSpace;
1403
1404 const MemSpaceRegion *const *AssociatedSpace = State->get<MemSpacesMap>(MR);
1405 return AssociatedSpace ? *AssociatedSpace : RawSpace;
1406}
1407
1409 const MemSpaceRegion *Space) const {
1410 const MemRegion *Base = getBaseRegion();
1411
1412 // Shouldn't set unknown space.
1413 assert(!isa<UnknownSpaceRegion>(Space));
1414
1415 // Currently, it we should have no accurate memspace for this region.
1416 assert(Base->hasMemorySpace<UnknownSpaceRegion>(State));
1417 return State->set<MemSpacesMap>(Base, Space);
1418}
1419
1420// Strips away all elements and fields.
1421// Returns the base region of them.
1423 const MemRegion *R = this;
1424 while (true) {
1425 switch (R->getKind()) {
1426 case MemRegion::ElementRegionKind:
1427 case MemRegion::FieldRegionKind:
1428 case MemRegion::ObjCIvarRegionKind:
1429 case MemRegion::CXXBaseObjectRegionKind:
1430 case MemRegion::CXXDerivedObjectRegionKind:
1431 R = cast<SubRegion>(R)->getSuperRegion();
1432 continue;
1433 default:
1434 break;
1435 }
1436 break;
1437 }
1438 return R;
1439}
1440
1441// Returns the region of the root class of a C++ class hierarchy.
1443 const MemRegion *R = this;
1444 while (const auto *BR = dyn_cast<CXXBaseObjectRegion>(R))
1445 R = BR->getSuperRegion();
1446 return R;
1447}
1448
1450 return false;
1451}
1452
1453//===----------------------------------------------------------------------===//
1454// View handling.
1455//===----------------------------------------------------------------------===//
1456
1457const MemRegion *MemRegion::StripCasts(bool StripBaseAndDerivedCasts) const {
1458 const MemRegion *R = this;
1459 while (true) {
1460 switch (R->getKind()) {
1461 case ElementRegionKind: {
1462 const auto *ER = cast<ElementRegion>(R);
1463 if (!ER->getIndex().isZeroConstant())
1464 return R;
1465 R = ER->getSuperRegion();
1466 break;
1467 }
1468 case CXXBaseObjectRegionKind:
1469 case CXXDerivedObjectRegionKind:
1470 if (!StripBaseAndDerivedCasts)
1471 return R;
1472 R = cast<TypedValueRegion>(R)->getSuperRegion();
1473 break;
1474 default:
1475 return R;
1476 }
1477 }
1478}
1479
1481 const auto *SubR = dyn_cast<SubRegion>(this);
1482
1483 while (SubR) {
1484 if (const auto *SymR = dyn_cast<SymbolicRegion>(SubR))
1485 return SymR;
1486 SubR = dyn_cast<SubRegion>(SubR->getSuperRegion());
1487 }
1488 return nullptr;
1489}
1490
1492 int64_t offset = 0;
1493 const ElementRegion *ER = this;
1494 const MemRegion *superR = nullptr;
1495 ASTContext &C = getContext();
1496
1497 // FIXME: Handle multi-dimensional arrays.
1498
1499 while (ER) {
1500 superR = ER->getSuperRegion();
1501
1502 // FIXME: generalize to symbolic offsets.
1503 SVal index = ER->getIndex();
1504 if (auto CI = index.getAs<nonloc::ConcreteInt>()) {
1505 // Update the offset.
1506 if (int64_t i = CI->getValue()->getSExtValue(); i != 0) {
1507 QualType elemType = ER->getElementType();
1508
1509 // If we are pointing to an incomplete type, go no further.
1510 if (elemType->isIncompleteType()) {
1511 superR = ER;
1512 break;
1513 }
1514
1515 int64_t size = C.getTypeSizeInChars(elemType).getQuantity();
1516 if (auto NewOffset = llvm::checkedMulAdd(i, size, offset)) {
1517 offset = *NewOffset;
1518 } else {
1519 LLVM_DEBUG(llvm::dbgs() << "MemRegion::getAsArrayOffset: "
1520 << "offset overflowing, returning unknown\n");
1521
1522 return nullptr;
1523 }
1524 }
1525
1526 // Go to the next ElementRegion (if any).
1527 ER = dyn_cast<ElementRegion>(superR);
1528 continue;
1529 }
1530
1531 return nullptr;
1532 }
1533
1534 assert(superR && "super region cannot be NULL");
1535 return RegionRawOffset(superR, CharUnits::fromQuantity(offset));
1536}
1537
1538/// Returns true if \p Base is an immediate base class of \p Child
1539static bool isImmediateBase(const CXXRecordDecl *Child,
1540 const CXXRecordDecl *Base) {
1541 assert(Child && "Child must not be null");
1542 // Note that we do NOT canonicalize the base class here, because
1543 // ASTRecordLayout doesn't either. If that leads us down the wrong path,
1544 // so be it; at least we won't crash.
1545 for (const auto &I : Child->bases()) {
1546 if (I.getType()->getAsCXXRecordDecl() == Base)
1547 return true;
1548 }
1549
1550 return false;
1551}
1552
1554 const MemRegion *SymbolicOffsetBase = nullptr;
1555 int64_t Offset = 0;
1556
1557 while (true) {
1558 switch (R->getKind()) {
1559 case MemRegion::CodeSpaceRegionKind:
1560 case MemRegion::StackLocalsSpaceRegionKind:
1561 case MemRegion::StackArgumentsSpaceRegionKind:
1562 case MemRegion::HeapSpaceRegionKind:
1563 case MemRegion::UnknownSpaceRegionKind:
1564 case MemRegion::StaticGlobalSpaceRegionKind:
1565 case MemRegion::GlobalInternalSpaceRegionKind:
1566 case MemRegion::GlobalSystemSpaceRegionKind:
1567 case MemRegion::GlobalImmutableSpaceRegionKind:
1568 // Stores can bind directly to a region space to set a default value.
1569 assert(Offset == 0 && !SymbolicOffsetBase);
1570 goto Finish;
1571
1572 case MemRegion::FunctionCodeRegionKind:
1573 case MemRegion::BlockCodeRegionKind:
1574 case MemRegion::BlockDataRegionKind:
1575 // These will never have bindings, but may end up having values requested
1576 // if the user does some strange casting.
1577 if (Offset != 0)
1578 SymbolicOffsetBase = R;
1579 goto Finish;
1580
1581 case MemRegion::SymbolicRegionKind:
1582 case MemRegion::AllocaRegionKind:
1583 case MemRegion::CompoundLiteralRegionKind:
1584 case MemRegion::CXXThisRegionKind:
1585 case MemRegion::StringRegionKind:
1586 case MemRegion::ObjCStringRegionKind:
1587 case MemRegion::NonParamVarRegionKind:
1588 case MemRegion::ParamVarRegionKind:
1589 case MemRegion::CXXTempObjectRegionKind:
1590 case MemRegion::CXXLifetimeExtendedObjectRegionKind:
1591 // Usual base regions.
1592 goto Finish;
1593
1594 case MemRegion::ObjCIvarRegionKind:
1595 // This is a little strange, but it's a compromise between
1596 // ObjCIvarRegions having unknown compile-time offsets (when using the
1597 // non-fragile runtime) and yet still being distinct, non-overlapping
1598 // regions. Thus we treat them as "like" base regions for the purposes
1599 // of computing offsets.
1600 goto Finish;
1601
1602 case MemRegion::CXXBaseObjectRegionKind: {
1603 const auto *BOR = cast<CXXBaseObjectRegion>(R);
1604 R = BOR->getSuperRegion();
1605
1606 QualType Ty;
1607 bool RootIsSymbolic = false;
1608 if (const auto *TVR = dyn_cast<TypedValueRegion>(R)) {
1609 Ty = TVR->getDesugaredValueType(R->getContext());
1610 } else if (const auto *SR = dyn_cast<SymbolicRegion>(R)) {
1611 // If our base region is symbolic, we don't know what type it really is.
1612 // Pretend the type of the symbol is the true dynamic type.
1613 // (This will at least be self-consistent for the life of the symbol.)
1614 Ty = SR->getPointeeStaticType();
1615 RootIsSymbolic = true;
1616 }
1617
1618 const CXXRecordDecl *Child = Ty->getAsCXXRecordDecl();
1619 if (!Child) {
1620 // We cannot compute the offset of the base class.
1621 SymbolicOffsetBase = R;
1622 } else {
1623 if (RootIsSymbolic) {
1624 // Base layers on symbolic regions may not be type-correct.
1625 // Double-check the inheritance here, and revert to a symbolic offset
1626 // if it's invalid (e.g. due to a reinterpret_cast).
1627 if (BOR->isVirtual()) {
1628 if (!Child->isVirtuallyDerivedFrom(BOR->getDecl()))
1629 SymbolicOffsetBase = R;
1630 } else {
1631 if (!isImmediateBase(Child, BOR->getDecl()))
1632 SymbolicOffsetBase = R;
1633 }
1634 }
1635 }
1636
1637 // Don't bother calculating precise offsets if we already have a
1638 // symbolic offset somewhere in the chain.
1639 if (SymbolicOffsetBase)
1640 continue;
1641
1642 CharUnits BaseOffset;
1643 const ASTRecordLayout &Layout = R->getContext().getASTRecordLayout(Child);
1644 if (BOR->isVirtual())
1645 BaseOffset = Layout.getVBaseClassOffset(BOR->getDecl());
1646 else
1647 BaseOffset = Layout.getBaseClassOffset(BOR->getDecl());
1648
1649 // The base offset is in chars, not in bits.
1650 Offset += BaseOffset.getQuantity() * R->getContext().getCharWidth();
1651 break;
1652 }
1653
1654 case MemRegion::CXXDerivedObjectRegionKind: {
1655 // TODO: Store the base type in the CXXDerivedObjectRegion and use it.
1656 goto Finish;
1657 }
1658
1659 case MemRegion::ElementRegionKind: {
1660 const auto *ER = cast<ElementRegion>(R);
1661 R = ER->getSuperRegion();
1662
1663 QualType EleTy = ER->getValueType();
1664 if (EleTy->isIncompleteType()) {
1665 // We cannot compute the offset of the base class.
1666 SymbolicOffsetBase = R;
1667 continue;
1668 }
1669
1670 SVal Index = ER->getIndex();
1671 if (std::optional<nonloc::ConcreteInt> CI =
1672 Index.getAs<nonloc::ConcreteInt>()) {
1673 // Don't bother calculating precise offsets if we already have a
1674 // symbolic offset somewhere in the chain.
1675 if (SymbolicOffsetBase)
1676 continue;
1677
1678 int64_t i = CI->getValue()->getSExtValue();
1679 // This type size is in bits.
1680 Offset += i * R->getContext().getTypeSize(EleTy);
1681 } else {
1682 // We cannot compute offset for non-concrete index.
1683 SymbolicOffsetBase = R;
1684 }
1685 break;
1686 }
1687 case MemRegion::FieldRegionKind: {
1688 const auto *FR = cast<FieldRegion>(R);
1689 R = FR->getSuperRegion();
1690 assert(R);
1691
1692 const RecordDecl *RD = FR->getDecl()->getParent();
1693 if (RD->isUnion() || !RD->isCompleteDefinition()) {
1694 // We cannot compute offset for incomplete type.
1695 // For unions, we could treat everything as offset 0, but we'd rather
1696 // treat each field as a symbolic offset so they aren't stored on top
1697 // of each other, since we depend on things in typed regions actually
1698 // matching their types.
1699 SymbolicOffsetBase = R;
1700 }
1701
1702 // Don't bother calculating precise offsets if we already have a
1703 // symbolic offset somewhere in the chain.
1704 if (SymbolicOffsetBase)
1705 continue;
1706
1707 assert(FR->getDecl()->getCanonicalDecl() == FR->getDecl());
1708 auto MaybeFieldIdx = [FR, RD]() -> std::optional<unsigned> {
1709 for (auto [Idx, Field] : llvm::enumerate(RD->fields())) {
1710 if (FR->getDecl() == Field->getCanonicalDecl())
1711 return Idx;
1712 }
1713 return std::nullopt;
1714 }();
1715
1716 if (!MaybeFieldIdx.has_value()) {
1717 assert(false && "Field not found");
1718 goto Finish; // Invalid offset.
1719 }
1720
1721 const ASTRecordLayout &Layout = R->getContext().getASTRecordLayout(RD);
1722 // This is offset in bits.
1723 Offset += Layout.getFieldOffset(MaybeFieldIdx.value());
1724 break;
1725 }
1726 }
1727 }
1728
1729 Finish:
1730 if (SymbolicOffsetBase)
1731 return RegionOffset(SymbolicOffsetBase, RegionOffset::Symbolic);
1732 return RegionOffset(R, Offset);
1733}
1734
1736 if (!cachedOffset)
1737 cachedOffset = calculateOffset(this);
1738 return *cachedOffset;
1739}
1740
1741//===----------------------------------------------------------------------===//
1742// BlockDataRegion
1743//===----------------------------------------------------------------------===//
1744
1745std::pair<const VarRegion *, const VarRegion *>
1746BlockDataRegion::getCaptureRegions(const VarDecl *VD) {
1748 const VarRegion *VR = nullptr;
1749 const VarRegion *OriginalVR = nullptr;
1750
1751 if (!VD->hasAttr<BlocksAttr>() && VD->hasLocalStorage()) {
1752 VR = MemMgr.getNonParamVarRegion(VD, this);
1753 OriginalVR = MemMgr.getVarRegion(VD, SF);
1754 }
1755 else {
1756 if (SF) {
1757 VR = MemMgr.getVarRegion(VD, SF);
1758 OriginalVR = VR;
1759 } else {
1760 VR = MemMgr.getNonParamVarRegion(VD, MemMgr.getUnknownRegion());
1761 OriginalVR = MemMgr.getVarRegion(VD, SF);
1762 }
1763 }
1764 return std::make_pair(VR, OriginalVR);
1765}
1766
1767void BlockDataRegion::LazyInitializeReferencedVars() {
1768 if (ReferencedVars)
1769 return;
1770
1771 AnalysisDeclContext *AC = getCodeRegion()->getAnalysisDeclContext();
1772 const auto &ReferencedBlockVars = AC->getReferencedBlockVars(BC->getDecl());
1773 auto NumBlockVars =
1774 std::distance(ReferencedBlockVars.begin(), ReferencedBlockVars.end());
1775
1776 if (NumBlockVars == 0) {
1777 ReferencedVars = (void*) 0x1;
1778 return;
1779 }
1780
1782 llvm::BumpPtrAllocator &A = MemMgr.getAllocator();
1783 BumpVectorContext BC(A);
1784
1785 using VarVec = BumpVector<const MemRegion *>;
1786
1787 auto *BV = new (A) VarVec(BC, NumBlockVars);
1788 auto *BVOriginal = new (A) VarVec(BC, NumBlockVars);
1789
1790 for (const auto *VD : ReferencedBlockVars) {
1791 const VarRegion *VR = nullptr;
1792 const VarRegion *OriginalVR = nullptr;
1793 std::tie(VR, OriginalVR) = getCaptureRegions(VD);
1794 assert(VR);
1795 assert(OriginalVR);
1796 BV->push_back(VR, BC);
1797 BVOriginal->push_back(OriginalVR, BC);
1798 }
1799
1800 ReferencedVars = BV;
1801 OriginalVars = BVOriginal;
1802}
1803
1806 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1807
1808 auto *Vec = static_cast<BumpVector<const MemRegion *> *>(ReferencedVars);
1809
1810 if (Vec == (void*) 0x1)
1811 return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1812
1813 auto *VecOriginal =
1814 static_cast<BumpVector<const MemRegion *> *>(OriginalVars);
1815
1817 VecOriginal->begin());
1818}
1819
1822 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1823
1824 auto *Vec = static_cast<BumpVector<const MemRegion *> *>(ReferencedVars);
1825
1826 if (Vec == (void*) 0x1)
1827 return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1828
1829 auto *VecOriginal =
1830 static_cast<BumpVector<const MemRegion *> *>(OriginalVars);
1831
1833 VecOriginal->end());
1834}
1835
1836llvm::iterator_range<BlockDataRegion::referenced_vars_iterator>
1838 return llvm::make_range(referenced_vars_begin(), referenced_vars_end());
1839}
1840
1842 for (const auto &I : referenced_vars()) {
1843 if (I.getCapturedRegion() == R)
1844 return I.getOriginalRegion();
1845 }
1846 return nullptr;
1847}
1848
1849//===----------------------------------------------------------------------===//
1850// RegionAndSymbolInvalidationTraits
1851//===----------------------------------------------------------------------===//
1852
1854 InvalidationKinds IK) {
1855 SymTraitsMap[Sym] |= IK;
1856}
1857
1859 InvalidationKinds IK) {
1860 assert(MR);
1861 if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1862 setTrait(SR->getSymbol(), IK);
1863 else
1864 MRTraitsMap[MR] |= IK;
1865}
1866
1868 InvalidationKinds IK) const {
1869 const_symbol_iterator I = SymTraitsMap.find(Sym);
1870 if (I != SymTraitsMap.end())
1871 return I->second & IK;
1872
1873 return false;
1874}
1875
1877 InvalidationKinds IK) const {
1878 if (!MR)
1879 return false;
1880
1881 if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1882 return hasTrait(SR->getSymbol(), IK);
1883
1884 const_region_iterator I = MRTraitsMap.find(MR);
1885 if (I != MRTraitsMap.end())
1886 return I->second & IK;
1887
1888 return false;
1889}
Defines the clang::ASTContext interface.
#define V(N, I)
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
static bool isStdStreamVar(const VarDecl *D)
static llvm::PointerUnion< const StackFrame *, const VarRegion * > getStackOrCaptureRegionForDeclContext(const StackFrame *SF, const DeclContext *DC, const VarDecl *VD)
Look through a chain of StackFrames to either find the StackFrame that matches a DeclContext,...
static bool isImmediateBase(const CXXRecordDecl *Child, const CXXRecordDecl *Base)
Returns true if Base is an immediate base class of Child.
static bool isValidBaseClass(const CXXRecordDecl *BaseClass, const TypedValueRegion *Super, bool IsVirtual)
Checks whether BaseClass is a valid virtual or direct non-virtual base class of the type of Super.
static RegionOffset calculateOffset(const MemRegion *R)
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
Defines the SourceManager interface.
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
QualType getFILEType() const
Retrieve the C FILE type.
CanQualType VoidTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
CanQualType getCanonicalTagType(const TagDecl *TD) const
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
AnalysisDeclContext contains the context data for the function, method or block under analysis.
llvm::iterator_range< referenced_decls_iterator > getReferencedBlockVars(const BlockDecl *BD)
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3784
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4694
size_t param_size() const
Definition Decl.h:4796
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4813
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:4800
TypeSourceInfo * getSignatureAsWritten() const
Definition Decl.h:4777
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is virtually derived from the class Base.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3608
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool isTranslationUnit() const
Definition DeclBase.h:2198
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
int64_t getID() const
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
bool hasAttr() const
Definition DeclBase.h:585
std::string getAsString() const
Retrieve the human-readable string for this name.
This represents one expression.
Definition Expr.h:112
Represents a member of a struct/union/class.
Definition Decl.h:3182
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition Decl.h:3429
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4565
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:84
Represents a parameter to a function.
Definition Decl.h:1808
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3390
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8566
QualType getCanonicalType() const
Definition TypeBase.h:8492
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8534
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8513
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
Represents a struct/union/class.
Definition Decl.h:4347
field_range fields() const
Definition Decl.h:4550
A trivial tuple used to represent a source range.
It represents a stack frame of the call stack.
const void * getData() const
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
const Expr * getCallSite() const
const Decl * getDecl() const
const StackFrame * getParent() const
It might return null.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3840
bool isUnion() const
Definition Decl.h:3950
A container of type source information.
Definition TypeBase.h:8411
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isPointerType() const
Definition TypeBase.h:8677
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:790
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2528
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9270
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2236
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1239
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2345
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1206
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1182
AllocaRegion - A region that represents an untyped blob of bytes created by a call to 'alloca'.
Definition MemRegion.h:505
void dumpToStream(raw_ostream &os) const override
void Profile(llvm::FoldingSetNodeID &ID) const override
BlockCodeRegion - A region that represents code texts of blocks (closures).
Definition MemRegion.h:658
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
Definition MemRegion.h:688
void dumpToStream(raw_ostream &os) const override
LLVM_ATTRIBUTE_RETURNS_NONNULL const BlockDecl * getDecl() const
Definition MemRegion.h:683
void Profile(llvm::FoldingSetNodeID &ID) const override
BlockDataRegion - A region that represents a block instance.
Definition MemRegion.h:705
const VarRegion * getOriginalRegion(const VarRegion *VR) const
Return the original region for a captured region, if one exists.
referenced_vars_iterator referenced_vars_begin() const
LLVM_ATTRIBUTE_RETURNS_NONNULL const BlockCodeRegion * getCodeRegion() const
Definition MemRegion.h:731
void Profile(llvm::FoldingSetNodeID &ID) const override
referenced_vars_iterator referenced_vars_end() const
void dumpToStream(raw_ostream &os) const override
llvm::iterator_range< referenced_vars_iterator > referenced_vars() const
void printPrettyAsExpr(raw_ostream &os) const override
Print the region as expression.
LLVM_ATTRIBUTE_RETURNS_NONNULL const CXXRecordDecl * getDecl() const
Definition MemRegion.h:1358
bool canPrintPrettyAsExpr() const override
Returns true if this region's textual representation can be used as part of a larger expression.
void Profile(llvm::FoldingSetNodeID &ID) const override
void dumpToStream(raw_ostream &os) const override
QualType getValueType() const override
void printPrettyAsExpr(raw_ostream &os) const override
Print the region as expression.
void Profile(llvm::FoldingSetNodeID &ID) const override
QualType getValueType() const override
void dumpToStream(raw_ostream &os) const override
bool canPrintPrettyAsExpr() const override
Returns true if this region's textual representation can be used as part of a larger expression.
LLVM_ATTRIBUTE_RETURNS_NONNULL const CXXRecordDecl * getDecl() const
Definition MemRegion.h:1401
void Profile(llvm::FoldingSetNodeID &ID) const override
const StackFrame * getStackFrame() const
It might return null.
void dumpToStream(raw_ostream &os) const override
QualType getValueType() const override
Definition MemRegion.h:1290
LLVM_ATTRIBUTE_RETURNS_NONNULL const StackFrame * getStackFrame() const
void Profile(llvm::FoldingSetNodeID &ID) const override
void dumpToStream(raw_ostream &os) const override
CXXThisRegion - Represents the region for the implicit 'this' parameter in a call to a C++ method.
Definition MemRegion.h:1105
void Profile(llvm::FoldingSetNodeID &ID) const override
void dumpToStream(raw_ostream &os) const override
CodeSpaceRegion - The memory space that holds the executable code of functions and blocks.
Definition MemRegion.h:258
void dumpToStream(raw_ostream &os) const override
CompoundLiteralRegion - A memory region representing a compound literal.
Definition MemRegion.h:926
void Profile(llvm::FoldingSetNodeID &ID) const override
void dumpToStream(raw_ostream &os) const override
ElementRegion is used to represent both array elements and casts.
Definition MemRegion.h:1230
QualType getElementType() const
Definition MemRegion.h:1254
void Profile(llvm::FoldingSetNodeID &ID) const override
RegionRawOffset getAsArrayOffset() const
Compute the offset within the array. The array might also be a subobject.
void dumpToStream(raw_ostream &os) const override
void printPrettyAsExpr(raw_ostream &os) const override
Print the region as expression.
bool canPrintPretty() const override
Returns true if this region can be printed in a user-friendly way.
bool canPrintPrettyAsExpr() const override
Returns true if this region's textual representation can be used as part of a larger expression.
void dumpToStream(raw_ostream &os) const override
void printPretty(raw_ostream &os) const override
Print the region for use in diagnostics.
void Profile(llvm::FoldingSetNodeID &ID) const override
LLVM_ATTRIBUTE_RETURNS_NONNULL const FieldDecl * getDecl() const override
Definition MemRegion.h:1156
FunctionCodeRegion - A region that represents code texts of function.
Definition MemRegion.h:611
const NamedDecl * getDecl() const
Definition MemRegion.h:639
void dumpToStream(raw_ostream &os) const override
void Profile(llvm::FoldingSetNodeID &ID) const override
void dumpToStream(raw_ostream &os) const override
void dumpToStream(raw_ostream &os) const override
void dumpToStream(raw_ostream &os) const override
void dumpToStream(raw_ostream &os) const override
const HeapSpaceRegion * getHeapRegion()
getHeapRegion - Retrieve the memory region associated with the generic "heap".
llvm::BumpPtrAllocator & getAllocator()
Definition MemRegion.h:1463
const StackLocalsSpaceRegion * getStackLocalsRegion(const StackFrame *SF)
getStackLocalsRegion - Retrieve the memory region associated with the specified stack frame.
const FieldRegion * getFieldRegion(const FieldDecl *FD, const SubRegion *SuperRegion)
getFieldRegion - Retrieve or create the memory region associated with a specified FieldDecl.
const ParamVarRegion * getParamVarRegion(const Expr *OriginExpr, unsigned Index, const StackFrame *SF)
getParamVarRegion - Retrieve or create the memory region associated with a specified CallExpr,...
const StackArgumentsSpaceRegion * getStackArgumentsRegion(const StackFrame *SF)
getStackArgumentsRegion - Retrieve the memory region associated with function/method arguments of the...
const BlockCodeRegion * getBlockCodeRegion(const BlockDecl *BD, CanQualType locTy, AnalysisDeclContext *AC)
const UnknownSpaceRegion * getUnknownRegion()
getUnknownRegion - Retrieve the memory region associated with unknown memory space.
const CXXDerivedObjectRegion * getCXXDerivedObjectRegion(const CXXRecordDecl *BaseClass, const SubRegion *Super)
Create a CXXDerivedObjectRegion with the given derived class for region Super.
const CXXLifetimeExtendedObjectRegion * getCXXLifetimeExtendedObjectRegion(Expr const *Ex, ValueDecl const *VD, StackFrame const *SF)
Create a CXXLifetimeExtendedObjectRegion for temporaries which are lifetime-extended by local referen...
const CompoundLiteralRegion * getCompoundLiteralRegion(const CompoundLiteralExpr *CL, const StackFrame *SF)
getCompoundLiteralRegion - Retrieve the region associated with a given CompoundLiteral.
const ElementRegion * getElementRegion(QualType elementType, NonLoc Idx, const SubRegion *superRegion, const ASTContext &Ctx)
getElementRegion - Retrieve the memory region associated with the associated element type,...
const NonParamVarRegion * getNonParamVarRegion(const VarDecl *VD, const MemRegion *superR)
getVarRegion - Retrieve or create the memory region associated with a specified VarDecl and StackFram...
const ObjCIvarRegion * getObjCIvarRegion(const ObjCIvarDecl *ivd, const SubRegion *superRegion)
getObjCIvarRegion - Retrieve or create the memory region associated with a specified Objective-c inst...
const VarRegion * getVarRegion(const VarDecl *VD, const StackFrame *SF)
getVarRegion - Retrieve or create the memory region associated with a specified VarDecl and StackFram...
const AllocaRegion * getAllocaRegion(const Expr *Ex, unsigned Cnt, const StackFrame *SF)
getAllocaRegion - Retrieve a region associated with a call to alloca().
const SymbolicRegion * getSymbolicHeapRegion(SymbolRef sym)
Return a unique symbolic region belonging to heap memory space.
const CXXTempObjectRegion * getCXXTempObjectRegion(Expr const *Ex, StackFrame const *SF)
const ObjCStringRegion * getObjCStringRegion(const ObjCStringLiteral *Str)
const StringRegion * getStringRegion(const StringLiteral *Str)
DefinedOrUnknownSVal getStaticSize(const MemRegion *MR, SValBuilder &SVB) const
const CodeSpaceRegion * getCodeRegion()
const GlobalsSpaceRegion * getGlobalsRegion(MemRegion::Kind K=MemRegion::GlobalInternalSpaceRegionKind, const CodeTextRegion *R=nullptr)
getGlobalsRegion - Retrieve the memory region associated with global variables.
const CXXThisRegion * getCXXThisRegion(QualType thisPointerTy, const StackFrame *SF)
getCXXThisRegion - Retrieve the [artificial] region associated with the parameter 'this'.
const SymbolicRegion * getSymbolicRegion(SymbolRef Sym, const MemSpaceRegion *MemSpace=nullptr)
Retrieve or create a "symbolic" memory region.
const FunctionCodeRegion * getFunctionCodeRegion(const NamedDecl *FD)
const CXXBaseObjectRegion * getCXXBaseObjectRegion(const CXXRecordDecl *BaseClass, const SubRegion *Super, bool IsVirtual)
Create a CXXBaseObjectRegion with the given base class for region Super.
const CXXLifetimeExtendedObjectRegion * getCXXStaticLifetimeExtendedObjectRegion(const Expr *Ex, ValueDecl const *VD)
Create a CXXLifetimeExtendedObjectRegion for temporaries which are lifetime-extended by static refere...
const BlockDataRegion * getBlockDataRegion(const BlockCodeRegion *bc, const StackFrame *SF, unsigned blockCount)
getBlockDataRegion - Get the memory region associated with an instance of a block.
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
virtual bool canPrintPrettyAsExpr() const
Returns true if this region's textual representation can be used as part of a larger expression.
StringRef getKindStr() const
RegionOffset getAsOffset() const
Compute the offset within the top level memory object.
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * StripCasts(bool StripBaseAndDerivedCasts=true) const
ProgramStateRef setMemorySpace(ProgramStateRef State, const MemSpaceRegion *Space) const
Set the dynamically deduced memory space of a MemRegion that currently has UnknownSpaceRegion.
ASTContext & getContext() const
Definition MemRegion.h:1647
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemSpaceRegion * getMemorySpace(ProgramStateRef State) const
Returns the most specific memory space for this memory region in the given ProgramStateRef.
std::string getDescriptiveName(bool UseQuotes=true) const
Get descriptive name for memory region.
virtual bool isSubRegionOf(const MemRegion *R) const
Check if the region is a subregion of the given region.
virtual void dumpToStream(raw_ostream &os) const
const SymbolicRegion * getSymbolicBase() const
If this is a symbolic region, returns the region.
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
virtual void printPretty(raw_ostream &os) const
Print the region for use in diagnostics.
virtual void printPrettyAsExpr(raw_ostream &os) const
Print the region as expression.
std::string getString() const
Get a string representation of a region for debug use.
Kind getKind() const
Definition MemRegion.h:202
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getMostDerivedObjectRegion() const
Recursively retrieve the region of the most derived class instance of regions of C++ base class insta...
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemSpaceRegion * getRawMemorySpace() const
Deprecated.
virtual bool canPrintPretty() const
Returns true if this region can be printed in a user-friendly way.
SourceRange sourceRange() const
Retrieve source range from memory region.
MemSpaceRegion - A memory region that represents a "memory space"; for example, the set of global var...
Definition MemRegion.h:235
void Profile(llvm::FoldingSetNodeID &ID) const override
bool canPrintPrettyAsExpr() const override
Returns true if this region's textual representation can be used as part of a larger expression.
void Profile(llvm::FoldingSetNodeID &ID) const override
void printPrettyAsExpr(raw_ostream &os) const override
Print the region as expression.
void dumpToStream(raw_ostream &os) const override
LLVM_ATTRIBUTE_RETURNS_NONNULL const VarDecl * getDecl() const override
Definition MemRegion.h:1036
bool canPrintPrettyAsExpr() const override
Returns true if this region's textual representation can be used as part of a larger expression.
void Profile(llvm::FoldingSetNodeID &ID) const override
QualType getValueType() const override
void printPrettyAsExpr(raw_ostream &os) const override
Print the region as expression.
LLVM_ATTRIBUTE_RETURNS_NONNULL const ObjCIvarDecl * getDecl() const override
void dumpToStream(raw_ostream &os) const override
The region associated with an ObjCStringLiteral.
Definition MemRegion.h:889
void dumpToStream(raw_ostream &os) const override
ParamVarRegion - Represents a region for parameters.
Definition MemRegion.h:1065
bool canPrintPrettyAsExpr() const override
Returns true if this region's textual representation can be used as part of a larger expression.
LLVM_ATTRIBUTE_RETURNS_NONNULL const Expr * getOriginExpr() const
Definition MemRegion.h:1082
const ParmVarDecl * getDecl() const override
TODO: What does this return?
unsigned getIndex() const
Definition MemRegion.h:1083
void Profile(llvm::FoldingSetNodeID &ID) const override
QualType getValueType() const override
void dumpToStream(raw_ostream &os) const override
void printPrettyAsExpr(raw_ostream &os) const override
Print the region as expression.
InvalidationKinds
Describes different invalidation traits.
Definition MemRegion.h:1669
bool hasTrait(SymbolRef Sym, InvalidationKinds IK) const
void setTrait(SymbolRef Sym, InvalidationKinds IK)
Represent a region's offset within the top level base region.
Definition MemRegion.h:64
static const int64_t Symbolic
Definition MemRegion.h:74
CharUnits getOffset() const
Definition MemRegion.h:1220
void dumpToStream(raw_ostream &os) const
const MemRegion * getRegion() const
Definition MemRegion.h:1223
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
QualType getArrayIndexType() const
SymbolManager & getSymbolManager()
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:56
void Profile(llvm::FoldingSetNodeID &ID) const
Definition SVals.h:97
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition SVals.h:87
void dumpToStream(raw_ostream &os) const override
void dumpToStream(raw_ostream &os) const override
LLVM_ATTRIBUTE_RETURNS_NONNULL const StackFrame * getStackFrame() const
Definition MemRegion.h:432
void Profile(llvm::FoldingSetNodeID &ID) const override
The region of the static variables within the current CodeTextRegion scope.
Definition MemRegion.h:292
void Profile(llvm::FoldingSetNodeID &ID) const override
void dumpToStream(raw_ostream &os) const override
LLVM_ATTRIBUTE_RETURNS_NONNULL const CodeTextRegion * getCodeRegion() const
Definition MemRegion.h:308
StringRegion - Region associated with a StringLiteral.
Definition MemRegion.h:855
void dumpToStream(raw_ostream &os) const override
SubRegion - A region that subsets another larger region.
Definition MemRegion.h:473
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getSuperRegion() const
Definition MemRegion.h:486
bool isSubRegionOf(const MemRegion *R) const override
Check if the region is a subregion of the given region.
SubRegion(const MemRegion *sReg, Kind k)
Definition MemRegion.h:479
const MemRegion * superRegion
Definition MemRegion.h:477
MemRegionManager & getMemRegionManager() const override
SymbolExtent - Represents the extent (size in bytes) of a bounded region.
const SymExprT * acquire(Args &&...args)
Create or retrieve a SymExpr of type SymExprT for the given arguments.
SymbolicRegion - A special, "non-concrete" region.
Definition MemRegion.h:806
void dumpToStream(raw_ostream &os) const override
void Profile(llvm::FoldingSetNodeID &ID) const override
static void ProfileRegion(llvm::FoldingSetNodeID &ID, SymbolRef sym, const MemRegion *superRegion)
TypedValueRegion - An abstract class representing regions having a typed value.
Definition MemRegion.h:562
virtual QualType getValueType() const =0
void dumpToStream(raw_ostream &os) const override
const StackFrame * getStackFrame() const
It might return null.
Value representing integer constant.
Definition SVals.h:300
Represents symbolic expression that isn't a location.
Definition SVals.h:279
Definition SPIR.cpp:35
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:133
DefinedOrUnknownSVal getElementExtent(QualType Ty, SValBuilder &SVB)
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
LangAS
Defines the address space values used by the address space qualifier of QualType.
U cast(CodeGen::Address addr)
Definition Address.h:327
Extra information about a function prototype.
Definition TypeBase.h:5454
Describes how types, statements, expressions, and declarations should be printed.