ExprEngine.cpp 121 KB

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