1 //===- MemRegion.cpp - Abstract memory regions for static analysis --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines MemRegion and its subclasses.  MemRegion defines a
10 //  partially-typed abstraction of memory useful for path-sensitive dataflow
11 //  analyses.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/PrettyPrinter.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/Type.h"
26 #include "clang/Analysis/AnalysisDeclContext.h"
27 #include "clang/Analysis/Support/BumpVector.h"
28 #include "clang/Basic/IdentifierTable.h"
29 #include "clang/Basic/LLVM.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
32 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
33 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
34 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
35 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
36 #include "llvm/ADT/APInt.h"
37 #include "llvm/ADT/FoldingSet.h"
38 #include "llvm/ADT/Optional.h"
39 #include "llvm/ADT/PointerUnion.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/ADT/Twine.h"
43 #include "llvm/Support/Allocator.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/CheckedArithmetic.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include <cassert>
51 #include <cstdint>
52 #include <functional>
53 #include <iterator>
54 #include <string>
55 #include <tuple>
56 #include <utility>
57 
58 using namespace clang;
59 using namespace ento;
60 
61 #define DEBUG_TYPE "MemRegion"
62 
63 //===----------------------------------------------------------------------===//
64 // MemRegion Construction.
65 //===----------------------------------------------------------------------===//
66 
67 template <typename RegionTy, typename SuperTy, typename Arg1Ty>
68 RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
69                                          const SuperTy *superRegion) {
70   llvm::FoldingSetNodeID ID;
71   RegionTy::ProfileRegion(ID, arg1, superRegion);
72   void *InsertPos;
73   auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
74 
75   if (!R) {
76     R = A.Allocate<RegionTy>();
77     new (R) RegionTy(arg1, superRegion);
78     Regions.InsertNode(R, InsertPos);
79   }
80 
81   return R;
82 }
83 
84 template <typename RegionTy, typename SuperTy, typename Arg1Ty, typename Arg2Ty>
85 RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
86                                          const SuperTy *superRegion) {
87   llvm::FoldingSetNodeID ID;
88   RegionTy::ProfileRegion(ID, arg1, arg2, superRegion);
89   void *InsertPos;
90   auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
91 
92   if (!R) {
93     R = A.Allocate<RegionTy>();
94     new (R) RegionTy(arg1, arg2, superRegion);
95     Regions.InsertNode(R, InsertPos);
96   }
97 
98   return R;
99 }
100 
101 template <typename RegionTy, typename SuperTy,
102           typename Arg1Ty, typename Arg2Ty, typename Arg3Ty>
103 RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
104                                          const Arg3Ty arg3,
105                                          const SuperTy *superRegion) {
106   llvm::FoldingSetNodeID ID;
107   RegionTy::ProfileRegion(ID, arg1, arg2, arg3, superRegion);
108   void *InsertPos;
109   auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
110 
111   if (!R) {
112     R = A.Allocate<RegionTy>();
113     new (R) RegionTy(arg1, arg2, arg3, superRegion);
114     Regions.InsertNode(R, InsertPos);
115   }
116 
117   return R;
118 }
119 
120 //===----------------------------------------------------------------------===//
121 // Object destruction.
122 //===----------------------------------------------------------------------===//
123 
124 MemRegion::~MemRegion() = default;
125 
126 // All regions and their data are BumpPtrAllocated.  No need to call their
127 // destructors.
128 MemRegionManager::~MemRegionManager() = default;
129 
130 //===----------------------------------------------------------------------===//
131 // Basic methods.
132 //===----------------------------------------------------------------------===//
133 
134 bool SubRegion::isSubRegionOf(const MemRegion* R) const {
135   const MemRegion* r = this;
136   do {
137     if (r == R)
138       return true;
139     if (const auto *sr = dyn_cast<SubRegion>(r))
140       r = sr->getSuperRegion();
141     else
142       break;
143   } while (r != nullptr);
144   return false;
145 }
146 
147 MemRegionManager &SubRegion::getMemRegionManager() const {
148   const SubRegion* r = this;
149   do {
150     const MemRegion *superRegion = r->getSuperRegion();
151     if (const auto *sr = dyn_cast<SubRegion>(superRegion)) {
152       r = sr;
153       continue;
154     }
155     return superRegion->getMemRegionManager();
156   } while (true);
157 }
158 
159 const StackFrameContext *VarRegion::getStackFrame() const {
160   const auto *SSR = dyn_cast<StackSpaceRegion>(getMemorySpace());
161   return SSR ? SSR->getStackFrame() : nullptr;
162 }
163 
164 ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, const SubRegion *sReg)
165     : DeclRegion(sReg, ObjCIvarRegionKind), IVD(ivd) {
166   assert(IVD);
167 }
168 
169 const ObjCIvarDecl *ObjCIvarRegion::getDecl() const { return IVD; }
170 
171 QualType ObjCIvarRegion::getValueType() const {
172   return getDecl()->getType();
173 }
174 
175 QualType CXXBaseObjectRegion::getValueType() const {
176   return QualType(getDecl()->getTypeForDecl(), 0);
177 }
178 
179 QualType CXXDerivedObjectRegion::getValueType() const {
180   return QualType(getDecl()->getTypeForDecl(), 0);
181 }
182 
183 QualType ParamVarRegion::getValueType() const {
184   assert(getDecl() &&
185          "`ParamVarRegion` support functions without `Decl` not implemented"
186          " yet.");
187   return getDecl()->getType();
188 }
189 
190 const ParmVarDecl *ParamVarRegion::getDecl() const {
191   const Decl *D = getStackFrame()->getDecl();
192 
193   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
194     assert(Index < FD->param_size());
195     return FD->parameters()[Index];
196   } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
197     assert(Index < BD->param_size());
198     return BD->parameters()[Index];
199   } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
200     assert(Index < MD->param_size());
201     return MD->parameters()[Index];
202   } else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
203     assert(Index < CD->param_size());
204     return CD->parameters()[Index];
205   } else {
206     llvm_unreachable("Unexpected Decl kind!");
207   }
208 }
209 
210 //===----------------------------------------------------------------------===//
211 // FoldingSet profiling.
212 //===----------------------------------------------------------------------===//
213 
214 void MemSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
215   ID.AddInteger(static_cast<unsigned>(getKind()));
216 }
217 
218 void StackSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
219   ID.AddInteger(static_cast<unsigned>(getKind()));
220   ID.AddPointer(getStackFrame());
221 }
222 
223 void StaticGlobalSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
224   ID.AddInteger(static_cast<unsigned>(getKind()));
225   ID.AddPointer(getCodeRegion());
226 }
227 
228 void StringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
229                                  const StringLiteral *Str,
230                                  const MemRegion *superRegion) {
231   ID.AddInteger(static_cast<unsigned>(StringRegionKind));
232   ID.AddPointer(Str);
233   ID.AddPointer(superRegion);
234 }
235 
236 void ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
237                                      const ObjCStringLiteral *Str,
238                                      const MemRegion *superRegion) {
239   ID.AddInteger(static_cast<unsigned>(ObjCStringRegionKind));
240   ID.AddPointer(Str);
241   ID.AddPointer(superRegion);
242 }
243 
244 void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
245                                  const Expr *Ex, unsigned cnt,
246                                  const MemRegion *superRegion) {
247   ID.AddInteger(static_cast<unsigned>(AllocaRegionKind));
248   ID.AddPointer(Ex);
249   ID.AddInteger(cnt);
250   ID.AddPointer(superRegion);
251 }
252 
253 void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
254   ProfileRegion(ID, Ex, Cnt, superRegion);
255 }
256 
257 void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
258   CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
259 }
260 
261 void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
262                                           const CompoundLiteralExpr *CL,
263                                           const MemRegion* superRegion) {
264   ID.AddInteger(static_cast<unsigned>(CompoundLiteralRegionKind));
265   ID.AddPointer(CL);
266   ID.AddPointer(superRegion);
267 }
268 
269 void CXXThisRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
270                                   const PointerType *PT,
271                                   const MemRegion *sRegion) {
272   ID.AddInteger(static_cast<unsigned>(CXXThisRegionKind));
273   ID.AddPointer(PT);
274   ID.AddPointer(sRegion);
275 }
276 
277 void CXXThisRegion::Profile(llvm::FoldingSetNodeID &ID) const {
278   CXXThisRegion::ProfileRegion(ID, ThisPointerTy, superRegion);
279 }
280 
281 void FieldRegion::Profile(llvm::FoldingSetNodeID &ID) const {
282   ProfileRegion(ID, getDecl(), superRegion);
283 }
284 
285 void ObjCIvarRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
286                                    const ObjCIvarDecl *ivd,
287                                    const MemRegion* superRegion) {
288   ID.AddInteger(static_cast<unsigned>(ObjCIvarRegionKind));
289   ID.AddPointer(ivd);
290   ID.AddPointer(superRegion);
291 }
292 
293 void ObjCIvarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
294   ProfileRegion(ID, getDecl(), superRegion);
295 }
296 
297 void NonParamVarRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
298                                       const VarDecl *VD,
299                                       const MemRegion *superRegion) {
300   ID.AddInteger(static_cast<unsigned>(NonParamVarRegionKind));
301   ID.AddPointer(VD);
302   ID.AddPointer(superRegion);
303 }
304 
305 void NonParamVarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
306   ProfileRegion(ID, getDecl(), superRegion);
307 }
308 
309 void ParamVarRegion::ProfileRegion(llvm::FoldingSetNodeID &ID, const Expr *OE,
310                                    unsigned Idx, const MemRegion *SReg) {
311   ID.AddInteger(static_cast<unsigned>(ParamVarRegionKind));
312   ID.AddPointer(OE);
313   ID.AddInteger(Idx);
314   ID.AddPointer(SReg);
315 }
316 
317 void ParamVarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
318   ProfileRegion(ID, getOriginExpr(), getIndex(), superRegion);
319 }
320 
321 void SymbolicRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym,
322                                    const MemRegion *sreg) {
323   ID.AddInteger(static_cast<unsigned>(MemRegion::SymbolicRegionKind));
324   ID.Add(sym);
325   ID.AddPointer(sreg);
326 }
327 
328 void SymbolicRegion::Profile(llvm::FoldingSetNodeID& ID) const {
329   SymbolicRegion::ProfileRegion(ID, sym, getSuperRegion());
330 }
331 
332 void ElementRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
333                                   QualType ElementType, SVal Idx,
334                                   const MemRegion* superRegion) {
335   ID.AddInteger(MemRegion::ElementRegionKind);
336   ID.Add(ElementType);
337   ID.AddPointer(superRegion);
338   Idx.Profile(ID);
339 }
340 
341 void ElementRegion::Profile(llvm::FoldingSetNodeID& ID) const {
342   ElementRegion::ProfileRegion(ID, ElementType, Index, superRegion);
343 }
344 
345 void FunctionCodeRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
346                                        const NamedDecl *FD,
347                                        const MemRegion*) {
348   ID.AddInteger(MemRegion::FunctionCodeRegionKind);
349   ID.AddPointer(FD);
350 }
351 
352 void FunctionCodeRegion::Profile(llvm::FoldingSetNodeID& ID) const {
353   FunctionCodeRegion::ProfileRegion(ID, FD, superRegion);
354 }
355 
356 void BlockCodeRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
357                                     const BlockDecl *BD, CanQualType,
358                                     const AnalysisDeclContext *AC,
359                                     const MemRegion*) {
360   ID.AddInteger(MemRegion::BlockCodeRegionKind);
361   ID.AddPointer(BD);
362 }
363 
364 void BlockCodeRegion::Profile(llvm::FoldingSetNodeID& ID) const {
365   BlockCodeRegion::ProfileRegion(ID, BD, locTy, AC, superRegion);
366 }
367 
368 void BlockDataRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
369                                     const BlockCodeRegion *BC,
370                                     const LocationContext *LC,
371                                     unsigned BlkCount,
372                                     const MemRegion *sReg) {
373   ID.AddInteger(MemRegion::BlockDataRegionKind);
374   ID.AddPointer(BC);
375   ID.AddPointer(LC);
376   ID.AddInteger(BlkCount);
377   ID.AddPointer(sReg);
378 }
379 
380 void BlockDataRegion::Profile(llvm::FoldingSetNodeID& ID) const {
381   BlockDataRegion::ProfileRegion(ID, BC, LC, BlockCount, getSuperRegion());
382 }
383 
384 void CXXTempObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
385                                         Expr const *Ex,
386                                         const MemRegion *sReg) {
387   ID.AddPointer(Ex);
388   ID.AddPointer(sReg);
389 }
390 
391 void CXXTempObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
392   ProfileRegion(ID, Ex, getSuperRegion());
393 }
394 
395 void CXXBaseObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
396                                         const CXXRecordDecl *RD,
397                                         bool IsVirtual,
398                                         const MemRegion *SReg) {
399   ID.AddPointer(RD);
400   ID.AddBoolean(IsVirtual);
401   ID.AddPointer(SReg);
402 }
403 
404 void CXXBaseObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
405   ProfileRegion(ID, getDecl(), isVirtual(), superRegion);
406 }
407 
408 void CXXDerivedObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
409                                            const CXXRecordDecl *RD,
410                                            const MemRegion *SReg) {
411   ID.AddPointer(RD);
412   ID.AddPointer(SReg);
413 }
414 
415 void CXXDerivedObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
416   ProfileRegion(ID, getDecl(), superRegion);
417 }
418 
419 //===----------------------------------------------------------------------===//
420 // Region anchors.
421 //===----------------------------------------------------------------------===//
422 
423 void GlobalsSpaceRegion::anchor() {}
424 
425 void NonStaticGlobalSpaceRegion::anchor() {}
426 
427 void StackSpaceRegion::anchor() {}
428 
429 void TypedRegion::anchor() {}
430 
431 void TypedValueRegion::anchor() {}
432 
433 void CodeTextRegion::anchor() {}
434 
435 void SubRegion::anchor() {}
436 
437 //===----------------------------------------------------------------------===//
438 // Region pretty-printing.
439 //===----------------------------------------------------------------------===//
440 
441 LLVM_DUMP_METHOD void MemRegion::dump() const {
442   dumpToStream(llvm::errs());
443 }
444 
445 std::string MemRegion::getString() const {
446   std::string s;
447   llvm::raw_string_ostream os(s);
448   dumpToStream(os);
449   return s;
450 }
451 
452 void MemRegion::dumpToStream(raw_ostream &os) const {
453   os << "<Unknown Region>";
454 }
455 
456 void AllocaRegion::dumpToStream(raw_ostream &os) const {
457   os << "alloca{S" << Ex->getID(getContext()) << ',' << Cnt << '}';
458 }
459 
460 void FunctionCodeRegion::dumpToStream(raw_ostream &os) const {
461   os << "code{" << getDecl()->getDeclName().getAsString() << '}';
462 }
463 
464 void BlockCodeRegion::dumpToStream(raw_ostream &os) const {
465   os << "block_code{" << static_cast<const void *>(this) << '}';
466 }
467 
468 void BlockDataRegion::dumpToStream(raw_ostream &os) const {
469   os << "block_data{" << BC;
470   os << "; ";
471   for (BlockDataRegion::referenced_vars_iterator
472          I = referenced_vars_begin(),
473          E = referenced_vars_end(); I != E; ++I)
474     os << "(" << I.getCapturedRegion() << "<-" <<
475                  I.getOriginalRegion() << ") ";
476   os << '}';
477 }
478 
479 void CompoundLiteralRegion::dumpToStream(raw_ostream &os) const {
480   // FIXME: More elaborate pretty-printing.
481   os << "{ S" << CL->getID(getContext()) <<  " }";
482 }
483 
484 void CXXTempObjectRegion::dumpToStream(raw_ostream &os) const {
485   os << "temp_object{" << getValueType() << ", "
486      << "S" << Ex->getID(getContext()) << '}';
487 }
488 
489 void CXXBaseObjectRegion::dumpToStream(raw_ostream &os) const {
490   os << "Base{" << superRegion << ',' << getDecl()->getName() << '}';
491 }
492 
493 void CXXDerivedObjectRegion::dumpToStream(raw_ostream &os) const {
494   os << "Derived{" << superRegion << ',' << getDecl()->getName() << '}';
495 }
496 
497 void CXXThisRegion::dumpToStream(raw_ostream &os) const {
498   os << "this";
499 }
500 
501 void ElementRegion::dumpToStream(raw_ostream &os) const {
502   os << "Element{" << superRegion << ',' << Index << ',' << getElementType()
503      << '}';
504 }
505 
506 void FieldRegion::dumpToStream(raw_ostream &os) const {
507   os << superRegion << "." << *getDecl();
508 }
509 
510 void ObjCIvarRegion::dumpToStream(raw_ostream &os) const {
511   os << "Ivar{" << superRegion << ',' << *getDecl() << '}';
512 }
513 
514 void StringRegion::dumpToStream(raw_ostream &os) const {
515   assert(Str != nullptr && "Expecting non-null StringLiteral");
516   Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts()));
517 }
518 
519 void ObjCStringRegion::dumpToStream(raw_ostream &os) const {
520   assert(Str != nullptr && "Expecting non-null ObjCStringLiteral");
521   Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts()));
522 }
523 
524 void SymbolicRegion::dumpToStream(raw_ostream &os) const {
525   if (isa<HeapSpaceRegion>(getSuperRegion()))
526     os << "Heap";
527   os << "SymRegion{" << sym << '}';
528 }
529 
530 void NonParamVarRegion::dumpToStream(raw_ostream &os) const {
531   if (const IdentifierInfo *ID = VD->getIdentifier())
532     os << ID->getName();
533   else
534     os << "NonParamVarRegion{D" << VD->getID() << '}';
535 }
536 
537 LLVM_DUMP_METHOD void RegionRawOffset::dump() const {
538   dumpToStream(llvm::errs());
539 }
540 
541 void RegionRawOffset::dumpToStream(raw_ostream &os) const {
542   os << "raw_offset{" << getRegion() << ',' << getOffset().getQuantity() << '}';
543 }
544 
545 void CodeSpaceRegion::dumpToStream(raw_ostream &os) const {
546   os << "CodeSpaceRegion";
547 }
548 
549 void StaticGlobalSpaceRegion::dumpToStream(raw_ostream &os) const {
550   os << "StaticGlobalsMemSpace{" << CR << '}';
551 }
552 
553 void GlobalInternalSpaceRegion::dumpToStream(raw_ostream &os) const {
554   os << "GlobalInternalSpaceRegion";
555 }
556 
557 void GlobalSystemSpaceRegion::dumpToStream(raw_ostream &os) const {
558   os << "GlobalSystemSpaceRegion";
559 }
560 
561 void GlobalImmutableSpaceRegion::dumpToStream(raw_ostream &os) const {
562   os << "GlobalImmutableSpaceRegion";
563 }
564 
565 void HeapSpaceRegion::dumpToStream(raw_ostream &os) const {
566   os << "HeapSpaceRegion";
567 }
568 
569 void UnknownSpaceRegion::dumpToStream(raw_ostream &os) const {
570   os << "UnknownSpaceRegion";
571 }
572 
573 void StackArgumentsSpaceRegion::dumpToStream(raw_ostream &os) const {
574   os << "StackArgumentsSpaceRegion";
575 }
576 
577 void StackLocalsSpaceRegion::dumpToStream(raw_ostream &os) const {
578   os << "StackLocalsSpaceRegion";
579 }
580 
581 void ParamVarRegion::dumpToStream(raw_ostream &os) const {
582   const ParmVarDecl *PVD = getDecl();
583   assert(PVD &&
584          "`ParamVarRegion` support functions without `Decl` not implemented"
585          " yet.");
586   if (const IdentifierInfo *ID = PVD->getIdentifier()) {
587     os << ID->getName();
588   } else {
589     os << "ParamVarRegion{P" << PVD->getID() << '}';
590   }
591 }
592 
593 bool MemRegion::canPrintPretty() const {
594   return canPrintPrettyAsExpr();
595 }
596 
597 bool MemRegion::canPrintPrettyAsExpr() const {
598   return false;
599 }
600 
601 void MemRegion::printPretty(raw_ostream &os) const {
602   assert(canPrintPretty() && "This region cannot be printed pretty.");
603   os << "'";
604   printPrettyAsExpr(os);
605   os << "'";
606 }
607 
608 void MemRegion::printPrettyAsExpr(raw_ostream &) const {
609   llvm_unreachable("This region cannot be printed pretty.");
610 }
611 
612 bool NonParamVarRegion::canPrintPrettyAsExpr() const { return true; }
613 
614 void NonParamVarRegion::printPrettyAsExpr(raw_ostream &os) const {
615   os << getDecl()->getName();
616 }
617 
618 bool ParamVarRegion::canPrintPrettyAsExpr() const { return true; }
619 
620 void ParamVarRegion::printPrettyAsExpr(raw_ostream &os) const {
621   assert(getDecl() &&
622          "`ParamVarRegion` support functions without `Decl` not implemented"
623          " yet.");
624   os << getDecl()->getName();
625 }
626 
627 bool ObjCIvarRegion::canPrintPrettyAsExpr() const {
628   return true;
629 }
630 
631 void ObjCIvarRegion::printPrettyAsExpr(raw_ostream &os) const {
632   os << getDecl()->getName();
633 }
634 
635 bool FieldRegion::canPrintPretty() const {
636   return true;
637 }
638 
639 bool FieldRegion::canPrintPrettyAsExpr() const {
640   return superRegion->canPrintPrettyAsExpr();
641 }
642 
643 void FieldRegion::printPrettyAsExpr(raw_ostream &os) const {
644   assert(canPrintPrettyAsExpr());
645   superRegion->printPrettyAsExpr(os);
646   os << "." << getDecl()->getName();
647 }
648 
649 void FieldRegion::printPretty(raw_ostream &os) const {
650   if (canPrintPrettyAsExpr()) {
651     os << "\'";
652     printPrettyAsExpr(os);
653     os << "'";
654   } else {
655     os << "field " << "\'" << getDecl()->getName() << "'";
656   }
657 }
658 
659 bool CXXBaseObjectRegion::canPrintPrettyAsExpr() const {
660   return superRegion->canPrintPrettyAsExpr();
661 }
662 
663 void CXXBaseObjectRegion::printPrettyAsExpr(raw_ostream &os) const {
664   superRegion->printPrettyAsExpr(os);
665 }
666 
667 bool CXXDerivedObjectRegion::canPrintPrettyAsExpr() const {
668   return superRegion->canPrintPrettyAsExpr();
669 }
670 
671 void CXXDerivedObjectRegion::printPrettyAsExpr(raw_ostream &os) const {
672   superRegion->printPrettyAsExpr(os);
673 }
674 
675 std::string MemRegion::getDescriptiveName(bool UseQuotes) const {
676   std::string VariableName;
677   std::string ArrayIndices;
678   const MemRegion *R = this;
679   SmallString<50> buf;
680   llvm::raw_svector_ostream os(buf);
681 
682   // Obtain array indices to add them to the variable name.
683   const ElementRegion *ER = nullptr;
684   while ((ER = R->getAs<ElementRegion>())) {
685     // Index is a ConcreteInt.
686     if (auto CI = ER->getIndex().getAs<nonloc::ConcreteInt>()) {
687       llvm::SmallString<2> Idx;
688       CI->getValue().toString(Idx);
689       ArrayIndices = (llvm::Twine("[") + Idx.str() + "]" + ArrayIndices).str();
690     }
691     // If not a ConcreteInt, try to obtain the variable
692     // name by calling 'getDescriptiveName' recursively.
693     else {
694       std::string Idx = ER->getDescriptiveName(false);
695       if (!Idx.empty()) {
696         ArrayIndices = (llvm::Twine("[") + Idx + "]" + ArrayIndices).str();
697       }
698     }
699     R = ER->getSuperRegion();
700   }
701 
702   // Get variable name.
703   if (R && R->canPrintPrettyAsExpr()) {
704     R->printPrettyAsExpr(os);
705     if (UseQuotes)
706       return (llvm::Twine("'") + os.str() + ArrayIndices + "'").str();
707     else
708       return (llvm::Twine(os.str()) + ArrayIndices).str();
709   }
710 
711   return VariableName;
712 }
713 
714 SourceRange MemRegion::sourceRange() const {
715   const auto *const VR = dyn_cast<VarRegion>(this->getBaseRegion());
716   const auto *const FR = dyn_cast<FieldRegion>(this);
717 
718   // Check for more specific regions first.
719   // FieldRegion
720   if (FR) {
721     return FR->getDecl()->getSourceRange();
722   }
723   // VarRegion
724   else if (VR) {
725     return VR->getDecl()->getSourceRange();
726   }
727   // Return invalid source range (can be checked by client).
728   else
729     return {};
730 }
731 
732 //===----------------------------------------------------------------------===//
733 // MemRegionManager methods.
734 //===----------------------------------------------------------------------===//
735 
736 DefinedOrUnknownSVal MemRegionManager::getStaticSize(const MemRegion *MR,
737                                                      SValBuilder &SVB) const {
738   const auto *SR = cast<SubRegion>(MR);
739   SymbolManager &SymMgr = SVB.getSymbolManager();
740 
741   switch (SR->getKind()) {
742   case MemRegion::AllocaRegionKind:
743   case MemRegion::SymbolicRegionKind:
744     return nonloc::SymbolVal(SymMgr.getExtentSymbol(SR));
745   case MemRegion::StringRegionKind:
746     return SVB.makeIntVal(
747         cast<StringRegion>(SR)->getStringLiteral()->getByteLength() + 1,
748         SVB.getArrayIndexType());
749   case MemRegion::CompoundLiteralRegionKind:
750   case MemRegion::CXXBaseObjectRegionKind:
751   case MemRegion::CXXDerivedObjectRegionKind:
752   case MemRegion::CXXTempObjectRegionKind:
753   case MemRegion::CXXThisRegionKind:
754   case MemRegion::ObjCIvarRegionKind:
755   case MemRegion::NonParamVarRegionKind:
756   case MemRegion::ParamVarRegionKind:
757   case MemRegion::ElementRegionKind:
758   case MemRegion::ObjCStringRegionKind: {
759     QualType Ty = cast<TypedValueRegion>(SR)->getDesugaredValueType(Ctx);
760     if (isa<VariableArrayType>(Ty))
761       return nonloc::SymbolVal(SymMgr.getExtentSymbol(SR));
762 
763     if (Ty->isIncompleteType())
764       return UnknownVal();
765 
766     return getElementExtent(Ty, SVB);
767   }
768   case MemRegion::FieldRegionKind: {
769     // Force callers to deal with bitfields explicitly.
770     if (cast<FieldRegion>(SR)->getDecl()->isBitField())
771       return UnknownVal();
772 
773     QualType Ty = cast<TypedValueRegion>(SR)->getDesugaredValueType(Ctx);
774     const DefinedOrUnknownSVal Size = getElementExtent(Ty, SVB);
775 
776     // We currently don't model flexible array members (FAMs), which are:
777     //  - int array[]; of IncompleteArrayType
778     //  - int array[0]; of ConstantArrayType with size 0
779     //  - int array[1]; of ConstantArrayType with size 1 (*)
780     // (*): Consider single element array object members as FAM candidates only
781     //      if the consider-single-element-arrays-as-flexible-array-members
782     //      analyzer option is true.
783     // https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
784     const auto isFlexibleArrayMemberCandidate = [this,
785                                                  &SVB](QualType Ty) -> bool {
786       const ArrayType *AT = Ctx.getAsArrayType(Ty);
787       if (!AT)
788         return false;
789       if (isa<IncompleteArrayType>(AT))
790         return true;
791 
792       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
793         const llvm::APInt &Size = CAT->getSize();
794         if (Size.isZero())
795           return true;
796 
797         const AnalyzerOptions &Opts = SVB.getAnalyzerOptions();
798         if (Opts.ShouldConsiderSingleElementArraysAsFlexibleArrayMembers &&
799             Size.isOne())
800           return true;
801       }
802       return false;
803     };
804 
805     if (isFlexibleArrayMemberCandidate(Ty))
806       return UnknownVal();
807 
808     return Size;
809   }
810     // FIXME: The following are being used in 'SimpleSValBuilder' and in
811     // 'ArrayBoundChecker::checkLocation' because there is no symbol to
812     // represent the regions more appropriately.
813   case MemRegion::BlockDataRegionKind:
814   case MemRegion::BlockCodeRegionKind:
815   case MemRegion::FunctionCodeRegionKind:
816     return nonloc::SymbolVal(SymMgr.getExtentSymbol(SR));
817   default:
818     llvm_unreachable("Unhandled region");
819   }
820 }
821 
822 template <typename REG>
823 const REG *MemRegionManager::LazyAllocate(REG*& region) {
824   if (!region) {
825     region = A.Allocate<REG>();
826     new (region) REG(*this);
827   }
828 
829   return region;
830 }
831 
832 template <typename REG, typename ARG>
833 const REG *MemRegionManager::LazyAllocate(REG*& region, ARG a) {
834   if (!region) {
835     region = A.Allocate<REG>();
836     new (region) REG(this, a);
837   }
838 
839   return region;
840 }
841 
842 const StackLocalsSpaceRegion*
843 MemRegionManager::getStackLocalsRegion(const StackFrameContext *STC) {
844   assert(STC);
845   StackLocalsSpaceRegion *&R = StackLocalsSpaceRegions[STC];
846 
847   if (R)
848     return R;
849 
850   R = A.Allocate<StackLocalsSpaceRegion>();
851   new (R) StackLocalsSpaceRegion(*this, STC);
852   return R;
853 }
854 
855 const StackArgumentsSpaceRegion *
856 MemRegionManager::getStackArgumentsRegion(const StackFrameContext *STC) {
857   assert(STC);
858   StackArgumentsSpaceRegion *&R = StackArgumentsSpaceRegions[STC];
859 
860   if (R)
861     return R;
862 
863   R = A.Allocate<StackArgumentsSpaceRegion>();
864   new (R) StackArgumentsSpaceRegion(*this, STC);
865   return R;
866 }
867 
868 const GlobalsSpaceRegion
869 *MemRegionManager::getGlobalsRegion(MemRegion::Kind K,
870                                     const CodeTextRegion *CR) {
871   if (!CR) {
872     if (K == MemRegion::GlobalSystemSpaceRegionKind)
873       return LazyAllocate(SystemGlobals);
874     if (K == MemRegion::GlobalImmutableSpaceRegionKind)
875       return LazyAllocate(ImmutableGlobals);
876     assert(K == MemRegion::GlobalInternalSpaceRegionKind);
877     return LazyAllocate(InternalGlobals);
878   }
879 
880   assert(K == MemRegion::StaticGlobalSpaceRegionKind);
881   StaticGlobalSpaceRegion *&R = StaticsGlobalSpaceRegions[CR];
882   if (R)
883     return R;
884 
885   R = A.Allocate<StaticGlobalSpaceRegion>();
886   new (R) StaticGlobalSpaceRegion(*this, CR);
887   return R;
888 }
889 
890 const HeapSpaceRegion *MemRegionManager::getHeapRegion() {
891   return LazyAllocate(heap);
892 }
893 
894 const UnknownSpaceRegion *MemRegionManager::getUnknownRegion() {
895   return LazyAllocate(unknown);
896 }
897 
898 const CodeSpaceRegion *MemRegionManager::getCodeRegion() {
899   return LazyAllocate(code);
900 }
901 
902 //===----------------------------------------------------------------------===//
903 // Constructing regions.
904 //===----------------------------------------------------------------------===//
905 
906 const StringRegion *MemRegionManager::getStringRegion(const StringLiteral *Str){
907   return getSubRegion<StringRegion>(
908       Str, cast<GlobalInternalSpaceRegion>(getGlobalsRegion()));
909 }
910 
911 const ObjCStringRegion *
912 MemRegionManager::getObjCStringRegion(const ObjCStringLiteral *Str){
913   return getSubRegion<ObjCStringRegion>(
914       Str, cast<GlobalInternalSpaceRegion>(getGlobalsRegion()));
915 }
916 
917 /// Look through a chain of LocationContexts to either find the
918 /// StackFrameContext that matches a DeclContext, or find a VarRegion
919 /// for a variable captured by a block.
920 static llvm::PointerUnion<const StackFrameContext *, const VarRegion *>
921 getStackOrCaptureRegionForDeclContext(const LocationContext *LC,
922                                       const DeclContext *DC,
923                                       const VarDecl *VD) {
924   while (LC) {
925     if (const auto *SFC = dyn_cast<StackFrameContext>(LC)) {
926       if (cast<DeclContext>(SFC->getDecl()) == DC)
927         return SFC;
928     }
929     if (const auto *BC = dyn_cast<BlockInvocationContext>(LC)) {
930       const auto *BR = static_cast<const BlockDataRegion *>(BC->getData());
931       // FIXME: This can be made more efficient.
932       for (BlockDataRegion::referenced_vars_iterator
933            I = BR->referenced_vars_begin(),
934            E = BR->referenced_vars_end(); I != E; ++I) {
935         const TypedValueRegion *OrigR = I.getOriginalRegion();
936         if (const auto *VR = dyn_cast<VarRegion>(OrigR)) {
937           if (VR->getDecl() == VD)
938             return cast<VarRegion>(I.getCapturedRegion());
939         }
940       }
941     }
942 
943     LC = LC->getParent();
944   }
945   return (const StackFrameContext *)nullptr;
946 }
947 
948 const VarRegion *MemRegionManager::getVarRegion(const VarDecl *D,
949                                                 const LocationContext *LC) {
950   const auto *PVD = dyn_cast<ParmVarDecl>(D);
951   if (PVD) {
952     unsigned Index = PVD->getFunctionScopeIndex();
953     const StackFrameContext *SFC = LC->getStackFrame();
954     const Stmt *CallSite = SFC->getCallSite();
955     if (CallSite) {
956       const Decl *D = SFC->getDecl();
957       if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
958         if (Index < FD->param_size() && FD->parameters()[Index] == PVD)
959           return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
960                                               getStackArgumentsRegion(SFC));
961       } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
962         if (Index < BD->param_size() && BD->parameters()[Index] == PVD)
963           return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
964                                               getStackArgumentsRegion(SFC));
965       } else {
966         return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
967                                             getStackArgumentsRegion(SFC));
968       }
969     }
970   }
971 
972   D = D->getCanonicalDecl();
973   const MemRegion *sReg = nullptr;
974 
975   if (D->hasGlobalStorage() && !D->isStaticLocal()) {
976 
977     // First handle the globals defined in system headers.
978     if (Ctx.getSourceManager().isInSystemHeader(D->getLocation())) {
979       //  Allow the system globals which often DO GET modified, assume the
980       // rest are immutable.
981       if (D->getName().contains("errno"))
982         sReg = getGlobalsRegion(MemRegion::GlobalSystemSpaceRegionKind);
983       else
984         sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
985 
986     // Treat other globals as GlobalInternal unless they are constants.
987     } else {
988       QualType GQT = D->getType();
989       const Type *GT = GQT.getTypePtrOrNull();
990       // TODO: We could walk the complex types here and see if everything is
991       // constified.
992       if (GT && GQT.isConstQualified() && GT->isArithmeticType())
993         sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
994       else
995         sReg = getGlobalsRegion();
996     }
997 
998   // Finally handle static locals.
999   } else {
1000     // FIXME: Once we implement scope handling, we will need to properly lookup
1001     // 'D' to the proper LocationContext.
1002     const DeclContext *DC = D->getDeclContext();
1003     llvm::PointerUnion<const StackFrameContext *, const VarRegion *> V =
1004       getStackOrCaptureRegionForDeclContext(LC, DC, D);
1005 
1006     if (V.is<const VarRegion*>())
1007       return V.get<const VarRegion*>();
1008 
1009     const auto *STC = V.get<const StackFrameContext *>();
1010 
1011     if (!STC) {
1012       // FIXME: Assign a more sensible memory space to static locals
1013       // we see from within blocks that we analyze as top-level declarations.
1014       sReg = getUnknownRegion();
1015     } else {
1016       if (D->hasLocalStorage()) {
1017         sReg =
1018             isa<ParmVarDecl, ImplicitParamDecl>(D)
1019                 ? static_cast<const MemRegion *>(getStackArgumentsRegion(STC))
1020                 : static_cast<const MemRegion *>(getStackLocalsRegion(STC));
1021       }
1022       else {
1023         assert(D->isStaticLocal());
1024         const Decl *STCD = STC->getDecl();
1025         if (isa<FunctionDecl, ObjCMethodDecl>(STCD))
1026           sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
1027                                   getFunctionCodeRegion(cast<NamedDecl>(STCD)));
1028         else if (const auto *BD = dyn_cast<BlockDecl>(STCD)) {
1029           // FIXME: The fallback type here is totally bogus -- though it should
1030           // never be queried, it will prevent uniquing with the real
1031           // BlockCodeRegion. Ideally we'd fix the AST so that we always had a
1032           // signature.
1033           QualType T;
1034           if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten())
1035             T = TSI->getType();
1036           if (T.isNull())
1037             T = getContext().VoidTy;
1038           if (!T->getAs<FunctionType>()) {
1039             FunctionProtoType::ExtProtoInfo Ext;
1040             T = getContext().getFunctionType(T, None, Ext);
1041           }
1042           T = getContext().getBlockPointerType(T);
1043 
1044           const BlockCodeRegion *BTR =
1045             getBlockCodeRegion(BD, Ctx.getCanonicalType(T),
1046                                STC->getAnalysisDeclContext());
1047           sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
1048                                   BTR);
1049         }
1050         else {
1051           sReg = getGlobalsRegion();
1052         }
1053       }
1054     }
1055   }
1056 
1057   return getSubRegion<NonParamVarRegion>(D, sReg);
1058 }
1059 
1060 const NonParamVarRegion *
1061 MemRegionManager::getNonParamVarRegion(const VarDecl *D,
1062                                        const MemRegion *superR) {
1063   D = D->getCanonicalDecl();
1064   return getSubRegion<NonParamVarRegion>(D, superR);
1065 }
1066 
1067 const ParamVarRegion *
1068 MemRegionManager::getParamVarRegion(const Expr *OriginExpr, unsigned Index,
1069                                     const LocationContext *LC) {
1070   const StackFrameContext *SFC = LC->getStackFrame();
1071   assert(SFC);
1072   return getSubRegion<ParamVarRegion>(OriginExpr, Index,
1073                                       getStackArgumentsRegion(SFC));
1074 }
1075 
1076 const BlockDataRegion *
1077 MemRegionManager::getBlockDataRegion(const BlockCodeRegion *BC,
1078                                      const LocationContext *LC,
1079                                      unsigned blockCount) {
1080   const MemSpaceRegion *sReg = nullptr;
1081   const BlockDecl *BD = BC->getDecl();
1082   if (!BD->hasCaptures()) {
1083     // This handles 'static' blocks.
1084     sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
1085   }
1086   else {
1087     if (LC) {
1088       // FIXME: Once we implement scope handling, we want the parent region
1089       // to be the scope.
1090       const StackFrameContext *STC = LC->getStackFrame();
1091       assert(STC);
1092       sReg = getStackLocalsRegion(STC);
1093     }
1094     else {
1095       // We allow 'LC' to be NULL for cases where want BlockDataRegions
1096       // without context-sensitivity.
1097       sReg = getUnknownRegion();
1098     }
1099   }
1100 
1101   return getSubRegion<BlockDataRegion>(BC, LC, blockCount, sReg);
1102 }
1103 
1104 const CXXTempObjectRegion *
1105 MemRegionManager::getCXXStaticTempObjectRegion(const Expr *Ex) {
1106   return getSubRegion<CXXTempObjectRegion>(
1107       Ex, getGlobalsRegion(MemRegion::GlobalInternalSpaceRegionKind, nullptr));
1108 }
1109 
1110 const CompoundLiteralRegion*
1111 MemRegionManager::getCompoundLiteralRegion(const CompoundLiteralExpr *CL,
1112                                            const LocationContext *LC) {
1113   const MemSpaceRegion *sReg = nullptr;
1114 
1115   if (CL->isFileScope())
1116     sReg = getGlobalsRegion();
1117   else {
1118     const StackFrameContext *STC = LC->getStackFrame();
1119     assert(STC);
1120     sReg = getStackLocalsRegion(STC);
1121   }
1122 
1123   return getSubRegion<CompoundLiteralRegion>(CL, sReg);
1124 }
1125 
1126 const ElementRegion*
1127 MemRegionManager::getElementRegion(QualType elementType, NonLoc Idx,
1128                                    const SubRegion* superRegion,
1129                                    ASTContext &Ctx){
1130   QualType T = Ctx.getCanonicalType(elementType).getUnqualifiedType();
1131 
1132   llvm::FoldingSetNodeID ID;
1133   ElementRegion::ProfileRegion(ID, T, Idx, superRegion);
1134 
1135   void *InsertPos;
1136   MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos);
1137   auto *R = cast_or_null<ElementRegion>(data);
1138 
1139   if (!R) {
1140     R = A.Allocate<ElementRegion>();
1141     new (R) ElementRegion(T, Idx, superRegion);
1142     Regions.InsertNode(R, InsertPos);
1143   }
1144 
1145   return R;
1146 }
1147 
1148 const FunctionCodeRegion *
1149 MemRegionManager::getFunctionCodeRegion(const NamedDecl *FD) {
1150   // To think: should we canonicalize the declaration here?
1151   return getSubRegion<FunctionCodeRegion>(FD, getCodeRegion());
1152 }
1153 
1154 const BlockCodeRegion *
1155 MemRegionManager::getBlockCodeRegion(const BlockDecl *BD, CanQualType locTy,
1156                                      AnalysisDeclContext *AC) {
1157   return getSubRegion<BlockCodeRegion>(BD, locTy, AC, getCodeRegion());
1158 }
1159 
1160 const SymbolicRegion *
1161 MemRegionManager::getSymbolicRegion(SymbolRef sym,
1162                                     const MemSpaceRegion *MemSpace) {
1163   if (MemSpace == nullptr)
1164     MemSpace = getUnknownRegion();
1165   return getSubRegion<SymbolicRegion>(sym, MemSpace);
1166 }
1167 
1168 const SymbolicRegion *MemRegionManager::getSymbolicHeapRegion(SymbolRef Sym) {
1169   return getSubRegion<SymbolicRegion>(Sym, getHeapRegion());
1170 }
1171 
1172 const FieldRegion*
1173 MemRegionManager::getFieldRegion(const FieldDecl *d,
1174                                  const SubRegion* superRegion){
1175   return getSubRegion<FieldRegion>(d, superRegion);
1176 }
1177 
1178 const ObjCIvarRegion*
1179 MemRegionManager::getObjCIvarRegion(const ObjCIvarDecl *d,
1180                                     const SubRegion* superRegion) {
1181   return getSubRegion<ObjCIvarRegion>(d, superRegion);
1182 }
1183 
1184 const CXXTempObjectRegion*
1185 MemRegionManager::getCXXTempObjectRegion(Expr const *E,
1186                                          LocationContext const *LC) {
1187   const StackFrameContext *SFC = LC->getStackFrame();
1188   assert(SFC);
1189   return getSubRegion<CXXTempObjectRegion>(E, getStackLocalsRegion(SFC));
1190 }
1191 
1192 /// Checks whether \p BaseClass is a valid virtual or direct non-virtual base
1193 /// class of the type of \p Super.
1194 static bool isValidBaseClass(const CXXRecordDecl *BaseClass,
1195                              const TypedValueRegion *Super,
1196                              bool IsVirtual) {
1197   BaseClass = BaseClass->getCanonicalDecl();
1198 
1199   const CXXRecordDecl *Class = Super->getValueType()->getAsCXXRecordDecl();
1200   if (!Class)
1201     return true;
1202 
1203   if (IsVirtual)
1204     return Class->isVirtuallyDerivedFrom(BaseClass);
1205 
1206   for (const auto &I : Class->bases()) {
1207     if (I.getType()->getAsCXXRecordDecl()->getCanonicalDecl() == BaseClass)
1208       return true;
1209   }
1210 
1211   return false;
1212 }
1213 
1214 const CXXBaseObjectRegion *
1215 MemRegionManager::getCXXBaseObjectRegion(const CXXRecordDecl *RD,
1216                                          const SubRegion *Super,
1217                                          bool IsVirtual) {
1218   if (isa<TypedValueRegion>(Super)) {
1219     assert(isValidBaseClass(RD, cast<TypedValueRegion>(Super), IsVirtual));
1220     (void)&isValidBaseClass;
1221 
1222     if (IsVirtual) {
1223       // Virtual base regions should not be layered, since the layout rules
1224       // are different.
1225       while (const auto *Base = dyn_cast<CXXBaseObjectRegion>(Super))
1226         Super = cast<SubRegion>(Base->getSuperRegion());
1227       assert(Super && !isa<MemSpaceRegion>(Super));
1228     }
1229   }
1230 
1231   return getSubRegion<CXXBaseObjectRegion>(RD, IsVirtual, Super);
1232 }
1233 
1234 const CXXDerivedObjectRegion *
1235 MemRegionManager::getCXXDerivedObjectRegion(const CXXRecordDecl *RD,
1236                                             const SubRegion *Super) {
1237   return getSubRegion<CXXDerivedObjectRegion>(RD, Super);
1238 }
1239 
1240 const CXXThisRegion*
1241 MemRegionManager::getCXXThisRegion(QualType thisPointerTy,
1242                                    const LocationContext *LC) {
1243   const auto *PT = thisPointerTy->getAs<PointerType>();
1244   assert(PT);
1245   // Inside the body of the operator() of a lambda a this expr might refer to an
1246   // object in one of the parent location contexts.
1247   const auto *D = dyn_cast<CXXMethodDecl>(LC->getDecl());
1248   // FIXME: when operator() of lambda is analyzed as a top level function and
1249   // 'this' refers to a this to the enclosing scope, there is no right region to
1250   // return.
1251   while (!LC->inTopFrame() && (!D || D->isStatic() ||
1252                                PT != D->getThisType()->getAs<PointerType>())) {
1253     LC = LC->getParent();
1254     D = dyn_cast<CXXMethodDecl>(LC->getDecl());
1255   }
1256   const StackFrameContext *STC = LC->getStackFrame();
1257   assert(STC);
1258   return getSubRegion<CXXThisRegion>(PT, getStackArgumentsRegion(STC));
1259 }
1260 
1261 const AllocaRegion*
1262 MemRegionManager::getAllocaRegion(const Expr *E, unsigned cnt,
1263                                   const LocationContext *LC) {
1264   const StackFrameContext *STC = LC->getStackFrame();
1265   assert(STC);
1266   return getSubRegion<AllocaRegion>(E, cnt, getStackLocalsRegion(STC));
1267 }
1268 
1269 const MemSpaceRegion *MemRegion::getMemorySpace() const {
1270   const MemRegion *R = this;
1271   const auto *SR = dyn_cast<SubRegion>(this);
1272 
1273   while (SR) {
1274     R = SR->getSuperRegion();
1275     SR = dyn_cast<SubRegion>(R);
1276   }
1277 
1278   return dyn_cast<MemSpaceRegion>(R);
1279 }
1280 
1281 bool MemRegion::hasStackStorage() const {
1282   return isa<StackSpaceRegion>(getMemorySpace());
1283 }
1284 
1285 bool MemRegion::hasStackNonParametersStorage() const {
1286   return isa<StackLocalsSpaceRegion>(getMemorySpace());
1287 }
1288 
1289 bool MemRegion::hasStackParametersStorage() const {
1290   return isa<StackArgumentsSpaceRegion>(getMemorySpace());
1291 }
1292 
1293 bool MemRegion::hasGlobalsOrParametersStorage() const {
1294   return isa<StackArgumentsSpaceRegion, GlobalsSpaceRegion>(getMemorySpace());
1295 }
1296 
1297 // getBaseRegion strips away all elements and fields, and get the base region
1298 // of them.
1299 const MemRegion *MemRegion::getBaseRegion() const {
1300   const MemRegion *R = this;
1301   while (true) {
1302     switch (R->getKind()) {
1303       case MemRegion::ElementRegionKind:
1304       case MemRegion::FieldRegionKind:
1305       case MemRegion::ObjCIvarRegionKind:
1306       case MemRegion::CXXBaseObjectRegionKind:
1307       case MemRegion::CXXDerivedObjectRegionKind:
1308         R = cast<SubRegion>(R)->getSuperRegion();
1309         continue;
1310       default:
1311         break;
1312     }
1313     break;
1314   }
1315   return R;
1316 }
1317 
1318 // getgetMostDerivedObjectRegion gets the region of the root class of a C++
1319 // class hierarchy.
1320 const MemRegion *MemRegion::getMostDerivedObjectRegion() const {
1321   const MemRegion *R = this;
1322   while (const auto *BR = dyn_cast<CXXBaseObjectRegion>(R))
1323     R = BR->getSuperRegion();
1324   return R;
1325 }
1326 
1327 bool MemRegion::isSubRegionOf(const MemRegion *) const {
1328   return false;
1329 }
1330 
1331 //===----------------------------------------------------------------------===//
1332 // View handling.
1333 //===----------------------------------------------------------------------===//
1334 
1335 const MemRegion *MemRegion::StripCasts(bool StripBaseAndDerivedCasts) const {
1336   const MemRegion *R = this;
1337   while (true) {
1338     switch (R->getKind()) {
1339     case ElementRegionKind: {
1340       const auto *ER = cast<ElementRegion>(R);
1341       if (!ER->getIndex().isZeroConstant())
1342         return R;
1343       R = ER->getSuperRegion();
1344       break;
1345     }
1346     case CXXBaseObjectRegionKind:
1347     case CXXDerivedObjectRegionKind:
1348       if (!StripBaseAndDerivedCasts)
1349         return R;
1350       R = cast<TypedValueRegion>(R)->getSuperRegion();
1351       break;
1352     default:
1353       return R;
1354     }
1355   }
1356 }
1357 
1358 const SymbolicRegion *MemRegion::getSymbolicBase() const {
1359   const auto *SubR = dyn_cast<SubRegion>(this);
1360 
1361   while (SubR) {
1362     if (const auto *SymR = dyn_cast<SymbolicRegion>(SubR))
1363       return SymR;
1364     SubR = dyn_cast<SubRegion>(SubR->getSuperRegion());
1365   }
1366   return nullptr;
1367 }
1368 
1369 RegionRawOffset ElementRegion::getAsArrayOffset() const {
1370   int64_t offset = 0;
1371   const ElementRegion *ER = this;
1372   const MemRegion *superR = nullptr;
1373   ASTContext &C = getContext();
1374 
1375   // FIXME: Handle multi-dimensional arrays.
1376 
1377   while (ER) {
1378     superR = ER->getSuperRegion();
1379 
1380     // FIXME: generalize to symbolic offsets.
1381     SVal index = ER->getIndex();
1382     if (auto CI = index.getAs<nonloc::ConcreteInt>()) {
1383       // Update the offset.
1384       int64_t i = CI->getValue().getSExtValue();
1385 
1386       if (i != 0) {
1387         QualType elemType = ER->getElementType();
1388 
1389         // If we are pointing to an incomplete type, go no further.
1390         if (elemType->isIncompleteType()) {
1391           superR = ER;
1392           break;
1393         }
1394 
1395         int64_t size = C.getTypeSizeInChars(elemType).getQuantity();
1396         if (auto NewOffset = llvm::checkedMulAdd(i, size, offset)) {
1397           offset = *NewOffset;
1398         } else {
1399           LLVM_DEBUG(llvm::dbgs() << "MemRegion::getAsArrayOffset: "
1400                                   << "offset overflowing, returning unknown\n");
1401 
1402           return nullptr;
1403         }
1404       }
1405 
1406       // Go to the next ElementRegion (if any).
1407       ER = dyn_cast<ElementRegion>(superR);
1408       continue;
1409     }
1410 
1411     return nullptr;
1412   }
1413 
1414   assert(superR && "super region cannot be NULL");
1415   return RegionRawOffset(superR, CharUnits::fromQuantity(offset));
1416 }
1417 
1418 /// Returns true if \p Base is an immediate base class of \p Child
1419 static bool isImmediateBase(const CXXRecordDecl *Child,
1420                             const CXXRecordDecl *Base) {
1421   assert(Child && "Child must not be null");
1422   // Note that we do NOT canonicalize the base class here, because
1423   // ASTRecordLayout doesn't either. If that leads us down the wrong path,
1424   // so be it; at least we won't crash.
1425   for (const auto &I : Child->bases()) {
1426     if (I.getType()->getAsCXXRecordDecl() == Base)
1427       return true;
1428   }
1429 
1430   return false;
1431 }
1432 
1433 static RegionOffset calculateOffset(const MemRegion *R) {
1434   const MemRegion *SymbolicOffsetBase = nullptr;
1435   int64_t Offset = 0;
1436 
1437   while (true) {
1438     switch (R->getKind()) {
1439     case MemRegion::CodeSpaceRegionKind:
1440     case MemRegion::StackLocalsSpaceRegionKind:
1441     case MemRegion::StackArgumentsSpaceRegionKind:
1442     case MemRegion::HeapSpaceRegionKind:
1443     case MemRegion::UnknownSpaceRegionKind:
1444     case MemRegion::StaticGlobalSpaceRegionKind:
1445     case MemRegion::GlobalInternalSpaceRegionKind:
1446     case MemRegion::GlobalSystemSpaceRegionKind:
1447     case MemRegion::GlobalImmutableSpaceRegionKind:
1448       // Stores can bind directly to a region space to set a default value.
1449       assert(Offset == 0 && !SymbolicOffsetBase);
1450       goto Finish;
1451 
1452     case MemRegion::FunctionCodeRegionKind:
1453     case MemRegion::BlockCodeRegionKind:
1454     case MemRegion::BlockDataRegionKind:
1455       // These will never have bindings, but may end up having values requested
1456       // if the user does some strange casting.
1457       if (Offset != 0)
1458         SymbolicOffsetBase = R;
1459       goto Finish;
1460 
1461     case MemRegion::SymbolicRegionKind:
1462     case MemRegion::AllocaRegionKind:
1463     case MemRegion::CompoundLiteralRegionKind:
1464     case MemRegion::CXXThisRegionKind:
1465     case MemRegion::StringRegionKind:
1466     case MemRegion::ObjCStringRegionKind:
1467     case MemRegion::NonParamVarRegionKind:
1468     case MemRegion::ParamVarRegionKind:
1469     case MemRegion::CXXTempObjectRegionKind:
1470       // Usual base regions.
1471       goto Finish;
1472 
1473     case MemRegion::ObjCIvarRegionKind:
1474       // This is a little strange, but it's a compromise between
1475       // ObjCIvarRegions having unknown compile-time offsets (when using the
1476       // non-fragile runtime) and yet still being distinct, non-overlapping
1477       // regions. Thus we treat them as "like" base regions for the purposes
1478       // of computing offsets.
1479       goto Finish;
1480 
1481     case MemRegion::CXXBaseObjectRegionKind: {
1482       const auto *BOR = cast<CXXBaseObjectRegion>(R);
1483       R = BOR->getSuperRegion();
1484 
1485       QualType Ty;
1486       bool RootIsSymbolic = false;
1487       if (const auto *TVR = dyn_cast<TypedValueRegion>(R)) {
1488         Ty = TVR->getDesugaredValueType(R->getContext());
1489       } else if (const auto *SR = dyn_cast<SymbolicRegion>(R)) {
1490         // If our base region is symbolic, we don't know what type it really is.
1491         // Pretend the type of the symbol is the true dynamic type.
1492         // (This will at least be self-consistent for the life of the symbol.)
1493         Ty = SR->getSymbol()->getType()->getPointeeType();
1494         RootIsSymbolic = true;
1495       }
1496 
1497       const CXXRecordDecl *Child = Ty->getAsCXXRecordDecl();
1498       if (!Child) {
1499         // We cannot compute the offset of the base class.
1500         SymbolicOffsetBase = R;
1501       } else {
1502         if (RootIsSymbolic) {
1503           // Base layers on symbolic regions may not be type-correct.
1504           // Double-check the inheritance here, and revert to a symbolic offset
1505           // if it's invalid (e.g. due to a reinterpret_cast).
1506           if (BOR->isVirtual()) {
1507             if (!Child->isVirtuallyDerivedFrom(BOR->getDecl()))
1508               SymbolicOffsetBase = R;
1509           } else {
1510             if (!isImmediateBase(Child, BOR->getDecl()))
1511               SymbolicOffsetBase = R;
1512           }
1513         }
1514       }
1515 
1516       // Don't bother calculating precise offsets if we already have a
1517       // symbolic offset somewhere in the chain.
1518       if (SymbolicOffsetBase)
1519         continue;
1520 
1521       CharUnits BaseOffset;
1522       const ASTRecordLayout &Layout = R->getContext().getASTRecordLayout(Child);
1523       if (BOR->isVirtual())
1524         BaseOffset = Layout.getVBaseClassOffset(BOR->getDecl());
1525       else
1526         BaseOffset = Layout.getBaseClassOffset(BOR->getDecl());
1527 
1528       // The base offset is in chars, not in bits.
1529       Offset += BaseOffset.getQuantity() * R->getContext().getCharWidth();
1530       break;
1531     }
1532 
1533     case MemRegion::CXXDerivedObjectRegionKind: {
1534       // TODO: Store the base type in the CXXDerivedObjectRegion and use it.
1535       goto Finish;
1536     }
1537 
1538     case MemRegion::ElementRegionKind: {
1539       const auto *ER = cast<ElementRegion>(R);
1540       R = ER->getSuperRegion();
1541 
1542       QualType EleTy = ER->getValueType();
1543       if (EleTy->isIncompleteType()) {
1544         // We cannot compute the offset of the base class.
1545         SymbolicOffsetBase = R;
1546         continue;
1547       }
1548 
1549       SVal Index = ER->getIndex();
1550       if (Optional<nonloc::ConcreteInt> CI =
1551               Index.getAs<nonloc::ConcreteInt>()) {
1552         // Don't bother calculating precise offsets if we already have a
1553         // symbolic offset somewhere in the chain.
1554         if (SymbolicOffsetBase)
1555           continue;
1556 
1557         int64_t i = CI->getValue().getSExtValue();
1558         // This type size is in bits.
1559         Offset += i * R->getContext().getTypeSize(EleTy);
1560       } else {
1561         // We cannot compute offset for non-concrete index.
1562         SymbolicOffsetBase = R;
1563       }
1564       break;
1565     }
1566     case MemRegion::FieldRegionKind: {
1567       const auto *FR = cast<FieldRegion>(R);
1568       R = FR->getSuperRegion();
1569       assert(R);
1570 
1571       const RecordDecl *RD = FR->getDecl()->getParent();
1572       if (RD->isUnion() || !RD->isCompleteDefinition()) {
1573         // We cannot compute offset for incomplete type.
1574         // For unions, we could treat everything as offset 0, but we'd rather
1575         // treat each field as a symbolic offset so they aren't stored on top
1576         // of each other, since we depend on things in typed regions actually
1577         // matching their types.
1578         SymbolicOffsetBase = R;
1579       }
1580 
1581       // Don't bother calculating precise offsets if we already have a
1582       // symbolic offset somewhere in the chain.
1583       if (SymbolicOffsetBase)
1584         continue;
1585 
1586       // Get the field number.
1587       unsigned idx = 0;
1588       for (RecordDecl::field_iterator FI = RD->field_begin(),
1589              FE = RD->field_end(); FI != FE; ++FI, ++idx) {
1590         if (FR->getDecl() == *FI)
1591           break;
1592       }
1593       const ASTRecordLayout &Layout = R->getContext().getASTRecordLayout(RD);
1594       // This is offset in bits.
1595       Offset += Layout.getFieldOffset(idx);
1596       break;
1597     }
1598     }
1599   }
1600 
1601  Finish:
1602   if (SymbolicOffsetBase)
1603     return RegionOffset(SymbolicOffsetBase, RegionOffset::Symbolic);
1604   return RegionOffset(R, Offset);
1605 }
1606 
1607 RegionOffset MemRegion::getAsOffset() const {
1608   if (!cachedOffset)
1609     cachedOffset = calculateOffset(this);
1610   return *cachedOffset;
1611 }
1612 
1613 //===----------------------------------------------------------------------===//
1614 // BlockDataRegion
1615 //===----------------------------------------------------------------------===//
1616 
1617 std::pair<const VarRegion *, const VarRegion *>
1618 BlockDataRegion::getCaptureRegions(const VarDecl *VD) {
1619   MemRegionManager &MemMgr = getMemRegionManager();
1620   const VarRegion *VR = nullptr;
1621   const VarRegion *OriginalVR = nullptr;
1622 
1623   if (!VD->hasAttr<BlocksAttr>() && VD->hasLocalStorage()) {
1624     VR = MemMgr.getNonParamVarRegion(VD, this);
1625     OriginalVR = MemMgr.getVarRegion(VD, LC);
1626   }
1627   else {
1628     if (LC) {
1629       VR = MemMgr.getVarRegion(VD, LC);
1630       OriginalVR = VR;
1631     }
1632     else {
1633       VR = MemMgr.getNonParamVarRegion(VD, MemMgr.getUnknownRegion());
1634       OriginalVR = MemMgr.getVarRegion(VD, LC);
1635     }
1636   }
1637   return std::make_pair(VR, OriginalVR);
1638 }
1639 
1640 void BlockDataRegion::LazyInitializeReferencedVars() {
1641   if (ReferencedVars)
1642     return;
1643 
1644   AnalysisDeclContext *AC = getCodeRegion()->getAnalysisDeclContext();
1645   const auto &ReferencedBlockVars = AC->getReferencedBlockVars(BC->getDecl());
1646   auto NumBlockVars =
1647       std::distance(ReferencedBlockVars.begin(), ReferencedBlockVars.end());
1648 
1649   if (NumBlockVars == 0) {
1650     ReferencedVars = (void*) 0x1;
1651     return;
1652   }
1653 
1654   MemRegionManager &MemMgr = getMemRegionManager();
1655   llvm::BumpPtrAllocator &A = MemMgr.getAllocator();
1656   BumpVectorContext BC(A);
1657 
1658   using VarVec = BumpVector<const MemRegion *>;
1659 
1660   auto *BV = A.Allocate<VarVec>();
1661   new (BV) VarVec(BC, NumBlockVars);
1662   auto *BVOriginal = A.Allocate<VarVec>();
1663   new (BVOriginal) VarVec(BC, NumBlockVars);
1664 
1665   for (const auto *VD : ReferencedBlockVars) {
1666     const VarRegion *VR = nullptr;
1667     const VarRegion *OriginalVR = nullptr;
1668     std::tie(VR, OriginalVR) = getCaptureRegions(VD);
1669     assert(VR);
1670     assert(OriginalVR);
1671     BV->push_back(VR, BC);
1672     BVOriginal->push_back(OriginalVR, BC);
1673   }
1674 
1675   ReferencedVars = BV;
1676   OriginalVars = BVOriginal;
1677 }
1678 
1679 BlockDataRegion::referenced_vars_iterator
1680 BlockDataRegion::referenced_vars_begin() const {
1681   const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1682 
1683   auto *Vec = static_cast<BumpVector<const MemRegion *> *>(ReferencedVars);
1684 
1685   if (Vec == (void*) 0x1)
1686     return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1687 
1688   auto *VecOriginal =
1689       static_cast<BumpVector<const MemRegion *> *>(OriginalVars);
1690 
1691   return BlockDataRegion::referenced_vars_iterator(Vec->begin(),
1692                                                    VecOriginal->begin());
1693 }
1694 
1695 BlockDataRegion::referenced_vars_iterator
1696 BlockDataRegion::referenced_vars_end() const {
1697   const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1698 
1699   auto *Vec = static_cast<BumpVector<const MemRegion *> *>(ReferencedVars);
1700 
1701   if (Vec == (void*) 0x1)
1702     return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1703 
1704   auto *VecOriginal =
1705       static_cast<BumpVector<const MemRegion *> *>(OriginalVars);
1706 
1707   return BlockDataRegion::referenced_vars_iterator(Vec->end(),
1708                                                    VecOriginal->end());
1709 }
1710 
1711 const VarRegion *BlockDataRegion::getOriginalRegion(const VarRegion *R) const {
1712   for (referenced_vars_iterator I = referenced_vars_begin(),
1713                                 E = referenced_vars_end();
1714        I != E; ++I) {
1715     if (I.getCapturedRegion() == R)
1716       return I.getOriginalRegion();
1717   }
1718   return nullptr;
1719 }
1720 
1721 //===----------------------------------------------------------------------===//
1722 // RegionAndSymbolInvalidationTraits
1723 //===----------------------------------------------------------------------===//
1724 
1725 void RegionAndSymbolInvalidationTraits::setTrait(SymbolRef Sym,
1726                                                  InvalidationKinds IK) {
1727   SymTraitsMap[Sym] |= IK;
1728 }
1729 
1730 void RegionAndSymbolInvalidationTraits::setTrait(const MemRegion *MR,
1731                                                  InvalidationKinds IK) {
1732   assert(MR);
1733   if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1734     setTrait(SR->getSymbol(), IK);
1735   else
1736     MRTraitsMap[MR] |= IK;
1737 }
1738 
1739 bool RegionAndSymbolInvalidationTraits::hasTrait(SymbolRef Sym,
1740                                                  InvalidationKinds IK) const {
1741   const_symbol_iterator I = SymTraitsMap.find(Sym);
1742   if (I != SymTraitsMap.end())
1743     return I->second & IK;
1744 
1745   return false;
1746 }
1747 
1748 bool RegionAndSymbolInvalidationTraits::hasTrait(const MemRegion *MR,
1749                                                  InvalidationKinds IK) const {
1750   if (!MR)
1751     return false;
1752 
1753   if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1754     return hasTrait(SR->getSymbol(), IK);
1755 
1756   const_region_iterator I = MRTraitsMap.find(MR);
1757   if (I != MRTraitsMap.end())
1758     return I->second & IK;
1759 
1760   return false;
1761 }
1762