ExprEngine.cpp 104 KB

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