ExprEngine.cpp 103 KB

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