MemRegion.cpp revision ae7396c3891748762d01431e16541b3eb9125c4d
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  BaseClass = BaseClass->getCanonicalDecl();
896
897  const CXXRecordDecl *Class = Super->getValueType()->getAsCXXRecordDecl();
898  if (!Class)
899    return true;
900
901  if (IsVirtual)
902    return Class->isVirtuallyDerivedFrom(BaseClass);
903
904  for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
905                                                E = Class->bases_end();
906       I != E; ++I) {
907    if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == BaseClass)
908      return true;
909  }
910
911  return false;
912}
913
914const CXXBaseObjectRegion *
915MemRegionManager::getCXXBaseObjectRegion(const CXXRecordDecl *RD,
916                                         const MemRegion *Super,
917                                         bool IsVirtual) {
918  if (isa<TypedValueRegion>(Super)) {
919    assert(isValidBaseClass(RD, dyn_cast<TypedValueRegion>(Super), IsVirtual));
920    (void)isValidBaseClass;
921
922    if (IsVirtual) {
923      // Virtual base regions should not be layered, since the layout rules
924      // are different.
925      while (const CXXBaseObjectRegion *Base =
926               dyn_cast<CXXBaseObjectRegion>(Super)) {
927        Super = Base->getSuperRegion();
928      }
929      assert(Super && !isa<MemSpaceRegion>(Super));
930    }
931  }
932
933  return getSubRegion<CXXBaseObjectRegion>(RD, IsVirtual, Super);
934}
935
936const CXXThisRegion*
937MemRegionManager::getCXXThisRegion(QualType thisPointerTy,
938                                   const LocationContext *LC) {
939  const StackFrameContext *STC = LC->getCurrentStackFrame();
940  assert(STC);
941  const PointerType *PT = thisPointerTy->getAs<PointerType>();
942  assert(PT);
943  return getSubRegion<CXXThisRegion>(PT, getStackArgumentsRegion(STC));
944}
945
946const AllocaRegion*
947MemRegionManager::getAllocaRegion(const Expr *E, unsigned cnt,
948                                  const LocationContext *LC) {
949  const StackFrameContext *STC = LC->getCurrentStackFrame();
950  assert(STC);
951  return getSubRegion<AllocaRegion>(E, cnt, getStackLocalsRegion(STC));
952}
953
954const MemSpaceRegion *MemRegion::getMemorySpace() const {
955  const MemRegion *R = this;
956  const SubRegion* SR = dyn_cast<SubRegion>(this);
957
958  while (SR) {
959    R = SR->getSuperRegion();
960    SR = dyn_cast<SubRegion>(R);
961  }
962
963  return dyn_cast<MemSpaceRegion>(R);
964}
965
966bool MemRegion::hasStackStorage() const {
967  return isa<StackSpaceRegion>(getMemorySpace());
968}
969
970bool MemRegion::hasStackNonParametersStorage() const {
971  return isa<StackLocalsSpaceRegion>(getMemorySpace());
972}
973
974bool MemRegion::hasStackParametersStorage() const {
975  return isa<StackArgumentsSpaceRegion>(getMemorySpace());
976}
977
978bool MemRegion::hasGlobalsOrParametersStorage() const {
979  const MemSpaceRegion *MS = getMemorySpace();
980  return isa<StackArgumentsSpaceRegion>(MS) ||
981         isa<GlobalsSpaceRegion>(MS);
982}
983
984// getBaseRegion strips away all elements and fields, and get the base region
985// of them.
986const MemRegion *MemRegion::getBaseRegion() const {
987  const MemRegion *R = this;
988  while (true) {
989    switch (R->getKind()) {
990      case MemRegion::ElementRegionKind:
991      case MemRegion::FieldRegionKind:
992      case MemRegion::ObjCIvarRegionKind:
993      case MemRegion::CXXBaseObjectRegionKind:
994        R = cast<SubRegion>(R)->getSuperRegion();
995        continue;
996      default:
997        break;
998    }
999    break;
1000  }
1001  return R;
1002}
1003
1004bool MemRegion::isSubRegionOf(const MemRegion *R) const {
1005  return false;
1006}
1007
1008//===----------------------------------------------------------------------===//
1009// View handling.
1010//===----------------------------------------------------------------------===//
1011
1012const MemRegion *MemRegion::StripCasts(bool StripBaseCasts) const {
1013  const MemRegion *R = this;
1014  while (true) {
1015    switch (R->getKind()) {
1016    case ElementRegionKind: {
1017      const ElementRegion *ER = cast<ElementRegion>(R);
1018      if (!ER->getIndex().isZeroConstant())
1019        return R;
1020      R = ER->getSuperRegion();
1021      break;
1022    }
1023    case CXXBaseObjectRegionKind:
1024      if (!StripBaseCasts)
1025        return R;
1026      R = cast<CXXBaseObjectRegion>(R)->getSuperRegion();
1027      break;
1028    default:
1029      return R;
1030    }
1031  }
1032}
1033
1034// FIXME: Merge with the implementation of the same method in Store.cpp
1035static bool IsCompleteType(ASTContext &Ctx, QualType Ty) {
1036  if (const RecordType *RT = Ty->getAs<RecordType>()) {
1037    const RecordDecl *D = RT->getDecl();
1038    if (!D->getDefinition())
1039      return false;
1040  }
1041
1042  return true;
1043}
1044
1045RegionRawOffset ElementRegion::getAsArrayOffset() const {
1046  CharUnits offset = CharUnits::Zero();
1047  const ElementRegion *ER = this;
1048  const MemRegion *superR = NULL;
1049  ASTContext &C = getContext();
1050
1051  // FIXME: Handle multi-dimensional arrays.
1052
1053  while (ER) {
1054    superR = ER->getSuperRegion();
1055
1056    // FIXME: generalize to symbolic offsets.
1057    SVal index = ER->getIndex();
1058    if (Optional<nonloc::ConcreteInt> CI = index.getAs<nonloc::ConcreteInt>()) {
1059      // Update the offset.
1060      int64_t i = CI->getValue().getSExtValue();
1061
1062      if (i != 0) {
1063        QualType elemType = ER->getElementType();
1064
1065        // If we are pointing to an incomplete type, go no further.
1066        if (!IsCompleteType(C, elemType)) {
1067          superR = ER;
1068          break;
1069        }
1070
1071        CharUnits size = C.getTypeSizeInChars(elemType);
1072        offset += (i * size);
1073      }
1074
1075      // Go to the next ElementRegion (if any).
1076      ER = dyn_cast<ElementRegion>(superR);
1077      continue;
1078    }
1079
1080    return NULL;
1081  }
1082
1083  assert(superR && "super region cannot be NULL");
1084  return RegionRawOffset(superR, offset);
1085}
1086
1087RegionOffset MemRegion::getAsOffset() const {
1088  const MemRegion *R = this;
1089  const MemRegion *SymbolicOffsetBase = 0;
1090  int64_t Offset = 0;
1091
1092  while (1) {
1093    switch (R->getKind()) {
1094    case GenericMemSpaceRegionKind:
1095    case StackLocalsSpaceRegionKind:
1096    case StackArgumentsSpaceRegionKind:
1097    case HeapSpaceRegionKind:
1098    case UnknownSpaceRegionKind:
1099    case StaticGlobalSpaceRegionKind:
1100    case GlobalInternalSpaceRegionKind:
1101    case GlobalSystemSpaceRegionKind:
1102    case GlobalImmutableSpaceRegionKind:
1103      // Stores can bind directly to a region space to set a default value.
1104      assert(Offset == 0 && !SymbolicOffsetBase);
1105      goto Finish;
1106
1107    case FunctionTextRegionKind:
1108    case BlockTextRegionKind:
1109    case BlockDataRegionKind:
1110      // These will never have bindings, but may end up having values requested
1111      // if the user does some strange casting.
1112      if (Offset != 0)
1113        SymbolicOffsetBase = R;
1114      goto Finish;
1115
1116    case SymbolicRegionKind:
1117    case AllocaRegionKind:
1118    case CompoundLiteralRegionKind:
1119    case CXXThisRegionKind:
1120    case StringRegionKind:
1121    case ObjCStringRegionKind:
1122    case VarRegionKind:
1123    case CXXTempObjectRegionKind:
1124      // Usual base regions.
1125      goto Finish;
1126
1127    case ObjCIvarRegionKind:
1128      // This is a little strange, but it's a compromise between
1129      // ObjCIvarRegions having unknown compile-time offsets (when using the
1130      // non-fragile runtime) and yet still being distinct, non-overlapping
1131      // regions. Thus we treat them as "like" base regions for the purposes
1132      // of computing offsets.
1133      goto Finish;
1134
1135    case CXXBaseObjectRegionKind: {
1136      const CXXBaseObjectRegion *BOR = cast<CXXBaseObjectRegion>(R);
1137      R = BOR->getSuperRegion();
1138
1139      QualType Ty;
1140      if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(R)) {
1141        Ty = TVR->getDesugaredValueType(getContext());
1142      } else if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R)) {
1143        // If our base region is symbolic, we don't know what type it really is.
1144        // Pretend the type of the symbol is the true dynamic type.
1145        // (This will at least be self-consistent for the life of the symbol.)
1146        Ty = SR->getSymbol()->getType()->getPointeeType();
1147      }
1148
1149      const CXXRecordDecl *Child = Ty->getAsCXXRecordDecl();
1150      if (!Child) {
1151        // We cannot compute the offset of the base class.
1152        SymbolicOffsetBase = R;
1153      }
1154
1155      // Don't bother calculating precise offsets if we already have a
1156      // symbolic offset somewhere in the chain.
1157      if (SymbolicOffsetBase)
1158        continue;
1159
1160      CharUnits BaseOffset;
1161      const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Child);
1162      if (BOR->isVirtual())
1163        BaseOffset = Layout.getVBaseClassOffset(BOR->getDecl());
1164      else
1165        BaseOffset = Layout.getBaseClassOffset(BOR->getDecl());
1166
1167      // The base offset is in chars, not in bits.
1168      Offset += BaseOffset.getQuantity() * getContext().getCharWidth();
1169      break;
1170    }
1171    case ElementRegionKind: {
1172      const ElementRegion *ER = cast<ElementRegion>(R);
1173      R = ER->getSuperRegion();
1174
1175      QualType EleTy = ER->getValueType();
1176      if (!IsCompleteType(getContext(), EleTy)) {
1177        // We cannot compute the offset of the base class.
1178        SymbolicOffsetBase = R;
1179        continue;
1180      }
1181
1182      SVal Index = ER->getIndex();
1183      if (Optional<nonloc::ConcreteInt> CI =
1184              Index.getAs<nonloc::ConcreteInt>()) {
1185        // Don't bother calculating precise offsets if we already have a
1186        // symbolic offset somewhere in the chain.
1187        if (SymbolicOffsetBase)
1188          continue;
1189
1190        int64_t i = CI->getValue().getSExtValue();
1191        // This type size is in bits.
1192        Offset += i * getContext().getTypeSize(EleTy);
1193      } else {
1194        // We cannot compute offset for non-concrete index.
1195        SymbolicOffsetBase = R;
1196      }
1197      break;
1198    }
1199    case FieldRegionKind: {
1200      const FieldRegion *FR = cast<FieldRegion>(R);
1201      R = FR->getSuperRegion();
1202
1203      const RecordDecl *RD = FR->getDecl()->getParent();
1204      if (RD->isUnion() || !RD->isCompleteDefinition()) {
1205        // We cannot compute offset for incomplete type.
1206        // For unions, we could treat everything as offset 0, but we'd rather
1207        // treat each field as a symbolic offset so they aren't stored on top
1208        // of each other, since we depend on things in typed regions actually
1209        // matching their types.
1210        SymbolicOffsetBase = R;
1211      }
1212
1213      // Don't bother calculating precise offsets if we already have a
1214      // symbolic offset somewhere in the chain.
1215      if (SymbolicOffsetBase)
1216        continue;
1217
1218      // Get the field number.
1219      unsigned idx = 0;
1220      for (RecordDecl::field_iterator FI = RD->field_begin(),
1221             FE = RD->field_end(); FI != FE; ++FI, ++idx)
1222        if (FR->getDecl() == *FI)
1223          break;
1224
1225      const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1226      // This is offset in bits.
1227      Offset += Layout.getFieldOffset(idx);
1228      break;
1229    }
1230    }
1231  }
1232
1233 Finish:
1234  if (SymbolicOffsetBase)
1235    return RegionOffset(SymbolicOffsetBase, RegionOffset::Symbolic);
1236  return RegionOffset(R, Offset);
1237}
1238
1239//===----------------------------------------------------------------------===//
1240// BlockDataRegion
1241//===----------------------------------------------------------------------===//
1242
1243std::pair<const VarRegion *, const VarRegion *>
1244BlockDataRegion::getCaptureRegions(const VarDecl *VD) {
1245  MemRegionManager &MemMgr = *getMemRegionManager();
1246  const VarRegion *VR = 0;
1247  const VarRegion *OriginalVR = 0;
1248
1249  if (!VD->getAttr<BlocksAttr>() && VD->hasLocalStorage()) {
1250    VR = MemMgr.getVarRegion(VD, this);
1251    OriginalVR = MemMgr.getVarRegion(VD, LC);
1252  }
1253  else {
1254    if (LC) {
1255      VR = MemMgr.getVarRegion(VD, LC);
1256      OriginalVR = VR;
1257    }
1258    else {
1259      VR = MemMgr.getVarRegion(VD, MemMgr.getUnknownRegion());
1260      OriginalVR = MemMgr.getVarRegion(VD, LC);
1261    }
1262  }
1263  return std::make_pair(VR, OriginalVR);
1264}
1265
1266void BlockDataRegion::LazyInitializeReferencedVars() {
1267  if (ReferencedVars)
1268    return;
1269
1270  AnalysisDeclContext *AC = getCodeRegion()->getAnalysisDeclContext();
1271  AnalysisDeclContext::referenced_decls_iterator I, E;
1272  llvm::tie(I, E) = AC->getReferencedBlockVars(BC->getDecl());
1273
1274  if (I == E) {
1275    ReferencedVars = (void*) 0x1;
1276    return;
1277  }
1278
1279  MemRegionManager &MemMgr = *getMemRegionManager();
1280  llvm::BumpPtrAllocator &A = MemMgr.getAllocator();
1281  BumpVectorContext BC(A);
1282
1283  typedef BumpVector<const MemRegion*> VarVec;
1284  VarVec *BV = (VarVec*) A.Allocate<VarVec>();
1285  new (BV) VarVec(BC, E - I);
1286  VarVec *BVOriginal = (VarVec*) A.Allocate<VarVec>();
1287  new (BVOriginal) VarVec(BC, E - I);
1288
1289  for ( ; I != E; ++I) {
1290    const VarRegion *VR = 0;
1291    const VarRegion *OriginalVR = 0;
1292    llvm::tie(VR, OriginalVR) = getCaptureRegions(*I);
1293    assert(VR);
1294    assert(OriginalVR);
1295    BV->push_back(VR, BC);
1296    BVOriginal->push_back(OriginalVR, BC);
1297  }
1298
1299  ReferencedVars = BV;
1300  OriginalVars = BVOriginal;
1301}
1302
1303BlockDataRegion::referenced_vars_iterator
1304BlockDataRegion::referenced_vars_begin() const {
1305  const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1306
1307  BumpVector<const MemRegion*> *Vec =
1308    static_cast<BumpVector<const MemRegion*>*>(ReferencedVars);
1309
1310  if (Vec == (void*) 0x1)
1311    return BlockDataRegion::referenced_vars_iterator(0, 0);
1312
1313  BumpVector<const MemRegion*> *VecOriginal =
1314    static_cast<BumpVector<const MemRegion*>*>(OriginalVars);
1315
1316  return BlockDataRegion::referenced_vars_iterator(Vec->begin(),
1317                                                   VecOriginal->begin());
1318}
1319
1320BlockDataRegion::referenced_vars_iterator
1321BlockDataRegion::referenced_vars_end() const {
1322  const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1323
1324  BumpVector<const MemRegion*> *Vec =
1325    static_cast<BumpVector<const MemRegion*>*>(ReferencedVars);
1326
1327  if (Vec == (void*) 0x1)
1328    return BlockDataRegion::referenced_vars_iterator(0, 0);
1329
1330  BumpVector<const MemRegion*> *VecOriginal =
1331    static_cast<BumpVector<const MemRegion*>*>(OriginalVars);
1332
1333  return BlockDataRegion::referenced_vars_iterator(Vec->end(),
1334                                                   VecOriginal->end());
1335}
1336
1337const VarRegion *BlockDataRegion::getOriginalRegion(const VarRegion *R) const {
1338  for (referenced_vars_iterator I = referenced_vars_begin(),
1339                                E = referenced_vars_end();
1340       I != E; ++I) {
1341    if (I.getCapturedRegion() == R)
1342      return I.getOriginalRegion();
1343  }
1344  return 0;
1345}
1346