• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //== MemRegion.cpp - Abstract memory regions for static analysis --*- C++ -*--//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines MemRegion and its subclasses.  MemRegion defines a
11 //  partially-typed abstraction of memory useful for path-sensitive dataflow
12 //  analyses.
13 //
14 //===----------------------------------------------------------------------===//
15 
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"
26 
27 using namespace clang;
28 using namespace ento;
29 
30 //===----------------------------------------------------------------------===//
31 // MemRegion Construction.
32 //===----------------------------------------------------------------------===//
33 
34 template<typename RegionTy> struct MemRegionManagerTrait;
35 
36 template <typename RegionTy, typename A1>
getRegion(const A1 a1)37 RegionTy* MemRegionManager::getRegion(const A1 a1) {
38 
39   const typename MemRegionManagerTrait<RegionTy>::SuperRegionTy *superRegion =
40   MemRegionManagerTrait<RegionTy>::getSuperRegion(*this, a1);
41 
42   llvm::FoldingSetNodeID ID;
43   RegionTy::ProfileRegion(ID, a1, superRegion);
44   void *InsertPos;
45   RegionTy* R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID,
46                                                                    InsertPos));
47 
48   if (!R) {
49     R = (RegionTy*) A.Allocate<RegionTy>();
50     new (R) RegionTy(a1, superRegion);
51     Regions.InsertNode(R, InsertPos);
52   }
53 
54   return R;
55 }
56 
57 template <typename RegionTy, typename A1>
getSubRegion(const A1 a1,const MemRegion * superRegion)58 RegionTy* MemRegionManager::getSubRegion(const A1 a1,
59                                          const MemRegion *superRegion) {
60   llvm::FoldingSetNodeID ID;
61   RegionTy::ProfileRegion(ID, a1, superRegion);
62   void *InsertPos;
63   RegionTy* R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID,
64                                                                    InsertPos));
65 
66   if (!R) {
67     R = (RegionTy*) A.Allocate<RegionTy>();
68     new (R) RegionTy(a1, superRegion);
69     Regions.InsertNode(R, InsertPos);
70   }
71 
72   return R;
73 }
74 
75 template <typename RegionTy, typename A1, typename A2>
getRegion(const A1 a1,const A2 a2)76 RegionTy* MemRegionManager::getRegion(const A1 a1, const A2 a2) {
77 
78   const typename MemRegionManagerTrait<RegionTy>::SuperRegionTy *superRegion =
79   MemRegionManagerTrait<RegionTy>::getSuperRegion(*this, a1, a2);
80 
81   llvm::FoldingSetNodeID ID;
82   RegionTy::ProfileRegion(ID, a1, a2, superRegion);
83   void *InsertPos;
84   RegionTy* R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID,
85                                                                    InsertPos));
86 
87   if (!R) {
88     R = (RegionTy*) A.Allocate<RegionTy>();
89     new (R) RegionTy(a1, a2, superRegion);
90     Regions.InsertNode(R, InsertPos);
91   }
92 
93   return R;
94 }
95 
96 template <typename RegionTy, typename A1, typename A2>
getSubRegion(const A1 a1,const A2 a2,const MemRegion * superRegion)97 RegionTy* MemRegionManager::getSubRegion(const A1 a1, const A2 a2,
98                                          const MemRegion *superRegion) {
99 
100   llvm::FoldingSetNodeID ID;
101   RegionTy::ProfileRegion(ID, a1, a2, superRegion);
102   void *InsertPos;
103   RegionTy* R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID,
104                                                                    InsertPos));
105 
106   if (!R) {
107     R = (RegionTy*) A.Allocate<RegionTy>();
108     new (R) RegionTy(a1, a2, superRegion);
109     Regions.InsertNode(R, InsertPos);
110   }
111 
112   return R;
113 }
114 
115 template <typename RegionTy, typename A1, typename A2, typename A3>
getSubRegion(const A1 a1,const A2 a2,const A3 a3,const MemRegion * superRegion)116 RegionTy* MemRegionManager::getSubRegion(const A1 a1, const A2 a2, const A3 a3,
117                                          const MemRegion *superRegion) {
118 
119   llvm::FoldingSetNodeID ID;
120   RegionTy::ProfileRegion(ID, a1, a2, a3, superRegion);
121   void *InsertPos;
122   RegionTy* R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID,
123                                                                    InsertPos));
124 
125   if (!R) {
126     R = (RegionTy*) A.Allocate<RegionTy>();
127     new (R) RegionTy(a1, a2, a3, superRegion);
128     Regions.InsertNode(R, InsertPos);
129   }
130 
131   return R;
132 }
133 
134 //===----------------------------------------------------------------------===//
135 // Object destruction.
136 //===----------------------------------------------------------------------===//
137 
~MemRegion()138 MemRegion::~MemRegion() {}
139 
~MemRegionManager()140 MemRegionManager::~MemRegionManager() {
141   // All regions and their data are BumpPtrAllocated.  No need to call
142   // their destructors.
143 }
144 
145 //===----------------------------------------------------------------------===//
146 // Basic methods.
147 //===----------------------------------------------------------------------===//
148 
isSubRegionOf(const MemRegion * R) const149 bool SubRegion::isSubRegionOf(const MemRegion* R) const {
150   const MemRegion* r = getSuperRegion();
151   while (r != nullptr) {
152     if (r == R)
153       return true;
154     if (const SubRegion* sr = dyn_cast<SubRegion>(r))
155       r = sr->getSuperRegion();
156     else
157       break;
158   }
159   return false;
160 }
161 
getMemRegionManager() const162 MemRegionManager* SubRegion::getMemRegionManager() const {
163   const SubRegion* r = this;
164   do {
165     const MemRegion *superRegion = r->getSuperRegion();
166     if (const SubRegion *sr = dyn_cast<SubRegion>(superRegion)) {
167       r = sr;
168       continue;
169     }
170     return superRegion->getMemRegionManager();
171   } while (1);
172 }
173 
getStackFrame() const174 const StackFrameContext *VarRegion::getStackFrame() const {
175   const StackSpaceRegion *SSR = dyn_cast<StackSpaceRegion>(getMemorySpace());
176   return SSR ? SSR->getStackFrame() : nullptr;
177 }
178 
179 //===----------------------------------------------------------------------===//
180 // Region extents.
181 //===----------------------------------------------------------------------===//
182 
getExtent(SValBuilder & svalBuilder) const183 DefinedOrUnknownSVal TypedValueRegion::getExtent(SValBuilder &svalBuilder) const {
184   ASTContext &Ctx = svalBuilder.getContext();
185   QualType T = getDesugaredValueType(Ctx);
186 
187   if (isa<VariableArrayType>(T))
188     return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this));
189   if (T->isIncompleteType())
190     return UnknownVal();
191 
192   CharUnits size = Ctx.getTypeSizeInChars(T);
193   QualType sizeTy = svalBuilder.getArrayIndexType();
194   return svalBuilder.makeIntVal(size.getQuantity(), sizeTy);
195 }
196 
getExtent(SValBuilder & svalBuilder) const197 DefinedOrUnknownSVal FieldRegion::getExtent(SValBuilder &svalBuilder) const {
198   // Force callers to deal with bitfields explicitly.
199   if (getDecl()->isBitField())
200     return UnknownVal();
201 
202   DefinedOrUnknownSVal Extent = DeclRegion::getExtent(svalBuilder);
203 
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());
208 
209     if (isa<ConstantArrayType>(T))
210       return UnknownVal();
211   }
212 
213   return Extent;
214 }
215 
getExtent(SValBuilder & svalBuilder) const216 DefinedOrUnknownSVal AllocaRegion::getExtent(SValBuilder &svalBuilder) const {
217   return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this));
218 }
219 
getExtent(SValBuilder & svalBuilder) const220 DefinedOrUnknownSVal SymbolicRegion::getExtent(SValBuilder &svalBuilder) const {
221   return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this));
222 }
223 
getExtent(SValBuilder & svalBuilder) const224 DefinedOrUnknownSVal StringRegion::getExtent(SValBuilder &svalBuilder) const {
225   return svalBuilder.makeIntVal(getStringLiteral()->getByteLength()+1,
226                                 svalBuilder.getArrayIndexType());
227 }
228 
ObjCIvarRegion(const ObjCIvarDecl * ivd,const MemRegion * sReg)229 ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, const MemRegion* sReg)
230   : DeclRegion(ivd, sReg, ObjCIvarRegionKind) {}
231 
getDecl() const232 const ObjCIvarDecl *ObjCIvarRegion::getDecl() const {
233   return cast<ObjCIvarDecl>(D);
234 }
235 
getValueType() const236 QualType ObjCIvarRegion::getValueType() const {
237   return getDecl()->getType();
238 }
239 
getValueType() const240 QualType CXXBaseObjectRegion::getValueType() const {
241   return QualType(getDecl()->getTypeForDecl(), 0);
242 }
243 
244 //===----------------------------------------------------------------------===//
245 // FoldingSet profiling.
246 //===----------------------------------------------------------------------===//
247 
Profile(llvm::FoldingSetNodeID & ID) const248 void MemSpaceRegion::Profile(llvm::FoldingSetNodeID& ID) const {
249   ID.AddInteger((unsigned)getKind());
250 }
251 
Profile(llvm::FoldingSetNodeID & ID) const252 void StackSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
253   ID.AddInteger((unsigned)getKind());
254   ID.AddPointer(getStackFrame());
255 }
256 
Profile(llvm::FoldingSetNodeID & ID) const257 void StaticGlobalSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
258   ID.AddInteger((unsigned)getKind());
259   ID.AddPointer(getCodeRegion());
260 }
261 
ProfileRegion(llvm::FoldingSetNodeID & ID,const StringLiteral * Str,const MemRegion * superRegion)262 void StringRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
263                                  const StringLiteral* Str,
264                                  const MemRegion* superRegion) {
265   ID.AddInteger((unsigned) StringRegionKind);
266   ID.AddPointer(Str);
267   ID.AddPointer(superRegion);
268 }
269 
ProfileRegion(llvm::FoldingSetNodeID & ID,const ObjCStringLiteral * Str,const MemRegion * superRegion)270 void ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
271                                      const ObjCStringLiteral* Str,
272                                      const MemRegion* superRegion) {
273   ID.AddInteger((unsigned) ObjCStringRegionKind);
274   ID.AddPointer(Str);
275   ID.AddPointer(superRegion);
276 }
277 
ProfileRegion(llvm::FoldingSetNodeID & ID,const Expr * Ex,unsigned cnt,const MemRegion * superRegion)278 void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
279                                  const Expr *Ex, unsigned cnt,
280                                  const MemRegion *superRegion) {
281   ID.AddInteger((unsigned) AllocaRegionKind);
282   ID.AddPointer(Ex);
283   ID.AddInteger(cnt);
284   ID.AddPointer(superRegion);
285 }
286 
Profile(llvm::FoldingSetNodeID & ID) const287 void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
288   ProfileRegion(ID, Ex, Cnt, superRegion);
289 }
290 
Profile(llvm::FoldingSetNodeID & ID) const291 void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
292   CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
293 }
294 
ProfileRegion(llvm::FoldingSetNodeID & ID,const CompoundLiteralExpr * CL,const MemRegion * superRegion)295 void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
296                                           const CompoundLiteralExpr *CL,
297                                           const MemRegion* superRegion) {
298   ID.AddInteger((unsigned) CompoundLiteralRegionKind);
299   ID.AddPointer(CL);
300   ID.AddPointer(superRegion);
301 }
302 
ProfileRegion(llvm::FoldingSetNodeID & ID,const PointerType * PT,const MemRegion * sRegion)303 void CXXThisRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
304                                   const PointerType *PT,
305                                   const MemRegion *sRegion) {
306   ID.AddInteger((unsigned) CXXThisRegionKind);
307   ID.AddPointer(PT);
308   ID.AddPointer(sRegion);
309 }
310 
Profile(llvm::FoldingSetNodeID & ID) const311 void CXXThisRegion::Profile(llvm::FoldingSetNodeID &ID) const {
312   CXXThisRegion::ProfileRegion(ID, ThisPointerTy, superRegion);
313 }
314 
ProfileRegion(llvm::FoldingSetNodeID & ID,const ObjCIvarDecl * ivd,const MemRegion * superRegion)315 void ObjCIvarRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
316                                    const ObjCIvarDecl *ivd,
317                                    const MemRegion* superRegion) {
318   DeclRegion::ProfileRegion(ID, ivd, superRegion, ObjCIvarRegionKind);
319 }
320 
ProfileRegion(llvm::FoldingSetNodeID & ID,const Decl * D,const MemRegion * superRegion,Kind k)321 void DeclRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const Decl *D,
322                                const MemRegion* superRegion, Kind k) {
323   ID.AddInteger((unsigned) k);
324   ID.AddPointer(D);
325   ID.AddPointer(superRegion);
326 }
327 
Profile(llvm::FoldingSetNodeID & ID) const328 void DeclRegion::Profile(llvm::FoldingSetNodeID& ID) const {
329   DeclRegion::ProfileRegion(ID, D, superRegion, getKind());
330 }
331 
Profile(llvm::FoldingSetNodeID & ID) const332 void VarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
333   VarRegion::ProfileRegion(ID, getDecl(), superRegion);
334 }
335 
ProfileRegion(llvm::FoldingSetNodeID & ID,SymbolRef sym,const MemRegion * sreg)336 void SymbolicRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym,
337                                    const MemRegion *sreg) {
338   ID.AddInteger((unsigned) MemRegion::SymbolicRegionKind);
339   ID.Add(sym);
340   ID.AddPointer(sreg);
341 }
342 
Profile(llvm::FoldingSetNodeID & ID) const343 void SymbolicRegion::Profile(llvm::FoldingSetNodeID& ID) const {
344   SymbolicRegion::ProfileRegion(ID, sym, getSuperRegion());
345 }
346 
ProfileRegion(llvm::FoldingSetNodeID & ID,QualType ElementType,SVal Idx,const MemRegion * superRegion)347 void ElementRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
348                                   QualType ElementType, SVal Idx,
349                                   const MemRegion* superRegion) {
350   ID.AddInteger(MemRegion::ElementRegionKind);
351   ID.Add(ElementType);
352   ID.AddPointer(superRegion);
353   Idx.Profile(ID);
354 }
355 
Profile(llvm::FoldingSetNodeID & ID) const356 void ElementRegion::Profile(llvm::FoldingSetNodeID& ID) const {
357   ElementRegion::ProfileRegion(ID, ElementType, Index, superRegion);
358 }
359 
ProfileRegion(llvm::FoldingSetNodeID & ID,const NamedDecl * FD,const MemRegion *)360 void FunctionTextRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
361                                        const NamedDecl *FD,
362                                        const MemRegion*) {
363   ID.AddInteger(MemRegion::FunctionTextRegionKind);
364   ID.AddPointer(FD);
365 }
366 
Profile(llvm::FoldingSetNodeID & ID) const367 void FunctionTextRegion::Profile(llvm::FoldingSetNodeID& ID) const {
368   FunctionTextRegion::ProfileRegion(ID, FD, superRegion);
369 }
370 
ProfileRegion(llvm::FoldingSetNodeID & ID,const BlockDecl * BD,CanQualType,const AnalysisDeclContext * AC,const MemRegion *)371 void BlockTextRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
372                                     const BlockDecl *BD, CanQualType,
373                                     const AnalysisDeclContext *AC,
374                                     const MemRegion*) {
375   ID.AddInteger(MemRegion::BlockTextRegionKind);
376   ID.AddPointer(BD);
377 }
378 
Profile(llvm::FoldingSetNodeID & ID) const379 void BlockTextRegion::Profile(llvm::FoldingSetNodeID& ID) const {
380   BlockTextRegion::ProfileRegion(ID, BD, locTy, AC, superRegion);
381 }
382 
ProfileRegion(llvm::FoldingSetNodeID & ID,const BlockTextRegion * BC,const LocationContext * LC,unsigned BlkCount,const MemRegion * sReg)383 void BlockDataRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
384                                     const BlockTextRegion *BC,
385                                     const LocationContext *LC,
386                                     unsigned BlkCount,
387                                     const MemRegion *sReg) {
388   ID.AddInteger(MemRegion::BlockDataRegionKind);
389   ID.AddPointer(BC);
390   ID.AddPointer(LC);
391   ID.AddInteger(BlkCount);
392   ID.AddPointer(sReg);
393 }
394 
Profile(llvm::FoldingSetNodeID & ID) const395 void BlockDataRegion::Profile(llvm::FoldingSetNodeID& ID) const {
396   BlockDataRegion::ProfileRegion(ID, BC, LC, BlockCount, getSuperRegion());
397 }
398 
ProfileRegion(llvm::FoldingSetNodeID & ID,Expr const * Ex,const MemRegion * sReg)399 void CXXTempObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
400                                         Expr const *Ex,
401                                         const MemRegion *sReg) {
402   ID.AddPointer(Ex);
403   ID.AddPointer(sReg);
404 }
405 
Profile(llvm::FoldingSetNodeID & ID) const406 void CXXTempObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
407   ProfileRegion(ID, Ex, getSuperRegion());
408 }
409 
ProfileRegion(llvm::FoldingSetNodeID & ID,const CXXRecordDecl * RD,bool IsVirtual,const MemRegion * SReg)410 void CXXBaseObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
411                                         const CXXRecordDecl *RD,
412                                         bool IsVirtual,
413                                         const MemRegion *SReg) {
414   ID.AddPointer(RD);
415   ID.AddBoolean(IsVirtual);
416   ID.AddPointer(SReg);
417 }
418 
Profile(llvm::FoldingSetNodeID & ID) const419 void CXXBaseObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
420   ProfileRegion(ID, getDecl(), isVirtual(), superRegion);
421 }
422 
423 //===----------------------------------------------------------------------===//
424 // Region anchors.
425 //===----------------------------------------------------------------------===//
426 
anchor()427 void GlobalsSpaceRegion::anchor() { }
anchor()428 void HeapSpaceRegion::anchor() { }
anchor()429 void UnknownSpaceRegion::anchor() { }
anchor()430 void StackLocalsSpaceRegion::anchor() { }
anchor()431 void StackArgumentsSpaceRegion::anchor() { }
anchor()432 void TypedRegion::anchor() { }
anchor()433 void TypedValueRegion::anchor() { }
anchor()434 void CodeTextRegion::anchor() { }
anchor()435 void SubRegion::anchor() { }
436 
437 //===----------------------------------------------------------------------===//
438 // Region pretty-printing.
439 //===----------------------------------------------------------------------===//
440 
dump() const441 void MemRegion::dump() const {
442   dumpToStream(llvm::errs());
443 }
444 
getString() const445 std::string MemRegion::getString() const {
446   std::string s;
447   llvm::raw_string_ostream os(s);
448   dumpToStream(os);
449   return os.str();
450 }
451 
dumpToStream(raw_ostream & os) const452 void MemRegion::dumpToStream(raw_ostream &os) const {
453   os << "<Unknown Region>";
454 }
455 
dumpToStream(raw_ostream & os) const456 void AllocaRegion::dumpToStream(raw_ostream &os) const {
457   os << "alloca{" << (const void*) Ex << ',' << Cnt << '}';
458 }
459 
dumpToStream(raw_ostream & os) const460 void FunctionTextRegion::dumpToStream(raw_ostream &os) const {
461   os << "code{" << getDecl()->getDeclName().getAsString() << '}';
462 }
463 
dumpToStream(raw_ostream & os) const464 void BlockTextRegion::dumpToStream(raw_ostream &os) const {
465   os << "block_code{" << (const void*) this << '}';
466 }
467 
dumpToStream(raw_ostream & os) const468 void BlockDataRegion::dumpToStream(raw_ostream &os) const {
469   os << "block_data{" << BC;
470   os << "; ";
471   for (BlockDataRegion::referenced_vars_iterator
472          I = referenced_vars_begin(),
473          E = referenced_vars_end(); I != E; ++I)
474     os << "(" << I.getCapturedRegion() << "," <<
475                  I.getOriginalRegion() << ") ";
476   os << '}';
477 }
478 
dumpToStream(raw_ostream & os) const479 void CompoundLiteralRegion::dumpToStream(raw_ostream &os) const {
480   // FIXME: More elaborate pretty-printing.
481   os << "{ " << (const void*) CL <<  " }";
482 }
483 
dumpToStream(raw_ostream & os) const484 void CXXTempObjectRegion::dumpToStream(raw_ostream &os) const {
485   os << "temp_object{" << getValueType().getAsString() << ','
486      << (const void*) Ex << '}';
487 }
488 
dumpToStream(raw_ostream & os) const489 void CXXBaseObjectRegion::dumpToStream(raw_ostream &os) const {
490   os << "base{" << superRegion << ',' << getDecl()->getName() << '}';
491 }
492 
dumpToStream(raw_ostream & os) const493 void CXXThisRegion::dumpToStream(raw_ostream &os) const {
494   os << "this";
495 }
496 
dumpToStream(raw_ostream & os) const497 void ElementRegion::dumpToStream(raw_ostream &os) const {
498   os << "element{" << superRegion << ','
499      << Index << ',' << getElementType().getAsString() << '}';
500 }
501 
dumpToStream(raw_ostream & os) const502 void FieldRegion::dumpToStream(raw_ostream &os) const {
503   os << superRegion << "->" << *getDecl();
504 }
505 
dumpToStream(raw_ostream & os) const506 void ObjCIvarRegion::dumpToStream(raw_ostream &os) const {
507   os << "ivar{" << superRegion << ',' << *getDecl() << '}';
508 }
509 
dumpToStream(raw_ostream & os) const510 void StringRegion::dumpToStream(raw_ostream &os) const {
511   assert(Str != nullptr && "Expecting non-null StringLiteral");
512   Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts()));
513 }
514 
dumpToStream(raw_ostream & os) const515 void ObjCStringRegion::dumpToStream(raw_ostream &os) const {
516   assert(Str != nullptr && "Expecting non-null ObjCStringLiteral");
517   Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts()));
518 }
519 
dumpToStream(raw_ostream & os) const520 void SymbolicRegion::dumpToStream(raw_ostream &os) const {
521   os << "SymRegion{" << sym << '}';
522 }
523 
dumpToStream(raw_ostream & os) const524 void VarRegion::dumpToStream(raw_ostream &os) const {
525   os << *cast<VarDecl>(D);
526 }
527 
dump() const528 void RegionRawOffset::dump() const {
529   dumpToStream(llvm::errs());
530 }
531 
dumpToStream(raw_ostream & os) const532 void RegionRawOffset::dumpToStream(raw_ostream &os) const {
533   os << "raw_offset{" << getRegion() << ',' << getOffset().getQuantity() << '}';
534 }
535 
dumpToStream(raw_ostream & os) const536 void StaticGlobalSpaceRegion::dumpToStream(raw_ostream &os) const {
537   os << "StaticGlobalsMemSpace{" << CR << '}';
538 }
539 
dumpToStream(raw_ostream & os) const540 void GlobalInternalSpaceRegion::dumpToStream(raw_ostream &os) const {
541   os << "GlobalInternalSpaceRegion";
542 }
543 
dumpToStream(raw_ostream & os) const544 void GlobalSystemSpaceRegion::dumpToStream(raw_ostream &os) const {
545   os << "GlobalSystemSpaceRegion";
546 }
547 
dumpToStream(raw_ostream & os) const548 void GlobalImmutableSpaceRegion::dumpToStream(raw_ostream &os) const {
549   os << "GlobalImmutableSpaceRegion";
550 }
551 
dumpToStream(raw_ostream & os) const552 void HeapSpaceRegion::dumpToStream(raw_ostream &os) const {
553   os << "HeapSpaceRegion";
554 }
555 
dumpToStream(raw_ostream & os) const556 void UnknownSpaceRegion::dumpToStream(raw_ostream &os) const {
557   os << "UnknownSpaceRegion";
558 }
559 
dumpToStream(raw_ostream & os) const560 void StackArgumentsSpaceRegion::dumpToStream(raw_ostream &os) const {
561   os << "StackArgumentsSpaceRegion";
562 }
563 
dumpToStream(raw_ostream & os) const564 void StackLocalsSpaceRegion::dumpToStream(raw_ostream &os) const {
565   os << "StackLocalsSpaceRegion";
566 }
567 
canPrintPretty() const568 bool MemRegion::canPrintPretty() const {
569   return canPrintPrettyAsExpr();
570 }
571 
canPrintPrettyAsExpr() const572 bool MemRegion::canPrintPrettyAsExpr() const {
573   return false;
574 }
575 
printPretty(raw_ostream & os) const576 void MemRegion::printPretty(raw_ostream &os) const {
577   assert(canPrintPretty() && "This region cannot be printed pretty.");
578   os << "'";
579   printPrettyAsExpr(os);
580   os << "'";
581   return;
582 }
583 
printPrettyAsExpr(raw_ostream & os) const584 void MemRegion::printPrettyAsExpr(raw_ostream &os) const {
585   llvm_unreachable("This region cannot be printed pretty.");
586   return;
587 }
588 
canPrintPrettyAsExpr() const589 bool VarRegion::canPrintPrettyAsExpr() const {
590   return true;
591 }
592 
printPrettyAsExpr(raw_ostream & os) const593 void VarRegion::printPrettyAsExpr(raw_ostream &os) const {
594   os << getDecl()->getName();
595 }
596 
canPrintPrettyAsExpr() const597 bool ObjCIvarRegion::canPrintPrettyAsExpr() const {
598   return true;
599 }
600 
printPrettyAsExpr(raw_ostream & os) const601 void ObjCIvarRegion::printPrettyAsExpr(raw_ostream &os) const {
602   os << getDecl()->getName();
603 }
604 
canPrintPretty() const605 bool FieldRegion::canPrintPretty() const {
606   return true;
607 }
608 
canPrintPrettyAsExpr() const609 bool FieldRegion::canPrintPrettyAsExpr() const {
610   return superRegion->canPrintPrettyAsExpr();
611 }
612 
printPrettyAsExpr(raw_ostream & os) const613 void FieldRegion::printPrettyAsExpr(raw_ostream &os) const {
614   assert(canPrintPrettyAsExpr());
615   superRegion->printPrettyAsExpr(os);
616   os << "." << getDecl()->getName();
617 }
618 
printPretty(raw_ostream & os) const619 void FieldRegion::printPretty(raw_ostream &os) const {
620   if (canPrintPrettyAsExpr()) {
621     os << "\'";
622     printPrettyAsExpr(os);
623     os << "'";
624   } else {
625     os << "field " << "\'" << getDecl()->getName() << "'";
626   }
627   return;
628 }
629 
canPrintPrettyAsExpr() const630 bool CXXBaseObjectRegion::canPrintPrettyAsExpr() const {
631   return superRegion->canPrintPrettyAsExpr();
632 }
633 
printPrettyAsExpr(raw_ostream & os) const634 void CXXBaseObjectRegion::printPrettyAsExpr(raw_ostream &os) const {
635   superRegion->printPrettyAsExpr(os);
636 }
637 
638 //===----------------------------------------------------------------------===//
639 // MemRegionManager methods.
640 //===----------------------------------------------------------------------===//
641 
642 template <typename REG>
LazyAllocate(REG * & region)643 const REG *MemRegionManager::LazyAllocate(REG*& region) {
644   if (!region) {
645     region = (REG*) A.Allocate<REG>();
646     new (region) REG(this);
647   }
648 
649   return region;
650 }
651 
652 template <typename REG, typename ARG>
LazyAllocate(REG * & region,ARG a)653 const REG *MemRegionManager::LazyAllocate(REG*& region, ARG a) {
654   if (!region) {
655     region = (REG*) A.Allocate<REG>();
656     new (region) REG(this, a);
657   }
658 
659   return region;
660 }
661 
662 const StackLocalsSpaceRegion*
getStackLocalsRegion(const StackFrameContext * STC)663 MemRegionManager::getStackLocalsRegion(const StackFrameContext *STC) {
664   assert(STC);
665   StackLocalsSpaceRegion *&R = StackLocalsSpaceRegions[STC];
666 
667   if (R)
668     return R;
669 
670   R = A.Allocate<StackLocalsSpaceRegion>();
671   new (R) StackLocalsSpaceRegion(this, STC);
672   return R;
673 }
674 
675 const StackArgumentsSpaceRegion *
getStackArgumentsRegion(const StackFrameContext * STC)676 MemRegionManager::getStackArgumentsRegion(const StackFrameContext *STC) {
677   assert(STC);
678   StackArgumentsSpaceRegion *&R = StackArgumentsSpaceRegions[STC];
679 
680   if (R)
681     return R;
682 
683   R = A.Allocate<StackArgumentsSpaceRegion>();
684   new (R) StackArgumentsSpaceRegion(this, STC);
685   return R;
686 }
687 
688 const GlobalsSpaceRegion
getGlobalsRegion(MemRegion::Kind K,const CodeTextRegion * CR)689 *MemRegionManager::getGlobalsRegion(MemRegion::Kind K,
690                                     const CodeTextRegion *CR) {
691   if (!CR) {
692     if (K == MemRegion::GlobalSystemSpaceRegionKind)
693       return LazyAllocate(SystemGlobals);
694     if (K == MemRegion::GlobalImmutableSpaceRegionKind)
695       return LazyAllocate(ImmutableGlobals);
696     assert(K == MemRegion::GlobalInternalSpaceRegionKind);
697     return LazyAllocate(InternalGlobals);
698   }
699 
700   assert(K == MemRegion::StaticGlobalSpaceRegionKind);
701   StaticGlobalSpaceRegion *&R = StaticsGlobalSpaceRegions[CR];
702   if (R)
703     return R;
704 
705   R = A.Allocate<StaticGlobalSpaceRegion>();
706   new (R) StaticGlobalSpaceRegion(this, CR);
707   return R;
708 }
709 
getHeapRegion()710 const HeapSpaceRegion *MemRegionManager::getHeapRegion() {
711   return LazyAllocate(heap);
712 }
713 
getUnknownRegion()714 const MemSpaceRegion *MemRegionManager::getUnknownRegion() {
715   return LazyAllocate(unknown);
716 }
717 
getCodeRegion()718 const MemSpaceRegion *MemRegionManager::getCodeRegion() {
719   return LazyAllocate(code);
720 }
721 
722 //===----------------------------------------------------------------------===//
723 // Constructing regions.
724 //===----------------------------------------------------------------------===//
getStringRegion(const StringLiteral * Str)725 const StringRegion* MemRegionManager::getStringRegion(const StringLiteral* Str){
726   return getSubRegion<StringRegion>(Str, getGlobalsRegion());
727 }
728 
729 const ObjCStringRegion *
getObjCStringRegion(const ObjCStringLiteral * Str)730 MemRegionManager::getObjCStringRegion(const ObjCStringLiteral* Str){
731   return getSubRegion<ObjCStringRegion>(Str, getGlobalsRegion());
732 }
733 
734 /// Look through a chain of LocationContexts to either find the
735 /// StackFrameContext that matches a DeclContext, or find a VarRegion
736 /// for a variable captured by a block.
737 static llvm::PointerUnion<const StackFrameContext *, const VarRegion *>
getStackOrCaptureRegionForDeclContext(const LocationContext * LC,const DeclContext * DC,const VarDecl * VD)738 getStackOrCaptureRegionForDeclContext(const LocationContext *LC,
739                                       const DeclContext *DC,
740                                       const VarDecl *VD) {
741   while (LC) {
742     if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC)) {
743       if (cast<DeclContext>(SFC->getDecl()) == DC)
744         return SFC;
745     }
746     if (const BlockInvocationContext *BC =
747         dyn_cast<BlockInvocationContext>(LC)) {
748       const BlockDataRegion *BR =
749         static_cast<const BlockDataRegion*>(BC->getContextData());
750       // FIXME: This can be made more efficient.
751       for (BlockDataRegion::referenced_vars_iterator
752            I = BR->referenced_vars_begin(),
753            E = BR->referenced_vars_end(); I != E; ++I) {
754         if (const VarRegion *VR = dyn_cast<VarRegion>(I.getOriginalRegion()))
755           if (VR->getDecl() == VD)
756             return cast<VarRegion>(I.getCapturedRegion());
757       }
758     }
759 
760     LC = LC->getParent();
761   }
762   return (const StackFrameContext *)nullptr;
763 }
764 
getVarRegion(const VarDecl * D,const LocationContext * LC)765 const VarRegion* MemRegionManager::getVarRegion(const VarDecl *D,
766                                                 const LocationContext *LC) {
767   const MemRegion *sReg = nullptr;
768 
769   if (D->hasGlobalStorage() && !D->isStaticLocal()) {
770 
771     // First handle the globals defined in system headers.
772     if (C.getSourceManager().isInSystemHeader(D->getLocation())) {
773       // Whitelist the system globals which often DO GET modified, assume the
774       // rest are immutable.
775       if (D->getName().find("errno") != StringRef::npos)
776         sReg = getGlobalsRegion(MemRegion::GlobalSystemSpaceRegionKind);
777       else
778         sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
779 
780     // Treat other globals as GlobalInternal unless they are constants.
781     } else {
782       QualType GQT = D->getType();
783       const Type *GT = GQT.getTypePtrOrNull();
784       // TODO: We could walk the complex types here and see if everything is
785       // constified.
786       if (GT && GQT.isConstQualified() && GT->isArithmeticType())
787         sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
788       else
789         sReg = getGlobalsRegion();
790     }
791 
792   // Finally handle static locals.
793   } else {
794     // FIXME: Once we implement scope handling, we will need to properly lookup
795     // 'D' to the proper LocationContext.
796     const DeclContext *DC = D->getDeclContext();
797     llvm::PointerUnion<const StackFrameContext *, const VarRegion *> V =
798       getStackOrCaptureRegionForDeclContext(LC, DC, D);
799 
800     if (V.is<const VarRegion*>())
801       return V.get<const VarRegion*>();
802 
803     const StackFrameContext *STC = V.get<const StackFrameContext*>();
804 
805     if (!STC)
806       sReg = getUnknownRegion();
807     else {
808       if (D->hasLocalStorage()) {
809         sReg = isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)
810                ? static_cast<const MemRegion*>(getStackArgumentsRegion(STC))
811                : static_cast<const MemRegion*>(getStackLocalsRegion(STC));
812       }
813       else {
814         assert(D->isStaticLocal());
815         const Decl *STCD = STC->getDecl();
816         if (isa<FunctionDecl>(STCD) || isa<ObjCMethodDecl>(STCD))
817           sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
818                                   getFunctionTextRegion(cast<NamedDecl>(STCD)));
819         else if (const BlockDecl *BD = dyn_cast<BlockDecl>(STCD)) {
820           // FIXME: The fallback type here is totally bogus -- though it should
821           // never be queried, it will prevent uniquing with the real
822           // BlockTextRegion. Ideally we'd fix the AST so that we always had a
823           // signature.
824           QualType T;
825           if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten())
826             T = TSI->getType();
827           else
828             T = getContext().getFunctionNoProtoType(getContext().VoidTy);
829 
830           const BlockTextRegion *BTR =
831             getBlockTextRegion(BD, C.getCanonicalType(T),
832                                STC->getAnalysisDeclContext());
833           sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
834                                   BTR);
835         }
836         else {
837           sReg = getGlobalsRegion();
838         }
839       }
840     }
841   }
842 
843   return getSubRegion<VarRegion>(D, sReg);
844 }
845 
getVarRegion(const VarDecl * D,const MemRegion * superR)846 const VarRegion *MemRegionManager::getVarRegion(const VarDecl *D,
847                                                 const MemRegion *superR) {
848   return getSubRegion<VarRegion>(D, superR);
849 }
850 
851 const BlockDataRegion *
getBlockDataRegion(const BlockTextRegion * BC,const LocationContext * LC,unsigned blockCount)852 MemRegionManager::getBlockDataRegion(const BlockTextRegion *BC,
853                                      const LocationContext *LC,
854                                      unsigned blockCount) {
855   const MemRegion *sReg = nullptr;
856   const BlockDecl *BD = BC->getDecl();
857   if (!BD->hasCaptures()) {
858     // This handles 'static' blocks.
859     sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
860   }
861   else {
862     if (LC) {
863       // FIXME: Once we implement scope handling, we want the parent region
864       // to be the scope.
865       const StackFrameContext *STC = LC->getCurrentStackFrame();
866       assert(STC);
867       sReg = getStackLocalsRegion(STC);
868     }
869     else {
870       // We allow 'LC' to be NULL for cases where want BlockDataRegions
871       // without context-sensitivity.
872       sReg = getUnknownRegion();
873     }
874   }
875 
876   return getSubRegion<BlockDataRegion>(BC, LC, blockCount, sReg);
877 }
878 
879 const CXXTempObjectRegion *
getCXXStaticTempObjectRegion(const Expr * Ex)880 MemRegionManager::getCXXStaticTempObjectRegion(const Expr *Ex) {
881   return getSubRegion<CXXTempObjectRegion>(
882       Ex, getGlobalsRegion(MemRegion::GlobalInternalSpaceRegionKind, nullptr));
883 }
884 
885 const CompoundLiteralRegion*
getCompoundLiteralRegion(const CompoundLiteralExpr * CL,const LocationContext * LC)886 MemRegionManager::getCompoundLiteralRegion(const CompoundLiteralExpr *CL,
887                                            const LocationContext *LC) {
888 
889   const MemRegion *sReg = nullptr;
890 
891   if (CL->isFileScope())
892     sReg = getGlobalsRegion();
893   else {
894     const StackFrameContext *STC = LC->getCurrentStackFrame();
895     assert(STC);
896     sReg = getStackLocalsRegion(STC);
897   }
898 
899   return getSubRegion<CompoundLiteralRegion>(CL, sReg);
900 }
901 
902 const ElementRegion*
getElementRegion(QualType elementType,NonLoc Idx,const MemRegion * superRegion,ASTContext & Ctx)903 MemRegionManager::getElementRegion(QualType elementType, NonLoc Idx,
904                                    const MemRegion* superRegion,
905                                    ASTContext &Ctx){
906 
907   QualType T = Ctx.getCanonicalType(elementType).getUnqualifiedType();
908 
909   llvm::FoldingSetNodeID ID;
910   ElementRegion::ProfileRegion(ID, T, Idx, superRegion);
911 
912   void *InsertPos;
913   MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos);
914   ElementRegion* R = cast_or_null<ElementRegion>(data);
915 
916   if (!R) {
917     R = (ElementRegion*) A.Allocate<ElementRegion>();
918     new (R) ElementRegion(T, Idx, superRegion);
919     Regions.InsertNode(R, InsertPos);
920   }
921 
922   return R;
923 }
924 
925 const FunctionTextRegion *
getFunctionTextRegion(const NamedDecl * FD)926 MemRegionManager::getFunctionTextRegion(const NamedDecl *FD) {
927   return getSubRegion<FunctionTextRegion>(FD, getCodeRegion());
928 }
929 
930 const BlockTextRegion *
getBlockTextRegion(const BlockDecl * BD,CanQualType locTy,AnalysisDeclContext * AC)931 MemRegionManager::getBlockTextRegion(const BlockDecl *BD, CanQualType locTy,
932                                      AnalysisDeclContext *AC) {
933   return getSubRegion<BlockTextRegion>(BD, locTy, AC, getCodeRegion());
934 }
935 
936 
937 /// getSymbolicRegion - Retrieve or create a "symbolic" memory region.
getSymbolicRegion(SymbolRef sym)938 const SymbolicRegion *MemRegionManager::getSymbolicRegion(SymbolRef sym) {
939   return getSubRegion<SymbolicRegion>(sym, getUnknownRegion());
940 }
941 
getSymbolicHeapRegion(SymbolRef Sym)942 const SymbolicRegion *MemRegionManager::getSymbolicHeapRegion(SymbolRef Sym) {
943   return getSubRegion<SymbolicRegion>(Sym, getHeapRegion());
944 }
945 
946 const FieldRegion*
getFieldRegion(const FieldDecl * d,const MemRegion * superRegion)947 MemRegionManager::getFieldRegion(const FieldDecl *d,
948                                  const MemRegion* superRegion){
949   return getSubRegion<FieldRegion>(d, superRegion);
950 }
951 
952 const ObjCIvarRegion*
getObjCIvarRegion(const ObjCIvarDecl * d,const MemRegion * superRegion)953 MemRegionManager::getObjCIvarRegion(const ObjCIvarDecl *d,
954                                     const MemRegion* superRegion) {
955   return getSubRegion<ObjCIvarRegion>(d, superRegion);
956 }
957 
958 const CXXTempObjectRegion*
getCXXTempObjectRegion(Expr const * E,LocationContext const * LC)959 MemRegionManager::getCXXTempObjectRegion(Expr const *E,
960                                          LocationContext const *LC) {
961   const StackFrameContext *SFC = LC->getCurrentStackFrame();
962   assert(SFC);
963   return getSubRegion<CXXTempObjectRegion>(E, getStackLocalsRegion(SFC));
964 }
965 
966 /// Checks whether \p BaseClass is a valid virtual or direct non-virtual base
967 /// class of the type of \p Super.
isValidBaseClass(const CXXRecordDecl * BaseClass,const TypedValueRegion * Super,bool IsVirtual)968 static bool isValidBaseClass(const CXXRecordDecl *BaseClass,
969                              const TypedValueRegion *Super,
970                              bool IsVirtual) {
971   BaseClass = BaseClass->getCanonicalDecl();
972 
973   const CXXRecordDecl *Class = Super->getValueType()->getAsCXXRecordDecl();
974   if (!Class)
975     return true;
976 
977   if (IsVirtual)
978     return Class->isVirtuallyDerivedFrom(BaseClass);
979 
980   for (const auto &I : Class->bases()) {
981     if (I.getType()->getAsCXXRecordDecl()->getCanonicalDecl() == BaseClass)
982       return true;
983   }
984 
985   return false;
986 }
987 
988 const CXXBaseObjectRegion *
getCXXBaseObjectRegion(const CXXRecordDecl * RD,const MemRegion * Super,bool IsVirtual)989 MemRegionManager::getCXXBaseObjectRegion(const CXXRecordDecl *RD,
990                                          const MemRegion *Super,
991                                          bool IsVirtual) {
992   if (isa<TypedValueRegion>(Super)) {
993     assert(isValidBaseClass(RD, dyn_cast<TypedValueRegion>(Super), IsVirtual));
994     (void)&isValidBaseClass;
995 
996     if (IsVirtual) {
997       // Virtual base regions should not be layered, since the layout rules
998       // are different.
999       while (const CXXBaseObjectRegion *Base =
1000                dyn_cast<CXXBaseObjectRegion>(Super)) {
1001         Super = Base->getSuperRegion();
1002       }
1003       assert(Super && !isa<MemSpaceRegion>(Super));
1004     }
1005   }
1006 
1007   return getSubRegion<CXXBaseObjectRegion>(RD, IsVirtual, Super);
1008 }
1009 
1010 const CXXThisRegion*
getCXXThisRegion(QualType thisPointerTy,const LocationContext * LC)1011 MemRegionManager::getCXXThisRegion(QualType thisPointerTy,
1012                                    const LocationContext *LC) {
1013   const StackFrameContext *STC = LC->getCurrentStackFrame();
1014   assert(STC);
1015   const PointerType *PT = thisPointerTy->getAs<PointerType>();
1016   assert(PT);
1017   return getSubRegion<CXXThisRegion>(PT, getStackArgumentsRegion(STC));
1018 }
1019 
1020 const AllocaRegion*
getAllocaRegion(const Expr * E,unsigned cnt,const LocationContext * LC)1021 MemRegionManager::getAllocaRegion(const Expr *E, unsigned cnt,
1022                                   const LocationContext *LC) {
1023   const StackFrameContext *STC = LC->getCurrentStackFrame();
1024   assert(STC);
1025   return getSubRegion<AllocaRegion>(E, cnt, getStackLocalsRegion(STC));
1026 }
1027 
getMemorySpace() const1028 const MemSpaceRegion *MemRegion::getMemorySpace() const {
1029   const MemRegion *R = this;
1030   const SubRegion* SR = dyn_cast<SubRegion>(this);
1031 
1032   while (SR) {
1033     R = SR->getSuperRegion();
1034     SR = dyn_cast<SubRegion>(R);
1035   }
1036 
1037   return dyn_cast<MemSpaceRegion>(R);
1038 }
1039 
hasStackStorage() const1040 bool MemRegion::hasStackStorage() const {
1041   return isa<StackSpaceRegion>(getMemorySpace());
1042 }
1043 
hasStackNonParametersStorage() const1044 bool MemRegion::hasStackNonParametersStorage() const {
1045   return isa<StackLocalsSpaceRegion>(getMemorySpace());
1046 }
1047 
hasStackParametersStorage() const1048 bool MemRegion::hasStackParametersStorage() const {
1049   return isa<StackArgumentsSpaceRegion>(getMemorySpace());
1050 }
1051 
hasGlobalsOrParametersStorage() const1052 bool MemRegion::hasGlobalsOrParametersStorage() const {
1053   const MemSpaceRegion *MS = getMemorySpace();
1054   return isa<StackArgumentsSpaceRegion>(MS) ||
1055          isa<GlobalsSpaceRegion>(MS);
1056 }
1057 
1058 // getBaseRegion strips away all elements and fields, and get the base region
1059 // of them.
getBaseRegion() const1060 const MemRegion *MemRegion::getBaseRegion() const {
1061   const MemRegion *R = this;
1062   while (true) {
1063     switch (R->getKind()) {
1064       case MemRegion::ElementRegionKind:
1065       case MemRegion::FieldRegionKind:
1066       case MemRegion::ObjCIvarRegionKind:
1067       case MemRegion::CXXBaseObjectRegionKind:
1068         R = cast<SubRegion>(R)->getSuperRegion();
1069         continue;
1070       default:
1071         break;
1072     }
1073     break;
1074   }
1075   return R;
1076 }
1077 
isSubRegionOf(const MemRegion * R) const1078 bool MemRegion::isSubRegionOf(const MemRegion *R) const {
1079   return false;
1080 }
1081 
1082 //===----------------------------------------------------------------------===//
1083 // View handling.
1084 //===----------------------------------------------------------------------===//
1085 
StripCasts(bool StripBaseCasts) const1086 const MemRegion *MemRegion::StripCasts(bool StripBaseCasts) const {
1087   const MemRegion *R = this;
1088   while (true) {
1089     switch (R->getKind()) {
1090     case ElementRegionKind: {
1091       const ElementRegion *ER = cast<ElementRegion>(R);
1092       if (!ER->getIndex().isZeroConstant())
1093         return R;
1094       R = ER->getSuperRegion();
1095       break;
1096     }
1097     case CXXBaseObjectRegionKind:
1098       if (!StripBaseCasts)
1099         return R;
1100       R = cast<CXXBaseObjectRegion>(R)->getSuperRegion();
1101       break;
1102     default:
1103       return R;
1104     }
1105   }
1106 }
1107 
getSymbolicBase() const1108 const SymbolicRegion *MemRegion::getSymbolicBase() const {
1109   const SubRegion *SubR = dyn_cast<SubRegion>(this);
1110 
1111   while (SubR) {
1112     if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(SubR))
1113       return SymR;
1114     SubR = dyn_cast<SubRegion>(SubR->getSuperRegion());
1115   }
1116   return nullptr;
1117 }
1118 
getAsArrayOffset() const1119 RegionRawOffset ElementRegion::getAsArrayOffset() const {
1120   CharUnits offset = CharUnits::Zero();
1121   const ElementRegion *ER = this;
1122   const MemRegion *superR = nullptr;
1123   ASTContext &C = getContext();
1124 
1125   // FIXME: Handle multi-dimensional arrays.
1126 
1127   while (ER) {
1128     superR = ER->getSuperRegion();
1129 
1130     // FIXME: generalize to symbolic offsets.
1131     SVal index = ER->getIndex();
1132     if (Optional<nonloc::ConcreteInt> CI = index.getAs<nonloc::ConcreteInt>()) {
1133       // Update the offset.
1134       int64_t i = CI->getValue().getSExtValue();
1135 
1136       if (i != 0) {
1137         QualType elemType = ER->getElementType();
1138 
1139         // If we are pointing to an incomplete type, go no further.
1140         if (elemType->isIncompleteType()) {
1141           superR = ER;
1142           break;
1143         }
1144 
1145         CharUnits size = C.getTypeSizeInChars(elemType);
1146         offset += (i * size);
1147       }
1148 
1149       // Go to the next ElementRegion (if any).
1150       ER = dyn_cast<ElementRegion>(superR);
1151       continue;
1152     }
1153 
1154     return nullptr;
1155   }
1156 
1157   assert(superR && "super region cannot be NULL");
1158   return RegionRawOffset(superR, offset);
1159 }
1160 
1161 
1162 /// Returns true if \p Base is an immediate base class of \p Child
isImmediateBase(const CXXRecordDecl * Child,const CXXRecordDecl * Base)1163 static bool isImmediateBase(const CXXRecordDecl *Child,
1164                             const CXXRecordDecl *Base) {
1165   // Note that we do NOT canonicalize the base class here, because
1166   // ASTRecordLayout doesn't either. If that leads us down the wrong path,
1167   // so be it; at least we won't crash.
1168   for (const auto &I : Child->bases()) {
1169     if (I.getType()->getAsCXXRecordDecl() == Base)
1170       return true;
1171   }
1172 
1173   return false;
1174 }
1175 
getAsOffset() const1176 RegionOffset MemRegion::getAsOffset() const {
1177   const MemRegion *R = this;
1178   const MemRegion *SymbolicOffsetBase = nullptr;
1179   int64_t Offset = 0;
1180 
1181   while (1) {
1182     switch (R->getKind()) {
1183     case GenericMemSpaceRegionKind:
1184     case StackLocalsSpaceRegionKind:
1185     case StackArgumentsSpaceRegionKind:
1186     case HeapSpaceRegionKind:
1187     case UnknownSpaceRegionKind:
1188     case StaticGlobalSpaceRegionKind:
1189     case GlobalInternalSpaceRegionKind:
1190     case GlobalSystemSpaceRegionKind:
1191     case GlobalImmutableSpaceRegionKind:
1192       // Stores can bind directly to a region space to set a default value.
1193       assert(Offset == 0 && !SymbolicOffsetBase);
1194       goto Finish;
1195 
1196     case FunctionTextRegionKind:
1197     case BlockTextRegionKind:
1198     case BlockDataRegionKind:
1199       // These will never have bindings, but may end up having values requested
1200       // if the user does some strange casting.
1201       if (Offset != 0)
1202         SymbolicOffsetBase = R;
1203       goto Finish;
1204 
1205     case SymbolicRegionKind:
1206     case AllocaRegionKind:
1207     case CompoundLiteralRegionKind:
1208     case CXXThisRegionKind:
1209     case StringRegionKind:
1210     case ObjCStringRegionKind:
1211     case VarRegionKind:
1212     case CXXTempObjectRegionKind:
1213       // Usual base regions.
1214       goto Finish;
1215 
1216     case ObjCIvarRegionKind:
1217       // This is a little strange, but it's a compromise between
1218       // ObjCIvarRegions having unknown compile-time offsets (when using the
1219       // non-fragile runtime) and yet still being distinct, non-overlapping
1220       // regions. Thus we treat them as "like" base regions for the purposes
1221       // of computing offsets.
1222       goto Finish;
1223 
1224     case CXXBaseObjectRegionKind: {
1225       const CXXBaseObjectRegion *BOR = cast<CXXBaseObjectRegion>(R);
1226       R = BOR->getSuperRegion();
1227 
1228       QualType Ty;
1229       bool RootIsSymbolic = false;
1230       if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R)) {
1231         Ty = TVR->getDesugaredValueType(getContext());
1232       } else if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
1233         // If our base region is symbolic, we don't know what type it really is.
1234         // Pretend the type of the symbol is the true dynamic type.
1235         // (This will at least be self-consistent for the life of the symbol.)
1236         Ty = SR->getSymbol()->getType()->getPointeeType();
1237         RootIsSymbolic = true;
1238       }
1239 
1240       const CXXRecordDecl *Child = Ty->getAsCXXRecordDecl();
1241       if (!Child) {
1242         // We cannot compute the offset of the base class.
1243         SymbolicOffsetBase = R;
1244       }
1245 
1246       if (RootIsSymbolic) {
1247         // Base layers on symbolic regions may not be type-correct.
1248         // Double-check the inheritance here, and revert to a symbolic offset
1249         // if it's invalid (e.g. due to a reinterpret_cast).
1250         if (BOR->isVirtual()) {
1251           if (!Child->isVirtuallyDerivedFrom(BOR->getDecl()))
1252             SymbolicOffsetBase = R;
1253         } else {
1254           if (!isImmediateBase(Child, BOR->getDecl()))
1255             SymbolicOffsetBase = R;
1256         }
1257       }
1258 
1259       // Don't bother calculating precise offsets if we already have a
1260       // symbolic offset somewhere in the chain.
1261       if (SymbolicOffsetBase)
1262         continue;
1263 
1264       CharUnits BaseOffset;
1265       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Child);
1266       if (BOR->isVirtual())
1267         BaseOffset = Layout.getVBaseClassOffset(BOR->getDecl());
1268       else
1269         BaseOffset = Layout.getBaseClassOffset(BOR->getDecl());
1270 
1271       // The base offset is in chars, not in bits.
1272       Offset += BaseOffset.getQuantity() * getContext().getCharWidth();
1273       break;
1274     }
1275     case ElementRegionKind: {
1276       const ElementRegion *ER = cast<ElementRegion>(R);
1277       R = ER->getSuperRegion();
1278 
1279       QualType EleTy = ER->getValueType();
1280       if (EleTy->isIncompleteType()) {
1281         // We cannot compute the offset of the base class.
1282         SymbolicOffsetBase = R;
1283         continue;
1284       }
1285 
1286       SVal Index = ER->getIndex();
1287       if (Optional<nonloc::ConcreteInt> CI =
1288               Index.getAs<nonloc::ConcreteInt>()) {
1289         // Don't bother calculating precise offsets if we already have a
1290         // symbolic offset somewhere in the chain.
1291         if (SymbolicOffsetBase)
1292           continue;
1293 
1294         int64_t i = CI->getValue().getSExtValue();
1295         // This type size is in bits.
1296         Offset += i * getContext().getTypeSize(EleTy);
1297       } else {
1298         // We cannot compute offset for non-concrete index.
1299         SymbolicOffsetBase = R;
1300       }
1301       break;
1302     }
1303     case FieldRegionKind: {
1304       const FieldRegion *FR = cast<FieldRegion>(R);
1305       R = FR->getSuperRegion();
1306 
1307       const RecordDecl *RD = FR->getDecl()->getParent();
1308       if (RD->isUnion() || !RD->isCompleteDefinition()) {
1309         // We cannot compute offset for incomplete type.
1310         // For unions, we could treat everything as offset 0, but we'd rather
1311         // treat each field as a symbolic offset so they aren't stored on top
1312         // of each other, since we depend on things in typed regions actually
1313         // matching their types.
1314         SymbolicOffsetBase = R;
1315       }
1316 
1317       // Don't bother calculating precise offsets if we already have a
1318       // symbolic offset somewhere in the chain.
1319       if (SymbolicOffsetBase)
1320         continue;
1321 
1322       // Get the field number.
1323       unsigned idx = 0;
1324       for (RecordDecl::field_iterator FI = RD->field_begin(),
1325              FE = RD->field_end(); FI != FE; ++FI, ++idx)
1326         if (FR->getDecl() == *FI)
1327           break;
1328 
1329       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1330       // This is offset in bits.
1331       Offset += Layout.getFieldOffset(idx);
1332       break;
1333     }
1334     }
1335   }
1336 
1337  Finish:
1338   if (SymbolicOffsetBase)
1339     return RegionOffset(SymbolicOffsetBase, RegionOffset::Symbolic);
1340   return RegionOffset(R, Offset);
1341 }
1342 
1343 //===----------------------------------------------------------------------===//
1344 // BlockDataRegion
1345 //===----------------------------------------------------------------------===//
1346 
1347 std::pair<const VarRegion *, const VarRegion *>
getCaptureRegions(const VarDecl * VD)1348 BlockDataRegion::getCaptureRegions(const VarDecl *VD) {
1349   MemRegionManager &MemMgr = *getMemRegionManager();
1350   const VarRegion *VR = nullptr;
1351   const VarRegion *OriginalVR = nullptr;
1352 
1353   if (!VD->hasAttr<BlocksAttr>() && VD->hasLocalStorage()) {
1354     VR = MemMgr.getVarRegion(VD, this);
1355     OriginalVR = MemMgr.getVarRegion(VD, LC);
1356   }
1357   else {
1358     if (LC) {
1359       VR = MemMgr.getVarRegion(VD, LC);
1360       OriginalVR = VR;
1361     }
1362     else {
1363       VR = MemMgr.getVarRegion(VD, MemMgr.getUnknownRegion());
1364       OriginalVR = MemMgr.getVarRegion(VD, LC);
1365     }
1366   }
1367   return std::make_pair(VR, OriginalVR);
1368 }
1369 
LazyInitializeReferencedVars()1370 void BlockDataRegion::LazyInitializeReferencedVars() {
1371   if (ReferencedVars)
1372     return;
1373 
1374   AnalysisDeclContext *AC = getCodeRegion()->getAnalysisDeclContext();
1375   const auto &ReferencedBlockVars = AC->getReferencedBlockVars(BC->getDecl());
1376   auto NumBlockVars =
1377       std::distance(ReferencedBlockVars.begin(), ReferencedBlockVars.end());
1378 
1379   if (NumBlockVars == 0) {
1380     ReferencedVars = (void*) 0x1;
1381     return;
1382   }
1383 
1384   MemRegionManager &MemMgr = *getMemRegionManager();
1385   llvm::BumpPtrAllocator &A = MemMgr.getAllocator();
1386   BumpVectorContext BC(A);
1387 
1388   typedef BumpVector<const MemRegion*> VarVec;
1389   VarVec *BV = (VarVec*) A.Allocate<VarVec>();
1390   new (BV) VarVec(BC, NumBlockVars);
1391   VarVec *BVOriginal = (VarVec*) A.Allocate<VarVec>();
1392   new (BVOriginal) VarVec(BC, NumBlockVars);
1393 
1394   for (const VarDecl *VD : ReferencedBlockVars) {
1395     const VarRegion *VR = nullptr;
1396     const VarRegion *OriginalVR = nullptr;
1397     std::tie(VR, OriginalVR) = getCaptureRegions(VD);
1398     assert(VR);
1399     assert(OriginalVR);
1400     BV->push_back(VR, BC);
1401     BVOriginal->push_back(OriginalVR, BC);
1402   }
1403 
1404   ReferencedVars = BV;
1405   OriginalVars = BVOriginal;
1406 }
1407 
1408 BlockDataRegion::referenced_vars_iterator
referenced_vars_begin() const1409 BlockDataRegion::referenced_vars_begin() const {
1410   const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1411 
1412   BumpVector<const MemRegion*> *Vec =
1413     static_cast<BumpVector<const MemRegion*>*>(ReferencedVars);
1414 
1415   if (Vec == (void*) 0x1)
1416     return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1417 
1418   BumpVector<const MemRegion*> *VecOriginal =
1419     static_cast<BumpVector<const MemRegion*>*>(OriginalVars);
1420 
1421   return BlockDataRegion::referenced_vars_iterator(Vec->begin(),
1422                                                    VecOriginal->begin());
1423 }
1424 
1425 BlockDataRegion::referenced_vars_iterator
referenced_vars_end() const1426 BlockDataRegion::referenced_vars_end() const {
1427   const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1428 
1429   BumpVector<const MemRegion*> *Vec =
1430     static_cast<BumpVector<const MemRegion*>*>(ReferencedVars);
1431 
1432   if (Vec == (void*) 0x1)
1433     return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1434 
1435   BumpVector<const MemRegion*> *VecOriginal =
1436     static_cast<BumpVector<const MemRegion*>*>(OriginalVars);
1437 
1438   return BlockDataRegion::referenced_vars_iterator(Vec->end(),
1439                                                    VecOriginal->end());
1440 }
1441 
getOriginalRegion(const VarRegion * R) const1442 const VarRegion *BlockDataRegion::getOriginalRegion(const VarRegion *R) const {
1443   for (referenced_vars_iterator I = referenced_vars_begin(),
1444                                 E = referenced_vars_end();
1445        I != E; ++I) {
1446     if (I.getCapturedRegion() == R)
1447       return I.getOriginalRegion();
1448   }
1449   return nullptr;
1450 }
1451 
1452 //===----------------------------------------------------------------------===//
1453 // RegionAndSymbolInvalidationTraits
1454 //===----------------------------------------------------------------------===//
1455 
setTrait(SymbolRef Sym,InvalidationKinds IK)1456 void RegionAndSymbolInvalidationTraits::setTrait(SymbolRef Sym,
1457                                                  InvalidationKinds IK) {
1458   SymTraitsMap[Sym] |= IK;
1459 }
1460 
setTrait(const MemRegion * MR,InvalidationKinds IK)1461 void RegionAndSymbolInvalidationTraits::setTrait(const MemRegion *MR,
1462                                                  InvalidationKinds IK) {
1463   assert(MR);
1464   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(MR))
1465     setTrait(SR->getSymbol(), IK);
1466   else
1467     MRTraitsMap[MR] |= IK;
1468 }
1469 
hasTrait(SymbolRef Sym,InvalidationKinds IK)1470 bool RegionAndSymbolInvalidationTraits::hasTrait(SymbolRef Sym,
1471                                                  InvalidationKinds IK) {
1472   const_symbol_iterator I = SymTraitsMap.find(Sym);
1473   if (I != SymTraitsMap.end())
1474     return I->second & IK;
1475 
1476   return false;
1477 }
1478 
hasTrait(const MemRegion * MR,InvalidationKinds IK)1479 bool RegionAndSymbolInvalidationTraits::hasTrait(const MemRegion *MR,
1480                                                  InvalidationKinds IK) {
1481   if (!MR)
1482     return false;
1483 
1484   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(MR))
1485     return hasTrait(SR->getSymbol(), IK);
1486 
1487   const_region_iterator I = MRTraitsMap.find(MR);
1488   if (I != MRTraitsMap.end())
1489     return I->second & IK;
1490 
1491   return false;
1492 }
1493