ExprEngine.cpp 108 KB

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