MemRegion.cpp 51 KB

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