ExprEngine.cpp 98 KB

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