1 //== MemRegion.h - Abstract memory regions for static analysis --*- C++ -*--==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines MemRegion and its subclasses. MemRegion defines a
11 // partially-typed abstraction of memory useful for path-sensitive dataflow
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_MEMREGION_H
17 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_MEMREGION_H
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/Analysis/AnalysisContext.h"
25 #include "clang/Basic/LLVM.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
27 #include "llvm/ADT/FoldingSet.h"
28 #include "llvm/Support/Allocator.h"
29 #include "llvm/Support/ErrorHandling.h"
34 class LocationContext;
35 class StackFrameContext;
40 class MemRegionManager;
46 /// Represent a region's offset within the top level base region.
51 /// The bit offset within the base region. Can be negative.
55 // We're using a const instead of an enumeration due to the size required;
56 // Visual Studio will only create enumerations of size int, not long long.
57 static const int64_t Symbolic = INT64_MAX;
59 RegionOffset() : R(nullptr) {}
60 RegionOffset(const MemRegion *r, int64_t off) : R(r), Offset(off) {}
62 const MemRegion *getRegion() const { return R; }
64 bool hasSymbolicOffset() const { return Offset == Symbolic; }
66 int64_t getOffset() const {
67 assert(!hasSymbolicOffset());
71 bool isValid() const { return R; }
74 //===----------------------------------------------------------------------===//
75 // Base region classes.
76 //===----------------------------------------------------------------------===//
78 /// MemRegion - The root abstract class for all memory regions.
79 class MemRegion : public llvm::FoldingSetNode {
82 #define REGION(Id, Parent) Id ## Kind,
83 #define REGION_RANGE(Id, First, Last) BEGIN_##Id = First, END_##Id = Last,
84 #include "clang/StaticAnalyzer/Core/PathSensitive/Regions.def"
91 MemRegion(Kind k) : kind(k) {}
95 ASTContext &getContext() const;
97 virtual void Profile(llvm::FoldingSetNodeID& ID) const = 0;
99 virtual MemRegionManager* getMemRegionManager() const = 0;
101 const MemSpaceRegion *getMemorySpace() const;
103 const MemRegion *getBaseRegion() const;
105 /// Check if the region is a subregion of the given region.
106 virtual bool isSubRegionOf(const MemRegion *R) const;
108 const MemRegion *StripCasts(bool StripBaseCasts = true) const;
110 /// \brief If this is a symbolic region, returns the region. Otherwise,
111 /// goes up the base chain looking for the first symbolic base region.
112 const SymbolicRegion *getSymbolicBase() const;
114 bool hasGlobalsOrParametersStorage() const;
116 bool hasStackStorage() const;
118 bool hasStackNonParametersStorage() const;
120 bool hasStackParametersStorage() const;
122 /// Compute the offset within the top level memory object.
123 RegionOffset getAsOffset() const;
125 /// \brief Get a string representation of a region for debug use.
126 std::string getString() const;
128 virtual void dumpToStream(raw_ostream &os) const;
132 /// \brief Returns true if this region can be printed in a user-friendly way.
133 virtual bool canPrintPretty() const;
135 /// \brief Print the region for use in diagnostics.
136 virtual void printPretty(raw_ostream &os) const;
138 /// \brief Returns true if this region's textual representation can be used
139 /// as part of a larger expression.
140 virtual bool canPrintPrettyAsExpr() const;
142 /// \brief Print the region as expression.
144 /// When this region represents a subexpression, the method is for printing
145 /// an expression containing it.
146 virtual void printPrettyAsExpr(raw_ostream &os) const;
148 Kind getKind() const { return kind; }
150 template<typename RegionTy> const RegionTy* getAs() const;
152 virtual bool isBoundable() const { return false; }
155 /// Get descriptive name for memory region. The name is obtained from
156 /// the variable/field declaration retrieved from the memory region.
157 /// Regions that point to an element of an array are returned as: "arr[0]".
158 /// Regions that point to a struct are returned as: "st.var".
160 /// \param UseQuotes Set if the name should be quoted.
162 /// \returns variable name for memory region
163 std::string getDescriptiveName(bool UseQuotes = true) const;
166 /// Retrieve source range from memory region. The range retrieval
167 /// is based on the decl obtained from the memory region.
168 /// For a VarRegion the range of the base region is returned.
169 /// For a FieldRegion the range of the field is returned.
170 /// If no declaration is found, an empty source range is returned.
171 /// The client is responsible for checking if the returned range is valid.
173 /// \returns source range for declaration retrieved from memory region
174 clang::SourceRange sourceRange() const;
177 /// MemSpaceRegion - A memory region that represents a "memory space";
178 /// for example, the set of global variables, the stack frame, etc.
179 class MemSpaceRegion : public MemRegion {
181 MemRegionManager *Mgr;
183 MemSpaceRegion(MemRegionManager *mgr, Kind k) : MemRegion(k), Mgr(mgr) {
184 assert(classof(this));
187 MemRegionManager* getMemRegionManager() const override { return Mgr; }
190 bool isBoundable() const override { return false; }
192 void Profile(llvm::FoldingSetNodeID &ID) const override;
194 static bool classof(const MemRegion *R) {
195 Kind k = R->getKind();
196 return k >= BEGIN_MEMSPACES && k <= END_MEMSPACES;
200 /// CodeSpaceRegion - The memory space that holds the executable code of
201 /// functions and blocks.
202 class CodeSpaceRegion : public MemSpaceRegion {
203 friend class MemRegionManager;
205 CodeSpaceRegion(MemRegionManager *mgr)
206 : MemSpaceRegion(mgr, CodeSpaceRegionKind) {}
209 void dumpToStream(raw_ostream &os) const override;
211 static bool classof(const MemRegion *R) {
212 return R->getKind() == CodeSpaceRegionKind;
216 class GlobalsSpaceRegion : public MemSpaceRegion {
217 virtual void anchor();
219 GlobalsSpaceRegion(MemRegionManager *mgr, Kind k)
220 : MemSpaceRegion(mgr, k) {}
222 static bool classof(const MemRegion *R) {
223 Kind k = R->getKind();
224 return k >= BEGIN_GLOBAL_MEMSPACES && k <= END_GLOBAL_MEMSPACES;
228 /// \brief The region of the static variables within the current CodeTextRegion
231 /// Currently, only the static locals are placed there, so we know that these
232 /// variables do not get invalidated by calls to other functions.
233 class StaticGlobalSpaceRegion : public GlobalsSpaceRegion {
234 friend class MemRegionManager;
236 const CodeTextRegion *CR;
238 StaticGlobalSpaceRegion(MemRegionManager *mgr, const CodeTextRegion *cr)
239 : GlobalsSpaceRegion(mgr, StaticGlobalSpaceRegionKind), CR(cr) {}
242 void Profile(llvm::FoldingSetNodeID &ID) const override;
244 void dumpToStream(raw_ostream &os) const override;
246 const CodeTextRegion *getCodeRegion() const { return CR; }
248 static bool classof(const MemRegion *R) {
249 return R->getKind() == StaticGlobalSpaceRegionKind;
253 /// \brief The region for all the non-static global variables.
255 /// This class is further split into subclasses for efficient implementation of
256 /// invalidating a set of related global values as is done in
257 /// RegionStoreManager::invalidateRegions (instead of finding all the dependent
258 /// globals, we invalidate the whole parent region).
259 class NonStaticGlobalSpaceRegion : public GlobalsSpaceRegion {
261 NonStaticGlobalSpaceRegion(MemRegionManager *mgr, Kind k)
262 : GlobalsSpaceRegion(mgr, k) {}
266 static bool classof(const MemRegion *R) {
267 Kind k = R->getKind();
268 return k >= BEGIN_NON_STATIC_GLOBAL_MEMSPACES &&
269 k <= END_NON_STATIC_GLOBAL_MEMSPACES;
273 /// \brief The region containing globals which are defined in system/external
274 /// headers and are considered modifiable by system calls (ex: errno).
275 class GlobalSystemSpaceRegion : public NonStaticGlobalSpaceRegion {
276 friend class MemRegionManager;
278 GlobalSystemSpaceRegion(MemRegionManager *mgr)
279 : NonStaticGlobalSpaceRegion(mgr, GlobalSystemSpaceRegionKind) {}
283 void dumpToStream(raw_ostream &os) const override;
285 static bool classof(const MemRegion *R) {
286 return R->getKind() == GlobalSystemSpaceRegionKind;
290 /// \brief The region containing globals which are considered not to be modified
291 /// or point to data which could be modified as a result of a function call
292 /// (system or internal). Ex: Const global scalars would be modeled as part of
293 /// this region. This region also includes most system globals since they have
294 /// low chance of being modified.
295 class GlobalImmutableSpaceRegion : public NonStaticGlobalSpaceRegion {
296 friend class MemRegionManager;
298 GlobalImmutableSpaceRegion(MemRegionManager *mgr)
299 : NonStaticGlobalSpaceRegion(mgr, GlobalImmutableSpaceRegionKind) {}
303 void dumpToStream(raw_ostream &os) const override;
305 static bool classof(const MemRegion *R) {
306 return R->getKind() == GlobalImmutableSpaceRegionKind;
310 /// \brief The region containing globals which can be modified by calls to
311 /// "internally" defined functions - (for now just) functions other then system
313 class GlobalInternalSpaceRegion : public NonStaticGlobalSpaceRegion {
314 friend class MemRegionManager;
316 GlobalInternalSpaceRegion(MemRegionManager *mgr)
317 : NonStaticGlobalSpaceRegion(mgr, GlobalInternalSpaceRegionKind) {}
321 void dumpToStream(raw_ostream &os) const override;
323 static bool classof(const MemRegion *R) {
324 return R->getKind() == GlobalInternalSpaceRegionKind;
328 class HeapSpaceRegion : public MemSpaceRegion {
329 virtual void anchor();
330 friend class MemRegionManager;
332 HeapSpaceRegion(MemRegionManager *mgr)
333 : MemSpaceRegion(mgr, HeapSpaceRegionKind) {}
336 void dumpToStream(raw_ostream &os) const override;
338 static bool classof(const MemRegion *R) {
339 return R->getKind() == HeapSpaceRegionKind;
343 class UnknownSpaceRegion : public MemSpaceRegion {
344 virtual void anchor();
345 friend class MemRegionManager;
346 UnknownSpaceRegion(MemRegionManager *mgr)
347 : MemSpaceRegion(mgr, UnknownSpaceRegionKind) {}
350 void dumpToStream(raw_ostream &os) const override;
352 static bool classof(const MemRegion *R) {
353 return R->getKind() == UnknownSpaceRegionKind;
357 class StackSpaceRegion : public MemSpaceRegion {
359 const StackFrameContext *SFC;
362 StackSpaceRegion(MemRegionManager *mgr, Kind k, const StackFrameContext *sfc)
363 : MemSpaceRegion(mgr, k), SFC(sfc) {
364 assert(classof(this));
368 const StackFrameContext *getStackFrame() const { return SFC; }
370 void Profile(llvm::FoldingSetNodeID &ID) const override;
372 static bool classof(const MemRegion *R) {
373 Kind k = R->getKind();
374 return k >= BEGIN_STACK_MEMSPACES && k <= END_STACK_MEMSPACES;
378 class StackLocalsSpaceRegion : public StackSpaceRegion {
379 virtual void anchor();
380 friend class MemRegionManager;
381 StackLocalsSpaceRegion(MemRegionManager *mgr, const StackFrameContext *sfc)
382 : StackSpaceRegion(mgr, StackLocalsSpaceRegionKind, sfc) {}
385 void dumpToStream(raw_ostream &os) const override;
387 static bool classof(const MemRegion *R) {
388 return R->getKind() == StackLocalsSpaceRegionKind;
392 class StackArgumentsSpaceRegion : public StackSpaceRegion {
394 virtual void anchor();
395 friend class MemRegionManager;
396 StackArgumentsSpaceRegion(MemRegionManager *mgr, const StackFrameContext *sfc)
397 : StackSpaceRegion(mgr, StackArgumentsSpaceRegionKind, sfc) {}
400 void dumpToStream(raw_ostream &os) const override;
402 static bool classof(const MemRegion *R) {
403 return R->getKind() == StackArgumentsSpaceRegionKind;
408 /// SubRegion - A region that subsets another larger region. Most regions
409 /// are subclasses of SubRegion.
410 class SubRegion : public MemRegion {
412 virtual void anchor();
414 const MemRegion* superRegion;
415 SubRegion(const MemRegion* sReg, Kind k) : MemRegion(k), superRegion(sReg) {}
417 const MemRegion* getSuperRegion() const {
421 /// getExtent - Returns the size of the region in bytes.
422 virtual DefinedOrUnknownSVal getExtent(SValBuilder &svalBuilder) const {
426 MemRegionManager* getMemRegionManager() const override;
428 bool isSubRegionOf(const MemRegion* R) const override;
430 static bool classof(const MemRegion* R) {
431 return R->getKind() > END_MEMSPACES;
435 //===----------------------------------------------------------------------===//
436 // MemRegion subclasses.
437 //===----------------------------------------------------------------------===//
439 /// AllocaRegion - A region that represents an untyped blob of bytes created
440 /// by a call to 'alloca'.
441 class AllocaRegion : public SubRegion {
442 friend class MemRegionManager;
444 unsigned Cnt; // Block counter. Used to distinguish different pieces of
445 // memory allocated by alloca at the same call site.
448 AllocaRegion(const Expr *ex, unsigned cnt, const MemRegion *superRegion)
449 : SubRegion(superRegion, AllocaRegionKind), Cnt(cnt), Ex(ex) {}
453 const Expr *getExpr() const { return Ex; }
455 bool isBoundable() const override { return true; }
457 DefinedOrUnknownSVal getExtent(SValBuilder &svalBuilder) const override;
459 void Profile(llvm::FoldingSetNodeID& ID) const override;
461 static void ProfileRegion(llvm::FoldingSetNodeID& ID, const Expr *Ex,
462 unsigned Cnt, const MemRegion *superRegion);
464 void dumpToStream(raw_ostream &os) const override;
466 static bool classof(const MemRegion* R) {
467 return R->getKind() == AllocaRegionKind;
471 /// TypedRegion - An abstract class representing regions that are typed.
472 class TypedRegion : public SubRegion {
474 void anchor() override;
476 TypedRegion(const MemRegion* sReg, Kind k) : SubRegion(sReg, k) {}
479 virtual QualType getLocationType() const = 0;
481 QualType getDesugaredLocationType(ASTContext &Context) const {
482 return getLocationType().getDesugaredType(Context);
485 bool isBoundable() const override { return true; }
487 static bool classof(const MemRegion* R) {
488 unsigned k = R->getKind();
489 return k >= BEGIN_TYPED_REGIONS && k <= END_TYPED_REGIONS;
493 /// TypedValueRegion - An abstract class representing regions having a typed value.
494 class TypedValueRegion : public TypedRegion {
496 void anchor() override;
498 TypedValueRegion(const MemRegion* sReg, Kind k) : TypedRegion(sReg, k) {}
501 virtual QualType getValueType() const = 0;
503 QualType getLocationType() const override {
504 // FIXME: We can possibly optimize this later to cache this value.
505 QualType T = getValueType();
506 ASTContext &ctx = getContext();
507 if (T->getAs<ObjCObjectType>())
508 return ctx.getObjCObjectPointerType(T);
509 return ctx.getPointerType(getValueType());
512 QualType getDesugaredValueType(ASTContext &Context) const {
513 QualType T = getValueType();
514 return T.getTypePtrOrNull() ? T.getDesugaredType(Context) : T;
517 DefinedOrUnknownSVal getExtent(SValBuilder &svalBuilder) const override;
519 static bool classof(const MemRegion* R) {
520 unsigned k = R->getKind();
521 return k >= BEGIN_TYPED_VALUE_REGIONS && k <= END_TYPED_VALUE_REGIONS;
526 class CodeTextRegion : public TypedRegion {
528 void anchor() override;
530 CodeTextRegion(const MemRegion *sreg, Kind k) : TypedRegion(sreg, k) {}
532 bool isBoundable() const override { return false; }
534 static bool classof(const MemRegion* R) {
535 Kind k = R->getKind();
536 return k >= BEGIN_CODE_TEXT_REGIONS && k <= END_CODE_TEXT_REGIONS;
540 /// FunctionCodeRegion - A region that represents code texts of function.
541 class FunctionCodeRegion : public CodeTextRegion {
544 FunctionCodeRegion(const NamedDecl *fd, const MemRegion* sreg)
545 : CodeTextRegion(sreg, FunctionCodeRegionKind), FD(fd) {
546 assert(isa<ObjCMethodDecl>(fd) || isa<FunctionDecl>(fd));
549 QualType getLocationType() const override {
550 const ASTContext &Ctx = getContext();
551 if (const FunctionDecl *D = dyn_cast<FunctionDecl>(FD)) {
552 return Ctx.getPointerType(D->getType());
555 assert(isa<ObjCMethodDecl>(FD));
556 assert(false && "Getting the type of ObjCMethod is not supported yet");
558 // TODO: We might want to return a different type here (ex: id (*ty)(...))
559 // depending on how it is used.
563 const NamedDecl *getDecl() const {
567 void dumpToStream(raw_ostream &os) const override;
569 void Profile(llvm::FoldingSetNodeID& ID) const override;
571 static void ProfileRegion(llvm::FoldingSetNodeID& ID, const NamedDecl *FD,
574 static bool classof(const MemRegion* R) {
575 return R->getKind() == FunctionCodeRegionKind;
580 /// BlockCodeRegion - A region that represents code texts of blocks (closures).
581 /// Blocks are represented with two kinds of regions. BlockCodeRegions
582 /// represent the "code", while BlockDataRegions represent instances of blocks,
583 /// which correspond to "code+data". The distinction is important, because
584 /// like a closure a block captures the values of externally referenced
586 class BlockCodeRegion : public CodeTextRegion {
587 friend class MemRegionManager;
590 AnalysisDeclContext *AC;
593 BlockCodeRegion(const BlockDecl *bd, CanQualType lTy,
594 AnalysisDeclContext *ac, const MemRegion* sreg)
595 : CodeTextRegion(sreg, BlockCodeRegionKind), BD(bd), AC(ac), locTy(lTy) {}
598 QualType getLocationType() const override {
602 const BlockDecl *getDecl() const {
606 AnalysisDeclContext *getAnalysisDeclContext() const { return AC; }
608 void dumpToStream(raw_ostream &os) const override;
610 void Profile(llvm::FoldingSetNodeID& ID) const override;
612 static void ProfileRegion(llvm::FoldingSetNodeID& ID, const BlockDecl *BD,
613 CanQualType, const AnalysisDeclContext*,
616 static bool classof(const MemRegion* R) {
617 return R->getKind() == BlockCodeRegionKind;
621 /// BlockDataRegion - A region that represents a block instance.
622 /// Blocks are represented with two kinds of regions. BlockCodeRegions
623 /// represent the "code", while BlockDataRegions represent instances of blocks,
624 /// which correspond to "code+data". The distinction is important, because
625 /// like a closure a block captures the values of externally referenced
627 class BlockDataRegion : public TypedRegion {
628 friend class MemRegionManager;
629 const BlockCodeRegion *BC;
630 const LocationContext *LC; // Can be null */
632 void *ReferencedVars;
635 BlockDataRegion(const BlockCodeRegion *bc, const LocationContext *lc,
636 unsigned count, const MemRegion *sreg)
637 : TypedRegion(sreg, BlockDataRegionKind), BC(bc), LC(lc),
639 ReferencedVars(nullptr), OriginalVars(nullptr) {}
642 const BlockCodeRegion *getCodeRegion() const { return BC; }
644 const BlockDecl *getDecl() const { return BC->getDecl(); }
646 QualType getLocationType() const override { return BC->getLocationType(); }
648 class referenced_vars_iterator {
649 const MemRegion * const *R;
650 const MemRegion * const *OriginalR;
652 explicit referenced_vars_iterator(const MemRegion * const *r,
653 const MemRegion * const *originalR)
654 : R(r), OriginalR(originalR) {}
656 const VarRegion *getCapturedRegion() const {
657 return cast<VarRegion>(*R);
659 const VarRegion *getOriginalRegion() const {
660 return cast<VarRegion>(*OriginalR);
663 bool operator==(const referenced_vars_iterator &I) const {
664 assert((R == nullptr) == (I.R == nullptr));
667 bool operator!=(const referenced_vars_iterator &I) const {
668 assert((R == nullptr) == (I.R == nullptr));
671 referenced_vars_iterator &operator++() {
678 /// Return the original region for a captured region, if
680 const VarRegion *getOriginalRegion(const VarRegion *VR) const;
682 referenced_vars_iterator referenced_vars_begin() const;
683 referenced_vars_iterator referenced_vars_end() const;
685 void dumpToStream(raw_ostream &os) const override;
687 void Profile(llvm::FoldingSetNodeID& ID) const override;
689 static void ProfileRegion(llvm::FoldingSetNodeID&, const BlockCodeRegion *,
690 const LocationContext *, unsigned,
693 static bool classof(const MemRegion* R) {
694 return R->getKind() == BlockDataRegionKind;
697 void LazyInitializeReferencedVars();
698 std::pair<const VarRegion *, const VarRegion *>
699 getCaptureRegions(const VarDecl *VD);
702 /// SymbolicRegion - A special, "non-concrete" region. Unlike other region
703 /// classes, SymbolicRegion represents a region that serves as an alias for
704 /// either a real region, a NULL pointer, etc. It essentially is used to
705 /// map the concept of symbolic values into the domain of regions. Symbolic
706 /// regions do not need to be typed.
707 class SymbolicRegion : public SubRegion {
712 SymbolicRegion(const SymbolRef s, const MemRegion* sreg)
713 : SubRegion(sreg, SymbolicRegionKind), sym(s) {}
715 SymbolRef getSymbol() const {
719 bool isBoundable() const override { return true; }
721 DefinedOrUnknownSVal getExtent(SValBuilder &svalBuilder) const override;
723 void Profile(llvm::FoldingSetNodeID& ID) const override;
725 static void ProfileRegion(llvm::FoldingSetNodeID& ID,
727 const MemRegion* superRegion);
729 void dumpToStream(raw_ostream &os) const override;
731 static bool classof(const MemRegion* R) {
732 return R->getKind() == SymbolicRegionKind;
736 /// StringRegion - Region associated with a StringLiteral.
737 class StringRegion : public TypedValueRegion {
738 friend class MemRegionManager;
739 const StringLiteral* Str;
742 StringRegion(const StringLiteral* str, const MemRegion* sreg)
743 : TypedValueRegion(sreg, StringRegionKind), Str(str) {}
745 static void ProfileRegion(llvm::FoldingSetNodeID& ID,
746 const StringLiteral* Str,
747 const MemRegion* superRegion);
751 const StringLiteral* getStringLiteral() const { return Str; }
753 QualType getValueType() const override {
754 return Str->getType();
757 DefinedOrUnknownSVal getExtent(SValBuilder &svalBuilder) const override;
759 bool isBoundable() const override { return false; }
761 void Profile(llvm::FoldingSetNodeID& ID) const override {
762 ProfileRegion(ID, Str, superRegion);
765 void dumpToStream(raw_ostream &os) const override;
767 static bool classof(const MemRegion* R) {
768 return R->getKind() == StringRegionKind;
772 /// The region associated with an ObjCStringLiteral.
773 class ObjCStringRegion : public TypedValueRegion {
774 friend class MemRegionManager;
775 const ObjCStringLiteral* Str;
778 ObjCStringRegion(const ObjCStringLiteral* str, const MemRegion* sreg)
779 : TypedValueRegion(sreg, ObjCStringRegionKind), Str(str) {}
781 static void ProfileRegion(llvm::FoldingSetNodeID& ID,
782 const ObjCStringLiteral* Str,
783 const MemRegion* superRegion);
787 const ObjCStringLiteral* getObjCStringLiteral() const { return Str; }
789 QualType getValueType() const override {
790 return Str->getType();
793 bool isBoundable() const override { return false; }
795 void Profile(llvm::FoldingSetNodeID& ID) const override {
796 ProfileRegion(ID, Str, superRegion);
799 void dumpToStream(raw_ostream &os) const override;
801 static bool classof(const MemRegion* R) {
802 return R->getKind() == ObjCStringRegionKind;
806 /// CompoundLiteralRegion - A memory region representing a compound literal.
807 /// Compound literals are essentially temporaries that are stack allocated
808 /// or in the global constant pool.
809 class CompoundLiteralRegion : public TypedValueRegion {
811 friend class MemRegionManager;
812 const CompoundLiteralExpr *CL;
814 CompoundLiteralRegion(const CompoundLiteralExpr *cl, const MemRegion* sReg)
815 : TypedValueRegion(sReg, CompoundLiteralRegionKind), CL(cl) {}
817 static void ProfileRegion(llvm::FoldingSetNodeID& ID,
818 const CompoundLiteralExpr *CL,
819 const MemRegion* superRegion);
821 QualType getValueType() const override {
822 return CL->getType();
825 bool isBoundable() const override { return !CL->isFileScope(); }
827 void Profile(llvm::FoldingSetNodeID& ID) const override;
829 void dumpToStream(raw_ostream &os) const override;
831 const CompoundLiteralExpr *getLiteralExpr() const { return CL; }
833 static bool classof(const MemRegion* R) {
834 return R->getKind() == CompoundLiteralRegionKind;
838 class DeclRegion : public TypedValueRegion {
842 DeclRegion(const Decl *d, const MemRegion* sReg, Kind k)
843 : TypedValueRegion(sReg, k), D(d) {}
845 static void ProfileRegion(llvm::FoldingSetNodeID& ID, const Decl *D,
846 const MemRegion* superRegion, Kind k);
849 const Decl *getDecl() const { return D; }
850 void Profile(llvm::FoldingSetNodeID& ID) const override;
852 static bool classof(const MemRegion* R) {
853 unsigned k = R->getKind();
854 return k >= BEGIN_DECL_REGIONS && k <= END_DECL_REGIONS;
858 class VarRegion : public DeclRegion {
859 friend class MemRegionManager;
861 // Constructors and private methods.
862 VarRegion(const VarDecl *vd, const MemRegion* sReg)
863 : DeclRegion(vd, sReg, VarRegionKind) {}
865 static void ProfileRegion(llvm::FoldingSetNodeID& ID, const VarDecl *VD,
866 const MemRegion *superRegion) {
867 DeclRegion::ProfileRegion(ID, VD, superRegion, VarRegionKind);
870 void Profile(llvm::FoldingSetNodeID& ID) const override;
873 const VarDecl *getDecl() const { return cast<VarDecl>(D); }
875 const StackFrameContext *getStackFrame() const;
877 QualType getValueType() const override {
878 // FIXME: We can cache this if needed.
879 return getDecl()->getType();
882 void dumpToStream(raw_ostream &os) const override;
884 static bool classof(const MemRegion* R) {
885 return R->getKind() == VarRegionKind;
888 bool canPrintPrettyAsExpr() const override;
890 void printPrettyAsExpr(raw_ostream &os) const override;
893 /// CXXThisRegion - Represents the region for the implicit 'this' parameter
894 /// in a call to a C++ method. This region doesn't represent the object
895 /// referred to by 'this', but rather 'this' itself.
896 class CXXThisRegion : public TypedValueRegion {
897 friend class MemRegionManager;
898 CXXThisRegion(const PointerType *thisPointerTy,
899 const MemRegion *sReg)
900 : TypedValueRegion(sReg, CXXThisRegionKind), ThisPointerTy(thisPointerTy) {}
902 static void ProfileRegion(llvm::FoldingSetNodeID &ID,
903 const PointerType *PT,
904 const MemRegion *sReg);
906 void Profile(llvm::FoldingSetNodeID &ID) const override;
909 QualType getValueType() const override {
910 return QualType(ThisPointerTy, 0);
913 void dumpToStream(raw_ostream &os) const override;
915 static bool classof(const MemRegion* R) {
916 return R->getKind() == CXXThisRegionKind;
920 const PointerType *ThisPointerTy;
923 class FieldRegion : public DeclRegion {
924 friend class MemRegionManager;
926 FieldRegion(const FieldDecl *fd, const MemRegion* sReg)
927 : DeclRegion(fd, sReg, FieldRegionKind) {}
930 const FieldDecl *getDecl() const { return cast<FieldDecl>(D); }
932 QualType getValueType() const override {
933 // FIXME: We can cache this if needed.
934 return getDecl()->getType();
937 DefinedOrUnknownSVal getExtent(SValBuilder &svalBuilder) const override;
939 static void ProfileRegion(llvm::FoldingSetNodeID& ID, const FieldDecl *FD,
940 const MemRegion* superRegion) {
941 DeclRegion::ProfileRegion(ID, FD, superRegion, FieldRegionKind);
944 static bool classof(const MemRegion* R) {
945 return R->getKind() == FieldRegionKind;
948 void dumpToStream(raw_ostream &os) const override;
950 bool canPrintPretty() const override;
951 void printPretty(raw_ostream &os) const override;
952 bool canPrintPrettyAsExpr() const override;
953 void printPrettyAsExpr(raw_ostream &os) const override;
956 class ObjCIvarRegion : public DeclRegion {
958 friend class MemRegionManager;
960 ObjCIvarRegion(const ObjCIvarDecl *ivd, const MemRegion* sReg);
962 static void ProfileRegion(llvm::FoldingSetNodeID& ID, const ObjCIvarDecl *ivd,
963 const MemRegion* superRegion);
966 const ObjCIvarDecl *getDecl() const;
967 QualType getValueType() const override;
969 bool canPrintPrettyAsExpr() const override;
970 void printPrettyAsExpr(raw_ostream &os) const override;
972 void dumpToStream(raw_ostream &os) const override;
974 static bool classof(const MemRegion* R) {
975 return R->getKind() == ObjCIvarRegionKind;
978 //===----------------------------------------------------------------------===//
979 // Auxiliary data classes for use with MemRegions.
980 //===----------------------------------------------------------------------===//
984 class RegionRawOffset {
986 friend class ElementRegion;
988 const MemRegion *Region;
991 RegionRawOffset(const MemRegion* reg, CharUnits offset = CharUnits::Zero())
992 : Region(reg), Offset(offset) {}
995 // FIXME: Eventually support symbolic offsets.
996 CharUnits getOffset() const { return Offset; }
997 const MemRegion *getRegion() const { return Region; }
999 void dumpToStream(raw_ostream &os) const;
1003 /// \brief ElementRegin is used to represent both array elements and casts.
1004 class ElementRegion : public TypedValueRegion {
1005 friend class MemRegionManager;
1007 QualType ElementType;
1010 ElementRegion(QualType elementType, NonLoc Idx, const MemRegion* sReg)
1011 : TypedValueRegion(sReg, ElementRegionKind),
1012 ElementType(elementType), Index(Idx) {
1013 assert((!Idx.getAs<nonloc::ConcreteInt>() ||
1014 Idx.castAs<nonloc::ConcreteInt>().getValue().isSigned()) &&
1015 "The index must be signed");
1018 static void ProfileRegion(llvm::FoldingSetNodeID& ID, QualType elementType,
1019 SVal Idx, const MemRegion* superRegion);
1023 NonLoc getIndex() const { return Index; }
1025 QualType getValueType() const override {
1029 QualType getElementType() const {
1032 /// Compute the offset within the array. The array might also be a subobject.
1033 RegionRawOffset getAsArrayOffset() const;
1035 void dumpToStream(raw_ostream &os) const override;
1037 void Profile(llvm::FoldingSetNodeID& ID) const override;
1039 static bool classof(const MemRegion* R) {
1040 return R->getKind() == ElementRegionKind;
1044 // C++ temporary object associated with an expression.
1045 class CXXTempObjectRegion : public TypedValueRegion {
1046 friend class MemRegionManager;
1050 CXXTempObjectRegion(Expr const *E, MemRegion const *sReg)
1051 : TypedValueRegion(sReg, CXXTempObjectRegionKind), Ex(E) {}
1053 static void ProfileRegion(llvm::FoldingSetNodeID &ID,
1054 Expr const *E, const MemRegion *sReg);
1057 const Expr *getExpr() const { return Ex; }
1059 QualType getValueType() const override {
1060 return Ex->getType();
1063 void dumpToStream(raw_ostream &os) const override;
1065 void Profile(llvm::FoldingSetNodeID &ID) const override;
1067 static bool classof(const MemRegion* R) {
1068 return R->getKind() == CXXTempObjectRegionKind;
1072 // CXXBaseObjectRegion represents a base object within a C++ object. It is
1073 // identified by the base class declaration and the region of its parent object.
1074 class CXXBaseObjectRegion : public TypedValueRegion {
1075 friend class MemRegionManager;
1077 llvm::PointerIntPair<const CXXRecordDecl *, 1, bool> Data;
1079 CXXBaseObjectRegion(const CXXRecordDecl *RD, bool IsVirtual,
1080 const MemRegion *SReg)
1081 : TypedValueRegion(SReg, CXXBaseObjectRegionKind), Data(RD, IsVirtual) {}
1083 static void ProfileRegion(llvm::FoldingSetNodeID &ID, const CXXRecordDecl *RD,
1084 bool IsVirtual, const MemRegion *SReg);
1087 const CXXRecordDecl *getDecl() const { return Data.getPointer(); }
1088 bool isVirtual() const { return Data.getInt(); }
1090 QualType getValueType() const override;
1092 void dumpToStream(raw_ostream &os) const override;
1094 void Profile(llvm::FoldingSetNodeID &ID) const override;
1096 static bool classof(const MemRegion *region) {
1097 return region->getKind() == CXXBaseObjectRegionKind;
1100 bool canPrintPrettyAsExpr() const override;
1102 void printPrettyAsExpr(raw_ostream &os) const override;
1105 template<typename RegionTy>
1106 const RegionTy* MemRegion::getAs() const {
1107 if (const RegionTy* RT = dyn_cast<RegionTy>(this))
1113 //===----------------------------------------------------------------------===//
1114 // MemRegionManager - Factory object for creating regions.
1115 //===----------------------------------------------------------------------===//
1117 class MemRegionManager {
1119 llvm::BumpPtrAllocator& A;
1120 llvm::FoldingSet<MemRegion> Regions;
1122 GlobalInternalSpaceRegion *InternalGlobals;
1123 GlobalSystemSpaceRegion *SystemGlobals;
1124 GlobalImmutableSpaceRegion *ImmutableGlobals;
1127 llvm::DenseMap<const StackFrameContext *, StackLocalsSpaceRegion *>
1128 StackLocalsSpaceRegions;
1129 llvm::DenseMap<const StackFrameContext *, StackArgumentsSpaceRegion *>
1130 StackArgumentsSpaceRegions;
1131 llvm::DenseMap<const CodeTextRegion *, StaticGlobalSpaceRegion *>
1132 StaticsGlobalSpaceRegions;
1134 HeapSpaceRegion *heap;
1135 UnknownSpaceRegion *unknown;
1136 CodeSpaceRegion *code;
1139 MemRegionManager(ASTContext &c, llvm::BumpPtrAllocator &a)
1140 : C(c), A(a), InternalGlobals(nullptr), SystemGlobals(nullptr),
1141 ImmutableGlobals(nullptr), heap(nullptr), unknown(nullptr),
1144 ~MemRegionManager();
1146 ASTContext &getContext() { return C; }
1148 llvm::BumpPtrAllocator &getAllocator() { return A; }
1150 /// getStackLocalsRegion - Retrieve the memory region associated with the
1151 /// specified stack frame.
1152 const StackLocalsSpaceRegion *
1153 getStackLocalsRegion(const StackFrameContext *STC);
1155 /// getStackArgumentsRegion - Retrieve the memory region associated with
1156 /// function/method arguments of the specified stack frame.
1157 const StackArgumentsSpaceRegion *
1158 getStackArgumentsRegion(const StackFrameContext *STC);
1160 /// getGlobalsRegion - Retrieve the memory region associated with
1161 /// global variables.
1162 const GlobalsSpaceRegion *getGlobalsRegion(
1163 MemRegion::Kind K = MemRegion::GlobalInternalSpaceRegionKind,
1164 const CodeTextRegion *R = nullptr);
1166 /// getHeapRegion - Retrieve the memory region associated with the
1168 const HeapSpaceRegion *getHeapRegion();
1170 /// getUnknownRegion - Retrieve the memory region associated with unknown
1172 const UnknownSpaceRegion *getUnknownRegion();
1174 const CodeSpaceRegion *getCodeRegion();
1176 /// getAllocaRegion - Retrieve a region associated with a call to alloca().
1177 const AllocaRegion *getAllocaRegion(const Expr *Ex, unsigned Cnt,
1178 const LocationContext *LC);
1180 /// getCompoundLiteralRegion - Retrieve the region associated with a
1181 /// given CompoundLiteral.
1182 const CompoundLiteralRegion*
1183 getCompoundLiteralRegion(const CompoundLiteralExpr *CL,
1184 const LocationContext *LC);
1186 /// getCXXThisRegion - Retrieve the [artificial] region associated with the
1187 /// parameter 'this'.
1188 const CXXThisRegion *getCXXThisRegion(QualType thisPointerTy,
1189 const LocationContext *LC);
1191 /// \brief Retrieve or create a "symbolic" memory region.
1192 const SymbolicRegion* getSymbolicRegion(SymbolRef Sym);
1194 /// \brief Return a unique symbolic region belonging to heap memory space.
1195 const SymbolicRegion *getSymbolicHeapRegion(SymbolRef sym);
1197 const StringRegion *getStringRegion(const StringLiteral* Str);
1199 const ObjCStringRegion *getObjCStringRegion(const ObjCStringLiteral *Str);
1201 /// getVarRegion - Retrieve or create the memory region associated with
1202 /// a specified VarDecl and LocationContext.
1203 const VarRegion* getVarRegion(const VarDecl *D, const LocationContext *LC);
1205 /// getVarRegion - Retrieve or create the memory region associated with
1206 /// a specified VarDecl and super region.
1207 const VarRegion* getVarRegion(const VarDecl *D, const MemRegion *superR);
1209 /// getElementRegion - Retrieve the memory region associated with the
1210 /// associated element type, index, and super region.
1211 const ElementRegion *getElementRegion(QualType elementType, NonLoc Idx,
1212 const MemRegion *superRegion,
1215 const ElementRegion *getElementRegionWithSuper(const ElementRegion *ER,
1216 const MemRegion *superRegion) {
1217 return getElementRegion(ER->getElementType(), ER->getIndex(),
1218 superRegion, ER->getContext());
1221 /// getFieldRegion - Retrieve or create the memory region associated with
1222 /// a specified FieldDecl. 'superRegion' corresponds to the containing
1223 /// memory region (which typically represents the memory representing
1224 /// a structure or class).
1225 const FieldRegion *getFieldRegion(const FieldDecl *fd,
1226 const MemRegion* superRegion);
1228 const FieldRegion *getFieldRegionWithSuper(const FieldRegion *FR,
1229 const MemRegion *superRegion) {
1230 return getFieldRegion(FR->getDecl(), superRegion);
1233 /// getObjCIvarRegion - Retrieve or create the memory region associated with
1234 /// a specified Objective-c instance variable. 'superRegion' corresponds
1235 /// to the containing region (which typically represents the Objective-C
1237 const ObjCIvarRegion *getObjCIvarRegion(const ObjCIvarDecl *ivd,
1238 const MemRegion* superRegion);
1240 const CXXTempObjectRegion *getCXXTempObjectRegion(Expr const *Ex,
1241 LocationContext const *LC);
1243 /// Create a CXXBaseObjectRegion with the given base class for region
1246 /// The type of \p Super is assumed be a class deriving from \p BaseClass.
1247 const CXXBaseObjectRegion *
1248 getCXXBaseObjectRegion(const CXXRecordDecl *BaseClass, const MemRegion *Super,
1251 /// Create a CXXBaseObjectRegion with the same CXXRecordDecl but a different
1253 const CXXBaseObjectRegion *
1254 getCXXBaseObjectRegionWithSuper(const CXXBaseObjectRegion *baseReg,
1255 const MemRegion *superRegion) {
1256 return getCXXBaseObjectRegion(baseReg->getDecl(), superRegion,
1257 baseReg->isVirtual());
1260 const FunctionCodeRegion *getFunctionCodeRegion(const NamedDecl *FD);
1261 const BlockCodeRegion *getBlockCodeRegion(const BlockDecl *BD,
1263 AnalysisDeclContext *AC);
1265 /// getBlockDataRegion - Get the memory region associated with an instance
1266 /// of a block. Unlike many other MemRegions, the LocationContext*
1267 /// argument is allowed to be NULL for cases where we have no known
1269 const BlockDataRegion *getBlockDataRegion(const BlockCodeRegion *bc,
1270 const LocationContext *lc,
1271 unsigned blockCount);
1273 /// Create a CXXTempObjectRegion for temporaries which are lifetime-extended
1274 /// by static references. This differs from getCXXTempObjectRegion in the
1275 /// super-region used.
1276 const CXXTempObjectRegion *getCXXStaticTempObjectRegion(const Expr *Ex);
1279 template <typename RegionTy, typename A1>
1280 RegionTy* getSubRegion(const A1 a1, const MemRegion* superRegion);
1282 template <typename RegionTy, typename A1, typename A2>
1283 RegionTy* getSubRegion(const A1 a1, const A2 a2,
1284 const MemRegion* superRegion);
1286 template <typename RegionTy, typename A1, typename A2, typename A3>
1287 RegionTy* getSubRegion(const A1 a1, const A2 a2, const A3 a3,
1288 const MemRegion* superRegion);
1290 template <typename REG>
1291 const REG* LazyAllocate(REG*& region);
1293 template <typename REG, typename ARG>
1294 const REG* LazyAllocate(REG*& region, ARG a);
1297 //===----------------------------------------------------------------------===//
1298 // Out-of-line member definitions.
1299 //===----------------------------------------------------------------------===//
1301 inline ASTContext &MemRegion::getContext() const {
1302 return getMemRegionManager()->getContext();
1305 //===----------------------------------------------------------------------===//
1306 // Means for storing region/symbol handling traits.
1307 //===----------------------------------------------------------------------===//
1309 /// Information about invalidation for a particular region/symbol.
1310 class RegionAndSymbolInvalidationTraits {
1311 typedef unsigned char StorageTypeForKinds;
1312 llvm::DenseMap<const MemRegion *, StorageTypeForKinds> MRTraitsMap;
1313 llvm::DenseMap<SymbolRef, StorageTypeForKinds> SymTraitsMap;
1315 typedef llvm::DenseMap<const MemRegion *, StorageTypeForKinds>::const_iterator
1316 const_region_iterator;
1317 typedef llvm::DenseMap<SymbolRef, StorageTypeForKinds>::const_iterator
1318 const_symbol_iterator;
1321 /// \brief Describes different invalidation traits.
1322 enum InvalidationKinds {
1323 /// Tells that a region's contents is not changed.
1324 TK_PreserveContents = 0x1,
1325 /// Suppress pointer-escaping of a region.
1326 TK_SuppressEscape = 0x2,
1327 // Do not invalidate super region.
1328 TK_DoNotInvalidateSuperRegion = 0x4,
1329 /// When applied to a MemSpaceRegion, indicates the entire memory space
1330 /// should be invalidated.
1331 TK_EntireMemSpace = 0x8
1333 // Do not forget to extend StorageTypeForKinds if number of traits exceed
1334 // the number of bits StorageTypeForKinds can store.
1337 void setTrait(SymbolRef Sym, InvalidationKinds IK);
1338 void setTrait(const MemRegion *MR, InvalidationKinds IK);
1339 bool hasTrait(SymbolRef Sym, InvalidationKinds IK) const;
1340 bool hasTrait(const MemRegion *MR, InvalidationKinds IK) const;
1343 } // end GR namespace
1345 } // end clang namespace
1347 //===----------------------------------------------------------------------===//
1348 // Pretty-printing regions.
1349 //===----------------------------------------------------------------------===//
1352 static inline raw_ostream &operator<<(raw_ostream &os,
1353 const clang::ento::MemRegion* R) {
1354 R->dumpToStream(os);
1357 } // end llvm namespace