MemRegion.cpp revision 4411b423e91da0a2c879b70c0222aeba35f72044
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
27using namespace clang;
28using namespace ento;
29
30//===----------------------------------------------------------------------===//
31// MemRegion Construction.
32//===----------------------------------------------------------------------===//
33
34template<typename RegionTy> struct MemRegionManagerTrait;
35
36template <typename RegionTy, typename A1>
37RegionTy* 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
57template <typename RegionTy, typename A1>
58RegionTy* 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
75template <typename RegionTy, typename A1, typename A2>
76RegionTy* 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
96template <typename RegionTy, typename A1, typename A2>
97RegionTy* 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
115template <typename RegionTy, typename A1, typename A2, typename A3>
116RegionTy* 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
138MemRegion::~MemRegion() {}
139
140MemRegionManager::~MemRegionManager() {
141  // All regions and their data are BumpPtrAllocated.  No need to call
142  // their destructors.
143}
144
145//===----------------------------------------------------------------------===//
146// Basic methods.
147//===----------------------------------------------------------------------===//
148
149bool SubRegion::isSubRegionOf(const MemRegion* R) const {
150  const MemRegion* r = getSuperRegion();
151  while (r != 0) {
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
162MemRegionManager* 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
174const StackFrameContext *VarRegion::getStackFrame() const {
175  const StackSpaceRegion *SSR = dyn_cast<StackSpaceRegion>(getMemorySpace());
176  return SSR ? SSR->getStackFrame() : NULL;
177}
178
179//===----------------------------------------------------------------------===//
180// Region extents.
181//===----------------------------------------------------------------------===//
182
183DefinedOrUnknownSVal 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 (isa<IncompleteArrayType>(T))
190    return UnknownVal();
191
192  CharUnits size = Ctx.getTypeSizeInChars(T);
193  QualType sizeTy = svalBuilder.getArrayIndexType();
194  return svalBuilder.makeIntVal(size.getQuantity(), sizeTy);
195}
196
197DefinedOrUnknownSVal FieldRegion::getExtent(SValBuilder &svalBuilder) const {
198  DefinedOrUnknownSVal Extent = DeclRegion::getExtent(svalBuilder);
199
200  // A zero-length array at the end of a struct often stands for dynamically-
201  // allocated extra memory.
202  if (Extent.isZeroConstant()) {
203    QualType T = getDesugaredValueType(svalBuilder.getContext());
204
205    if (isa<ConstantArrayType>(T))
206      return UnknownVal();
207  }
208
209  return Extent;
210}
211
212DefinedOrUnknownSVal AllocaRegion::getExtent(SValBuilder &svalBuilder) const {
213  return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this));
214}
215
216DefinedOrUnknownSVal SymbolicRegion::getExtent(SValBuilder &svalBuilder) const {
217  return nonloc::SymbolVal(svalBuilder.getSymbolManager().getExtentSymbol(this));
218}
219
220DefinedOrUnknownSVal StringRegion::getExtent(SValBuilder &svalBuilder) const {
221  return svalBuilder.makeIntVal(getStringLiteral()->getByteLength()+1,
222                                svalBuilder.getArrayIndexType());
223}
224
225ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, const MemRegion* sReg)
226  : DeclRegion(ivd, sReg, ObjCIvarRegionKind) {}
227
228const ObjCIvarDecl *ObjCIvarRegion::getDecl() const {
229  return cast<ObjCIvarDecl>(D);
230}
231
232QualType ObjCIvarRegion::getValueType() const {
233  return getDecl()->getType();
234}
235
236QualType CXXBaseObjectRegion::getValueType() const {
237  return QualType(getDecl()->getTypeForDecl(), 0);
238}
239
240//===----------------------------------------------------------------------===//
241// FoldingSet profiling.
242//===----------------------------------------------------------------------===//
243
244void MemSpaceRegion::Profile(llvm::FoldingSetNodeID& ID) const {
245  ID.AddInteger((unsigned)getKind());
246}
247
248void StackSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
249  ID.AddInteger((unsigned)getKind());
250  ID.AddPointer(getStackFrame());
251}
252
253void StaticGlobalSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
254  ID.AddInteger((unsigned)getKind());
255  ID.AddPointer(getCodeRegion());
256}
257
258void StringRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
259                                 const StringLiteral* Str,
260                                 const MemRegion* superRegion) {
261  ID.AddInteger((unsigned) StringRegionKind);
262  ID.AddPointer(Str);
263  ID.AddPointer(superRegion);
264}
265
266void ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
267                                     const ObjCStringLiteral* Str,
268                                     const MemRegion* superRegion) {
269  ID.AddInteger((unsigned) ObjCStringRegionKind);
270  ID.AddPointer(Str);
271  ID.AddPointer(superRegion);
272}
273
274void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
275                                 const Expr *Ex, unsigned cnt,
276                                 const MemRegion *superRegion) {
277  ID.AddInteger((unsigned) AllocaRegionKind);
278  ID.AddPointer(Ex);
279  ID.AddInteger(cnt);
280  ID.AddPointer(superRegion);
281}
282
283void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
284  ProfileRegion(ID, Ex, Cnt, superRegion);
285}
286
287void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
288  CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
289}
290
291void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
292                                          const CompoundLiteralExpr *CL,
293                                          const MemRegion* superRegion) {
294  ID.AddInteger((unsigned) CompoundLiteralRegionKind);
295  ID.AddPointer(CL);
296  ID.AddPointer(superRegion);
297}
298
299void CXXThisRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
300                                  const PointerType *PT,
301                                  const MemRegion *sRegion) {
302  ID.AddInteger((unsigned) CXXThisRegionKind);
303  ID.AddPointer(PT);
304  ID.AddPointer(sRegion);
305}
306
307void CXXThisRegion::Profile(llvm::FoldingSetNodeID &ID) const {
308  CXXThisRegion::ProfileRegion(ID, ThisPointerTy, superRegion);
309}
310
311void ObjCIvarRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
312                                   const ObjCIvarDecl *ivd,
313                                   const MemRegion* superRegion) {
314  DeclRegion::ProfileRegion(ID, ivd, superRegion, ObjCIvarRegionKind);
315}
316
317void DeclRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const Decl *D,
318                               const MemRegion* superRegion, Kind k) {
319  ID.AddInteger((unsigned) k);
320  ID.AddPointer(D);
321  ID.AddPointer(superRegion);
322}
323
324void DeclRegion::Profile(llvm::FoldingSetNodeID& ID) const {
325  DeclRegion::ProfileRegion(ID, D, superRegion, getKind());
326}
327
328void VarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
329  VarRegion::ProfileRegion(ID, getDecl(), superRegion);
330}
331
332void SymbolicRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym,
333                                   const MemRegion *sreg) {
334  ID.AddInteger((unsigned) MemRegion::SymbolicRegionKind);
335  ID.Add(sym);
336  ID.AddPointer(sreg);
337}
338
339void SymbolicRegion::Profile(llvm::FoldingSetNodeID& ID) const {
340  SymbolicRegion::ProfileRegion(ID, sym, getSuperRegion());
341}
342
343void ElementRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
344                                  QualType ElementType, SVal Idx,
345                                  const MemRegion* superRegion) {
346  ID.AddInteger(MemRegion::ElementRegionKind);
347  ID.Add(ElementType);
348  ID.AddPointer(superRegion);
349  Idx.Profile(ID);
350}
351
352void ElementRegion::Profile(llvm::FoldingSetNodeID& ID) const {
353  ElementRegion::ProfileRegion(ID, ElementType, Index, superRegion);
354}
355
356void FunctionTextRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
357                                       const NamedDecl *FD,
358                                       const MemRegion*) {
359  ID.AddInteger(MemRegion::FunctionTextRegionKind);
360  ID.AddPointer(FD);
361}
362
363void FunctionTextRegion::Profile(llvm::FoldingSetNodeID& ID) const {
364  FunctionTextRegion::ProfileRegion(ID, FD, superRegion);
365}
366
367void BlockTextRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
368                                    const BlockDecl *BD, CanQualType,
369                                    const AnalysisDeclContext *AC,
370                                    const MemRegion*) {
371  ID.AddInteger(MemRegion::BlockTextRegionKind);
372  ID.AddPointer(BD);
373}
374
375void BlockTextRegion::Profile(llvm::FoldingSetNodeID& ID) const {
376  BlockTextRegion::ProfileRegion(ID, BD, locTy, AC, superRegion);
377}
378
379void BlockDataRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
380                                    const BlockTextRegion *BC,
381                                    const LocationContext *LC,
382                                    const MemRegion *sReg) {
383  ID.AddInteger(MemRegion::BlockDataRegionKind);
384  ID.AddPointer(BC);
385  ID.AddPointer(LC);
386  ID.AddPointer(sReg);
387}
388
389void BlockDataRegion::Profile(llvm::FoldingSetNodeID& ID) const {
390  BlockDataRegion::ProfileRegion(ID, BC, LC, getSuperRegion());
391}
392
393void CXXTempObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
394                                        Expr const *Ex,
395                                        const MemRegion *sReg) {
396  ID.AddPointer(Ex);
397  ID.AddPointer(sReg);
398}
399
400void CXXTempObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
401  ProfileRegion(ID, Ex, getSuperRegion());
402}
403
404void CXXBaseObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
405                                        const CXXRecordDecl *RD,
406                                        bool IsVirtual,
407                                        const MemRegion *SReg) {
408  ID.AddPointer(RD);
409  ID.AddBoolean(IsVirtual);
410  ID.AddPointer(SReg);
411}
412
413void CXXBaseObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
414  ProfileRegion(ID, getDecl(), isVirtual(), superRegion);
415}
416
417//===----------------------------------------------------------------------===//
418// Region anchors.
419//===----------------------------------------------------------------------===//
420
421void GlobalsSpaceRegion::anchor() { }
422void HeapSpaceRegion::anchor() { }
423void UnknownSpaceRegion::anchor() { }
424void StackLocalsSpaceRegion::anchor() { }
425void StackArgumentsSpaceRegion::anchor() { }
426void TypedRegion::anchor() { }
427void TypedValueRegion::anchor() { }
428void CodeTextRegion::anchor() { }
429void SubRegion::anchor() { }
430
431//===----------------------------------------------------------------------===//
432// Region pretty-printing.
433//===----------------------------------------------------------------------===//
434
435void MemRegion::dump() const {
436  dumpToStream(llvm::errs());
437}
438
439std::string MemRegion::getString() const {
440  std::string s;
441  llvm::raw_string_ostream os(s);
442  dumpToStream(os);
443  return os.str();
444}
445
446void MemRegion::dumpToStream(raw_ostream &os) const {
447  os << "<Unknown Region>";
448}
449
450void AllocaRegion::dumpToStream(raw_ostream &os) const {
451  os << "alloca{" << (const void*) Ex << ',' << Cnt << '}';
452}
453
454void FunctionTextRegion::dumpToStream(raw_ostream &os) const {
455  os << "code{" << getDecl()->getDeclName().getAsString() << '}';
456}
457
458void BlockTextRegion::dumpToStream(raw_ostream &os) const {
459  os << "block_code{" << (const void*) this << '}';
460}
461
462void BlockDataRegion::dumpToStream(raw_ostream &os) const {
463  os << "block_data{" << BC << '}';
464}
465
466void CompoundLiteralRegion::dumpToStream(raw_ostream &os) const {
467  // FIXME: More elaborate pretty-printing.
468  os << "{ " << (const void*) CL <<  " }";
469}
470
471void CXXTempObjectRegion::dumpToStream(raw_ostream &os) const {
472  os << "temp_object{" << getValueType().getAsString() << ','
473     << (const void*) Ex << '}';
474}
475
476void CXXBaseObjectRegion::dumpToStream(raw_ostream &os) const {
477  os << "base{" << superRegion << ',' << getDecl()->getName() << '}';
478}
479
480void CXXThisRegion::dumpToStream(raw_ostream &os) const {
481  os << "this";
482}
483
484void ElementRegion::dumpToStream(raw_ostream &os) const {
485  os << "element{" << superRegion << ','
486     << Index << ',' << getElementType().getAsString() << '}';
487}
488
489void FieldRegion::dumpToStream(raw_ostream &os) const {
490  os << superRegion << "->" << *getDecl();
491}
492
493void ObjCIvarRegion::dumpToStream(raw_ostream &os) const {
494  os << "ivar{" << superRegion << ',' << *getDecl() << '}';
495}
496
497void StringRegion::dumpToStream(raw_ostream &os) const {
498  Str->printPretty(os, 0, PrintingPolicy(getContext().getLangOpts()));
499}
500
501void ObjCStringRegion::dumpToStream(raw_ostream &os) const {
502  Str->printPretty(os, 0, PrintingPolicy(getContext().getLangOpts()));
503}
504
505void SymbolicRegion::dumpToStream(raw_ostream &os) const {
506  os << "SymRegion{" << sym << '}';
507}
508
509void VarRegion::dumpToStream(raw_ostream &os) const {
510  os << *cast<VarDecl>(D);
511}
512
513void RegionRawOffset::dump() const {
514  dumpToStream(llvm::errs());
515}
516
517void RegionRawOffset::dumpToStream(raw_ostream &os) const {
518  os << "raw_offset{" << getRegion() << ',' << getOffset().getQuantity() << '}';
519}
520
521void StaticGlobalSpaceRegion::dumpToStream(raw_ostream &os) const {
522  os << "StaticGlobalsMemSpace{" << CR << '}';
523}
524
525void GlobalInternalSpaceRegion::dumpToStream(raw_ostream &os) const {
526  os << "GlobalInternalSpaceRegion";
527}
528
529void GlobalSystemSpaceRegion::dumpToStream(raw_ostream &os) const {
530  os << "GlobalSystemSpaceRegion";
531}
532
533void GlobalImmutableSpaceRegion::dumpToStream(raw_ostream &os) const {
534  os << "GlobalImmutableSpaceRegion";
535}
536
537void HeapSpaceRegion::dumpToStream(raw_ostream &os) const {
538  os << "HeapSpaceRegion";
539}
540
541void UnknownSpaceRegion::dumpToStream(raw_ostream &os) const {
542  os << "UnknownSpaceRegion";
543}
544
545void StackArgumentsSpaceRegion::dumpToStream(raw_ostream &os) const {
546  os << "StackArgumentsSpaceRegion";
547}
548
549void StackLocalsSpaceRegion::dumpToStream(raw_ostream &os) const {
550  os << "StackLocalsSpaceRegion";
551}
552
553bool MemRegion::canPrintPretty() const {
554  return false;
555}
556
557void MemRegion::printPretty(raw_ostream &os) const {
558  return;
559}
560
561bool VarRegion::canPrintPretty() const {
562  return true;
563}
564
565void VarRegion::printPretty(raw_ostream &os) const {
566  os << getDecl()->getName();
567}
568
569bool FieldRegion::canPrintPretty() const {
570  return superRegion->canPrintPretty();
571}
572
573void FieldRegion::printPretty(raw_ostream &os) const {
574  superRegion->printPretty(os);
575  os << "." << getDecl()->getName();
576}
577
578//===----------------------------------------------------------------------===//
579// MemRegionManager methods.
580//===----------------------------------------------------------------------===//
581
582template <typename REG>
583const REG *MemRegionManager::LazyAllocate(REG*& region) {
584  if (!region) {
585    region = (REG*) A.Allocate<REG>();
586    new (region) REG(this);
587  }
588
589  return region;
590}
591
592template <typename REG, typename ARG>
593const REG *MemRegionManager::LazyAllocate(REG*& region, ARG a) {
594  if (!region) {
595    region = (REG*) A.Allocate<REG>();
596    new (region) REG(this, a);
597  }
598
599  return region;
600}
601
602const StackLocalsSpaceRegion*
603MemRegionManager::getStackLocalsRegion(const StackFrameContext *STC) {
604  assert(STC);
605  StackLocalsSpaceRegion *&R = StackLocalsSpaceRegions[STC];
606
607  if (R)
608    return R;
609
610  R = A.Allocate<StackLocalsSpaceRegion>();
611  new (R) StackLocalsSpaceRegion(this, STC);
612  return R;
613}
614
615const StackArgumentsSpaceRegion *
616MemRegionManager::getStackArgumentsRegion(const StackFrameContext *STC) {
617  assert(STC);
618  StackArgumentsSpaceRegion *&R = StackArgumentsSpaceRegions[STC];
619
620  if (R)
621    return R;
622
623  R = A.Allocate<StackArgumentsSpaceRegion>();
624  new (R) StackArgumentsSpaceRegion(this, STC);
625  return R;
626}
627
628const GlobalsSpaceRegion
629*MemRegionManager::getGlobalsRegion(MemRegion::Kind K,
630                                    const CodeTextRegion *CR) {
631  if (!CR) {
632    if (K == MemRegion::GlobalSystemSpaceRegionKind)
633      return LazyAllocate(SystemGlobals);
634    if (K == MemRegion::GlobalImmutableSpaceRegionKind)
635      return LazyAllocate(ImmutableGlobals);
636    assert(K == MemRegion::GlobalInternalSpaceRegionKind);
637    return LazyAllocate(InternalGlobals);
638  }
639
640  assert(K == MemRegion::StaticGlobalSpaceRegionKind);
641  StaticGlobalSpaceRegion *&R = StaticsGlobalSpaceRegions[CR];
642  if (R)
643    return R;
644
645  R = A.Allocate<StaticGlobalSpaceRegion>();
646  new (R) StaticGlobalSpaceRegion(this, CR);
647  return R;
648}
649
650const HeapSpaceRegion *MemRegionManager::getHeapRegion() {
651  return LazyAllocate(heap);
652}
653
654const MemSpaceRegion *MemRegionManager::getUnknownRegion() {
655  return LazyAllocate(unknown);
656}
657
658const MemSpaceRegion *MemRegionManager::getCodeRegion() {
659  return LazyAllocate(code);
660}
661
662//===----------------------------------------------------------------------===//
663// Constructing regions.
664//===----------------------------------------------------------------------===//
665const StringRegion* MemRegionManager::getStringRegion(const StringLiteral* Str){
666  return getSubRegion<StringRegion>(Str, getGlobalsRegion());
667}
668
669const ObjCStringRegion *
670MemRegionManager::getObjCStringRegion(const ObjCStringLiteral* Str){
671  return getSubRegion<ObjCStringRegion>(Str, getGlobalsRegion());
672}
673
674/// Look through a chain of LocationContexts to either find the
675/// StackFrameContext that matches a DeclContext, or find a VarRegion
676/// for a variable captured by a block.
677static llvm::PointerUnion<const StackFrameContext *, const VarRegion *>
678getStackOrCaptureRegionForDeclContext(const LocationContext *LC,
679                                      const DeclContext *DC,
680                                      const VarDecl *VD) {
681  while (LC) {
682    if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC)) {
683      if (cast<DeclContext>(SFC->getDecl()) == DC)
684        return SFC;
685    }
686    if (const BlockInvocationContext *BC =
687        dyn_cast<BlockInvocationContext>(LC)) {
688      const BlockDataRegion *BR =
689        static_cast<const BlockDataRegion*>(BC->getContextData());
690      // FIXME: This can be made more efficient.
691      for (BlockDataRegion::referenced_vars_iterator
692           I = BR->referenced_vars_begin(),
693           E = BR->referenced_vars_end(); I != E; ++I) {
694        if (const VarRegion *VR = dyn_cast<VarRegion>(I.getOriginalRegion()))
695          if (VR->getDecl() == VD)
696            return cast<VarRegion>(I.getCapturedRegion());
697      }
698    }
699
700    LC = LC->getParent();
701  }
702  return (const StackFrameContext*)0;
703}
704
705const VarRegion* MemRegionManager::getVarRegion(const VarDecl *D,
706                                                const LocationContext *LC) {
707  const MemRegion *sReg = 0;
708
709  if (D->hasGlobalStorage() && !D->isStaticLocal()) {
710
711    // First handle the globals defined in system headers.
712    if (C.getSourceManager().isInSystemHeader(D->getLocation())) {
713      // Whitelist the system globals which often DO GET modified, assume the
714      // rest are immutable.
715      if (D->getName().find("errno") != StringRef::npos)
716        sReg = getGlobalsRegion(MemRegion::GlobalSystemSpaceRegionKind);
717      else
718        sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
719
720    // Treat other globals as GlobalInternal unless they are constants.
721    } else {
722      QualType GQT = D->getType();
723      const Type *GT = GQT.getTypePtrOrNull();
724      // TODO: We could walk the complex types here and see if everything is
725      // constified.
726      if (GT && GQT.isConstQualified() && GT->isArithmeticType())
727        sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
728      else
729        sReg = getGlobalsRegion();
730    }
731
732  // Finally handle static locals.
733  } else {
734    // FIXME: Once we implement scope handling, we will need to properly lookup
735    // 'D' to the proper LocationContext.
736    const DeclContext *DC = D->getDeclContext();
737    llvm::PointerUnion<const StackFrameContext *, const VarRegion *> V =
738      getStackOrCaptureRegionForDeclContext(LC, DC, D);
739
740    if (V.is<const VarRegion*>())
741      return V.get<const VarRegion*>();
742
743    const StackFrameContext *STC = V.get<const StackFrameContext*>();
744
745    if (!STC)
746      sReg = getUnknownRegion();
747    else {
748      if (D->hasLocalStorage()) {
749        sReg = isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)
750               ? static_cast<const MemRegion*>(getStackArgumentsRegion(STC))
751               : static_cast<const MemRegion*>(getStackLocalsRegion(STC));
752      }
753      else {
754        assert(D->isStaticLocal());
755        const Decl *STCD = STC->getDecl();
756        if (isa<FunctionDecl>(STCD) || isa<ObjCMethodDecl>(STCD))
757          sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
758                                  getFunctionTextRegion(cast<NamedDecl>(STCD)));
759        else if (const BlockDecl *BD = dyn_cast<BlockDecl>(STCD)) {
760          const BlockTextRegion *BTR =
761            getBlockTextRegion(BD,
762                     C.getCanonicalType(BD->getSignatureAsWritten()->getType()),
763                     STC->getAnalysisDeclContext());
764          sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
765                                  BTR);
766        }
767        else {
768          sReg = getGlobalsRegion();
769        }
770      }
771    }
772  }
773
774  return getSubRegion<VarRegion>(D, sReg);
775}
776
777const VarRegion *MemRegionManager::getVarRegion(const VarDecl *D,
778                                                const MemRegion *superR) {
779  return getSubRegion<VarRegion>(D, superR);
780}
781
782const BlockDataRegion *
783MemRegionManager::getBlockDataRegion(const BlockTextRegion *BC,
784                                     const LocationContext *LC) {
785  const MemRegion *sReg = 0;
786  const BlockDecl *BD = BC->getDecl();
787  if (!BD->hasCaptures()) {
788    // This handles 'static' blocks.
789    sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
790  }
791  else {
792    if (LC) {
793      // FIXME: Once we implement scope handling, we want the parent region
794      // to be the scope.
795      const StackFrameContext *STC = LC->getCurrentStackFrame();
796      assert(STC);
797      sReg = getStackLocalsRegion(STC);
798    }
799    else {
800      // We allow 'LC' to be NULL for cases where want BlockDataRegions
801      // without context-sensitivity.
802      sReg = getUnknownRegion();
803    }
804  }
805
806  return getSubRegion<BlockDataRegion>(BC, LC, sReg);
807}
808
809const CompoundLiteralRegion*
810MemRegionManager::getCompoundLiteralRegion(const CompoundLiteralExpr *CL,
811                                           const LocationContext *LC) {
812
813  const MemRegion *sReg = 0;
814
815  if (CL->isFileScope())
816    sReg = getGlobalsRegion();
817  else {
818    const StackFrameContext *STC = LC->getCurrentStackFrame();
819    assert(STC);
820    sReg = getStackLocalsRegion(STC);
821  }
822
823  return getSubRegion<CompoundLiteralRegion>(CL, sReg);
824}
825
826const ElementRegion*
827MemRegionManager::getElementRegion(QualType elementType, NonLoc Idx,
828                                   const MemRegion* superRegion,
829                                   ASTContext &Ctx){
830
831  QualType T = Ctx.getCanonicalType(elementType).getUnqualifiedType();
832
833  llvm::FoldingSetNodeID ID;
834  ElementRegion::ProfileRegion(ID, T, Idx, superRegion);
835
836  void *InsertPos;
837  MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos);
838  ElementRegion* R = cast_or_null<ElementRegion>(data);
839
840  if (!R) {
841    R = (ElementRegion*) A.Allocate<ElementRegion>();
842    new (R) ElementRegion(T, Idx, superRegion);
843    Regions.InsertNode(R, InsertPos);
844  }
845
846  return R;
847}
848
849const FunctionTextRegion *
850MemRegionManager::getFunctionTextRegion(const NamedDecl *FD) {
851  return getSubRegion<FunctionTextRegion>(FD, getCodeRegion());
852}
853
854const BlockTextRegion *
855MemRegionManager::getBlockTextRegion(const BlockDecl *BD, CanQualType locTy,
856                                     AnalysisDeclContext *AC) {
857  return getSubRegion<BlockTextRegion>(BD, locTy, AC, getCodeRegion());
858}
859
860
861/// getSymbolicRegion - Retrieve or create a "symbolic" memory region.
862const SymbolicRegion *MemRegionManager::getSymbolicRegion(SymbolRef sym) {
863  return getSubRegion<SymbolicRegion>(sym, getUnknownRegion());
864}
865
866const SymbolicRegion *MemRegionManager::getSymbolicHeapRegion(SymbolRef Sym) {
867  return getSubRegion<SymbolicRegion>(Sym, getHeapRegion());
868}
869
870const FieldRegion*
871MemRegionManager::getFieldRegion(const FieldDecl *d,
872                                 const MemRegion* superRegion){
873  return getSubRegion<FieldRegion>(d, superRegion);
874}
875
876const ObjCIvarRegion*
877MemRegionManager::getObjCIvarRegion(const ObjCIvarDecl *d,
878                                    const MemRegion* superRegion) {
879  return getSubRegion<ObjCIvarRegion>(d, superRegion);
880}
881
882const CXXTempObjectRegion*
883MemRegionManager::getCXXTempObjectRegion(Expr const *E,
884                                         LocationContext const *LC) {
885  const StackFrameContext *SFC = LC->getCurrentStackFrame();
886  assert(SFC);
887  return getSubRegion<CXXTempObjectRegion>(E, getStackLocalsRegion(SFC));
888}
889
890/// Checks whether \p BaseClass is a valid virtual or direct non-virtual base
891/// class of the type of \p Super.
892static bool isValidBaseClass(const CXXRecordDecl *BaseClass,
893                             const TypedValueRegion *Super,
894                             bool IsVirtual) {
895  const CXXRecordDecl *Class = Super->getValueType()->getAsCXXRecordDecl();
896  if (!Class)
897    return true;
898
899  if (IsVirtual)
900    return Class->isVirtuallyDerivedFrom(BaseClass);
901
902  for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
903                                                E = Class->bases_end();
904       I != E; ++I) {
905    if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == BaseClass)
906      return true;
907  }
908
909  return false;
910}
911
912const CXXBaseObjectRegion *
913MemRegionManager::getCXXBaseObjectRegion(const CXXRecordDecl *RD,
914                                         const MemRegion *Super,
915                                         bool IsVirtual) {
916  RD = RD->getCanonicalDecl();
917
918  if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(Super)) {
919    assert(isValidBaseClass(RD, TVR, IsVirtual));
920
921    if (IsVirtual) {
922      // Virtual base regions should not be layered, since the layout rules
923      // are different.
924      while (const CXXBaseObjectRegion *Base =
925               dyn_cast<CXXBaseObjectRegion>(Super)) {
926        Super = Base->getSuperRegion();
927      }
928      assert(Super && !isa<MemSpaceRegion>(Super));
929    }
930  }
931
932  return getSubRegion<CXXBaseObjectRegion>(RD, IsVirtual, Super);
933}
934
935const CXXThisRegion*
936MemRegionManager::getCXXThisRegion(QualType thisPointerTy,
937                                   const LocationContext *LC) {
938  const StackFrameContext *STC = LC->getCurrentStackFrame();
939  assert(STC);
940  const PointerType *PT = thisPointerTy->getAs<PointerType>();
941  assert(PT);
942  return getSubRegion<CXXThisRegion>(PT, getStackArgumentsRegion(STC));
943}
944
945const AllocaRegion*
946MemRegionManager::getAllocaRegion(const Expr *E, unsigned cnt,
947                                  const LocationContext *LC) {
948  const StackFrameContext *STC = LC->getCurrentStackFrame();
949  assert(STC);
950  return getSubRegion<AllocaRegion>(E, cnt, getStackLocalsRegion(STC));
951}
952
953const MemSpaceRegion *MemRegion::getMemorySpace() const {
954  const MemRegion *R = this;
955  const SubRegion* SR = dyn_cast<SubRegion>(this);
956
957  while (SR) {
958    R = SR->getSuperRegion();
959    SR = dyn_cast<SubRegion>(R);
960  }
961
962  return dyn_cast<MemSpaceRegion>(R);
963}
964
965bool MemRegion::hasStackStorage() const {
966  return isa<StackSpaceRegion>(getMemorySpace());
967}
968
969bool MemRegion::hasStackNonParametersStorage() const {
970  return isa<StackLocalsSpaceRegion>(getMemorySpace());
971}
972
973bool MemRegion::hasStackParametersStorage() const {
974  return isa<StackArgumentsSpaceRegion>(getMemorySpace());
975}
976
977bool MemRegion::hasGlobalsOrParametersStorage() const {
978  const MemSpaceRegion *MS = getMemorySpace();
979  return isa<StackArgumentsSpaceRegion>(MS) ||
980         isa<GlobalsSpaceRegion>(MS);
981}
982
983// getBaseRegion strips away all elements and fields, and get the base region
984// of them.
985const MemRegion *MemRegion::getBaseRegion() const {
986  const MemRegion *R = this;
987  while (true) {
988    switch (R->getKind()) {
989      case MemRegion::ElementRegionKind:
990      case MemRegion::FieldRegionKind:
991      case MemRegion::ObjCIvarRegionKind:
992      case MemRegion::CXXBaseObjectRegionKind:
993        R = cast<SubRegion>(R)->getSuperRegion();
994        continue;
995      default:
996        break;
997    }
998    break;
999  }
1000  return R;
1001}
1002
1003bool MemRegion::isSubRegionOf(const MemRegion *R) const {
1004  return false;
1005}
1006
1007//===----------------------------------------------------------------------===//
1008// View handling.
1009//===----------------------------------------------------------------------===//
1010
1011const MemRegion *MemRegion::StripCasts(bool StripBaseCasts) const {
1012  const MemRegion *R = this;
1013  while (true) {
1014    switch (R->getKind()) {
1015    case ElementRegionKind: {
1016      const ElementRegion *ER = cast<ElementRegion>(R);
1017      if (!ER->getIndex().isZeroConstant())
1018        return R;
1019      R = ER->getSuperRegion();
1020      break;
1021    }
1022    case CXXBaseObjectRegionKind:
1023      if (!StripBaseCasts)
1024        return R;
1025      R = cast<CXXBaseObjectRegion>(R)->getSuperRegion();
1026      break;
1027    default:
1028      return R;
1029    }
1030  }
1031}
1032
1033// FIXME: Merge with the implementation of the same method in Store.cpp
1034static bool IsCompleteType(ASTContext &Ctx, QualType Ty) {
1035  if (const RecordType *RT = Ty->getAs<RecordType>()) {
1036    const RecordDecl *D = RT->getDecl();
1037    if (!D->getDefinition())
1038      return false;
1039  }
1040
1041  return true;
1042}
1043
1044RegionRawOffset ElementRegion::getAsArrayOffset() const {
1045  CharUnits offset = CharUnits::Zero();
1046  const ElementRegion *ER = this;
1047  const MemRegion *superR = NULL;
1048  ASTContext &C = getContext();
1049
1050  // FIXME: Handle multi-dimensional arrays.
1051
1052  while (ER) {
1053    superR = ER->getSuperRegion();
1054
1055    // FIXME: generalize to symbolic offsets.
1056    SVal index = ER->getIndex();
1057    if (Optional<nonloc::ConcreteInt> CI = index.getAs<nonloc::ConcreteInt>()) {
1058      // Update the offset.
1059      int64_t i = CI->getValue().getSExtValue();
1060
1061      if (i != 0) {
1062        QualType elemType = ER->getElementType();
1063
1064        // If we are pointing to an incomplete type, go no further.
1065        if (!IsCompleteType(C, elemType)) {
1066          superR = ER;
1067          break;
1068        }
1069
1070        CharUnits size = C.getTypeSizeInChars(elemType);
1071        offset += (i * size);
1072      }
1073
1074      // Go to the next ElementRegion (if any).
1075      ER = dyn_cast<ElementRegion>(superR);
1076      continue;
1077    }
1078
1079    return NULL;
1080  }
1081
1082  assert(superR && "super region cannot be NULL");
1083  return RegionRawOffset(superR, offset);
1084}
1085
1086RegionOffset MemRegion::getAsOffset() const {
1087  const MemRegion *R = this;
1088  const MemRegion *SymbolicOffsetBase = 0;
1089  int64_t Offset = 0;
1090
1091  while (1) {
1092    switch (R->getKind()) {
1093    case GenericMemSpaceRegionKind:
1094    case StackLocalsSpaceRegionKind:
1095    case StackArgumentsSpaceRegionKind:
1096    case HeapSpaceRegionKind:
1097    case UnknownSpaceRegionKind:
1098    case StaticGlobalSpaceRegionKind:
1099    case GlobalInternalSpaceRegionKind:
1100    case GlobalSystemSpaceRegionKind:
1101    case GlobalImmutableSpaceRegionKind:
1102      // Stores can bind directly to a region space to set a default value.
1103      assert(Offset == 0 && !SymbolicOffsetBase);
1104      goto Finish;
1105
1106    case FunctionTextRegionKind:
1107    case BlockTextRegionKind:
1108    case BlockDataRegionKind:
1109      // These will never have bindings, but may end up having values requested
1110      // if the user does some strange casting.
1111      if (Offset != 0)
1112        SymbolicOffsetBase = R;
1113      goto Finish;
1114
1115    case SymbolicRegionKind:
1116    case AllocaRegionKind:
1117    case CompoundLiteralRegionKind:
1118    case CXXThisRegionKind:
1119    case StringRegionKind:
1120    case ObjCStringRegionKind:
1121    case VarRegionKind:
1122    case CXXTempObjectRegionKind:
1123      // Usual base regions.
1124      goto Finish;
1125
1126    case ObjCIvarRegionKind:
1127      // This is a little strange, but it's a compromise between
1128      // ObjCIvarRegions having unknown compile-time offsets (when using the
1129      // non-fragile runtime) and yet still being distinct, non-overlapping
1130      // regions. Thus we treat them as "like" base regions for the purposes
1131      // of computing offsets.
1132      goto Finish;
1133
1134    case CXXBaseObjectRegionKind: {
1135      const CXXBaseObjectRegion *BOR = cast<CXXBaseObjectRegion>(R);
1136      R = BOR->getSuperRegion();
1137
1138      QualType Ty;
1139      if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R)) {
1140        Ty = TVR->getDesugaredValueType(getContext());
1141      } else if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
1142        // If our base region is symbolic, we don't know what type it really is.
1143        // Pretend the type of the symbol is the true dynamic type.
1144        // (This will at least be self-consistent for the life of the symbol.)
1145        Ty = SR->getSymbol()->getType()->getPointeeType();
1146      }
1147
1148      const CXXRecordDecl *Child = Ty->getAsCXXRecordDecl();
1149      if (!Child) {
1150        // We cannot compute the offset of the base class.
1151        SymbolicOffsetBase = R;
1152      }
1153
1154      // Don't bother calculating precise offsets if we already have a
1155      // symbolic offset somewhere in the chain.
1156      if (SymbolicOffsetBase)
1157        continue;
1158
1159      CharUnits BaseOffset;
1160      const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Child);
1161      if (BOR->isVirtual())
1162        BaseOffset = Layout.getVBaseClassOffset(BOR->getDecl());
1163      else
1164        BaseOffset = Layout.getBaseClassOffset(BOR->getDecl());
1165
1166      // The base offset is in chars, not in bits.
1167      Offset += BaseOffset.getQuantity() * getContext().getCharWidth();
1168      break;
1169    }
1170    case ElementRegionKind: {
1171      const ElementRegion *ER = cast<ElementRegion>(R);
1172      R = ER->getSuperRegion();
1173
1174      QualType EleTy = ER->getValueType();
1175      if (!IsCompleteType(getContext(), EleTy)) {
1176        // We cannot compute the offset of the base class.
1177        SymbolicOffsetBase = R;
1178        continue;
1179      }
1180
1181      SVal Index = ER->getIndex();
1182      if (Optional<nonloc::ConcreteInt> CI =
1183              Index.getAs<nonloc::ConcreteInt>()) {
1184        // Don't bother calculating precise offsets if we already have a
1185        // symbolic offset somewhere in the chain.
1186        if (SymbolicOffsetBase)
1187          continue;
1188
1189        int64_t i = CI->getValue().getSExtValue();
1190        // This type size is in bits.
1191        Offset += i * getContext().getTypeSize(EleTy);
1192      } else {
1193        // We cannot compute offset for non-concrete index.
1194        SymbolicOffsetBase = R;
1195      }
1196      break;
1197    }
1198    case FieldRegionKind: {
1199      const FieldRegion *FR = cast<FieldRegion>(R);
1200      R = FR->getSuperRegion();
1201
1202      const RecordDecl *RD = FR->getDecl()->getParent();
1203      if (RD->isUnion() || !RD->isCompleteDefinition()) {
1204        // We cannot compute offset for incomplete type.
1205        // For unions, we could treat everything as offset 0, but we'd rather
1206        // treat each field as a symbolic offset so they aren't stored on top
1207        // of each other, since we depend on things in typed regions actually
1208        // matching their types.
1209        SymbolicOffsetBase = R;
1210      }
1211
1212      // Don't bother calculating precise offsets if we already have a
1213      // symbolic offset somewhere in the chain.
1214      if (SymbolicOffsetBase)
1215        continue;
1216
1217      // Get the field number.
1218      unsigned idx = 0;
1219      for (RecordDecl::field_iterator FI = RD->field_begin(),
1220             FE = RD->field_end(); FI != FE; ++FI, ++idx)
1221        if (FR->getDecl() == *FI)
1222          break;
1223
1224      const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1225      // This is offset in bits.
1226      Offset += Layout.getFieldOffset(idx);
1227      break;
1228    }
1229    }
1230  }
1231
1232 Finish:
1233  if (SymbolicOffsetBase)
1234    return RegionOffset(SymbolicOffsetBase, RegionOffset::Symbolic);
1235  return RegionOffset(R, Offset);
1236}
1237
1238//===----------------------------------------------------------------------===//
1239// BlockDataRegion
1240//===----------------------------------------------------------------------===//
1241
1242std::pair<const VarRegion *, const VarRegion *>
1243BlockDataRegion::getCaptureRegions(const VarDecl *VD) {
1244  MemRegionManager &MemMgr = *getMemRegionManager();
1245  const VarRegion *VR = 0;
1246  const VarRegion *OriginalVR = 0;
1247
1248  if (!VD->getAttr<BlocksAttr>() && VD->hasLocalStorage()) {
1249    VR = MemMgr.getVarRegion(VD, this);
1250    OriginalVR = MemMgr.getVarRegion(VD, LC);
1251  }
1252  else {
1253    if (LC) {
1254      VR = MemMgr.getVarRegion(VD, LC);
1255      OriginalVR = VR;
1256    }
1257    else {
1258      VR = MemMgr.getVarRegion(VD, MemMgr.getUnknownRegion());
1259      OriginalVR = MemMgr.getVarRegion(VD, LC);
1260    }
1261  }
1262  return std::make_pair(VR, OriginalVR);
1263}
1264
1265void BlockDataRegion::LazyInitializeReferencedVars() {
1266  if (ReferencedVars)
1267    return;
1268
1269  AnalysisDeclContext *AC = getCodeRegion()->getAnalysisDeclContext();
1270  AnalysisDeclContext::referenced_decls_iterator I, E;
1271  llvm::tie(I, E) = AC->getReferencedBlockVars(BC->getDecl());
1272
1273  if (I == E) {
1274    ReferencedVars = (void*) 0x1;
1275    return;
1276  }
1277
1278  MemRegionManager &MemMgr = *getMemRegionManager();
1279  llvm::BumpPtrAllocator &A = MemMgr.getAllocator();
1280  BumpVectorContext BC(A);
1281
1282  typedef BumpVector<const MemRegion*> VarVec;
1283  VarVec *BV = (VarVec*) A.Allocate<VarVec>();
1284  new (BV) VarVec(BC, E - I);
1285  VarVec *BVOriginal = (VarVec*) A.Allocate<VarVec>();
1286  new (BVOriginal) VarVec(BC, E - I);
1287
1288  for ( ; I != E; ++I) {
1289    const VarRegion *VR = 0;
1290    const VarRegion *OriginalVR = 0;
1291    llvm::tie(VR, OriginalVR) = getCaptureRegions(*I);
1292    assert(VR);
1293    assert(OriginalVR);
1294    BV->push_back(VR, BC);
1295    BVOriginal->push_back(OriginalVR, BC);
1296  }
1297
1298  ReferencedVars = BV;
1299  OriginalVars = BVOriginal;
1300}
1301
1302BlockDataRegion::referenced_vars_iterator
1303BlockDataRegion::referenced_vars_begin() const {
1304  const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1305
1306  BumpVector<const MemRegion*> *Vec =
1307    static_cast<BumpVector<const MemRegion*>*>(ReferencedVars);
1308
1309  if (Vec == (void*) 0x1)
1310    return BlockDataRegion::referenced_vars_iterator(0, 0);
1311
1312  BumpVector<const MemRegion*> *VecOriginal =
1313    static_cast<BumpVector<const MemRegion*>*>(OriginalVars);
1314
1315  return BlockDataRegion::referenced_vars_iterator(Vec->begin(),
1316                                                   VecOriginal->begin());
1317}
1318
1319BlockDataRegion::referenced_vars_iterator
1320BlockDataRegion::referenced_vars_end() const {
1321  const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1322
1323  BumpVector<const MemRegion*> *Vec =
1324    static_cast<BumpVector<const MemRegion*>*>(ReferencedVars);
1325
1326  if (Vec == (void*) 0x1)
1327    return BlockDataRegion::referenced_vars_iterator(0, 0);
1328
1329  BumpVector<const MemRegion*> *VecOriginal =
1330    static_cast<BumpVector<const MemRegion*>*>(OriginalVars);
1331
1332  return BlockDataRegion::referenced_vars_iterator(Vec->end(),
1333                                                   VecOriginal->end());
1334}
1335
1336const VarRegion *BlockDataRegion::getOriginalRegion(const VarRegion *R) const {
1337  for (referenced_vars_iterator I = referenced_vars_begin(),
1338                                E = referenced_vars_end();
1339       I != E; ++I) {
1340    if (I.getCapturedRegion() == R)
1341      return I.getOriginalRegion();
1342  }
1343  return 0;
1344}
1345