1 //== MemRegion.cpp - 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 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/RecordLayout.h"
21 #include "clang/Analysis/AnalysisContext.h"
22 #include "clang/Analysis/Support/BumpVector.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
25 #include "llvm/Support/raw_ostream.h"
27 using namespace clang;
30 //===----------------------------------------------------------------------===//
31 // MemRegion Construction.
32 //===----------------------------------------------------------------------===//
34 template<typename RegionTy> struct MemRegionManagerTrait;
36 template <typename RegionTy, typename A1>
37 RegionTy* MemRegionManager::getRegion(const A1 a1) {
39 const typename MemRegionManagerTrait<RegionTy>::SuperRegionTy *superRegion =
40 MemRegionManagerTrait<RegionTy>::getSuperRegion(*this, a1);
42 llvm::FoldingSetNodeID ID;
43 RegionTy::ProfileRegion(ID, a1, superRegion);
45 RegionTy* R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID,
49 R = (RegionTy*) A.Allocate<RegionTy>();
50 new (R) RegionTy(a1, superRegion);
51 Regions.InsertNode(R, InsertPos);
57 template <typename RegionTy, typename A1>
58 RegionTy* MemRegionManager::getSubRegion(const A1 a1,
59 const MemRegion *superRegion) {
60 llvm::FoldingSetNodeID ID;
61 RegionTy::ProfileRegion(ID, a1, superRegion);
63 RegionTy* R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID,
67 R = (RegionTy*) A.Allocate<RegionTy>();
68 new (R) RegionTy(a1, superRegion);
69 Regions.InsertNode(R, InsertPos);
75 template <typename RegionTy, typename A1, typename A2>
76 RegionTy* MemRegionManager::getRegion(const A1 a1, const A2 a2) {
78 const typename MemRegionManagerTrait<RegionTy>::SuperRegionTy *superRegion =
79 MemRegionManagerTrait<RegionTy>::getSuperRegion(*this, a1, a2);
81 llvm::FoldingSetNodeID ID;
82 RegionTy::ProfileRegion(ID, a1, a2, superRegion);
84 RegionTy* R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID,
88 R = (RegionTy*) A.Allocate<RegionTy>();
89 new (R) RegionTy(a1, a2, superRegion);
90 Regions.InsertNode(R, InsertPos);
96 template <typename RegionTy, typename A1, typename A2>
97 RegionTy* MemRegionManager::getSubRegion(const A1 a1, const A2 a2,
98 const MemRegion *superRegion) {
100 llvm::FoldingSetNodeID ID;
101 RegionTy::ProfileRegion(ID, a1, a2, superRegion);
103 RegionTy* R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID,
107 R = (RegionTy*) A.Allocate<RegionTy>();
108 new (R) RegionTy(a1, a2, superRegion);
109 Regions.InsertNode(R, InsertPos);
115 template <typename RegionTy, typename A1, typename A2, typename A3>
116 RegionTy* MemRegionManager::getSubRegion(const A1 a1, const A2 a2, const A3 a3,
117 const MemRegion *superRegion) {
119 llvm::FoldingSetNodeID ID;
120 RegionTy::ProfileRegion(ID, a1, a2, a3, superRegion);
122 RegionTy* R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID,
126 R = (RegionTy*) A.Allocate<RegionTy>();
127 new (R) RegionTy(a1, a2, a3, superRegion);
128 Regions.InsertNode(R, InsertPos);
134 //===----------------------------------------------------------------------===//
135 // Object destruction.
136 //===----------------------------------------------------------------------===//
138 MemRegion::~MemRegion() {}
140 MemRegionManager::~MemRegionManager() {
141 // All regions and their data are BumpPtrAllocated. No need to call
142 // their destructors.
145 //===----------------------------------------------------------------------===//
147 //===----------------------------------------------------------------------===//
149 bool SubRegion::isSubRegionOf(const MemRegion* R) const {
150 const MemRegion* r = getSuperRegion();
154 if (const SubRegion* sr = dyn_cast<SubRegion>(r))
155 r = sr->getSuperRegion();
162 MemRegionManager* SubRegion::getMemRegionManager() const {
163 const SubRegion* r = this;
165 const MemRegion *superRegion = r->getSuperRegion();
166 if (const SubRegion *sr = dyn_cast<SubRegion>(superRegion)) {
170 return superRegion->getMemRegionManager();
174 const StackFrameContext *VarRegion::getStackFrame() const {
175 const StackSpaceRegion *SSR = dyn_cast<StackSpaceRegion>(getMemorySpace());
176 return SSR ? SSR->getStackFrame() : NULL;
179 //===----------------------------------------------------------------------===//
181 //===----------------------------------------------------------------------===//
183 DefinedOrUnknownSVal TypedValueRegion::getExtent(SValBuilder &svalBuilder) const {
184 ASTContext &Ctx = svalBuilder.getContext();
185 QualType T = getDesugaredValueType(Ctx);
187 if (isa<VariableArrayType>(T))
188 return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this));
189 if (isa<IncompleteArrayType>(T))
192 CharUnits size = Ctx.getTypeSizeInChars(T);
193 QualType sizeTy = svalBuilder.getArrayIndexType();
194 return svalBuilder.makeIntVal(size.getQuantity(), sizeTy);
197 DefinedOrUnknownSVal FieldRegion::getExtent(SValBuilder &svalBuilder) const {
198 // Force callers to deal with bitfields explicitly.
199 if (getDecl()->isBitField())
202 DefinedOrUnknownSVal Extent = DeclRegion::getExtent(svalBuilder);
204 // A zero-length array at the end of a struct often stands for dynamically-
205 // allocated extra memory.
206 if (Extent.isZeroConstant()) {
207 QualType T = getDesugaredValueType(svalBuilder.getContext());
209 if (isa<ConstantArrayType>(T))
216 DefinedOrUnknownSVal AllocaRegion::getExtent(SValBuilder &svalBuilder) const {
217 return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this));
220 DefinedOrUnknownSVal SymbolicRegion::getExtent(SValBuilder &svalBuilder) const {
221 return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this));
224 DefinedOrUnknownSVal StringRegion::getExtent(SValBuilder &svalBuilder) const {
225 return svalBuilder.makeIntVal(getStringLiteral()->getByteLength()+1,
226 svalBuilder.getArrayIndexType());
229 ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, const MemRegion* sReg)
230 : DeclRegion(ivd, sReg, ObjCIvarRegionKind) {}
232 const ObjCIvarDecl *ObjCIvarRegion::getDecl() const {
233 return cast<ObjCIvarDecl>(D);
236 QualType ObjCIvarRegion::getValueType() const {
237 return getDecl()->getType();
240 QualType CXXBaseObjectRegion::getValueType() const {
241 return QualType(getDecl()->getTypeForDecl(), 0);
244 //===----------------------------------------------------------------------===//
245 // FoldingSet profiling.
246 //===----------------------------------------------------------------------===//
248 void MemSpaceRegion::Profile(llvm::FoldingSetNodeID& ID) const {
249 ID.AddInteger((unsigned)getKind());
252 void StackSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
253 ID.AddInteger((unsigned)getKind());
254 ID.AddPointer(getStackFrame());
257 void StaticGlobalSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
258 ID.AddInteger((unsigned)getKind());
259 ID.AddPointer(getCodeRegion());
262 void StringRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
263 const StringLiteral* Str,
264 const MemRegion* superRegion) {
265 ID.AddInteger((unsigned) StringRegionKind);
267 ID.AddPointer(superRegion);
270 void ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
271 const ObjCStringLiteral* Str,
272 const MemRegion* superRegion) {
273 ID.AddInteger((unsigned) ObjCStringRegionKind);
275 ID.AddPointer(superRegion);
278 void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
279 const Expr *Ex, unsigned cnt,
280 const MemRegion *superRegion) {
281 ID.AddInteger((unsigned) AllocaRegionKind);
284 ID.AddPointer(superRegion);
287 void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
288 ProfileRegion(ID, Ex, Cnt, superRegion);
291 void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
292 CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
295 void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
296 const CompoundLiteralExpr *CL,
297 const MemRegion* superRegion) {
298 ID.AddInteger((unsigned) CompoundLiteralRegionKind);
300 ID.AddPointer(superRegion);
303 void CXXThisRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
304 const PointerType *PT,
305 const MemRegion *sRegion) {
306 ID.AddInteger((unsigned) CXXThisRegionKind);
308 ID.AddPointer(sRegion);
311 void CXXThisRegion::Profile(llvm::FoldingSetNodeID &ID) const {
312 CXXThisRegion::ProfileRegion(ID, ThisPointerTy, superRegion);
315 void ObjCIvarRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
316 const ObjCIvarDecl *ivd,
317 const MemRegion* superRegion) {
318 DeclRegion::ProfileRegion(ID, ivd, superRegion, ObjCIvarRegionKind);
321 void DeclRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const Decl *D,
322 const MemRegion* superRegion, Kind k) {
323 ID.AddInteger((unsigned) k);
325 ID.AddPointer(superRegion);
328 void DeclRegion::Profile(llvm::FoldingSetNodeID& ID) const {
329 DeclRegion::ProfileRegion(ID, D, superRegion, getKind());
332 void VarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
333 VarRegion::ProfileRegion(ID, getDecl(), superRegion);
336 void SymbolicRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym,
337 const MemRegion *sreg) {
338 ID.AddInteger((unsigned) MemRegion::SymbolicRegionKind);
343 void SymbolicRegion::Profile(llvm::FoldingSetNodeID& ID) const {
344 SymbolicRegion::ProfileRegion(ID, sym, getSuperRegion());
347 void ElementRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
348 QualType ElementType, SVal Idx,
349 const MemRegion* superRegion) {
350 ID.AddInteger(MemRegion::ElementRegionKind);
352 ID.AddPointer(superRegion);
356 void ElementRegion::Profile(llvm::FoldingSetNodeID& ID) const {
357 ElementRegion::ProfileRegion(ID, ElementType, Index, superRegion);
360 void FunctionTextRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
363 ID.AddInteger(MemRegion::FunctionTextRegionKind);
367 void FunctionTextRegion::Profile(llvm::FoldingSetNodeID& ID) const {
368 FunctionTextRegion::ProfileRegion(ID, FD, superRegion);
371 void BlockTextRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
372 const BlockDecl *BD, CanQualType,
373 const AnalysisDeclContext *AC,
375 ID.AddInteger(MemRegion::BlockTextRegionKind);
379 void BlockTextRegion::Profile(llvm::FoldingSetNodeID& ID) const {
380 BlockTextRegion::ProfileRegion(ID, BD, locTy, AC, superRegion);
383 void BlockDataRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
384 const BlockTextRegion *BC,
385 const LocationContext *LC,
386 const MemRegion *sReg) {
387 ID.AddInteger(MemRegion::BlockDataRegionKind);
393 void BlockDataRegion::Profile(llvm::FoldingSetNodeID& ID) const {
394 BlockDataRegion::ProfileRegion(ID, BC, LC, getSuperRegion());
397 void CXXTempObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
399 const MemRegion *sReg) {
404 void CXXTempObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
405 ProfileRegion(ID, Ex, getSuperRegion());
408 void CXXBaseObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
409 const CXXRecordDecl *RD,
411 const MemRegion *SReg) {
413 ID.AddBoolean(IsVirtual);
417 void CXXBaseObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
418 ProfileRegion(ID, getDecl(), isVirtual(), superRegion);
421 //===----------------------------------------------------------------------===//
423 //===----------------------------------------------------------------------===//
425 void GlobalsSpaceRegion::anchor() { }
426 void HeapSpaceRegion::anchor() { }
427 void UnknownSpaceRegion::anchor() { }
428 void StackLocalsSpaceRegion::anchor() { }
429 void StackArgumentsSpaceRegion::anchor() { }
430 void TypedRegion::anchor() { }
431 void TypedValueRegion::anchor() { }
432 void CodeTextRegion::anchor() { }
433 void SubRegion::anchor() { }
435 //===----------------------------------------------------------------------===//
436 // Region pretty-printing.
437 //===----------------------------------------------------------------------===//
439 void MemRegion::dump() const {
440 dumpToStream(llvm::errs());
443 std::string MemRegion::getString() const {
445 llvm::raw_string_ostream os(s);
450 void MemRegion::dumpToStream(raw_ostream &os) const {
451 os << "<Unknown Region>";
454 void AllocaRegion::dumpToStream(raw_ostream &os) const {
455 os << "alloca{" << (const void*) Ex << ',' << Cnt << '}';
458 void FunctionTextRegion::dumpToStream(raw_ostream &os) const {
459 os << "code{" << getDecl()->getDeclName().getAsString() << '}';
462 void BlockTextRegion::dumpToStream(raw_ostream &os) const {
463 os << "block_code{" << (const void*) this << '}';
466 void BlockDataRegion::dumpToStream(raw_ostream &os) const {
467 os << "block_data{" << BC << '}';
470 void CompoundLiteralRegion::dumpToStream(raw_ostream &os) const {
471 // FIXME: More elaborate pretty-printing.
472 os << "{ " << (const void*) CL << " }";
475 void CXXTempObjectRegion::dumpToStream(raw_ostream &os) const {
476 os << "temp_object{" << getValueType().getAsString() << ','
477 << (const void*) Ex << '}';
480 void CXXBaseObjectRegion::dumpToStream(raw_ostream &os) const {
481 os << "base{" << superRegion << ',' << getDecl()->getName() << '}';
484 void CXXThisRegion::dumpToStream(raw_ostream &os) const {
488 void ElementRegion::dumpToStream(raw_ostream &os) const {
489 os << "element{" << superRegion << ','
490 << Index << ',' << getElementType().getAsString() << '}';
493 void FieldRegion::dumpToStream(raw_ostream &os) const {
494 os << superRegion << "->" << *getDecl();
497 void ObjCIvarRegion::dumpToStream(raw_ostream &os) const {
498 os << "ivar{" << superRegion << ',' << *getDecl() << '}';
501 void StringRegion::dumpToStream(raw_ostream &os) const {
502 Str->printPretty(os, 0, PrintingPolicy(getContext().getLangOpts()));
505 void ObjCStringRegion::dumpToStream(raw_ostream &os) const {
506 Str->printPretty(os, 0, PrintingPolicy(getContext().getLangOpts()));
509 void SymbolicRegion::dumpToStream(raw_ostream &os) const {
510 os << "SymRegion{" << sym << '}';
513 void VarRegion::dumpToStream(raw_ostream &os) const {
514 os << *cast<VarDecl>(D);
517 void RegionRawOffset::dump() const {
518 dumpToStream(llvm::errs());
521 void RegionRawOffset::dumpToStream(raw_ostream &os) const {
522 os << "raw_offset{" << getRegion() << ',' << getOffset().getQuantity() << '}';
525 void StaticGlobalSpaceRegion::dumpToStream(raw_ostream &os) const {
526 os << "StaticGlobalsMemSpace{" << CR << '}';
529 void GlobalInternalSpaceRegion::dumpToStream(raw_ostream &os) const {
530 os << "GlobalInternalSpaceRegion";
533 void GlobalSystemSpaceRegion::dumpToStream(raw_ostream &os) const {
534 os << "GlobalSystemSpaceRegion";
537 void GlobalImmutableSpaceRegion::dumpToStream(raw_ostream &os) const {
538 os << "GlobalImmutableSpaceRegion";
541 void HeapSpaceRegion::dumpToStream(raw_ostream &os) const {
542 os << "HeapSpaceRegion";
545 void UnknownSpaceRegion::dumpToStream(raw_ostream &os) const {
546 os << "UnknownSpaceRegion";
549 void StackArgumentsSpaceRegion::dumpToStream(raw_ostream &os) const {
550 os << "StackArgumentsSpaceRegion";
553 void StackLocalsSpaceRegion::dumpToStream(raw_ostream &os) const {
554 os << "StackLocalsSpaceRegion";
557 bool MemRegion::canPrintPretty() const {
558 return canPrintPrettyAsExpr();
561 bool MemRegion::canPrintPrettyAsExpr() const {
565 void MemRegion::printPretty(raw_ostream &os) const {
566 assert(canPrintPretty() && "This region cannot be printed pretty.");
568 printPrettyAsExpr(os);
573 void MemRegion::printPrettyAsExpr(raw_ostream &os) const {
574 llvm_unreachable("This region cannot be printed pretty.");
578 bool VarRegion::canPrintPrettyAsExpr() const {
582 void VarRegion::printPrettyAsExpr(raw_ostream &os) const {
583 os << getDecl()->getName();
586 bool ObjCIvarRegion::canPrintPrettyAsExpr() const {
590 void ObjCIvarRegion::printPrettyAsExpr(raw_ostream &os) const {
591 os << getDecl()->getName();
594 bool FieldRegion::canPrintPretty() const {
598 bool FieldRegion::canPrintPrettyAsExpr() const {
599 return superRegion->canPrintPrettyAsExpr();
602 void FieldRegion::printPrettyAsExpr(raw_ostream &os) const {
603 assert(canPrintPrettyAsExpr());
604 superRegion->printPrettyAsExpr(os);
605 os << "." << getDecl()->getName();
608 void FieldRegion::printPretty(raw_ostream &os) const {
609 if (canPrintPrettyAsExpr()) {
611 printPrettyAsExpr(os);
614 os << "field " << "\'" << getDecl()->getName() << "'";
619 bool CXXBaseObjectRegion::canPrintPrettyAsExpr() const {
620 return superRegion->canPrintPrettyAsExpr();
623 void CXXBaseObjectRegion::printPrettyAsExpr(raw_ostream &os) const {
624 superRegion->printPrettyAsExpr(os);
627 //===----------------------------------------------------------------------===//
628 // MemRegionManager methods.
629 //===----------------------------------------------------------------------===//
631 template <typename REG>
632 const REG *MemRegionManager::LazyAllocate(REG*& region) {
634 region = (REG*) A.Allocate<REG>();
635 new (region) REG(this);
641 template <typename REG, typename ARG>
642 const REG *MemRegionManager::LazyAllocate(REG*& region, ARG a) {
644 region = (REG*) A.Allocate<REG>();
645 new (region) REG(this, a);
651 const StackLocalsSpaceRegion*
652 MemRegionManager::getStackLocalsRegion(const StackFrameContext *STC) {
654 StackLocalsSpaceRegion *&R = StackLocalsSpaceRegions[STC];
659 R = A.Allocate<StackLocalsSpaceRegion>();
660 new (R) StackLocalsSpaceRegion(this, STC);
664 const StackArgumentsSpaceRegion *
665 MemRegionManager::getStackArgumentsRegion(const StackFrameContext *STC) {
667 StackArgumentsSpaceRegion *&R = StackArgumentsSpaceRegions[STC];
672 R = A.Allocate<StackArgumentsSpaceRegion>();
673 new (R) StackArgumentsSpaceRegion(this, STC);
677 const GlobalsSpaceRegion
678 *MemRegionManager::getGlobalsRegion(MemRegion::Kind K,
679 const CodeTextRegion *CR) {
681 if (K == MemRegion::GlobalSystemSpaceRegionKind)
682 return LazyAllocate(SystemGlobals);
683 if (K == MemRegion::GlobalImmutableSpaceRegionKind)
684 return LazyAllocate(ImmutableGlobals);
685 assert(K == MemRegion::GlobalInternalSpaceRegionKind);
686 return LazyAllocate(InternalGlobals);
689 assert(K == MemRegion::StaticGlobalSpaceRegionKind);
690 StaticGlobalSpaceRegion *&R = StaticsGlobalSpaceRegions[CR];
694 R = A.Allocate<StaticGlobalSpaceRegion>();
695 new (R) StaticGlobalSpaceRegion(this, CR);
699 const HeapSpaceRegion *MemRegionManager::getHeapRegion() {
700 return LazyAllocate(heap);
703 const MemSpaceRegion *MemRegionManager::getUnknownRegion() {
704 return LazyAllocate(unknown);
707 const MemSpaceRegion *MemRegionManager::getCodeRegion() {
708 return LazyAllocate(code);
711 //===----------------------------------------------------------------------===//
712 // Constructing regions.
713 //===----------------------------------------------------------------------===//
714 const StringRegion* MemRegionManager::getStringRegion(const StringLiteral* Str){
715 return getSubRegion<StringRegion>(Str, getGlobalsRegion());
718 const ObjCStringRegion *
719 MemRegionManager::getObjCStringRegion(const ObjCStringLiteral* Str){
720 return getSubRegion<ObjCStringRegion>(Str, getGlobalsRegion());
723 /// Look through a chain of LocationContexts to either find the
724 /// StackFrameContext that matches a DeclContext, or find a VarRegion
725 /// for a variable captured by a block.
726 static llvm::PointerUnion<const StackFrameContext *, const VarRegion *>
727 getStackOrCaptureRegionForDeclContext(const LocationContext *LC,
728 const DeclContext *DC,
731 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC)) {
732 if (cast<DeclContext>(SFC->getDecl()) == DC)
735 if (const BlockInvocationContext *BC =
736 dyn_cast<BlockInvocationContext>(LC)) {
737 const BlockDataRegion *BR =
738 static_cast<const BlockDataRegion*>(BC->getContextData());
739 // FIXME: This can be made more efficient.
740 for (BlockDataRegion::referenced_vars_iterator
741 I = BR->referenced_vars_begin(),
742 E = BR->referenced_vars_end(); I != E; ++I) {
743 if (const VarRegion *VR = dyn_cast<VarRegion>(I.getOriginalRegion()))
744 if (VR->getDecl() == VD)
745 return cast<VarRegion>(I.getCapturedRegion());
749 LC = LC->getParent();
751 return (const StackFrameContext*)0;
754 const VarRegion* MemRegionManager::getVarRegion(const VarDecl *D,
755 const LocationContext *LC) {
756 const MemRegion *sReg = 0;
758 if (D->hasGlobalStorage() && !D->isStaticLocal()) {
760 // First handle the globals defined in system headers.
761 if (C.getSourceManager().isInSystemHeader(D->getLocation())) {
762 // Whitelist the system globals which often DO GET modified, assume the
763 // rest are immutable.
764 if (D->getName().find("errno") != StringRef::npos)
765 sReg = getGlobalsRegion(MemRegion::GlobalSystemSpaceRegionKind);
767 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
769 // Treat other globals as GlobalInternal unless they are constants.
771 QualType GQT = D->getType();
772 const Type *GT = GQT.getTypePtrOrNull();
773 // TODO: We could walk the complex types here and see if everything is
775 if (GT && GQT.isConstQualified() && GT->isArithmeticType())
776 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
778 sReg = getGlobalsRegion();
781 // Finally handle static locals.
783 // FIXME: Once we implement scope handling, we will need to properly lookup
784 // 'D' to the proper LocationContext.
785 const DeclContext *DC = D->getDeclContext();
786 llvm::PointerUnion<const StackFrameContext *, const VarRegion *> V =
787 getStackOrCaptureRegionForDeclContext(LC, DC, D);
789 if (V.is<const VarRegion*>())
790 return V.get<const VarRegion*>();
792 const StackFrameContext *STC = V.get<const StackFrameContext*>();
795 sReg = getUnknownRegion();
797 if (D->hasLocalStorage()) {
798 sReg = isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)
799 ? static_cast<const MemRegion*>(getStackArgumentsRegion(STC))
800 : static_cast<const MemRegion*>(getStackLocalsRegion(STC));
803 assert(D->isStaticLocal());
804 const Decl *STCD = STC->getDecl();
805 if (isa<FunctionDecl>(STCD) || isa<ObjCMethodDecl>(STCD))
806 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
807 getFunctionTextRegion(cast<NamedDecl>(STCD)));
808 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(STCD)) {
809 const BlockTextRegion *BTR =
810 getBlockTextRegion(BD,
811 C.getCanonicalType(BD->getSignatureAsWritten()->getType()),
812 STC->getAnalysisDeclContext());
813 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
817 sReg = getGlobalsRegion();
823 return getSubRegion<VarRegion>(D, sReg);
826 const VarRegion *MemRegionManager::getVarRegion(const VarDecl *D,
827 const MemRegion *superR) {
828 return getSubRegion<VarRegion>(D, superR);
831 const BlockDataRegion *
832 MemRegionManager::getBlockDataRegion(const BlockTextRegion *BC,
833 const LocationContext *LC) {
834 const MemRegion *sReg = 0;
835 const BlockDecl *BD = BC->getDecl();
836 if (!BD->hasCaptures()) {
837 // This handles 'static' blocks.
838 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
842 // FIXME: Once we implement scope handling, we want the parent region
844 const StackFrameContext *STC = LC->getCurrentStackFrame();
846 sReg = getStackLocalsRegion(STC);
849 // We allow 'LC' to be NULL for cases where want BlockDataRegions
850 // without context-sensitivity.
851 sReg = getUnknownRegion();
855 return getSubRegion<BlockDataRegion>(BC, LC, sReg);
858 const CompoundLiteralRegion*
859 MemRegionManager::getCompoundLiteralRegion(const CompoundLiteralExpr *CL,
860 const LocationContext *LC) {
862 const MemRegion *sReg = 0;
864 if (CL->isFileScope())
865 sReg = getGlobalsRegion();
867 const StackFrameContext *STC = LC->getCurrentStackFrame();
869 sReg = getStackLocalsRegion(STC);
872 return getSubRegion<CompoundLiteralRegion>(CL, sReg);
876 MemRegionManager::getElementRegion(QualType elementType, NonLoc Idx,
877 const MemRegion* superRegion,
880 QualType T = Ctx.getCanonicalType(elementType).getUnqualifiedType();
882 llvm::FoldingSetNodeID ID;
883 ElementRegion::ProfileRegion(ID, T, Idx, superRegion);
886 MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos);
887 ElementRegion* R = cast_or_null<ElementRegion>(data);
890 R = (ElementRegion*) A.Allocate<ElementRegion>();
891 new (R) ElementRegion(T, Idx, superRegion);
892 Regions.InsertNode(R, InsertPos);
898 const FunctionTextRegion *
899 MemRegionManager::getFunctionTextRegion(const NamedDecl *FD) {
900 return getSubRegion<FunctionTextRegion>(FD, getCodeRegion());
903 const BlockTextRegion *
904 MemRegionManager::getBlockTextRegion(const BlockDecl *BD, CanQualType locTy,
905 AnalysisDeclContext *AC) {
906 return getSubRegion<BlockTextRegion>(BD, locTy, AC, getCodeRegion());
910 /// getSymbolicRegion - Retrieve or create a "symbolic" memory region.
911 const SymbolicRegion *MemRegionManager::getSymbolicRegion(SymbolRef sym) {
912 return getSubRegion<SymbolicRegion>(sym, getUnknownRegion());
915 const SymbolicRegion *MemRegionManager::getSymbolicHeapRegion(SymbolRef Sym) {
916 return getSubRegion<SymbolicRegion>(Sym, getHeapRegion());
920 MemRegionManager::getFieldRegion(const FieldDecl *d,
921 const MemRegion* superRegion){
922 return getSubRegion<FieldRegion>(d, superRegion);
925 const ObjCIvarRegion*
926 MemRegionManager::getObjCIvarRegion(const ObjCIvarDecl *d,
927 const MemRegion* superRegion) {
928 return getSubRegion<ObjCIvarRegion>(d, superRegion);
931 const CXXTempObjectRegion*
932 MemRegionManager::getCXXTempObjectRegion(Expr const *E,
933 LocationContext const *LC) {
934 const StackFrameContext *SFC = LC->getCurrentStackFrame();
936 return getSubRegion<CXXTempObjectRegion>(E, getStackLocalsRegion(SFC));
939 /// Checks whether \p BaseClass is a valid virtual or direct non-virtual base
940 /// class of the type of \p Super.
941 static bool isValidBaseClass(const CXXRecordDecl *BaseClass,
942 const TypedValueRegion *Super,
944 BaseClass = BaseClass->getCanonicalDecl();
946 const CXXRecordDecl *Class = Super->getValueType()->getAsCXXRecordDecl();
951 return Class->isVirtuallyDerivedFrom(BaseClass);
953 for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
954 E = Class->bases_end();
956 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == BaseClass)
963 const CXXBaseObjectRegion *
964 MemRegionManager::getCXXBaseObjectRegion(const CXXRecordDecl *RD,
965 const MemRegion *Super,
967 if (isa<TypedValueRegion>(Super)) {
968 assert(isValidBaseClass(RD, dyn_cast<TypedValueRegion>(Super), IsVirtual));
969 (void)isValidBaseClass;
972 // Virtual base regions should not be layered, since the layout rules
974 while (const CXXBaseObjectRegion *Base =
975 dyn_cast<CXXBaseObjectRegion>(Super)) {
976 Super = Base->getSuperRegion();
978 assert(Super && !isa<MemSpaceRegion>(Super));
982 return getSubRegion<CXXBaseObjectRegion>(RD, IsVirtual, Super);
986 MemRegionManager::getCXXThisRegion(QualType thisPointerTy,
987 const LocationContext *LC) {
988 const StackFrameContext *STC = LC->getCurrentStackFrame();
990 const PointerType *PT = thisPointerTy->getAs<PointerType>();
992 return getSubRegion<CXXThisRegion>(PT, getStackArgumentsRegion(STC));
996 MemRegionManager::getAllocaRegion(const Expr *E, unsigned cnt,
997 const LocationContext *LC) {
998 const StackFrameContext *STC = LC->getCurrentStackFrame();
1000 return getSubRegion<AllocaRegion>(E, cnt, getStackLocalsRegion(STC));
1003 const MemSpaceRegion *MemRegion::getMemorySpace() const {
1004 const MemRegion *R = this;
1005 const SubRegion* SR = dyn_cast<SubRegion>(this);
1008 R = SR->getSuperRegion();
1009 SR = dyn_cast<SubRegion>(R);
1012 return dyn_cast<MemSpaceRegion>(R);
1015 bool MemRegion::hasStackStorage() const {
1016 return isa<StackSpaceRegion>(getMemorySpace());
1019 bool MemRegion::hasStackNonParametersStorage() const {
1020 return isa<StackLocalsSpaceRegion>(getMemorySpace());
1023 bool MemRegion::hasStackParametersStorage() const {
1024 return isa<StackArgumentsSpaceRegion>(getMemorySpace());
1027 bool MemRegion::hasGlobalsOrParametersStorage() const {
1028 const MemSpaceRegion *MS = getMemorySpace();
1029 return isa<StackArgumentsSpaceRegion>(MS) ||
1030 isa<GlobalsSpaceRegion>(MS);
1033 // getBaseRegion strips away all elements and fields, and get the base region
1035 const MemRegion *MemRegion::getBaseRegion() const {
1036 const MemRegion *R = this;
1038 switch (R->getKind()) {
1039 case MemRegion::ElementRegionKind:
1040 case MemRegion::FieldRegionKind:
1041 case MemRegion::ObjCIvarRegionKind:
1042 case MemRegion::CXXBaseObjectRegionKind:
1043 R = cast<SubRegion>(R)->getSuperRegion();
1053 bool MemRegion::isSubRegionOf(const MemRegion *R) const {
1057 //===----------------------------------------------------------------------===//
1059 //===----------------------------------------------------------------------===//
1061 const MemRegion *MemRegion::StripCasts(bool StripBaseCasts) const {
1062 const MemRegion *R = this;
1064 switch (R->getKind()) {
1065 case ElementRegionKind: {
1066 const ElementRegion *ER = cast<ElementRegion>(R);
1067 if (!ER->getIndex().isZeroConstant())
1069 R = ER->getSuperRegion();
1072 case CXXBaseObjectRegionKind:
1073 if (!StripBaseCasts)
1075 R = cast<CXXBaseObjectRegion>(R)->getSuperRegion();
1083 const SymbolicRegion *MemRegion::getSymbolicBase() const {
1084 const SubRegion *SubR = dyn_cast<SubRegion>(this);
1087 if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(SubR))
1089 SubR = dyn_cast<SubRegion>(SubR->getSuperRegion());
1094 // FIXME: Merge with the implementation of the same method in Store.cpp
1095 static bool IsCompleteType(ASTContext &Ctx, QualType Ty) {
1096 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1097 const RecordDecl *D = RT->getDecl();
1098 if (!D->getDefinition())
1105 RegionRawOffset ElementRegion::getAsArrayOffset() const {
1106 CharUnits offset = CharUnits::Zero();
1107 const ElementRegion *ER = this;
1108 const MemRegion *superR = NULL;
1109 ASTContext &C = getContext();
1111 // FIXME: Handle multi-dimensional arrays.
1114 superR = ER->getSuperRegion();
1116 // FIXME: generalize to symbolic offsets.
1117 SVal index = ER->getIndex();
1118 if (Optional<nonloc::ConcreteInt> CI = index.getAs<nonloc::ConcreteInt>()) {
1119 // Update the offset.
1120 int64_t i = CI->getValue().getSExtValue();
1123 QualType elemType = ER->getElementType();
1125 // If we are pointing to an incomplete type, go no further.
1126 if (!IsCompleteType(C, elemType)) {
1131 CharUnits size = C.getTypeSizeInChars(elemType);
1132 offset += (i * size);
1135 // Go to the next ElementRegion (if any).
1136 ER = dyn_cast<ElementRegion>(superR);
1143 assert(superR && "super region cannot be NULL");
1144 return RegionRawOffset(superR, offset);
1148 /// Returns true if \p Base is an immediate base class of \p Child
1149 static bool isImmediateBase(const CXXRecordDecl *Child,
1150 const CXXRecordDecl *Base) {
1151 // Note that we do NOT canonicalize the base class here, because
1152 // ASTRecordLayout doesn't either. If that leads us down the wrong path,
1153 // so be it; at least we won't crash.
1154 for (CXXRecordDecl::base_class_const_iterator I = Child->bases_begin(),
1155 E = Child->bases_end();
1157 if (I->getType()->getAsCXXRecordDecl() == Base)
1164 RegionOffset MemRegion::getAsOffset() const {
1165 const MemRegion *R = this;
1166 const MemRegion *SymbolicOffsetBase = 0;
1170 switch (R->getKind()) {
1171 case GenericMemSpaceRegionKind:
1172 case StackLocalsSpaceRegionKind:
1173 case StackArgumentsSpaceRegionKind:
1174 case HeapSpaceRegionKind:
1175 case UnknownSpaceRegionKind:
1176 case StaticGlobalSpaceRegionKind:
1177 case GlobalInternalSpaceRegionKind:
1178 case GlobalSystemSpaceRegionKind:
1179 case GlobalImmutableSpaceRegionKind:
1180 // Stores can bind directly to a region space to set a default value.
1181 assert(Offset == 0 && !SymbolicOffsetBase);
1184 case FunctionTextRegionKind:
1185 case BlockTextRegionKind:
1186 case BlockDataRegionKind:
1187 // These will never have bindings, but may end up having values requested
1188 // if the user does some strange casting.
1190 SymbolicOffsetBase = R;
1193 case SymbolicRegionKind:
1194 case AllocaRegionKind:
1195 case CompoundLiteralRegionKind:
1196 case CXXThisRegionKind:
1197 case StringRegionKind:
1198 case ObjCStringRegionKind:
1200 case CXXTempObjectRegionKind:
1201 // Usual base regions.
1204 case ObjCIvarRegionKind:
1205 // This is a little strange, but it's a compromise between
1206 // ObjCIvarRegions having unknown compile-time offsets (when using the
1207 // non-fragile runtime) and yet still being distinct, non-overlapping
1208 // regions. Thus we treat them as "like" base regions for the purposes
1209 // of computing offsets.
1212 case CXXBaseObjectRegionKind: {
1213 const CXXBaseObjectRegion *BOR = cast<CXXBaseObjectRegion>(R);
1214 R = BOR->getSuperRegion();
1217 bool RootIsSymbolic = false;
1218 if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R)) {
1219 Ty = TVR->getDesugaredValueType(getContext());
1220 } else if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
1221 // If our base region is symbolic, we don't know what type it really is.
1222 // Pretend the type of the symbol is the true dynamic type.
1223 // (This will at least be self-consistent for the life of the symbol.)
1224 Ty = SR->getSymbol()->getType()->getPointeeType();
1225 RootIsSymbolic = true;
1228 const CXXRecordDecl *Child = Ty->getAsCXXRecordDecl();
1230 // We cannot compute the offset of the base class.
1231 SymbolicOffsetBase = R;
1234 if (RootIsSymbolic) {
1235 // Base layers on symbolic regions may not be type-correct.
1236 // Double-check the inheritance here, and revert to a symbolic offset
1237 // if it's invalid (e.g. due to a reinterpret_cast).
1238 if (BOR->isVirtual()) {
1239 if (!Child->isVirtuallyDerivedFrom(BOR->getDecl()))
1240 SymbolicOffsetBase = R;
1242 if (!isImmediateBase(Child, BOR->getDecl()))
1243 SymbolicOffsetBase = R;
1247 // Don't bother calculating precise offsets if we already have a
1248 // symbolic offset somewhere in the chain.
1249 if (SymbolicOffsetBase)
1252 CharUnits BaseOffset;
1253 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Child);
1254 if (BOR->isVirtual())
1255 BaseOffset = Layout.getVBaseClassOffset(BOR->getDecl());
1257 BaseOffset = Layout.getBaseClassOffset(BOR->getDecl());
1259 // The base offset is in chars, not in bits.
1260 Offset += BaseOffset.getQuantity() * getContext().getCharWidth();
1263 case ElementRegionKind: {
1264 const ElementRegion *ER = cast<ElementRegion>(R);
1265 R = ER->getSuperRegion();
1267 QualType EleTy = ER->getValueType();
1268 if (!IsCompleteType(getContext(), EleTy)) {
1269 // We cannot compute the offset of the base class.
1270 SymbolicOffsetBase = R;
1274 SVal Index = ER->getIndex();
1275 if (Optional<nonloc::ConcreteInt> CI =
1276 Index.getAs<nonloc::ConcreteInt>()) {
1277 // Don't bother calculating precise offsets if we already have a
1278 // symbolic offset somewhere in the chain.
1279 if (SymbolicOffsetBase)
1282 int64_t i = CI->getValue().getSExtValue();
1283 // This type size is in bits.
1284 Offset += i * getContext().getTypeSize(EleTy);
1286 // We cannot compute offset for non-concrete index.
1287 SymbolicOffsetBase = R;
1291 case FieldRegionKind: {
1292 const FieldRegion *FR = cast<FieldRegion>(R);
1293 R = FR->getSuperRegion();
1295 const RecordDecl *RD = FR->getDecl()->getParent();
1296 if (RD->isUnion() || !RD->isCompleteDefinition()) {
1297 // We cannot compute offset for incomplete type.
1298 // For unions, we could treat everything as offset 0, but we'd rather
1299 // treat each field as a symbolic offset so they aren't stored on top
1300 // of each other, since we depend on things in typed regions actually
1301 // matching their types.
1302 SymbolicOffsetBase = R;
1305 // Don't bother calculating precise offsets if we already have a
1306 // symbolic offset somewhere in the chain.
1307 if (SymbolicOffsetBase)
1310 // Get the field number.
1312 for (RecordDecl::field_iterator FI = RD->field_begin(),
1313 FE = RD->field_end(); FI != FE; ++FI, ++idx)
1314 if (FR->getDecl() == *FI)
1317 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1318 // This is offset in bits.
1319 Offset += Layout.getFieldOffset(idx);
1326 if (SymbolicOffsetBase)
1327 return RegionOffset(SymbolicOffsetBase, RegionOffset::Symbolic);
1328 return RegionOffset(R, Offset);
1331 //===----------------------------------------------------------------------===//
1333 //===----------------------------------------------------------------------===//
1335 std::pair<const VarRegion *, const VarRegion *>
1336 BlockDataRegion::getCaptureRegions(const VarDecl *VD) {
1337 MemRegionManager &MemMgr = *getMemRegionManager();
1338 const VarRegion *VR = 0;
1339 const VarRegion *OriginalVR = 0;
1341 if (!VD->getAttr<BlocksAttr>() && VD->hasLocalStorage()) {
1342 VR = MemMgr.getVarRegion(VD, this);
1343 OriginalVR = MemMgr.getVarRegion(VD, LC);
1347 VR = MemMgr.getVarRegion(VD, LC);
1351 VR = MemMgr.getVarRegion(VD, MemMgr.getUnknownRegion());
1352 OriginalVR = MemMgr.getVarRegion(VD, LC);
1355 return std::make_pair(VR, OriginalVR);
1358 void BlockDataRegion::LazyInitializeReferencedVars() {
1362 AnalysisDeclContext *AC = getCodeRegion()->getAnalysisDeclContext();
1363 AnalysisDeclContext::referenced_decls_iterator I, E;
1364 llvm::tie(I, E) = AC->getReferencedBlockVars(BC->getDecl());
1367 ReferencedVars = (void*) 0x1;
1371 MemRegionManager &MemMgr = *getMemRegionManager();
1372 llvm::BumpPtrAllocator &A = MemMgr.getAllocator();
1373 BumpVectorContext BC(A);
1375 typedef BumpVector<const MemRegion*> VarVec;
1376 VarVec *BV = (VarVec*) A.Allocate<VarVec>();
1377 new (BV) VarVec(BC, E - I);
1378 VarVec *BVOriginal = (VarVec*) A.Allocate<VarVec>();
1379 new (BVOriginal) VarVec(BC, E - I);
1381 for ( ; I != E; ++I) {
1382 const VarRegion *VR = 0;
1383 const VarRegion *OriginalVR = 0;
1384 llvm::tie(VR, OriginalVR) = getCaptureRegions(*I);
1387 BV->push_back(VR, BC);
1388 BVOriginal->push_back(OriginalVR, BC);
1391 ReferencedVars = BV;
1392 OriginalVars = BVOriginal;
1395 BlockDataRegion::referenced_vars_iterator
1396 BlockDataRegion::referenced_vars_begin() const {
1397 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1399 BumpVector<const MemRegion*> *Vec =
1400 static_cast<BumpVector<const MemRegion*>*>(ReferencedVars);
1402 if (Vec == (void*) 0x1)
1403 return BlockDataRegion::referenced_vars_iterator(0, 0);
1405 BumpVector<const MemRegion*> *VecOriginal =
1406 static_cast<BumpVector<const MemRegion*>*>(OriginalVars);
1408 return BlockDataRegion::referenced_vars_iterator(Vec->begin(),
1409 VecOriginal->begin());
1412 BlockDataRegion::referenced_vars_iterator
1413 BlockDataRegion::referenced_vars_end() const {
1414 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1416 BumpVector<const MemRegion*> *Vec =
1417 static_cast<BumpVector<const MemRegion*>*>(ReferencedVars);
1419 if (Vec == (void*) 0x1)
1420 return BlockDataRegion::referenced_vars_iterator(0, 0);
1422 BumpVector<const MemRegion*> *VecOriginal =
1423 static_cast<BumpVector<const MemRegion*>*>(OriginalVars);
1425 return BlockDataRegion::referenced_vars_iterator(Vec->end(),
1426 VecOriginal->end());
1429 const VarRegion *BlockDataRegion::getOriginalRegion(const VarRegion *R) const {
1430 for (referenced_vars_iterator I = referenced_vars_begin(),
1431 E = referenced_vars_end();
1433 if (I.getCapturedRegion() == R)
1434 return I.getOriginalRegion();