ExprEngine.cpp 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107
  1. //===- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ----------===//
  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 a meta-engine for path-sensitive dataflow analysis that
  11. // is built on GREngine, but provides the boilerplate to execute transfer
  12. // functions and build the ExplodedGraph at the expression level.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  16. #include "PrettyStackTraceLocationContext.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclBase.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/ExprObjC.h"
  25. #include "clang/AST/ParentMap.h"
  26. #include "clang/AST/PrettyPrinter.h"
  27. #include "clang/AST/Stmt.h"
  28. #include "clang/AST/StmtCXX.h"
  29. #include "clang/AST/StmtObjC.h"
  30. #include "clang/AST/Type.h"
  31. #include "clang/Analysis/AnalysisDeclContext.h"
  32. #include "clang/Analysis/CFG.h"
  33. #include "clang/Analysis/ConstructionContext.h"
  34. #include "clang/Analysis/ProgramPoint.h"
  35. #include "clang/Basic/IdentifierTable.h"
  36. #include "clang/Basic/LLVM.h"
  37. #include "clang/Basic/LangOptions.h"
  38. #include "clang/Basic/PrettyStackTrace.h"
  39. #include "clang/Basic/SourceLocation.h"
  40. #include "clang/Basic/SourceManager.h"
  41. #include "clang/Basic/Specifiers.h"
  42. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  43. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  44. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  45. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  46. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  47. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  48. #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
  49. #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
  50. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  51. #include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
  52. #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
  53. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  54. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  55. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  56. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
  57. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  58. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  59. #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
  60. #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
  61. #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
  62. #include "llvm/ADT/APSInt.h"
  63. #include "llvm/ADT/DenseMap.h"
  64. #include "llvm/ADT/ImmutableMap.h"
  65. #include "llvm/ADT/ImmutableSet.h"
  66. #include "llvm/ADT/Optional.h"
  67. #include "llvm/ADT/SmallVector.h"
  68. #include "llvm/ADT/Statistic.h"
  69. #include "llvm/Support/Casting.h"
  70. #include "llvm/Support/Compiler.h"
  71. #include "llvm/Support/DOTGraphTraits.h"
  72. #include "llvm/Support/ErrorHandling.h"
  73. #include "llvm/Support/GraphWriter.h"
  74. #include "llvm/Support/SaveAndRestore.h"
  75. #include "llvm/Support/raw_ostream.h"
  76. #include <cassert>
  77. #include <cstdint>
  78. #include <memory>
  79. #include <string>
  80. #include <tuple>
  81. #include <utility>
  82. #include <vector>
  83. using namespace clang;
  84. using namespace ento;
  85. #define DEBUG_TYPE "ExprEngine"
  86. STATISTIC(NumRemoveDeadBindings,
  87. "The # of times RemoveDeadBindings is called");
  88. STATISTIC(NumMaxBlockCountReached,
  89. "The # of aborted paths due to reaching the maximum block count in "
  90. "a top level function");
  91. STATISTIC(NumMaxBlockCountReachedInInlined,
  92. "The # of aborted paths due to reaching the maximum block count in "
  93. "an inlined function");
  94. STATISTIC(NumTimesRetriedWithoutInlining,
  95. "The # of times we re-evaluated a call without inlining");
  96. //===----------------------------------------------------------------------===//
  97. // Internal program state traits.
  98. //===----------------------------------------------------------------------===//
  99. namespace {
  100. // When modeling a C++ constructor, for a variety of reasons we need to track
  101. // the location of the object for the duration of its ConstructionContext.
  102. // ObjectsUnderConstruction maps statements within the construction context
  103. // to the object's location, so that on every such statement the location
  104. // could have been retrieved.
  105. /// ConstructedObjectKey is used for being able to find the path-sensitive
  106. /// memory region of a freshly constructed object while modeling the AST node
  107. /// that syntactically represents the object that is being constructed.
  108. /// Semantics of such nodes may sometimes require access to the region that's
  109. /// not otherwise present in the program state, or to the very fact that
  110. /// the construction context was present and contained references to these
  111. /// AST nodes.
  112. class ConstructedObjectKey {
  113. typedef std::pair<ConstructionContextItem, const LocationContext *>
  114. ConstructedObjectKeyImpl;
  115. const ConstructedObjectKeyImpl Impl;
  116. const void *getAnyASTNodePtr() const {
  117. if (const Stmt *S = getItem().getStmtOrNull())
  118. return S;
  119. else
  120. return getItem().getCXXCtorInitializer();
  121. }
  122. public:
  123. explicit ConstructedObjectKey(const ConstructionContextItem &Item,
  124. const LocationContext *LC)
  125. : Impl(Item, LC) {}
  126. const ConstructionContextItem &getItem() const { return Impl.first; }
  127. const LocationContext *getLocationContext() const { return Impl.second; }
  128. void print(llvm::raw_ostream &OS, PrinterHelper *Helper, PrintingPolicy &PP) {
  129. OS << '(' << getLocationContext() << ',' << getAnyASTNodePtr() << ','
  130. << getItem().getKindAsString();
  131. if (getItem().getKind() == ConstructionContextItem::ArgumentKind)
  132. OS << " #" << getItem().getIndex();
  133. OS << ") ";
  134. if (const Stmt *S = getItem().getStmtOrNull()) {
  135. S->printPretty(OS, Helper, PP);
  136. } else {
  137. const CXXCtorInitializer *I = getItem().getCXXCtorInitializer();
  138. OS << I->getAnyMember()->getNameAsString();
  139. }
  140. }
  141. void Profile(llvm::FoldingSetNodeID &ID) const {
  142. ID.Add(Impl.first);
  143. ID.AddPointer(Impl.second);
  144. }
  145. bool operator==(const ConstructedObjectKey &RHS) const {
  146. return Impl == RHS.Impl;
  147. }
  148. bool operator<(const ConstructedObjectKey &RHS) const {
  149. return Impl < RHS.Impl;
  150. }
  151. };
  152. } // namespace
  153. typedef llvm::ImmutableMap<ConstructedObjectKey, SVal>
  154. ObjectsUnderConstructionMap;
  155. REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
  156. ObjectsUnderConstructionMap)
  157. //===----------------------------------------------------------------------===//
  158. // Engine construction and deletion.
  159. //===----------------------------------------------------------------------===//
  160. static const char* TagProviderName = "ExprEngine";
  161. ExprEngine::ExprEngine(cross_tu::CrossTranslationUnitContext &CTU,
  162. AnalysisManager &mgr,
  163. SetOfConstDecls *VisitedCalleesIn,
  164. FunctionSummariesTy *FS,
  165. InliningModes HowToInlineIn)
  166. : CTU(CTU), AMgr(mgr),
  167. AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
  168. Engine(*this, FS, mgr.getAnalyzerOptions()), G(Engine.getGraph()),
  169. StateMgr(getContext(), mgr.getStoreManagerCreator(),
  170. mgr.getConstraintManagerCreator(), G.getAllocator(),
  171. this),
  172. SymMgr(StateMgr.getSymbolManager()),
  173. svalBuilder(StateMgr.getSValBuilder()), ObjCNoRet(mgr.getASTContext()),
  174. BR(mgr, *this),
  175. VisitedCallees(VisitedCalleesIn), HowToInline(HowToInlineIn) {
  176. unsigned TrimInterval = mgr.options.getGraphTrimInterval();
  177. if (TrimInterval != 0) {
  178. // Enable eager node reclaimation when constructing the ExplodedGraph.
  179. G.enableNodeReclamation(TrimInterval);
  180. }
  181. }
  182. ExprEngine::~ExprEngine() {
  183. BR.FlushReports();
  184. }
  185. //===----------------------------------------------------------------------===//
  186. // Utility methods.
  187. //===----------------------------------------------------------------------===//
  188. ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
  189. ProgramStateRef state = StateMgr.getInitialState(InitLoc);
  190. const Decl *D = InitLoc->getDecl();
  191. // Preconditions.
  192. // FIXME: It would be nice if we had a more general mechanism to add
  193. // such preconditions. Some day.
  194. do {
  195. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  196. // Precondition: the first argument of 'main' is an integer guaranteed
  197. // to be > 0.
  198. const IdentifierInfo *II = FD->getIdentifier();
  199. if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
  200. break;
  201. const ParmVarDecl *PD = FD->getParamDecl(0);
  202. QualType T = PD->getType();
  203. const auto *BT = dyn_cast<BuiltinType>(T);
  204. if (!BT || !BT->isInteger())
  205. break;
  206. const MemRegion *R = state->getRegion(PD, InitLoc);
  207. if (!R)
  208. break;
  209. SVal V = state->getSVal(loc::MemRegionVal(R));
  210. SVal Constraint_untested = evalBinOp(state, BO_GT, V,
  211. svalBuilder.makeZeroVal(T),
  212. svalBuilder.getConditionType());
  213. Optional<DefinedOrUnknownSVal> Constraint =
  214. Constraint_untested.getAs<DefinedOrUnknownSVal>();
  215. if (!Constraint)
  216. break;
  217. if (ProgramStateRef newState = state->assume(*Constraint, true))
  218. state = newState;
  219. }
  220. break;
  221. }
  222. while (false);
  223. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  224. // Precondition: 'self' is always non-null upon entry to an Objective-C
  225. // method.
  226. const ImplicitParamDecl *SelfD = MD->getSelfDecl();
  227. const MemRegion *R = state->getRegion(SelfD, InitLoc);
  228. SVal V = state->getSVal(loc::MemRegionVal(R));
  229. if (Optional<Loc> LV = V.getAs<Loc>()) {
  230. // Assume that the pointer value in 'self' is non-null.
  231. state = state->assume(*LV, true);
  232. assert(state && "'self' cannot be null");
  233. }
  234. }
  235. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  236. if (!MD->isStatic()) {
  237. // Precondition: 'this' is always non-null upon entry to the
  238. // top-level function. This is our starting assumption for
  239. // analyzing an "open" program.
  240. const StackFrameContext *SFC = InitLoc->getStackFrame();
  241. if (SFC->getParent() == nullptr) {
  242. loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
  243. SVal V = state->getSVal(L);
  244. if (Optional<Loc> LV = V.getAs<Loc>()) {
  245. state = state->assume(*LV, true);
  246. assert(state && "'this' cannot be null");
  247. }
  248. }
  249. }
  250. }
  251. return state;
  252. }
  253. ProgramStateRef ExprEngine::createTemporaryRegionIfNeeded(
  254. ProgramStateRef State, const LocationContext *LC,
  255. const Expr *InitWithAdjustments, const Expr *Result,
  256. const SubRegion **OutRegionWithAdjustments) {
  257. // FIXME: This function is a hack that works around the quirky AST
  258. // we're often having with respect to C++ temporaries. If only we modelled
  259. // the actual execution order of statements properly in the CFG,
  260. // all the hassle with adjustments would not be necessary,
  261. // and perhaps the whole function would be removed.
  262. SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
  263. if (!Result) {
  264. // If we don't have an explicit result expression, we're in "if needed"
  265. // mode. Only create a region if the current value is a NonLoc.
  266. if (!InitValWithAdjustments.getAs<NonLoc>()) {
  267. if (OutRegionWithAdjustments)
  268. *OutRegionWithAdjustments = nullptr;
  269. return State;
  270. }
  271. Result = InitWithAdjustments;
  272. } else {
  273. // We need to create a region no matter what. For sanity, make sure we don't
  274. // try to stuff a Loc into a non-pointer temporary region.
  275. assert(!InitValWithAdjustments.getAs<Loc>() ||
  276. Loc::isLocType(Result->getType()) ||
  277. Result->getType()->isMemberPointerType());
  278. }
  279. ProgramStateManager &StateMgr = State->getStateManager();
  280. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  281. StoreManager &StoreMgr = StateMgr.getStoreManager();
  282. // MaterializeTemporaryExpr may appear out of place, after a few field and
  283. // base-class accesses have been made to the object, even though semantically
  284. // it is the whole object that gets materialized and lifetime-extended.
  285. //
  286. // For example:
  287. //
  288. // `-MaterializeTemporaryExpr
  289. // `-MemberExpr
  290. // `-CXXTemporaryObjectExpr
  291. //
  292. // instead of the more natural
  293. //
  294. // `-MemberExpr
  295. // `-MaterializeTemporaryExpr
  296. // `-CXXTemporaryObjectExpr
  297. //
  298. // Use the usual methods for obtaining the expression of the base object,
  299. // and record the adjustments that we need to make to obtain the sub-object
  300. // that the whole expression 'Ex' refers to. This trick is usual,
  301. // in the sense that CodeGen takes a similar route.
  302. SmallVector<const Expr *, 2> CommaLHSs;
  303. SmallVector<SubobjectAdjustment, 2> Adjustments;
  304. const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
  305. CommaLHSs, Adjustments);
  306. // Take the region for Init, i.e. for the whole object. If we do not remember
  307. // the region in which the object originally was constructed, come up with
  308. // a new temporary region out of thin air and copy the contents of the object
  309. // (which are currently present in the Environment, because Init is an rvalue)
  310. // into that region. This is not correct, but it is better than nothing.
  311. const TypedValueRegion *TR = nullptr;
  312. if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) {
  313. if (Optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) {
  314. State = finishObjectConstruction(State, MT, LC);
  315. State = State->BindExpr(Result, LC, *V);
  316. return State;
  317. } else {
  318. StorageDuration SD = MT->getStorageDuration();
  319. // If this object is bound to a reference with static storage duration, we
  320. // put it in a different region to prevent "address leakage" warnings.
  321. if (SD == SD_Static || SD == SD_Thread) {
  322. TR = MRMgr.getCXXStaticTempObjectRegion(Init);
  323. } else {
  324. TR = MRMgr.getCXXTempObjectRegion(Init, LC);
  325. }
  326. }
  327. } else {
  328. TR = MRMgr.getCXXTempObjectRegion(Init, LC);
  329. }
  330. SVal Reg = loc::MemRegionVal(TR);
  331. SVal BaseReg = Reg;
  332. // Make the necessary adjustments to obtain the sub-object.
  333. for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
  334. const SubobjectAdjustment &Adj = *I;
  335. switch (Adj.Kind) {
  336. case SubobjectAdjustment::DerivedToBaseAdjustment:
  337. Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
  338. break;
  339. case SubobjectAdjustment::FieldAdjustment:
  340. Reg = StoreMgr.getLValueField(Adj.Field, Reg);
  341. break;
  342. case SubobjectAdjustment::MemberPointerAdjustment:
  343. // FIXME: Unimplemented.
  344. State = State->invalidateRegions(Reg, InitWithAdjustments,
  345. currBldrCtx->blockCount(), LC, true,
  346. nullptr, nullptr, nullptr);
  347. return State;
  348. }
  349. }
  350. // What remains is to copy the value of the object to the new region.
  351. // FIXME: In other words, what we should always do is copy value of the
  352. // Init expression (which corresponds to the bigger object) to the whole
  353. // temporary region TR. However, this value is often no longer present
  354. // in the Environment. If it has disappeared, we instead invalidate TR.
  355. // Still, what we can do is assign the value of expression Ex (which
  356. // corresponds to the sub-object) to the TR's sub-region Reg. At least,
  357. // values inside Reg would be correct.
  358. SVal InitVal = State->getSVal(Init, LC);
  359. if (InitVal.isUnknown()) {
  360. InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
  361. currBldrCtx->blockCount());
  362. State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
  363. // Then we'd need to take the value that certainly exists and bind it
  364. // over.
  365. if (InitValWithAdjustments.isUnknown()) {
  366. // Try to recover some path sensitivity in case we couldn't
  367. // compute the value.
  368. InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
  369. Result, LC, InitWithAdjustments->getType(),
  370. currBldrCtx->blockCount());
  371. }
  372. State =
  373. State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
  374. } else {
  375. State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
  376. }
  377. // The result expression would now point to the correct sub-region of the
  378. // newly created temporary region. Do this last in order to getSVal of Init
  379. // correctly in case (Result == Init).
  380. if (Result->isGLValue()) {
  381. State = State->BindExpr(Result, LC, Reg);
  382. } else {
  383. State = State->BindExpr(Result, LC, InitValWithAdjustments);
  384. }
  385. // Notify checkers once for two bindLoc()s.
  386. State = processRegionChange(State, TR, LC);
  387. if (OutRegionWithAdjustments)
  388. *OutRegionWithAdjustments = cast<SubRegion>(Reg.getAsRegion());
  389. return State;
  390. }
  391. ProgramStateRef
  392. ExprEngine::addObjectUnderConstruction(ProgramStateRef State,
  393. const ConstructionContextItem &Item,
  394. const LocationContext *LC, SVal V) {
  395. ConstructedObjectKey Key(Item, LC->getStackFrame());
  396. // FIXME: Currently the state might already contain the marker due to
  397. // incorrect handling of temporaries bound to default parameters.
  398. assert(!State->get<ObjectsUnderConstruction>(Key) ||
  399. Key.getItem().getKind() ==
  400. ConstructionContextItem::TemporaryDestructorKind);
  401. return State->set<ObjectsUnderConstruction>(Key, V);
  402. }
  403. Optional<SVal>
  404. ExprEngine::getObjectUnderConstruction(ProgramStateRef State,
  405. const ConstructionContextItem &Item,
  406. const LocationContext *LC) {
  407. ConstructedObjectKey Key(Item, LC->getStackFrame());
  408. return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key));
  409. }
  410. ProgramStateRef
  411. ExprEngine::finishObjectConstruction(ProgramStateRef State,
  412. const ConstructionContextItem &Item,
  413. const LocationContext *LC) {
  414. ConstructedObjectKey Key(Item, LC->getStackFrame());
  415. assert(State->contains<ObjectsUnderConstruction>(Key));
  416. return State->remove<ObjectsUnderConstruction>(Key);
  417. }
  418. ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State,
  419. const CXXBindTemporaryExpr *BTE,
  420. const LocationContext *LC) {
  421. ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
  422. // FIXME: Currently the state might already contain the marker due to
  423. // incorrect handling of temporaries bound to default parameters.
  424. return State->set<ObjectsUnderConstruction>(Key, UnknownVal());
  425. }
  426. ProgramStateRef
  427. ExprEngine::cleanupElidedDestructor(ProgramStateRef State,
  428. const CXXBindTemporaryExpr *BTE,
  429. const LocationContext *LC) {
  430. ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
  431. assert(State->contains<ObjectsUnderConstruction>(Key));
  432. return State->remove<ObjectsUnderConstruction>(Key);
  433. }
  434. bool ExprEngine::isDestructorElided(ProgramStateRef State,
  435. const CXXBindTemporaryExpr *BTE,
  436. const LocationContext *LC) {
  437. ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
  438. return State->contains<ObjectsUnderConstruction>(Key);
  439. }
  440. bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State,
  441. const LocationContext *FromLC,
  442. const LocationContext *ToLC) {
  443. const LocationContext *LC = FromLC;
  444. while (LC != ToLC) {
  445. assert(LC && "ToLC must be a parent of FromLC!");
  446. for (auto I : State->get<ObjectsUnderConstruction>())
  447. if (I.first.getLocationContext() == LC)
  448. return false;
  449. LC = LC->getParent();
  450. }
  451. return true;
  452. }
  453. //===----------------------------------------------------------------------===//
  454. // Top-level transfer function logic (Dispatcher).
  455. //===----------------------------------------------------------------------===//
  456. /// evalAssume - Called by ConstraintManager. Used to call checker-specific
  457. /// logic for handling assumptions on symbolic values.
  458. ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
  459. SVal cond, bool assumption) {
  460. return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
  461. }
  462. ProgramStateRef
  463. ExprEngine::processRegionChanges(ProgramStateRef state,
  464. const InvalidatedSymbols *invalidated,
  465. ArrayRef<const MemRegion *> Explicits,
  466. ArrayRef<const MemRegion *> Regions,
  467. const LocationContext *LCtx,
  468. const CallEvent *Call) {
  469. return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
  470. Explicits, Regions,
  471. LCtx, Call);
  472. }
  473. static void printObjectsUnderConstructionForContext(raw_ostream &Out,
  474. ProgramStateRef State,
  475. const char *NL,
  476. const LocationContext *LC) {
  477. PrintingPolicy PP =
  478. LC->getAnalysisDeclContext()->getASTContext().getPrintingPolicy();
  479. for (auto I : State->get<ObjectsUnderConstruction>()) {
  480. ConstructedObjectKey Key = I.first;
  481. SVal Value = I.second;
  482. if (Key.getLocationContext() != LC)
  483. continue;
  484. Key.print(Out, nullptr, PP);
  485. Out << " : " << Value << NL;
  486. }
  487. }
  488. void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
  489. const char *NL, const char *Sep,
  490. const LocationContext *LCtx) {
  491. if (LCtx) {
  492. if (!State->get<ObjectsUnderConstruction>().isEmpty()) {
  493. Out << Sep << "Objects under construction:" << NL;
  494. LCtx->dumpStack(Out, "", NL, Sep, [&](const LocationContext *LC) {
  495. printObjectsUnderConstructionForContext(Out, State, NL, LC);
  496. });
  497. }
  498. }
  499. getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
  500. }
  501. void ExprEngine::processEndWorklist() {
  502. getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
  503. }
  504. void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
  505. unsigned StmtIdx, NodeBuilderContext *Ctx) {
  506. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  507. currStmtIdx = StmtIdx;
  508. currBldrCtx = Ctx;
  509. switch (E.getKind()) {
  510. case CFGElement::Statement:
  511. case CFGElement::Constructor:
  512. case CFGElement::CXXRecordTypedCall:
  513. ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred);
  514. return;
  515. case CFGElement::Initializer:
  516. ProcessInitializer(E.castAs<CFGInitializer>(), Pred);
  517. return;
  518. case CFGElement::NewAllocator:
  519. ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
  520. Pred);
  521. return;
  522. case CFGElement::AutomaticObjectDtor:
  523. case CFGElement::DeleteDtor:
  524. case CFGElement::BaseDtor:
  525. case CFGElement::MemberDtor:
  526. case CFGElement::TemporaryDtor:
  527. ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
  528. return;
  529. case CFGElement::LoopExit:
  530. ProcessLoopExit(E.castAs<CFGLoopExit>().getLoopStmt(), Pred);
  531. return;
  532. case CFGElement::LifetimeEnds:
  533. case CFGElement::ScopeBegin:
  534. case CFGElement::ScopeEnd:
  535. return;
  536. }
  537. }
  538. static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
  539. const Stmt *S,
  540. const ExplodedNode *Pred,
  541. const LocationContext *LC) {
  542. // Are we never purging state values?
  543. if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
  544. return false;
  545. // Is this the beginning of a basic block?
  546. if (Pred->getLocation().getAs<BlockEntrance>())
  547. return true;
  548. // Is this on a non-expression?
  549. if (!isa<Expr>(S))
  550. return true;
  551. // Run before processing a call.
  552. if (CallEvent::isCallStmt(S))
  553. return true;
  554. // Is this an expression that is consumed by another expression? If so,
  555. // postpone cleaning out the state.
  556. ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
  557. return !PM.isConsumedExpr(cast<Expr>(S));
  558. }
  559. void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
  560. const Stmt *ReferenceStmt,
  561. const LocationContext *LC,
  562. const Stmt *DiagnosticStmt,
  563. ProgramPoint::Kind K) {
  564. assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
  565. ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
  566. && "PostStmt is not generally supported by the SymbolReaper yet");
  567. assert(LC && "Must pass the current (or expiring) LocationContext");
  568. if (!DiagnosticStmt) {
  569. DiagnosticStmt = ReferenceStmt;
  570. assert(DiagnosticStmt && "Required for clearing a LocationContext");
  571. }
  572. NumRemoveDeadBindings++;
  573. ProgramStateRef CleanedState = Pred->getState();
  574. // LC is the location context being destroyed, but SymbolReaper wants a
  575. // location context that is still live. (If this is the top-level stack
  576. // frame, this will be null.)
  577. if (!ReferenceStmt) {
  578. assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
  579. "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
  580. LC = LC->getParent();
  581. }
  582. const StackFrameContext *SFC = LC ? LC->getStackFrame() : nullptr;
  583. SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
  584. for (auto I : CleanedState->get<ObjectsUnderConstruction>()) {
  585. if (SymbolRef Sym = I.second.getAsSymbol())
  586. SymReaper.markLive(Sym);
  587. if (const MemRegion *MR = I.second.getAsRegion())
  588. SymReaper.markLive(MR);
  589. }
  590. getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
  591. // Create a state in which dead bindings are removed from the environment
  592. // and the store. TODO: The function should just return new env and store,
  593. // not a new state.
  594. CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
  595. // Process any special transfer function for dead symbols.
  596. // A tag to track convenience transitions, which can be removed at cleanup.
  597. static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
  598. // Call checkers with the non-cleaned state so that they could query the
  599. // values of the soon to be dead symbols.
  600. ExplodedNodeSet CheckedSet;
  601. getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
  602. DiagnosticStmt, *this, K);
  603. // For each node in CheckedSet, generate CleanedNodes that have the
  604. // environment, the store, and the constraints cleaned up but have the
  605. // user-supplied states as the predecessors.
  606. StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
  607. for (const auto I : CheckedSet) {
  608. ProgramStateRef CheckerState = I->getState();
  609. // The constraint manager has not been cleaned up yet, so clean up now.
  610. CheckerState =
  611. getConstraintManager().removeDeadBindings(CheckerState, SymReaper);
  612. assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
  613. "Checkers are not allowed to modify the Environment as a part of "
  614. "checkDeadSymbols processing.");
  615. assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
  616. "Checkers are not allowed to modify the Store as a part of "
  617. "checkDeadSymbols processing.");
  618. // Create a state based on CleanedState with CheckerState GDM and
  619. // generate a transition to that state.
  620. ProgramStateRef CleanedCheckerSt =
  621. StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
  622. Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, &cleanupTag, K);
  623. }
  624. }
  625. void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) {
  626. // Reclaim any unnecessary nodes in the ExplodedGraph.
  627. G.reclaimRecentlyAllocatedNodes();
  628. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  629. currStmt->getBeginLoc(),
  630. "Error evaluating statement");
  631. // Remove dead bindings and symbols.
  632. ExplodedNodeSet CleanedStates;
  633. if (shouldRemoveDeadBindings(AMgr, currStmt, Pred,
  634. Pred->getLocationContext())) {
  635. removeDead(Pred, CleanedStates, currStmt,
  636. Pred->getLocationContext());
  637. } else
  638. CleanedStates.Add(Pred);
  639. // Visit the statement.
  640. ExplodedNodeSet Dst;
  641. for (const auto I : CleanedStates) {
  642. ExplodedNodeSet DstI;
  643. // Visit the statement.
  644. Visit(currStmt, I, DstI);
  645. Dst.insert(DstI);
  646. }
  647. // Enqueue the new nodes onto the work list.
  648. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  649. }
  650. void ExprEngine::ProcessLoopExit(const Stmt* S, ExplodedNode *Pred) {
  651. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  652. S->getBeginLoc(),
  653. "Error evaluating end of the loop");
  654. ExplodedNodeSet Dst;
  655. Dst.Add(Pred);
  656. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  657. ProgramStateRef NewState = Pred->getState();
  658. if(AMgr.options.shouldUnrollLoops())
  659. NewState = processLoopEnd(S, NewState);
  660. LoopExit PP(S, Pred->getLocationContext());
  661. Bldr.generateNode(PP, NewState, Pred);
  662. // Enqueue the new nodes onto the work list.
  663. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  664. }
  665. void ExprEngine::ProcessInitializer(const CFGInitializer CFGInit,
  666. ExplodedNode *Pred) {
  667. const CXXCtorInitializer *BMI = CFGInit.getInitializer();
  668. const Expr *Init = BMI->getInit()->IgnoreImplicit();
  669. const LocationContext *LC = Pred->getLocationContext();
  670. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  671. BMI->getSourceLocation(),
  672. "Error evaluating initializer");
  673. // We don't clean up dead bindings here.
  674. const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext());
  675. const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
  676. ProgramStateRef State = Pred->getState();
  677. SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
  678. ExplodedNodeSet Tmp;
  679. SVal FieldLoc;
  680. // Evaluate the initializer, if necessary
  681. if (BMI->isAnyMemberInitializer()) {
  682. // Constructors build the object directly in the field,
  683. // but non-objects must be copied in from the initializer.
  684. if (getObjectUnderConstruction(State, BMI, LC)) {
  685. // The field was directly constructed, so there is no need to bind.
  686. // But we still need to stop tracking the object under construction.
  687. State = finishObjectConstruction(State, BMI, LC);
  688. NodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
  689. PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr);
  690. Bldr.generateNode(PS, State, Pred);
  691. } else {
  692. const ValueDecl *Field;
  693. if (BMI->isIndirectMemberInitializer()) {
  694. Field = BMI->getIndirectMember();
  695. FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
  696. } else {
  697. Field = BMI->getMember();
  698. FieldLoc = State->getLValue(BMI->getMember(), thisVal);
  699. }
  700. SVal InitVal;
  701. if (Init->getType()->isArrayType()) {
  702. // Handle arrays of trivial type. We can represent this with a
  703. // primitive load/copy from the base array region.
  704. const ArraySubscriptExpr *ASE;
  705. while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
  706. Init = ASE->getBase()->IgnoreImplicit();
  707. SVal LValue = State->getSVal(Init, stackFrame);
  708. if (!Field->getType()->isReferenceType())
  709. if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
  710. InitVal = State->getSVal(*LValueLoc);
  711. // If we fail to get the value for some reason, use a symbolic value.
  712. if (InitVal.isUnknownOrUndef()) {
  713. SValBuilder &SVB = getSValBuilder();
  714. InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
  715. Field->getType(),
  716. currBldrCtx->blockCount());
  717. }
  718. } else {
  719. InitVal = State->getSVal(BMI->getInit(), stackFrame);
  720. }
  721. PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
  722. evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
  723. }
  724. } else {
  725. assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
  726. Tmp.insert(Pred);
  727. // We already did all the work when visiting the CXXConstructExpr.
  728. }
  729. // Construct PostInitializer nodes whether the state changed or not,
  730. // so that the diagnostics don't get confused.
  731. PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
  732. ExplodedNodeSet Dst;
  733. NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  734. for (const auto I : Tmp) {
  735. ProgramStateRef State = I->getState();
  736. Bldr.generateNode(PP, State, I);
  737. }
  738. // Enqueue the new nodes onto the work list.
  739. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  740. }
  741. void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
  742. ExplodedNode *Pred) {
  743. ExplodedNodeSet Dst;
  744. switch (D.getKind()) {
  745. case CFGElement::AutomaticObjectDtor:
  746. ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
  747. break;
  748. case CFGElement::BaseDtor:
  749. ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
  750. break;
  751. case CFGElement::MemberDtor:
  752. ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
  753. break;
  754. case CFGElement::TemporaryDtor:
  755. ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
  756. break;
  757. case CFGElement::DeleteDtor:
  758. ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
  759. break;
  760. default:
  761. llvm_unreachable("Unexpected dtor kind.");
  762. }
  763. // Enqueue the new nodes onto the work list.
  764. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  765. }
  766. void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
  767. ExplodedNode *Pred) {
  768. ExplodedNodeSet Dst;
  769. AnalysisManager &AMgr = getAnalysisManager();
  770. AnalyzerOptions &Opts = AMgr.options;
  771. // TODO: We're not evaluating allocators for all cases just yet as
  772. // we're not handling the return value correctly, which causes false
  773. // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
  774. if (Opts.mayInlineCXXAllocator())
  775. VisitCXXNewAllocatorCall(NE, Pred, Dst);
  776. else {
  777. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  778. const LocationContext *LCtx = Pred->getLocationContext();
  779. PostImplicitCall PP(NE->getOperatorNew(), NE->getBeginLoc(), LCtx);
  780. Bldr.generateNode(PP, Pred->getState(), Pred);
  781. }
  782. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  783. }
  784. void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
  785. ExplodedNode *Pred,
  786. ExplodedNodeSet &Dst) {
  787. const VarDecl *varDecl = Dtor.getVarDecl();
  788. QualType varType = varDecl->getType();
  789. ProgramStateRef state = Pred->getState();
  790. SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
  791. const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
  792. if (varType->isReferenceType()) {
  793. const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
  794. if (!ValueRegion) {
  795. // FIXME: This should not happen. The language guarantees a presence
  796. // of a valid initializer here, so the reference shall not be undefined.
  797. // It seems that we're calling destructors over variables that
  798. // were not initialized yet.
  799. return;
  800. }
  801. Region = ValueRegion->getBaseRegion();
  802. varType = cast<TypedValueRegion>(Region)->getValueType();
  803. }
  804. // FIXME: We need to run the same destructor on every element of the array.
  805. // This workaround will just run the first destructor (which will still
  806. // invalidate the entire array).
  807. EvalCallOptions CallOpts;
  808. Region = makeZeroElementRegion(state, loc::MemRegionVal(Region), varType,
  809. CallOpts.IsArrayCtorOrDtor).getAsRegion();
  810. VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
  811. Pred, Dst, CallOpts);
  812. }
  813. void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
  814. ExplodedNode *Pred,
  815. ExplodedNodeSet &Dst) {
  816. ProgramStateRef State = Pred->getState();
  817. const LocationContext *LCtx = Pred->getLocationContext();
  818. const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
  819. const Stmt *Arg = DE->getArgument();
  820. QualType DTy = DE->getDestroyedType();
  821. SVal ArgVal = State->getSVal(Arg, LCtx);
  822. // If the argument to delete is known to be a null value,
  823. // don't run destructor.
  824. if (State->isNull(ArgVal).isConstrainedTrue()) {
  825. QualType BTy = getContext().getBaseElementType(DTy);
  826. const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
  827. const CXXDestructorDecl *Dtor = RD->getDestructor();
  828. PostImplicitCall PP(Dtor, DE->getBeginLoc(), LCtx);
  829. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  830. Bldr.generateNode(PP, Pred->getState(), Pred);
  831. return;
  832. }
  833. EvalCallOptions CallOpts;
  834. const MemRegion *ArgR = ArgVal.getAsRegion();
  835. if (DE->isArrayForm()) {
  836. // FIXME: We need to run the same destructor on every element of the array.
  837. // This workaround will just run the first destructor (which will still
  838. // invalidate the entire array).
  839. CallOpts.IsArrayCtorOrDtor = true;
  840. // Yes, it may even be a multi-dimensional array.
  841. while (const auto *AT = getContext().getAsArrayType(DTy))
  842. DTy = AT->getElementType();
  843. if (ArgR)
  844. ArgR = getStoreManager().GetElementZeroRegion(cast<SubRegion>(ArgR), DTy);
  845. }
  846. VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
  847. }
  848. void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
  849. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  850. const LocationContext *LCtx = Pred->getLocationContext();
  851. const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  852. Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
  853. LCtx->getStackFrame());
  854. SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
  855. // Create the base object region.
  856. const CXXBaseSpecifier *Base = D.getBaseSpecifier();
  857. QualType BaseTy = Base->getType();
  858. SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
  859. Base->isVirtual());
  860. VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
  861. CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst, {});
  862. }
  863. void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
  864. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  865. const FieldDecl *Member = D.getFieldDecl();
  866. QualType T = Member->getType();
  867. ProgramStateRef State = Pred->getState();
  868. const LocationContext *LCtx = Pred->getLocationContext();
  869. const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  870. Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
  871. LCtx->getStackFrame());
  872. SVal FieldVal =
  873. State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
  874. // FIXME: We need to run the same destructor on every element of the array.
  875. // This workaround will just run the first destructor (which will still
  876. // invalidate the entire array).
  877. EvalCallOptions CallOpts;
  878. FieldVal = makeZeroElementRegion(State, FieldVal, T,
  879. CallOpts.IsArrayCtorOrDtor);
  880. VisitCXXDestructor(T, FieldVal.castAs<loc::MemRegionVal>().getRegion(),
  881. CurDtor->getBody(), /*IsBase=*/false, Pred, Dst, CallOpts);
  882. }
  883. void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
  884. ExplodedNode *Pred,
  885. ExplodedNodeSet &Dst) {
  886. const CXXBindTemporaryExpr *BTE = D.getBindTemporaryExpr();
  887. ProgramStateRef State = Pred->getState();
  888. const LocationContext *LC = Pred->getLocationContext();
  889. const MemRegion *MR = nullptr;
  890. if (Optional<SVal> V =
  891. getObjectUnderConstruction(State, D.getBindTemporaryExpr(),
  892. Pred->getLocationContext())) {
  893. // FIXME: Currently we insert temporary destructors for default parameters,
  894. // but we don't insert the constructors, so the entry in
  895. // ObjectsUnderConstruction may be missing.
  896. State = finishObjectConstruction(State, D.getBindTemporaryExpr(),
  897. Pred->getLocationContext());
  898. MR = V->getAsRegion();
  899. }
  900. // If copy elision has occured, and the constructor corresponding to the
  901. // destructor was elided, we need to skip the destructor as well.
  902. if (isDestructorElided(State, BTE, LC)) {
  903. State = cleanupElidedDestructor(State, BTE, LC);
  904. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  905. PostImplicitCall PP(D.getDestructorDecl(getContext()),
  906. D.getBindTemporaryExpr()->getBeginLoc(),
  907. Pred->getLocationContext());
  908. Bldr.generateNode(PP, State, Pred);
  909. return;
  910. }
  911. ExplodedNodeSet CleanDtorState;
  912. StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
  913. StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
  914. QualType T = D.getBindTemporaryExpr()->getSubExpr()->getType();
  915. // FIXME: Currently CleanDtorState can be empty here due to temporaries being
  916. // bound to default parameters.
  917. assert(CleanDtorState.size() <= 1);
  918. ExplodedNode *CleanPred =
  919. CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
  920. EvalCallOptions CallOpts;
  921. CallOpts.IsTemporaryCtorOrDtor = true;
  922. if (!MR) {
  923. CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
  924. // If we have no MR, we still need to unwrap the array to avoid destroying
  925. // the whole array at once. Regardless, we'd eventually need to model array
  926. // destructors properly, element-by-element.
  927. while (const ArrayType *AT = getContext().getAsArrayType(T)) {
  928. T = AT->getElementType();
  929. CallOpts.IsArrayCtorOrDtor = true;
  930. }
  931. } else {
  932. // We'd eventually need to makeZeroElementRegion() trick here,
  933. // but for now we don't have the respective construction contexts,
  934. // so MR would always be null in this case. Do nothing for now.
  935. }
  936. VisitCXXDestructor(T, MR, D.getBindTemporaryExpr(),
  937. /*IsBase=*/false, CleanPred, Dst, CallOpts);
  938. }
  939. void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
  940. NodeBuilderContext &BldCtx,
  941. ExplodedNode *Pred,
  942. ExplodedNodeSet &Dst,
  943. const CFGBlock *DstT,
  944. const CFGBlock *DstF) {
  945. BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
  946. ProgramStateRef State = Pred->getState();
  947. const LocationContext *LC = Pred->getLocationContext();
  948. if (getObjectUnderConstruction(State, BTE, LC)) {
  949. TempDtorBuilder.markInfeasible(false);
  950. TempDtorBuilder.generateNode(State, true, Pred);
  951. } else {
  952. TempDtorBuilder.markInfeasible(true);
  953. TempDtorBuilder.generateNode(State, false, Pred);
  954. }
  955. }
  956. void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
  957. ExplodedNodeSet &PreVisit,
  958. ExplodedNodeSet &Dst) {
  959. // This is a fallback solution in case we didn't have a construction
  960. // context when we were constructing the temporary. Otherwise the map should
  961. // have been populated there.
  962. if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) {
  963. // In case we don't have temporary destructors in the CFG, do not mark
  964. // the initialization - we would otherwise never clean it up.
  965. Dst = PreVisit;
  966. return;
  967. }
  968. StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
  969. for (ExplodedNode *Node : PreVisit) {
  970. ProgramStateRef State = Node->getState();
  971. const LocationContext *LC = Node->getLocationContext();
  972. if (!getObjectUnderConstruction(State, BTE, LC)) {
  973. // FIXME: Currently the state might also already contain the marker due to
  974. // incorrect handling of temporaries bound to default parameters; for
  975. // those, we currently skip the CXXBindTemporaryExpr but rely on adding
  976. // temporary destructor nodes.
  977. State = addObjectUnderConstruction(State, BTE, LC, UnknownVal());
  978. }
  979. StmtBldr.generateNode(BTE, Node, State);
  980. }
  981. }
  982. ProgramStateRef ExprEngine::escapeValue(ProgramStateRef State, SVal V,
  983. PointerEscapeKind K) const {
  984. class CollectReachableSymbolsCallback final : public SymbolVisitor {
  985. InvalidatedSymbols Symbols;
  986. public:
  987. explicit CollectReachableSymbolsCallback(ProgramStateRef) {}
  988. const InvalidatedSymbols &getSymbols() const { return Symbols; }
  989. bool VisitSymbol(SymbolRef Sym) override {
  990. Symbols.insert(Sym);
  991. return true;
  992. }
  993. };
  994. const CollectReachableSymbolsCallback &Scanner =
  995. State->scanReachableSymbols<CollectReachableSymbolsCallback>(V);
  996. return getCheckerManager().runCheckersForPointerEscape(
  997. State, Scanner.getSymbols(), /*CallEvent*/ nullptr, K, nullptr);
  998. }
  999. void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
  1000. ExplodedNodeSet &DstTop) {
  1001. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1002. S->getBeginLoc(), "Error evaluating statement");
  1003. ExplodedNodeSet Dst;
  1004. StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
  1005. assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
  1006. switch (S->getStmtClass()) {
  1007. // C++, OpenMP and ARC stuff we don't support yet.
  1008. case Expr::ObjCIndirectCopyRestoreExprClass:
  1009. case Stmt::CXXDependentScopeMemberExprClass:
  1010. case Stmt::CXXInheritedCtorInitExprClass:
  1011. case Stmt::CXXTryStmtClass:
  1012. case Stmt::CXXTypeidExprClass:
  1013. case Stmt::CXXUuidofExprClass:
  1014. case Stmt::CXXFoldExprClass:
  1015. case Stmt::MSPropertyRefExprClass:
  1016. case Stmt::MSPropertySubscriptExprClass:
  1017. case Stmt::CXXUnresolvedConstructExprClass:
  1018. case Stmt::DependentScopeDeclRefExprClass:
  1019. case Stmt::ArrayTypeTraitExprClass:
  1020. case Stmt::ExpressionTraitExprClass:
  1021. case Stmt::UnresolvedLookupExprClass:
  1022. case Stmt::UnresolvedMemberExprClass:
  1023. case Stmt::TypoExprClass:
  1024. case Stmt::CXXNoexceptExprClass:
  1025. case Stmt::PackExpansionExprClass:
  1026. case Stmt::SubstNonTypeTemplateParmPackExprClass:
  1027. case Stmt::FunctionParmPackExprClass:
  1028. case Stmt::CoroutineBodyStmtClass:
  1029. case Stmt::CoawaitExprClass:
  1030. case Stmt::DependentCoawaitExprClass:
  1031. case Stmt::CoreturnStmtClass:
  1032. case Stmt::CoyieldExprClass:
  1033. case Stmt::SEHTryStmtClass:
  1034. case Stmt::SEHExceptStmtClass:
  1035. case Stmt::SEHLeaveStmtClass:
  1036. case Stmt::SEHFinallyStmtClass:
  1037. case Stmt::OMPParallelDirectiveClass:
  1038. case Stmt::OMPSimdDirectiveClass:
  1039. case Stmt::OMPForDirectiveClass:
  1040. case Stmt::OMPForSimdDirectiveClass:
  1041. case Stmt::OMPSectionsDirectiveClass:
  1042. case Stmt::OMPSectionDirectiveClass:
  1043. case Stmt::OMPSingleDirectiveClass:
  1044. case Stmt::OMPMasterDirectiveClass:
  1045. case Stmt::OMPCriticalDirectiveClass:
  1046. case Stmt::OMPParallelForDirectiveClass:
  1047. case Stmt::OMPParallelForSimdDirectiveClass:
  1048. case Stmt::OMPParallelSectionsDirectiveClass:
  1049. case Stmt::OMPTaskDirectiveClass:
  1050. case Stmt::OMPTaskyieldDirectiveClass:
  1051. case Stmt::OMPBarrierDirectiveClass:
  1052. case Stmt::OMPTaskwaitDirectiveClass:
  1053. case Stmt::OMPTaskgroupDirectiveClass:
  1054. case Stmt::OMPFlushDirectiveClass:
  1055. case Stmt::OMPOrderedDirectiveClass:
  1056. case Stmt::OMPAtomicDirectiveClass:
  1057. case Stmt::OMPTargetDirectiveClass:
  1058. case Stmt::OMPTargetDataDirectiveClass:
  1059. case Stmt::OMPTargetEnterDataDirectiveClass:
  1060. case Stmt::OMPTargetExitDataDirectiveClass:
  1061. case Stmt::OMPTargetParallelDirectiveClass:
  1062. case Stmt::OMPTargetParallelForDirectiveClass:
  1063. case Stmt::OMPTargetUpdateDirectiveClass:
  1064. case Stmt::OMPTeamsDirectiveClass:
  1065. case Stmt::OMPCancellationPointDirectiveClass:
  1066. case Stmt::OMPCancelDirectiveClass:
  1067. case Stmt::OMPTaskLoopDirectiveClass:
  1068. case Stmt::OMPTaskLoopSimdDirectiveClass:
  1069. case Stmt::OMPDistributeDirectiveClass:
  1070. case Stmt::OMPDistributeParallelForDirectiveClass:
  1071. case Stmt::OMPDistributeParallelForSimdDirectiveClass:
  1072. case Stmt::OMPDistributeSimdDirectiveClass:
  1073. case Stmt::OMPTargetParallelForSimdDirectiveClass:
  1074. case Stmt::OMPTargetSimdDirectiveClass:
  1075. case Stmt::OMPTeamsDistributeDirectiveClass:
  1076. case Stmt::OMPTeamsDistributeSimdDirectiveClass:
  1077. case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
  1078. case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
  1079. case Stmt::OMPTargetTeamsDirectiveClass:
  1080. case Stmt::OMPTargetTeamsDistributeDirectiveClass:
  1081. case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
  1082. case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
  1083. case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
  1084. case Stmt::CapturedStmtClass: {
  1085. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  1086. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  1087. break;
  1088. }
  1089. case Stmt::ParenExprClass:
  1090. llvm_unreachable("ParenExprs already handled.");
  1091. case Stmt::GenericSelectionExprClass:
  1092. llvm_unreachable("GenericSelectionExprs already handled.");
  1093. // Cases that should never be evaluated simply because they shouldn't
  1094. // appear in the CFG.
  1095. case Stmt::BreakStmtClass:
  1096. case Stmt::CaseStmtClass:
  1097. case Stmt::CompoundStmtClass:
  1098. case Stmt::ContinueStmtClass:
  1099. case Stmt::CXXForRangeStmtClass:
  1100. case Stmt::DefaultStmtClass:
  1101. case Stmt::DoStmtClass:
  1102. case Stmt::ForStmtClass:
  1103. case Stmt::GotoStmtClass:
  1104. case Stmt::IfStmtClass:
  1105. case Stmt::IndirectGotoStmtClass:
  1106. case Stmt::LabelStmtClass:
  1107. case Stmt::NoStmtClass:
  1108. case Stmt::NullStmtClass:
  1109. case Stmt::SwitchStmtClass:
  1110. case Stmt::WhileStmtClass:
  1111. case Expr::MSDependentExistsStmtClass:
  1112. llvm_unreachable("Stmt should not be in analyzer evaluation loop");
  1113. case Stmt::ObjCSubscriptRefExprClass:
  1114. case Stmt::ObjCPropertyRefExprClass:
  1115. llvm_unreachable("These are handled by PseudoObjectExpr");
  1116. case Stmt::GNUNullExprClass: {
  1117. // GNU __null is a pointer-width integer, not an actual pointer.
  1118. ProgramStateRef state = Pred->getState();
  1119. state = state->BindExpr(S, Pred->getLocationContext(),
  1120. svalBuilder.makeIntValWithPtrWidth(0, false));
  1121. Bldr.generateNode(S, Pred, state);
  1122. break;
  1123. }
  1124. case Stmt::ObjCAtSynchronizedStmtClass:
  1125. Bldr.takeNodes(Pred);
  1126. VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
  1127. Bldr.addNodes(Dst);
  1128. break;
  1129. case Expr::ConstantExprClass:
  1130. case Stmt::ExprWithCleanupsClass:
  1131. // Handled due to fully linearised CFG.
  1132. break;
  1133. case Stmt::CXXBindTemporaryExprClass: {
  1134. Bldr.takeNodes(Pred);
  1135. ExplodedNodeSet PreVisit;
  1136. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1137. ExplodedNodeSet Next;
  1138. VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
  1139. getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
  1140. Bldr.addNodes(Dst);
  1141. break;
  1142. }
  1143. // Cases not handled yet; but will handle some day.
  1144. case Stmt::DesignatedInitExprClass:
  1145. case Stmt::DesignatedInitUpdateExprClass:
  1146. case Stmt::ArrayInitLoopExprClass:
  1147. case Stmt::ArrayInitIndexExprClass:
  1148. case Stmt::ExtVectorElementExprClass:
  1149. case Stmt::ImaginaryLiteralClass:
  1150. case Stmt::ObjCAtCatchStmtClass:
  1151. case Stmt::ObjCAtFinallyStmtClass:
  1152. case Stmt::ObjCAtTryStmtClass:
  1153. case Stmt::ObjCAutoreleasePoolStmtClass:
  1154. case Stmt::ObjCEncodeExprClass:
  1155. case Stmt::ObjCIsaExprClass:
  1156. case Stmt::ObjCProtocolExprClass:
  1157. case Stmt::ObjCSelectorExprClass:
  1158. case Stmt::ParenListExprClass:
  1159. case Stmt::ShuffleVectorExprClass:
  1160. case Stmt::ConvertVectorExprClass:
  1161. case Stmt::VAArgExprClass:
  1162. case Stmt::CUDAKernelCallExprClass:
  1163. case Stmt::OpaqueValueExprClass:
  1164. case Stmt::AsTypeExprClass:
  1165. // Fall through.
  1166. // Cases we intentionally don't evaluate, since they don't need
  1167. // to be explicitly evaluated.
  1168. case Stmt::PredefinedExprClass:
  1169. case Stmt::AddrLabelExprClass:
  1170. case Stmt::AttributedStmtClass:
  1171. case Stmt::IntegerLiteralClass:
  1172. case Stmt::FixedPointLiteralClass:
  1173. case Stmt::CharacterLiteralClass:
  1174. case Stmt::ImplicitValueInitExprClass:
  1175. case Stmt::CXXScalarValueInitExprClass:
  1176. case Stmt::CXXBoolLiteralExprClass:
  1177. case Stmt::ObjCBoolLiteralExprClass:
  1178. case Stmt::ObjCAvailabilityCheckExprClass:
  1179. case Stmt::FloatingLiteralClass:
  1180. case Stmt::NoInitExprClass:
  1181. case Stmt::SizeOfPackExprClass:
  1182. case Stmt::StringLiteralClass:
  1183. case Stmt::ObjCStringLiteralClass:
  1184. case Stmt::CXXPseudoDestructorExprClass:
  1185. case Stmt::SubstNonTypeTemplateParmExprClass:
  1186. case Stmt::CXXNullPtrLiteralExprClass:
  1187. case Stmt::OMPArraySectionExprClass:
  1188. case Stmt::TypeTraitExprClass: {
  1189. Bldr.takeNodes(Pred);
  1190. ExplodedNodeSet preVisit;
  1191. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  1192. getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
  1193. Bldr.addNodes(Dst);
  1194. break;
  1195. }
  1196. case Stmt::CXXDefaultArgExprClass:
  1197. case Stmt::CXXDefaultInitExprClass: {
  1198. Bldr.takeNodes(Pred);
  1199. ExplodedNodeSet PreVisit;
  1200. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1201. ExplodedNodeSet Tmp;
  1202. StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
  1203. const Expr *ArgE;
  1204. if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S))
  1205. ArgE = DefE->getExpr();
  1206. else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S))
  1207. ArgE = DefE->getExpr();
  1208. else
  1209. llvm_unreachable("unknown constant wrapper kind");
  1210. bool IsTemporary = false;
  1211. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
  1212. ArgE = MTE->GetTemporaryExpr();
  1213. IsTemporary = true;
  1214. }
  1215. Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
  1216. if (!ConstantVal)
  1217. ConstantVal = UnknownVal();
  1218. const LocationContext *LCtx = Pred->getLocationContext();
  1219. for (const auto I : PreVisit) {
  1220. ProgramStateRef State = I->getState();
  1221. State = State->BindExpr(S, LCtx, *ConstantVal);
  1222. if (IsTemporary)
  1223. State = createTemporaryRegionIfNeeded(State, LCtx,
  1224. cast<Expr>(S),
  1225. cast<Expr>(S));
  1226. Bldr2.generateNode(S, I, State);
  1227. }
  1228. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  1229. Bldr.addNodes(Dst);
  1230. break;
  1231. }
  1232. // Cases we evaluate as opaque expressions, conjuring a symbol.
  1233. case Stmt::CXXStdInitializerListExprClass:
  1234. case Expr::ObjCArrayLiteralClass:
  1235. case Expr::ObjCDictionaryLiteralClass:
  1236. case Expr::ObjCBoxedExprClass: {
  1237. Bldr.takeNodes(Pred);
  1238. ExplodedNodeSet preVisit;
  1239. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  1240. ExplodedNodeSet Tmp;
  1241. StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
  1242. const auto *Ex = cast<Expr>(S);
  1243. QualType resultType = Ex->getType();
  1244. for (const auto N : preVisit) {
  1245. const LocationContext *LCtx = N->getLocationContext();
  1246. SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
  1247. resultType,
  1248. currBldrCtx->blockCount());
  1249. ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
  1250. // Escape pointers passed into the list, unless it's an ObjC boxed
  1251. // expression which is not a boxable C structure.
  1252. if (!(isa<ObjCBoxedExpr>(Ex) &&
  1253. !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
  1254. ->getType()->isRecordType()))
  1255. for (auto Child : Ex->children()) {
  1256. assert(Child);
  1257. SVal Val = State->getSVal(Child, LCtx);
  1258. State = escapeValue(State, Val, PSK_EscapeOther);
  1259. }
  1260. Bldr2.generateNode(S, N, State);
  1261. }
  1262. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  1263. Bldr.addNodes(Dst);
  1264. break;
  1265. }
  1266. case Stmt::ArraySubscriptExprClass:
  1267. Bldr.takeNodes(Pred);
  1268. VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
  1269. Bldr.addNodes(Dst);
  1270. break;
  1271. case Stmt::GCCAsmStmtClass:
  1272. Bldr.takeNodes(Pred);
  1273. VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
  1274. Bldr.addNodes(Dst);
  1275. break;
  1276. case Stmt::MSAsmStmtClass:
  1277. Bldr.takeNodes(Pred);
  1278. VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
  1279. Bldr.addNodes(Dst);
  1280. break;
  1281. case Stmt::BlockExprClass:
  1282. Bldr.takeNodes(Pred);
  1283. VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
  1284. Bldr.addNodes(Dst);
  1285. break;
  1286. case Stmt::LambdaExprClass:
  1287. if (AMgr.options.shouldInlineLambdas()) {
  1288. Bldr.takeNodes(Pred);
  1289. VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
  1290. Bldr.addNodes(Dst);
  1291. } else {
  1292. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  1293. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  1294. }
  1295. break;
  1296. case Stmt::BinaryOperatorClass: {
  1297. const auto *B = cast<BinaryOperator>(S);
  1298. if (B->isLogicalOp()) {
  1299. Bldr.takeNodes(Pred);
  1300. VisitLogicalExpr(B, Pred, Dst);
  1301. Bldr.addNodes(Dst);
  1302. break;
  1303. }
  1304. else if (B->getOpcode() == BO_Comma) {
  1305. ProgramStateRef state = Pred->getState();
  1306. Bldr.generateNode(B, Pred,
  1307. state->BindExpr(B, Pred->getLocationContext(),
  1308. state->getSVal(B->getRHS(),
  1309. Pred->getLocationContext())));
  1310. break;
  1311. }
  1312. Bldr.takeNodes(Pred);
  1313. if (AMgr.options.shouldEagerlyAssume() &&
  1314. (B->isRelationalOp() || B->isEqualityOp())) {
  1315. ExplodedNodeSet Tmp;
  1316. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
  1317. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
  1318. }
  1319. else
  1320. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  1321. Bldr.addNodes(Dst);
  1322. break;
  1323. }
  1324. case Stmt::CXXOperatorCallExprClass: {
  1325. const auto *OCE = cast<CXXOperatorCallExpr>(S);
  1326. // For instance method operators, make sure the 'this' argument has a
  1327. // valid region.
  1328. const Decl *Callee = OCE->getCalleeDecl();
  1329. if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
  1330. if (MD->isInstance()) {
  1331. ProgramStateRef State = Pred->getState();
  1332. const LocationContext *LCtx = Pred->getLocationContext();
  1333. ProgramStateRef NewState =
  1334. createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
  1335. if (NewState != State) {
  1336. Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
  1337. ProgramPoint::PreStmtKind);
  1338. // Did we cache out?
  1339. if (!Pred)
  1340. break;
  1341. }
  1342. }
  1343. }
  1344. // FALLTHROUGH
  1345. LLVM_FALLTHROUGH;
  1346. }
  1347. case Stmt::CallExprClass:
  1348. case Stmt::CXXMemberCallExprClass:
  1349. case Stmt::UserDefinedLiteralClass:
  1350. Bldr.takeNodes(Pred);
  1351. VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
  1352. Bldr.addNodes(Dst);
  1353. break;
  1354. case Stmt::CXXCatchStmtClass:
  1355. Bldr.takeNodes(Pred);
  1356. VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
  1357. Bldr.addNodes(Dst);
  1358. break;
  1359. case Stmt::CXXTemporaryObjectExprClass:
  1360. case Stmt::CXXConstructExprClass:
  1361. Bldr.takeNodes(Pred);
  1362. VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
  1363. Bldr.addNodes(Dst);
  1364. break;
  1365. case Stmt::CXXNewExprClass: {
  1366. Bldr.takeNodes(Pred);
  1367. ExplodedNodeSet PreVisit;
  1368. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1369. ExplodedNodeSet PostVisit;
  1370. for (const auto i : PreVisit)
  1371. VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit);
  1372. getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
  1373. Bldr.addNodes(Dst);
  1374. break;
  1375. }
  1376. case Stmt::CXXDeleteExprClass: {
  1377. Bldr.takeNodes(Pred);
  1378. ExplodedNodeSet PreVisit;
  1379. const auto *CDE = cast<CXXDeleteExpr>(S);
  1380. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1381. for (const auto i : PreVisit)
  1382. VisitCXXDeleteExpr(CDE, i, Dst);
  1383. Bldr.addNodes(Dst);
  1384. break;
  1385. }
  1386. // FIXME: ChooseExpr is really a constant. We need to fix
  1387. // the CFG do not model them as explicit control-flow.
  1388. case Stmt::ChooseExprClass: { // __builtin_choose_expr
  1389. Bldr.takeNodes(Pred);
  1390. const auto *C = cast<ChooseExpr>(S);
  1391. VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
  1392. Bldr.addNodes(Dst);
  1393. break;
  1394. }
  1395. case Stmt::CompoundAssignOperatorClass:
  1396. Bldr.takeNodes(Pred);
  1397. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  1398. Bldr.addNodes(Dst);
  1399. break;
  1400. case Stmt::CompoundLiteralExprClass:
  1401. Bldr.takeNodes(Pred);
  1402. VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
  1403. Bldr.addNodes(Dst);
  1404. break;
  1405. case Stmt::BinaryConditionalOperatorClass:
  1406. case Stmt::ConditionalOperatorClass: { // '?' operator
  1407. Bldr.takeNodes(Pred);
  1408. const auto *C = cast<AbstractConditionalOperator>(S);
  1409. VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
  1410. Bldr.addNodes(Dst);
  1411. break;
  1412. }
  1413. case Stmt::CXXThisExprClass:
  1414. Bldr.takeNodes(Pred);
  1415. VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
  1416. Bldr.addNodes(Dst);
  1417. break;
  1418. case Stmt::DeclRefExprClass: {
  1419. Bldr.takeNodes(Pred);
  1420. const auto *DE = cast<DeclRefExpr>(S);
  1421. VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
  1422. Bldr.addNodes(Dst);
  1423. break;
  1424. }
  1425. case Stmt::DeclStmtClass:
  1426. Bldr.takeNodes(Pred);
  1427. VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
  1428. Bldr.addNodes(Dst);
  1429. break;
  1430. case Stmt::ImplicitCastExprClass:
  1431. case Stmt::CStyleCastExprClass:
  1432. case Stmt::CXXStaticCastExprClass:
  1433. case Stmt::CXXDynamicCastExprClass:
  1434. case Stmt::CXXReinterpretCastExprClass:
  1435. case Stmt::CXXConstCastExprClass:
  1436. case Stmt::CXXFunctionalCastExprClass:
  1437. case Stmt::ObjCBridgedCastExprClass: {
  1438. Bldr.takeNodes(Pred);
  1439. const auto *C = cast<CastExpr>(S);
  1440. ExplodedNodeSet dstExpr;
  1441. VisitCast(C, C->getSubExpr(), Pred, dstExpr);
  1442. // Handle the postvisit checks.
  1443. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
  1444. Bldr.addNodes(Dst);
  1445. break;
  1446. }
  1447. case Expr::MaterializeTemporaryExprClass: {
  1448. Bldr.takeNodes(Pred);
  1449. const auto *MTE = cast<MaterializeTemporaryExpr>(S);
  1450. ExplodedNodeSet dstPrevisit;
  1451. getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
  1452. ExplodedNodeSet dstExpr;
  1453. for (const auto i : dstPrevisit)
  1454. CreateCXXTemporaryObject(MTE, i, dstExpr);
  1455. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
  1456. Bldr.addNodes(Dst);
  1457. break;
  1458. }
  1459. case Stmt::InitListExprClass:
  1460. Bldr.takeNodes(Pred);
  1461. VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
  1462. Bldr.addNodes(Dst);
  1463. break;
  1464. case Stmt::MemberExprClass:
  1465. Bldr.takeNodes(Pred);
  1466. VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
  1467. Bldr.addNodes(Dst);
  1468. break;
  1469. case Stmt::AtomicExprClass:
  1470. Bldr.takeNodes(Pred);
  1471. VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
  1472. Bldr.addNodes(Dst);
  1473. break;
  1474. case Stmt::ObjCIvarRefExprClass:
  1475. Bldr.takeNodes(Pred);
  1476. VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
  1477. Bldr.addNodes(Dst);
  1478. break;
  1479. case Stmt::ObjCForCollectionStmtClass:
  1480. Bldr.takeNodes(Pred);
  1481. VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
  1482. Bldr.addNodes(Dst);
  1483. break;
  1484. case Stmt::ObjCMessageExprClass:
  1485. Bldr.takeNodes(Pred);
  1486. VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
  1487. Bldr.addNodes(Dst);
  1488. break;
  1489. case Stmt::ObjCAtThrowStmtClass:
  1490. case Stmt::CXXThrowExprClass:
  1491. // FIXME: This is not complete. We basically treat @throw as
  1492. // an abort.
  1493. Bldr.generateSink(S, Pred, Pred->getState());
  1494. break;
  1495. case Stmt::ReturnStmtClass:
  1496. Bldr.takeNodes(Pred);
  1497. VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
  1498. Bldr.addNodes(Dst);
  1499. break;
  1500. case Stmt::OffsetOfExprClass: {
  1501. Bldr.takeNodes(Pred);
  1502. ExplodedNodeSet PreVisit;
  1503. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1504. ExplodedNodeSet PostVisit;
  1505. for (const auto Node : PreVisit)
  1506. VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit);
  1507. getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
  1508. Bldr.addNodes(Dst);
  1509. break;
  1510. }
  1511. case Stmt::UnaryExprOrTypeTraitExprClass:
  1512. Bldr.takeNodes(Pred);
  1513. VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  1514. Pred, Dst);
  1515. Bldr.addNodes(Dst);
  1516. break;
  1517. case Stmt::StmtExprClass: {
  1518. const auto *SE = cast<StmtExpr>(S);
  1519. if (SE->getSubStmt()->body_empty()) {
  1520. // Empty statement expression.
  1521. assert(SE->getType() == getContext().VoidTy
  1522. && "Empty statement expression must have void type.");
  1523. break;
  1524. }
  1525. if (const auto *LastExpr =
  1526. dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
  1527. ProgramStateRef state = Pred->getState();
  1528. Bldr.generateNode(SE, Pred,
  1529. state->BindExpr(SE, Pred->getLocationContext(),
  1530. state->getSVal(LastExpr,
  1531. Pred->getLocationContext())));
  1532. }
  1533. break;
  1534. }
  1535. case Stmt::UnaryOperatorClass: {
  1536. Bldr.takeNodes(Pred);
  1537. const auto *U = cast<UnaryOperator>(S);
  1538. if (AMgr.options.shouldEagerlyAssume() && (U->getOpcode() == UO_LNot)) {
  1539. ExplodedNodeSet Tmp;
  1540. VisitUnaryOperator(U, Pred, Tmp);
  1541. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
  1542. }
  1543. else
  1544. VisitUnaryOperator(U, Pred, Dst);
  1545. Bldr.addNodes(Dst);
  1546. break;
  1547. }
  1548. case Stmt::PseudoObjectExprClass: {
  1549. Bldr.takeNodes(Pred);
  1550. ProgramStateRef state = Pred->getState();
  1551. const auto *PE = cast<PseudoObjectExpr>(S);
  1552. if (const Expr *Result = PE->getResultExpr()) {
  1553. SVal V = state->getSVal(Result, Pred->getLocationContext());
  1554. Bldr.generateNode(S, Pred,
  1555. state->BindExpr(S, Pred->getLocationContext(), V));
  1556. }
  1557. else
  1558. Bldr.generateNode(S, Pred,
  1559. state->BindExpr(S, Pred->getLocationContext(),
  1560. UnknownVal()));
  1561. Bldr.addNodes(Dst);
  1562. break;
  1563. }
  1564. }
  1565. }
  1566. bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
  1567. const LocationContext *CalleeLC) {
  1568. const StackFrameContext *CalleeSF = CalleeLC->getStackFrame();
  1569. const StackFrameContext *CallerSF = CalleeSF->getParent()->getStackFrame();
  1570. assert(CalleeSF && CallerSF);
  1571. ExplodedNode *BeforeProcessingCall = nullptr;
  1572. const Stmt *CE = CalleeSF->getCallSite();
  1573. // Find the first node before we started processing the call expression.
  1574. while (N) {
  1575. ProgramPoint L = N->getLocation();
  1576. BeforeProcessingCall = N;
  1577. N = N->pred_empty() ? nullptr : *(N->pred_begin());
  1578. // Skip the nodes corresponding to the inlined code.
  1579. if (L.getStackFrame() != CallerSF)
  1580. continue;
  1581. // We reached the caller. Find the node right before we started
  1582. // processing the call.
  1583. if (L.isPurgeKind())
  1584. continue;
  1585. if (L.getAs<PreImplicitCall>())
  1586. continue;
  1587. if (L.getAs<CallEnter>())
  1588. continue;
  1589. if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
  1590. if (SP->getStmt() == CE)
  1591. continue;
  1592. break;
  1593. }
  1594. if (!BeforeProcessingCall)
  1595. return false;
  1596. // TODO: Clean up the unneeded nodes.
  1597. // Build an Epsilon node from which we will restart the analyzes.
  1598. // Note that CE is permitted to be NULL!
  1599. ProgramPoint NewNodeLoc =
  1600. EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
  1601. // Add the special flag to GDM to signal retrying with no inlining.
  1602. // Note, changing the state ensures that we are not going to cache out.
  1603. ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
  1604. NewNodeState =
  1605. NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
  1606. // Make the new node a successor of BeforeProcessingCall.
  1607. bool IsNew = false;
  1608. ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
  1609. // We cached out at this point. Caching out is common due to us backtracking
  1610. // from the inlined function, which might spawn several paths.
  1611. if (!IsNew)
  1612. return true;
  1613. NewNode->addPredecessor(BeforeProcessingCall, G);
  1614. // Add the new node to the work list.
  1615. Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
  1616. CalleeSF->getIndex());
  1617. NumTimesRetriedWithoutInlining++;
  1618. return true;
  1619. }
  1620. /// Block entrance. (Update counters).
  1621. void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
  1622. NodeBuilderWithSinks &nodeBuilder,
  1623. ExplodedNode *Pred) {
  1624. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1625. // If we reach a loop which has a known bound (and meets
  1626. // other constraints) then consider completely unrolling it.
  1627. if(AMgr.options.shouldUnrollLoops()) {
  1628. unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
  1629. const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
  1630. if (Term) {
  1631. ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
  1632. Pred, maxBlockVisitOnPath);
  1633. if (NewState != Pred->getState()) {
  1634. ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
  1635. if (!UpdatedNode)
  1636. return;
  1637. Pred = UpdatedNode;
  1638. }
  1639. }
  1640. // Is we are inside an unrolled loop then no need the check the counters.
  1641. if(isUnrolledState(Pred->getState()))
  1642. return;
  1643. }
  1644. // If this block is terminated by a loop and it has already been visited the
  1645. // maximum number of times, widen the loop.
  1646. unsigned int BlockCount = nodeBuilder.getContext().blockCount();
  1647. if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
  1648. AMgr.options.shouldWidenLoops()) {
  1649. const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
  1650. if (!(Term &&
  1651. (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
  1652. return;
  1653. // Widen.
  1654. const LocationContext *LCtx = Pred->getLocationContext();
  1655. ProgramStateRef WidenedState =
  1656. getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
  1657. nodeBuilder.generateNode(WidenedState, Pred);
  1658. return;
  1659. }
  1660. // FIXME: Refactor this into a checker.
  1661. if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
  1662. static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
  1663. const ExplodedNode *Sink =
  1664. nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
  1665. // Check if we stopped at the top level function or not.
  1666. // Root node should have the location context of the top most function.
  1667. const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
  1668. const LocationContext *CalleeSF = CalleeLC->getStackFrame();
  1669. const LocationContext *RootLC =
  1670. (*G.roots_begin())->getLocation().getLocationContext();
  1671. if (RootLC->getStackFrame() != CalleeSF) {
  1672. Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
  1673. // Re-run the call evaluation without inlining it, by storing the
  1674. // no-inlining policy in the state and enqueuing the new work item on
  1675. // the list. Replay should almost never fail. Use the stats to catch it
  1676. // if it does.
  1677. if ((!AMgr.options.NoRetryExhausted &&
  1678. replayWithoutInlining(Pred, CalleeLC)))
  1679. return;
  1680. NumMaxBlockCountReachedInInlined++;
  1681. } else
  1682. NumMaxBlockCountReached++;
  1683. // Make sink nodes as exhausted(for stats) only if retry failed.
  1684. Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
  1685. }
  1686. }
  1687. //===----------------------------------------------------------------------===//
  1688. // Branch processing.
  1689. //===----------------------------------------------------------------------===//
  1690. /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
  1691. /// to try to recover some path-sensitivity for casts of symbolic
  1692. /// integers that promote their values (which are currently not tracked well).
  1693. /// This function returns the SVal bound to Condition->IgnoreCasts if all the
  1694. // cast(s) did was sign-extend the original value.
  1695. static SVal RecoverCastedSymbol(ProgramStateRef state,
  1696. const Stmt *Condition,
  1697. const LocationContext *LCtx,
  1698. ASTContext &Ctx) {
  1699. const auto *Ex = dyn_cast<Expr>(Condition);
  1700. if (!Ex)
  1701. return UnknownVal();
  1702. uint64_t bits = 0;
  1703. bool bitsInit = false;
  1704. while (const auto *CE = dyn_cast<CastExpr>(Ex)) {
  1705. QualType T = CE->getType();
  1706. if (!T->isIntegralOrEnumerationType())
  1707. return UnknownVal();
  1708. uint64_t newBits = Ctx.getTypeSize(T);
  1709. if (!bitsInit || newBits < bits) {
  1710. bitsInit = true;
  1711. bits = newBits;
  1712. }
  1713. Ex = CE->getSubExpr();
  1714. }
  1715. // We reached a non-cast. Is it a symbolic value?
  1716. QualType T = Ex->getType();
  1717. if (!bitsInit || !T->isIntegralOrEnumerationType() ||
  1718. Ctx.getTypeSize(T) > bits)
  1719. return UnknownVal();
  1720. return state->getSVal(Ex, LCtx);
  1721. }
  1722. #ifndef NDEBUG
  1723. static const Stmt *getRightmostLeaf(const Stmt *Condition) {
  1724. while (Condition) {
  1725. const auto *BO = dyn_cast<BinaryOperator>(Condition);
  1726. if (!BO || !BO->isLogicalOp()) {
  1727. return Condition;
  1728. }
  1729. Condition = BO->getRHS()->IgnoreParens();
  1730. }
  1731. return nullptr;
  1732. }
  1733. #endif
  1734. // Returns the condition the branch at the end of 'B' depends on and whose value
  1735. // has been evaluated within 'B'.
  1736. // In most cases, the terminator condition of 'B' will be evaluated fully in
  1737. // the last statement of 'B'; in those cases, the resolved condition is the
  1738. // given 'Condition'.
  1739. // If the condition of the branch is a logical binary operator tree, the CFG is
  1740. // optimized: in that case, we know that the expression formed by all but the
  1741. // rightmost leaf of the logical binary operator tree must be true, and thus
  1742. // the branch condition is at this point equivalent to the truth value of that
  1743. // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
  1744. // expression in its final statement. As the full condition in that case was
  1745. // not evaluated, and is thus not in the SVal cache, we need to use that leaf
  1746. // expression to evaluate the truth value of the condition in the current state
  1747. // space.
  1748. static const Stmt *ResolveCondition(const Stmt *Condition,
  1749. const CFGBlock *B) {
  1750. if (const auto *Ex = dyn_cast<Expr>(Condition))
  1751. Condition = Ex->IgnoreParens();
  1752. const auto *BO = dyn_cast<BinaryOperator>(Condition);
  1753. if (!BO || !BO->isLogicalOp())
  1754. return Condition;
  1755. assert(!B->getTerminator().isTemporaryDtorsBranch() &&
  1756. "Temporary destructor branches handled by processBindTemporary.");
  1757. // For logical operations, we still have the case where some branches
  1758. // use the traditional "merge" approach and others sink the branch
  1759. // directly into the basic blocks representing the logical operation.
  1760. // We need to distinguish between those two cases here.
  1761. // The invariants are still shifting, but it is possible that the
  1762. // last element in a CFGBlock is not a CFGStmt. Look for the last
  1763. // CFGStmt as the value of the condition.
  1764. CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
  1765. for (; I != E; ++I) {
  1766. CFGElement Elem = *I;
  1767. Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
  1768. if (!CS)
  1769. continue;
  1770. const Stmt *LastStmt = CS->getStmt();
  1771. assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
  1772. return LastStmt;
  1773. }
  1774. llvm_unreachable("could not resolve condition");
  1775. }
  1776. void ExprEngine::processBranch(const Stmt *Condition,
  1777. NodeBuilderContext& BldCtx,
  1778. ExplodedNode *Pred,
  1779. ExplodedNodeSet &Dst,
  1780. const CFGBlock *DstT,
  1781. const CFGBlock *DstF) {
  1782. assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
  1783. "CXXBindTemporaryExprs are handled by processBindTemporary.");
  1784. const LocationContext *LCtx = Pred->getLocationContext();
  1785. PrettyStackTraceLocationContext StackCrashInfo(LCtx);
  1786. currBldrCtx = &BldCtx;
  1787. // Check for NULL conditions; e.g. "for(;;)"
  1788. if (!Condition) {
  1789. BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
  1790. NullCondBldr.markInfeasible(false);
  1791. NullCondBldr.generateNode(Pred->getState(), true, Pred);
  1792. return;
  1793. }
  1794. if (const auto *Ex = dyn_cast<Expr>(Condition))
  1795. Condition = Ex->IgnoreParens();
  1796. Condition = ResolveCondition(Condition, BldCtx.getBlock());
  1797. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1798. Condition->getBeginLoc(),
  1799. "Error evaluating branch");
  1800. ExplodedNodeSet CheckersOutSet;
  1801. getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
  1802. Pred, *this);
  1803. // We generated only sinks.
  1804. if (CheckersOutSet.empty())
  1805. return;
  1806. BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
  1807. for (const auto PredI : CheckersOutSet) {
  1808. if (PredI->isSink())
  1809. continue;
  1810. ProgramStateRef PrevState = PredI->getState();
  1811. SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
  1812. if (X.isUnknownOrUndef()) {
  1813. // Give it a chance to recover from unknown.
  1814. if (const auto *Ex = dyn_cast<Expr>(Condition)) {
  1815. if (Ex->getType()->isIntegralOrEnumerationType()) {
  1816. // Try to recover some path-sensitivity. Right now casts of symbolic
  1817. // integers that promote their values are currently not tracked well.
  1818. // If 'Condition' is such an expression, try and recover the
  1819. // underlying value and use that instead.
  1820. SVal recovered = RecoverCastedSymbol(PrevState, Condition,
  1821. PredI->getLocationContext(),
  1822. getContext());
  1823. if (!recovered.isUnknown()) {
  1824. X = recovered;
  1825. }
  1826. }
  1827. }
  1828. }
  1829. // If the condition is still unknown, give up.
  1830. if (X.isUnknownOrUndef()) {
  1831. builder.generateNode(PrevState, true, PredI);
  1832. builder.generateNode(PrevState, false, PredI);
  1833. continue;
  1834. }
  1835. DefinedSVal V = X.castAs<DefinedSVal>();
  1836. ProgramStateRef StTrue, StFalse;
  1837. std::tie(StTrue, StFalse) = PrevState->assume(V);
  1838. // Process the true branch.
  1839. if (builder.isFeasible(true)) {
  1840. if (StTrue)
  1841. builder.generateNode(StTrue, true, PredI);
  1842. else
  1843. builder.markInfeasible(true);
  1844. }
  1845. // Process the false branch.
  1846. if (builder.isFeasible(false)) {
  1847. if (StFalse)
  1848. builder.generateNode(StFalse, false, PredI);
  1849. else
  1850. builder.markInfeasible(false);
  1851. }
  1852. }
  1853. currBldrCtx = nullptr;
  1854. }
  1855. /// The GDM component containing the set of global variables which have been
  1856. /// previously initialized with explicit initializers.
  1857. REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
  1858. llvm::ImmutableSet<const VarDecl *>)
  1859. void ExprEngine::processStaticInitializer(const DeclStmt *DS,
  1860. NodeBuilderContext &BuilderCtx,
  1861. ExplodedNode *Pred,
  1862. ExplodedNodeSet &Dst,
  1863. const CFGBlock *DstT,
  1864. const CFGBlock *DstF) {
  1865. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1866. currBldrCtx = &BuilderCtx;
  1867. const auto *VD = cast<VarDecl>(DS->getSingleDecl());
  1868. ProgramStateRef state = Pred->getState();
  1869. bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
  1870. BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
  1871. if (!initHasRun) {
  1872. state = state->add<InitializedGlobalsSet>(VD);
  1873. }
  1874. builder.generateNode(state, initHasRun, Pred);
  1875. builder.markInfeasible(!initHasRun);
  1876. currBldrCtx = nullptr;
  1877. }
  1878. /// processIndirectGoto - Called by CoreEngine. Used to generate successor
  1879. /// nodes by processing the 'effects' of a computed goto jump.
  1880. void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
  1881. ProgramStateRef state = builder.getState();
  1882. SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
  1883. // Three possibilities:
  1884. //
  1885. // (1) We know the computed label.
  1886. // (2) The label is NULL (or some other constant), or Undefined.
  1887. // (3) We have no clue about the label. Dispatch to all targets.
  1888. //
  1889. using iterator = IndirectGotoNodeBuilder::iterator;
  1890. if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
  1891. const LabelDecl *L = LV->getLabel();
  1892. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
  1893. if (I.getLabel() == L) {
  1894. builder.generateNode(I, state);
  1895. return;
  1896. }
  1897. }
  1898. llvm_unreachable("No block with label.");
  1899. }
  1900. if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
  1901. // Dispatch to the first target and mark it as a sink.
  1902. //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
  1903. // FIXME: add checker visit.
  1904. // UndefBranches.insert(N);
  1905. return;
  1906. }
  1907. // This is really a catch-all. We don't support symbolics yet.
  1908. // FIXME: Implement dispatch for symbolic pointers.
  1909. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I)
  1910. builder.generateNode(I, state);
  1911. }
  1912. void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
  1913. ExplodedNode *Pred,
  1914. ExplodedNodeSet &Dst,
  1915. const BlockEdge &L) {
  1916. SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
  1917. getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
  1918. }
  1919. /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
  1920. /// nodes when the control reaches the end of a function.
  1921. void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
  1922. ExplodedNode *Pred,
  1923. const ReturnStmt *RS) {
  1924. ProgramStateRef State = Pred->getState();
  1925. if (!Pred->getStackFrame()->inTopFrame())
  1926. State = finishArgumentConstruction(
  1927. State, *getStateManager().getCallEventManager().getCaller(
  1928. Pred->getStackFrame(), Pred->getState()));
  1929. // FIXME: We currently cannot assert that temporaries are clear, because
  1930. // lifetime extended temporaries are not always modelled correctly. In some
  1931. // cases when we materialize the temporary, we do
  1932. // createTemporaryRegionIfNeeded(), and the region changes, and also the
  1933. // respective destructor becomes automatic from temporary. So for now clean up
  1934. // the state manually before asserting. Ideally, this braced block of code
  1935. // should go away.
  1936. {
  1937. const LocationContext *FromLC = Pred->getLocationContext();
  1938. const LocationContext *ToLC = FromLC->getStackFrame()->getParent();
  1939. const LocationContext *LC = FromLC;
  1940. while (LC != ToLC) {
  1941. assert(LC && "ToLC must be a parent of FromLC!");
  1942. for (auto I : State->get<ObjectsUnderConstruction>())
  1943. if (I.first.getLocationContext() == LC) {
  1944. // The comment above only pardons us for not cleaning up a
  1945. // temporary destructor. If any other statements are found here,
  1946. // it must be a separate problem.
  1947. assert(I.first.getItem().getKind() ==
  1948. ConstructionContextItem::TemporaryDestructorKind ||
  1949. I.first.getItem().getKind() ==
  1950. ConstructionContextItem::ElidedDestructorKind);
  1951. State = State->remove<ObjectsUnderConstruction>(I.first);
  1952. }
  1953. LC = LC->getParent();
  1954. }
  1955. }
  1956. // Perform the transition with cleanups.
  1957. if (State != Pred->getState()) {
  1958. ExplodedNodeSet PostCleanup;
  1959. NodeBuilder Bldr(Pred, PostCleanup, BC);
  1960. Pred = Bldr.generateNode(Pred->getLocation(), State, Pred);
  1961. if (!Pred) {
  1962. // The node with clean temporaries already exists. We might have reached
  1963. // it on a path on which we initialize different temporaries.
  1964. return;
  1965. }
  1966. }
  1967. assert(areAllObjectsFullyConstructed(Pred->getState(),
  1968. Pred->getLocationContext(),
  1969. Pred->getStackFrame()->getParent()));
  1970. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1971. StateMgr.EndPath(Pred->getState());
  1972. ExplodedNodeSet Dst;
  1973. if (Pred->getLocationContext()->inTopFrame()) {
  1974. // Remove dead symbols.
  1975. ExplodedNodeSet AfterRemovedDead;
  1976. removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
  1977. // Notify checkers.
  1978. for (const auto I : AfterRemovedDead)
  1979. getCheckerManager().runCheckersForEndFunction(BC, Dst, I, *this, RS);
  1980. } else {
  1981. getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this, RS);
  1982. }
  1983. Engine.enqueueEndOfFunction(Dst, RS);
  1984. }
  1985. /// ProcessSwitch - Called by CoreEngine. Used to generate successor
  1986. /// nodes by processing the 'effects' of a switch statement.
  1987. void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
  1988. using iterator = SwitchNodeBuilder::iterator;
  1989. ProgramStateRef state = builder.getState();
  1990. const Expr *CondE = builder.getCondition();
  1991. SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
  1992. if (CondV_untested.isUndef()) {
  1993. //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
  1994. // FIXME: add checker
  1995. //UndefBranches.insert(N);
  1996. return;
  1997. }
  1998. DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
  1999. ProgramStateRef DefaultSt = state;
  2000. iterator I = builder.begin(), EI = builder.end();
  2001. bool defaultIsFeasible = I == EI;
  2002. for ( ; I != EI; ++I) {
  2003. // Successor may be pruned out during CFG construction.
  2004. if (!I.getBlock())
  2005. continue;
  2006. const CaseStmt *Case = I.getCase();
  2007. // Evaluate the LHS of the case value.
  2008. llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
  2009. assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
  2010. // Get the RHS of the case, if it exists.
  2011. llvm::APSInt V2;
  2012. if (const Expr *E = Case->getRHS())
  2013. V2 = E->EvaluateKnownConstInt(getContext());
  2014. else
  2015. V2 = V1;
  2016. ProgramStateRef StateCase;
  2017. if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
  2018. std::tie(StateCase, DefaultSt) =
  2019. DefaultSt->assumeInclusiveRange(*NL, V1, V2);
  2020. else // UnknownVal
  2021. StateCase = DefaultSt;
  2022. if (StateCase)
  2023. builder.generateCaseStmtNode(I, StateCase);
  2024. // Now "assume" that the case doesn't match. Add this state
  2025. // to the default state (if it is feasible).
  2026. if (DefaultSt)
  2027. defaultIsFeasible = true;
  2028. else {
  2029. defaultIsFeasible = false;
  2030. break;
  2031. }
  2032. }
  2033. if (!defaultIsFeasible)
  2034. return;
  2035. // If we have switch(enum value), the default branch is not
  2036. // feasible if all of the enum constants not covered by 'case:' statements
  2037. // are not feasible values for the switch condition.
  2038. //
  2039. // Note that this isn't as accurate as it could be. Even if there isn't
  2040. // a case for a particular enum value as long as that enum value isn't
  2041. // feasible then it shouldn't be considered for making 'default:' reachable.
  2042. const SwitchStmt *SS = builder.getSwitch();
  2043. const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
  2044. if (CondExpr->getType()->getAs<EnumType>()) {
  2045. if (SS->isAllEnumCasesCovered())
  2046. return;
  2047. }
  2048. builder.generateDefaultCaseNode(DefaultSt);
  2049. }
  2050. //===----------------------------------------------------------------------===//
  2051. // Transfer functions: Loads and stores.
  2052. //===----------------------------------------------------------------------===//
  2053. void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
  2054. ExplodedNode *Pred,
  2055. ExplodedNodeSet &Dst) {
  2056. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2057. ProgramStateRef state = Pred->getState();
  2058. const LocationContext *LCtx = Pred->getLocationContext();
  2059. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  2060. // C permits "extern void v", and if you cast the address to a valid type,
  2061. // you can even do things with it. We simply pretend
  2062. assert(Ex->isGLValue() || VD->getType()->isVoidType());
  2063. const LocationContext *LocCtxt = Pred->getLocationContext();
  2064. const Decl *D = LocCtxt->getDecl();
  2065. const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
  2066. const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
  2067. Optional<std::pair<SVal, QualType>> VInfo;
  2068. if (AMgr.options.shouldInlineLambdas() && DeclRefEx &&
  2069. DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
  2070. MD->getParent()->isLambda()) {
  2071. // Lookup the field of the lambda.
  2072. const CXXRecordDecl *CXXRec = MD->getParent();
  2073. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  2074. FieldDecl *LambdaThisCaptureField;
  2075. CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
  2076. // Sema follows a sequence of complex rules to determine whether the
  2077. // variable should be captured.
  2078. if (const FieldDecl *FD = LambdaCaptureFields[VD]) {
  2079. Loc CXXThis =
  2080. svalBuilder.getCXXThis(MD, LocCtxt->getStackFrame());
  2081. SVal CXXThisVal = state->getSVal(CXXThis);
  2082. VInfo = std::make_pair(state->getLValue(FD, CXXThisVal), FD->getType());
  2083. }
  2084. }
  2085. if (!VInfo)
  2086. VInfo = std::make_pair(state->getLValue(VD, LocCtxt), VD->getType());
  2087. SVal V = VInfo->first;
  2088. bool IsReference = VInfo->second->isReferenceType();
  2089. // For references, the 'lvalue' is the pointer address stored in the
  2090. // reference region.
  2091. if (IsReference) {
  2092. if (const MemRegion *R = V.getAsRegion())
  2093. V = state->getSVal(R);
  2094. else
  2095. V = UnknownVal();
  2096. }
  2097. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  2098. ProgramPoint::PostLValueKind);
  2099. return;
  2100. }
  2101. if (const auto *ED = dyn_cast<EnumConstantDecl>(D)) {
  2102. assert(!Ex->isGLValue());
  2103. SVal V = svalBuilder.makeIntVal(ED->getInitVal());
  2104. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
  2105. return;
  2106. }
  2107. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2108. SVal V = svalBuilder.getFunctionPointer(FD);
  2109. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  2110. ProgramPoint::PostLValueKind);
  2111. return;
  2112. }
  2113. if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
  2114. // FIXME: Compute lvalue of field pointers-to-member.
  2115. // Right now we just use a non-null void pointer, so that it gives proper
  2116. // results in boolean contexts.
  2117. // FIXME: Maybe delegate this to the surrounding operator&.
  2118. // Note how this expression is lvalue, however pointer-to-member is NonLoc.
  2119. SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
  2120. currBldrCtx->blockCount());
  2121. state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
  2122. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  2123. ProgramPoint::PostLValueKind);
  2124. return;
  2125. }
  2126. if (isa<BindingDecl>(D)) {
  2127. // FIXME: proper support for bound declarations.
  2128. // For now, let's just prevent crashing.
  2129. return;
  2130. }
  2131. llvm_unreachable("Support for this Decl not implemented.");
  2132. }
  2133. /// VisitArraySubscriptExpr - Transfer function for array accesses
  2134. void ExprEngine::VisitArraySubscriptExpr(const ArraySubscriptExpr *A,
  2135. ExplodedNode *Pred,
  2136. ExplodedNodeSet &Dst){
  2137. const Expr *Base = A->getBase()->IgnoreParens();
  2138. const Expr *Idx = A->getIdx()->IgnoreParens();
  2139. ExplodedNodeSet CheckerPreStmt;
  2140. getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
  2141. ExplodedNodeSet EvalSet;
  2142. StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
  2143. bool IsVectorType = A->getBase()->getType()->isVectorType();
  2144. // The "like" case is for situations where C standard prohibits the type to
  2145. // be an lvalue, e.g. taking the address of a subscript of an expression of
  2146. // type "void *".
  2147. bool IsGLValueLike = A->isGLValue() ||
  2148. (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
  2149. for (auto *Node : CheckerPreStmt) {
  2150. const LocationContext *LCtx = Node->getLocationContext();
  2151. ProgramStateRef state = Node->getState();
  2152. if (IsGLValueLike) {
  2153. QualType T = A->getType();
  2154. // One of the forbidden LValue types! We still need to have sensible
  2155. // symbolic locations to represent this stuff. Note that arithmetic on
  2156. // void pointers is a GCC extension.
  2157. if (T->isVoidType())
  2158. T = getContext().CharTy;
  2159. SVal V = state->getLValue(T,
  2160. state->getSVal(Idx, LCtx),
  2161. state->getSVal(Base, LCtx));
  2162. Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
  2163. ProgramPoint::PostLValueKind);
  2164. } else if (IsVectorType) {
  2165. // FIXME: non-glvalue vector reads are not modelled.
  2166. Bldr.generateNode(A, Node, state, nullptr);
  2167. } else {
  2168. llvm_unreachable("Array subscript should be an lValue when not \
  2169. a vector and not a forbidden lvalue type");
  2170. }
  2171. }
  2172. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
  2173. }
  2174. /// VisitMemberExpr - Transfer function for member expressions.
  2175. void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
  2176. ExplodedNodeSet &Dst) {
  2177. // FIXME: Prechecks eventually go in ::Visit().
  2178. ExplodedNodeSet CheckedSet;
  2179. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
  2180. ExplodedNodeSet EvalSet;
  2181. ValueDecl *Member = M->getMemberDecl();
  2182. // Handle static member variables and enum constants accessed via
  2183. // member syntax.
  2184. if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
  2185. for (const auto I : CheckedSet)
  2186. VisitCommonDeclRefExpr(M, Member, I, EvalSet);
  2187. } else {
  2188. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  2189. ExplodedNodeSet Tmp;
  2190. for (const auto I : CheckedSet) {
  2191. ProgramStateRef state = I->getState();
  2192. const LocationContext *LCtx = I->getLocationContext();
  2193. Expr *BaseExpr = M->getBase();
  2194. // Handle C++ method calls.
  2195. if (const auto *MD = dyn_cast<CXXMethodDecl>(Member)) {
  2196. if (MD->isInstance())
  2197. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
  2198. SVal MDVal = svalBuilder.getFunctionPointer(MD);
  2199. state = state->BindExpr(M, LCtx, MDVal);
  2200. Bldr.generateNode(M, I, state);
  2201. continue;
  2202. }
  2203. // Handle regular struct fields / member variables.
  2204. const SubRegion *MR = nullptr;
  2205. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr,
  2206. /*Result=*/nullptr,
  2207. /*OutRegionWithAdjustments=*/&MR);
  2208. SVal baseExprVal =
  2209. MR ? loc::MemRegionVal(MR) : state->getSVal(BaseExpr, LCtx);
  2210. const auto *field = cast<FieldDecl>(Member);
  2211. SVal L = state->getLValue(field, baseExprVal);
  2212. if (M->isGLValue() || M->getType()->isArrayType()) {
  2213. // We special-case rvalues of array type because the analyzer cannot
  2214. // reason about them, since we expect all regions to be wrapped in Locs.
  2215. // We instead treat these as lvalues and assume that they will decay to
  2216. // pointers as soon as they are used.
  2217. if (!M->isGLValue()) {
  2218. assert(M->getType()->isArrayType());
  2219. const auto *PE =
  2220. dyn_cast<ImplicitCastExpr>(I->getParentMap().getParentIgnoreParens(M));
  2221. if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
  2222. llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
  2223. }
  2224. }
  2225. if (field->getType()->isReferenceType()) {
  2226. if (const MemRegion *R = L.getAsRegion())
  2227. L = state->getSVal(R);
  2228. else
  2229. L = UnknownVal();
  2230. }
  2231. Bldr.generateNode(M, I, state->BindExpr(M, LCtx, L), nullptr,
  2232. ProgramPoint::PostLValueKind);
  2233. } else {
  2234. Bldr.takeNodes(I);
  2235. evalLoad(Tmp, M, M, I, state, L);
  2236. Bldr.addNodes(Tmp);
  2237. }
  2238. }
  2239. }
  2240. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
  2241. }
  2242. void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred,
  2243. ExplodedNodeSet &Dst) {
  2244. ExplodedNodeSet AfterPreSet;
  2245. getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
  2246. // For now, treat all the arguments to C11 atomics as escaping.
  2247. // FIXME: Ideally we should model the behavior of the atomics precisely here.
  2248. ExplodedNodeSet AfterInvalidateSet;
  2249. StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
  2250. for (const auto I : AfterPreSet) {
  2251. ProgramStateRef State = I->getState();
  2252. const LocationContext *LCtx = I->getLocationContext();
  2253. SmallVector<SVal, 8> ValuesToInvalidate;
  2254. for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
  2255. const Expr *SubExpr = AE->getSubExprs()[SI];
  2256. SVal SubExprVal = State->getSVal(SubExpr, LCtx);
  2257. ValuesToInvalidate.push_back(SubExprVal);
  2258. }
  2259. State = State->invalidateRegions(ValuesToInvalidate, AE,
  2260. currBldrCtx->blockCount(),
  2261. LCtx,
  2262. /*CausedByPointerEscape*/true,
  2263. /*Symbols=*/nullptr);
  2264. SVal ResultVal = UnknownVal();
  2265. State = State->BindExpr(AE, LCtx, ResultVal);
  2266. Bldr.generateNode(AE, I, State, nullptr,
  2267. ProgramPoint::PostStmtKind);
  2268. }
  2269. getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
  2270. }
  2271. // A value escapes in three possible cases:
  2272. // (1) We are binding to something that is not a memory region.
  2273. // (2) We are binding to a MemrRegion that does not have stack storage.
  2274. // (3) We are binding to a MemRegion with stack storage that the store
  2275. // does not understand.
  2276. ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
  2277. SVal Loc,
  2278. SVal Val,
  2279. const LocationContext *LCtx) {
  2280. // Are we storing to something that causes the value to "escape"?
  2281. bool escapes = true;
  2282. // TODO: Move to StoreManager.
  2283. if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
  2284. escapes = !regionLoc->getRegion()->hasStackStorage();
  2285. if (!escapes) {
  2286. // To test (3), generate a new state with the binding added. If it is
  2287. // the same state, then it escapes (since the store cannot represent
  2288. // the binding).
  2289. // Do this only if we know that the store is not supposed to generate the
  2290. // same state.
  2291. SVal StoredVal = State->getSVal(regionLoc->getRegion());
  2292. if (StoredVal != Val)
  2293. escapes = (State == (State->bindLoc(*regionLoc, Val, LCtx)));
  2294. }
  2295. }
  2296. // If our store can represent the binding and we aren't storing to something
  2297. // that doesn't have local storage then just return and have the simulation
  2298. // state continue as is.
  2299. if (!escapes)
  2300. return State;
  2301. // Otherwise, find all symbols referenced by 'val' that we are tracking
  2302. // and stop tracking them.
  2303. State = escapeValue(State, Val, PSK_EscapeOnBind);
  2304. return State;
  2305. }
  2306. ProgramStateRef
  2307. ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
  2308. const InvalidatedSymbols *Invalidated,
  2309. ArrayRef<const MemRegion *> ExplicitRegions,
  2310. const CallEvent *Call,
  2311. RegionAndSymbolInvalidationTraits &ITraits) {
  2312. if (!Invalidated || Invalidated->empty())
  2313. return State;
  2314. if (!Call)
  2315. return getCheckerManager().runCheckersForPointerEscape(State,
  2316. *Invalidated,
  2317. nullptr,
  2318. PSK_EscapeOther,
  2319. &ITraits);
  2320. // If the symbols were invalidated by a call, we want to find out which ones
  2321. // were invalidated directly due to being arguments to the call.
  2322. InvalidatedSymbols SymbolsDirectlyInvalidated;
  2323. for (const auto I : ExplicitRegions) {
  2324. if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>())
  2325. SymbolsDirectlyInvalidated.insert(R->getSymbol());
  2326. }
  2327. InvalidatedSymbols SymbolsIndirectlyInvalidated;
  2328. for (const auto &sym : *Invalidated) {
  2329. if (SymbolsDirectlyInvalidated.count(sym))
  2330. continue;
  2331. SymbolsIndirectlyInvalidated.insert(sym);
  2332. }
  2333. if (!SymbolsDirectlyInvalidated.empty())
  2334. State = getCheckerManager().runCheckersForPointerEscape(State,
  2335. SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
  2336. // Notify about the symbols that get indirectly invalidated by the call.
  2337. if (!SymbolsIndirectlyInvalidated.empty())
  2338. State = getCheckerManager().runCheckersForPointerEscape(State,
  2339. SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
  2340. return State;
  2341. }
  2342. /// evalBind - Handle the semantics of binding a value to a specific location.
  2343. /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
  2344. void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
  2345. ExplodedNode *Pred,
  2346. SVal location, SVal Val,
  2347. bool atDeclInit, const ProgramPoint *PP) {
  2348. const LocationContext *LC = Pred->getLocationContext();
  2349. PostStmt PS(StoreE, LC);
  2350. if (!PP)
  2351. PP = &PS;
  2352. // Do a previsit of the bind.
  2353. ExplodedNodeSet CheckedSet;
  2354. getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
  2355. StoreE, *this, *PP);
  2356. StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
  2357. // If the location is not a 'Loc', it will already be handled by
  2358. // the checkers. There is nothing left to do.
  2359. if (!location.getAs<Loc>()) {
  2360. const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
  2361. /*tag*/nullptr);
  2362. ProgramStateRef state = Pred->getState();
  2363. state = processPointerEscapedOnBind(state, location, Val, LC);
  2364. Bldr.generateNode(L, state, Pred);
  2365. return;
  2366. }
  2367. for (const auto PredI : CheckedSet) {
  2368. ProgramStateRef state = PredI->getState();
  2369. state = processPointerEscapedOnBind(state, location, Val, LC);
  2370. // When binding the value, pass on the hint that this is a initialization.
  2371. // For initializations, we do not need to inform clients of region
  2372. // changes.
  2373. state = state->bindLoc(location.castAs<Loc>(),
  2374. Val, LC, /* notifyChanges = */ !atDeclInit);
  2375. const MemRegion *LocReg = nullptr;
  2376. if (Optional<loc::MemRegionVal> LocRegVal =
  2377. location.getAs<loc::MemRegionVal>()) {
  2378. LocReg = LocRegVal->getRegion();
  2379. }
  2380. const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
  2381. Bldr.generateNode(L, state, PredI);
  2382. }
  2383. }
  2384. /// evalStore - Handle the semantics of a store via an assignment.
  2385. /// @param Dst The node set to store generated state nodes
  2386. /// @param AssignE The assignment expression if the store happens in an
  2387. /// assignment.
  2388. /// @param LocationE The location expression that is stored to.
  2389. /// @param state The current simulation state
  2390. /// @param location The location to store the value
  2391. /// @param Val The value to be stored
  2392. void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
  2393. const Expr *LocationE,
  2394. ExplodedNode *Pred,
  2395. ProgramStateRef state, SVal location, SVal Val,
  2396. const ProgramPointTag *tag) {
  2397. // Proceed with the store. We use AssignE as the anchor for the PostStore
  2398. // ProgramPoint if it is non-NULL, and LocationE otherwise.
  2399. const Expr *StoreE = AssignE ? AssignE : LocationE;
  2400. // Evaluate the location (checks for bad dereferences).
  2401. ExplodedNodeSet Tmp;
  2402. evalLocation(Tmp, AssignE, LocationE, Pred, state, location, false);
  2403. if (Tmp.empty())
  2404. return;
  2405. if (location.isUndef())
  2406. return;
  2407. for (const auto I : Tmp)
  2408. evalBind(Dst, StoreE, I, location, Val, false);
  2409. }
  2410. void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
  2411. const Expr *NodeEx,
  2412. const Expr *BoundEx,
  2413. ExplodedNode *Pred,
  2414. ProgramStateRef state,
  2415. SVal location,
  2416. const ProgramPointTag *tag,
  2417. QualType LoadTy) {
  2418. assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
  2419. assert(NodeEx);
  2420. assert(BoundEx);
  2421. // Evaluate the location (checks for bad dereferences).
  2422. ExplodedNodeSet Tmp;
  2423. evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, true);
  2424. if (Tmp.empty())
  2425. return;
  2426. StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  2427. if (location.isUndef())
  2428. return;
  2429. // Proceed with the load.
  2430. for (const auto I : Tmp) {
  2431. state = I->getState();
  2432. const LocationContext *LCtx = I->getLocationContext();
  2433. SVal V = UnknownVal();
  2434. if (location.isValid()) {
  2435. if (LoadTy.isNull())
  2436. LoadTy = BoundEx->getType();
  2437. V = state->getSVal(location.castAs<Loc>(), LoadTy);
  2438. }
  2439. Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag,
  2440. ProgramPoint::PostLoadKind);
  2441. }
  2442. }
  2443. void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
  2444. const Stmt *NodeEx,
  2445. const Stmt *BoundEx,
  2446. ExplodedNode *Pred,
  2447. ProgramStateRef state,
  2448. SVal location,
  2449. bool isLoad) {
  2450. StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
  2451. // Early checks for performance reason.
  2452. if (location.isUnknown()) {
  2453. return;
  2454. }
  2455. ExplodedNodeSet Src;
  2456. BldrTop.takeNodes(Pred);
  2457. StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
  2458. if (Pred->getState() != state) {
  2459. // Associate this new state with an ExplodedNode.
  2460. // FIXME: If I pass null tag, the graph is incorrect, e.g for
  2461. // int *p;
  2462. // p = 0;
  2463. // *p = 0xDEADBEEF;
  2464. // "p = 0" is not noted as "Null pointer value stored to 'p'" but
  2465. // instead "int *p" is noted as
  2466. // "Variable 'p' initialized to a null pointer value"
  2467. static SimpleProgramPointTag tag(TagProviderName, "Location");
  2468. Bldr.generateNode(NodeEx, Pred, state, &tag);
  2469. }
  2470. ExplodedNodeSet Tmp;
  2471. getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
  2472. NodeEx, BoundEx, *this);
  2473. BldrTop.addNodes(Tmp);
  2474. }
  2475. std::pair<const ProgramPointTag *, const ProgramPointTag*>
  2476. ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
  2477. static SimpleProgramPointTag
  2478. eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
  2479. "Eagerly Assume True"),
  2480. eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
  2481. "Eagerly Assume False");
  2482. return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
  2483. &eagerlyAssumeBinOpBifurcationFalse);
  2484. }
  2485. void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
  2486. ExplodedNodeSet &Src,
  2487. const Expr *Ex) {
  2488. StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
  2489. for (const auto Pred : Src) {
  2490. // Test if the previous node was as the same expression. This can happen
  2491. // when the expression fails to evaluate to anything meaningful and
  2492. // (as an optimization) we don't generate a node.
  2493. ProgramPoint P = Pred->getLocation();
  2494. if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
  2495. continue;
  2496. }
  2497. ProgramStateRef state = Pred->getState();
  2498. SVal V = state->getSVal(Ex, Pred->getLocationContext());
  2499. Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
  2500. if (SEV && SEV->isExpression()) {
  2501. const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
  2502. geteagerlyAssumeBinOpBifurcationTags();
  2503. ProgramStateRef StateTrue, StateFalse;
  2504. std::tie(StateTrue, StateFalse) = state->assume(*SEV);
  2505. // First assume that the condition is true.
  2506. if (StateTrue) {
  2507. SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
  2508. StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
  2509. Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
  2510. }
  2511. // Next, assume that the condition is false.
  2512. if (StateFalse) {
  2513. SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
  2514. StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
  2515. Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
  2516. }
  2517. }
  2518. }
  2519. }
  2520. void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
  2521. ExplodedNodeSet &Dst) {
  2522. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2523. // We have processed both the inputs and the outputs. All of the outputs
  2524. // should evaluate to Locs. Nuke all of their values.
  2525. // FIXME: Some day in the future it would be nice to allow a "plug-in"
  2526. // which interprets the inline asm and stores proper results in the
  2527. // outputs.
  2528. ProgramStateRef state = Pred->getState();
  2529. for (const Expr *O : A->outputs()) {
  2530. SVal X = state->getSVal(O, Pred->getLocationContext());
  2531. assert(!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
  2532. if (Optional<Loc> LV = X.getAs<Loc>())
  2533. state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
  2534. }
  2535. Bldr.generateNode(A, Pred, state);
  2536. }
  2537. void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
  2538. ExplodedNodeSet &Dst) {
  2539. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2540. Bldr.generateNode(A, Pred, Pred->getState());
  2541. }
  2542. //===----------------------------------------------------------------------===//
  2543. // Visualization.
  2544. //===----------------------------------------------------------------------===//
  2545. #ifndef NDEBUG
  2546. namespace llvm {
  2547. template<>
  2548. struct DOTGraphTraits<ExplodedGraph*> : public DefaultDOTGraphTraits {
  2549. DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  2550. static bool nodeHasBugReport(const ExplodedNode *N) {
  2551. BugReporter &BR = static_cast<ExprEngine *>(
  2552. N->getState()->getStateManager().getOwningEngine())->getBugReporter();
  2553. const auto EQClasses =
  2554. llvm::make_range(BR.EQClasses_begin(), BR.EQClasses_end());
  2555. for (const auto &EQ : EQClasses) {
  2556. for (const BugReport &Report : EQ) {
  2557. if (Report.getErrorNode() == N)
  2558. return true;
  2559. }
  2560. }
  2561. return false;
  2562. }
  2563. /// \p PreCallback: callback before break.
  2564. /// \p PostCallback: callback after break.
  2565. /// \p Stop: stop iteration if returns {@code true}
  2566. /// \return Whether {@code Stop} ever returned {@code true}.
  2567. static bool traverseHiddenNodes(
  2568. const ExplodedNode *N,
  2569. llvm::function_ref<void(const ExplodedNode *)> PreCallback,
  2570. llvm::function_ref<void(const ExplodedNode *)> PostCallback,
  2571. llvm::function_ref<bool(const ExplodedNode *)> Stop) {
  2572. const ExplodedNode *FirstHiddenNode = N;
  2573. while (FirstHiddenNode->pred_size() == 1 &&
  2574. isNodeHidden(*FirstHiddenNode->pred_begin())) {
  2575. FirstHiddenNode = *FirstHiddenNode->pred_begin();
  2576. }
  2577. const ExplodedNode *OtherNode = FirstHiddenNode;
  2578. while (true) {
  2579. PreCallback(OtherNode);
  2580. if (Stop(OtherNode))
  2581. return true;
  2582. if (OtherNode == N)
  2583. break;
  2584. PostCallback(OtherNode);
  2585. OtherNode = *OtherNode->succ_begin();
  2586. }
  2587. return false;
  2588. }
  2589. static std::string getNodeAttributes(const ExplodedNode *N,
  2590. ExplodedGraph *) {
  2591. SmallVector<StringRef, 10> Out;
  2592. auto Noop = [](const ExplodedNode*){};
  2593. if (traverseHiddenNodes(N, Noop, Noop, &nodeHasBugReport)) {
  2594. Out.push_back("style=filled");
  2595. Out.push_back("fillcolor=red");
  2596. }
  2597. if (traverseHiddenNodes(N, Noop, Noop,
  2598. [](const ExplodedNode *C) { return C->isSink(); }))
  2599. Out.push_back("color=blue");
  2600. return llvm::join(Out, ",");
  2601. }
  2602. static bool isNodeHidden(const ExplodedNode *N) {
  2603. return N->isTrivial();
  2604. }
  2605. static std::string getNodeLabel(const ExplodedNode *N, ExplodedGraph *G){
  2606. std::string sbuf;
  2607. llvm::raw_string_ostream Out(sbuf);
  2608. ProgramStateRef State = N->getState();
  2609. // Dump program point for all the previously skipped nodes.
  2610. traverseHiddenNodes(
  2611. N,
  2612. [&](const ExplodedNode *OtherNode) {
  2613. OtherNode->getLocation().print(/*CR=*/"\\l", Out);
  2614. if (const ProgramPointTag *Tag = OtherNode->getLocation().getTag())
  2615. Out << "\\lTag:" << Tag->getTagDescription();
  2616. if (N->isSink())
  2617. Out << "\\lNode is sink\\l";
  2618. if (nodeHasBugReport(N))
  2619. Out << "\\lBug report attached\\l";
  2620. },
  2621. [&](const ExplodedNode *) { Out << "\\l--------\\l"; },
  2622. [&](const ExplodedNode *) { return false; });
  2623. Out << "\\l\\|";
  2624. Out << "StateID: ST" << State->getID() << ", NodeID: N" << N->getID(G)
  2625. << " <" << (const void *)N << ">\\|";
  2626. bool SameAsAllPredecessors =
  2627. std::all_of(N->pred_begin(), N->pred_end(), [&](const ExplodedNode *P) {
  2628. return P->getState() == State;
  2629. });
  2630. if (!SameAsAllPredecessors)
  2631. State->printDOT(Out, N->getLocationContext());
  2632. return Out.str();
  2633. }
  2634. };
  2635. } // namespace llvm
  2636. #endif
  2637. void ExprEngine::ViewGraph(bool trim) {
  2638. #ifndef NDEBUG
  2639. std::string Filename = DumpGraph(trim);
  2640. llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
  2641. #endif
  2642. llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
  2643. }
  2644. void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
  2645. #ifndef NDEBUG
  2646. std::string Filename = DumpGraph(Nodes);
  2647. llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
  2648. #endif
  2649. llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
  2650. }
  2651. std::string ExprEngine::DumpGraph(bool trim, StringRef Filename) {
  2652. #ifndef NDEBUG
  2653. if (trim) {
  2654. std::vector<const ExplodedNode *> Src;
  2655. // Iterate through the reports and get their nodes.
  2656. for (BugReporter::EQClasses_iterator
  2657. EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
  2658. const auto *N = const_cast<ExplodedNode *>(EI->begin()->getErrorNode());
  2659. if (N) Src.push_back(N);
  2660. }
  2661. return DumpGraph(Src, Filename);
  2662. } else {
  2663. return llvm::WriteGraph(&G, "ExprEngine", /*ShortNames=*/false,
  2664. /*Title=*/"Exploded Graph", /*Filename=*/Filename);
  2665. }
  2666. #endif
  2667. llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
  2668. return "";
  2669. }
  2670. std::string ExprEngine::DumpGraph(ArrayRef<const ExplodedNode*> Nodes,
  2671. StringRef Filename) {
  2672. #ifndef NDEBUG
  2673. std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
  2674. if (!TrimmedG.get()) {
  2675. llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
  2676. } else {
  2677. return llvm::WriteGraph(TrimmedG.get(), "TrimmedExprEngine",
  2678. /*ShortNames=*/false,
  2679. /*Title=*/"Trimmed Exploded Graph",
  2680. /*Filename=*/Filename);
  2681. }
  2682. #endif
  2683. llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
  2684. return "";
  2685. }
  2686. void *ProgramStateTrait<ReplayWithoutInlining>::GDMIndex() {
  2687. static int index = 0;
  2688. return &index;
  2689. }