ExprEngine.cpp 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168
  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()->getNameAsString() << '\"';
  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. For sanity, make sure we don't
  290. // try to 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 (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
  350. const SubobjectAdjustment &Adj = *I;
  351. switch (Adj.Kind) {
  352. case SubobjectAdjustment::DerivedToBaseAdjustment:
  353. Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
  354. break;
  355. case SubobjectAdjustment::FieldAdjustment:
  356. Reg = StoreMgr.getLValueField(Adj.Field, Reg);
  357. break;
  358. case SubobjectAdjustment::MemberPointerAdjustment:
  359. // FIXME: Unimplemented.
  360. State = State->invalidateRegions(Reg, InitWithAdjustments,
  361. currBldrCtx->blockCount(), LC, true,
  362. nullptr, nullptr, nullptr);
  363. return State;
  364. }
  365. }
  366. // What remains is to copy the value of the object to the new region.
  367. // FIXME: In other words, what we should always do is copy value of the
  368. // Init expression (which corresponds to the bigger object) to the whole
  369. // temporary region TR. However, this value is often no longer present
  370. // in the Environment. If it has disappeared, we instead invalidate TR.
  371. // Still, what we can do is assign the value of expression Ex (which
  372. // corresponds to the sub-object) to the TR's sub-region Reg. At least,
  373. // values inside Reg would be correct.
  374. SVal InitVal = State->getSVal(Init, LC);
  375. if (InitVal.isUnknown()) {
  376. InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
  377. currBldrCtx->blockCount());
  378. State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
  379. // Then we'd need to take the value that certainly exists and bind it
  380. // over.
  381. if (InitValWithAdjustments.isUnknown()) {
  382. // Try to recover some path sensitivity in case we couldn't
  383. // compute the value.
  384. InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
  385. Result, LC, InitWithAdjustments->getType(),
  386. currBldrCtx->blockCount());
  387. }
  388. State =
  389. State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
  390. } else {
  391. State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
  392. }
  393. // The result expression would now point to the correct sub-region of the
  394. // newly created temporary region. Do this last in order to getSVal of Init
  395. // correctly in case (Result == Init).
  396. if (Result->isGLValue()) {
  397. State = State->BindExpr(Result, LC, Reg);
  398. } else {
  399. State = State->BindExpr(Result, LC, InitValWithAdjustments);
  400. }
  401. // Notify checkers once for two bindLoc()s.
  402. State = processRegionChange(State, TR, LC);
  403. if (OutRegionWithAdjustments)
  404. *OutRegionWithAdjustments = cast<SubRegion>(Reg.getAsRegion());
  405. return State;
  406. }
  407. ProgramStateRef
  408. ExprEngine::addObjectUnderConstruction(ProgramStateRef State,
  409. const ConstructionContextItem &Item,
  410. const LocationContext *LC, SVal V) {
  411. ConstructedObjectKey Key(Item, LC->getStackFrame());
  412. // FIXME: Currently the state might already contain the marker due to
  413. // incorrect handling of temporaries bound to default parameters.
  414. assert(!State->get<ObjectsUnderConstruction>(Key) ||
  415. Key.getItem().getKind() ==
  416. ConstructionContextItem::TemporaryDestructorKind);
  417. return State->set<ObjectsUnderConstruction>(Key, V);
  418. }
  419. Optional<SVal>
  420. ExprEngine::getObjectUnderConstruction(ProgramStateRef State,
  421. const ConstructionContextItem &Item,
  422. const LocationContext *LC) {
  423. ConstructedObjectKey Key(Item, LC->getStackFrame());
  424. return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key));
  425. }
  426. ProgramStateRef
  427. ExprEngine::finishObjectConstruction(ProgramStateRef State,
  428. const ConstructionContextItem &Item,
  429. const LocationContext *LC) {
  430. ConstructedObjectKey Key(Item, LC->getStackFrame());
  431. assert(State->contains<ObjectsUnderConstruction>(Key));
  432. return State->remove<ObjectsUnderConstruction>(Key);
  433. }
  434. ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State,
  435. const CXXBindTemporaryExpr *BTE,
  436. const LocationContext *LC) {
  437. ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
  438. // FIXME: Currently the state might already contain the marker due to
  439. // incorrect handling of temporaries bound to default parameters.
  440. return State->set<ObjectsUnderConstruction>(Key, UnknownVal());
  441. }
  442. ProgramStateRef
  443. ExprEngine::cleanupElidedDestructor(ProgramStateRef State,
  444. const CXXBindTemporaryExpr *BTE,
  445. const LocationContext *LC) {
  446. ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
  447. assert(State->contains<ObjectsUnderConstruction>(Key));
  448. return State->remove<ObjectsUnderConstruction>(Key);
  449. }
  450. bool ExprEngine::isDestructorElided(ProgramStateRef State,
  451. const CXXBindTemporaryExpr *BTE,
  452. const LocationContext *LC) {
  453. ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
  454. return State->contains<ObjectsUnderConstruction>(Key);
  455. }
  456. bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State,
  457. const LocationContext *FromLC,
  458. const LocationContext *ToLC) {
  459. const LocationContext *LC = FromLC;
  460. while (LC != ToLC) {
  461. assert(LC && "ToLC must be a parent of FromLC!");
  462. for (auto I : State->get<ObjectsUnderConstruction>())
  463. if (I.first.getLocationContext() == LC)
  464. return false;
  465. LC = LC->getParent();
  466. }
  467. return true;
  468. }
  469. //===----------------------------------------------------------------------===//
  470. // Top-level transfer function logic (Dispatcher).
  471. //===----------------------------------------------------------------------===//
  472. /// evalAssume - Called by ConstraintManager. Used to call checker-specific
  473. /// logic for handling assumptions on symbolic values.
  474. ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
  475. SVal cond, bool assumption) {
  476. return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
  477. }
  478. ProgramStateRef
  479. ExprEngine::processRegionChanges(ProgramStateRef state,
  480. const InvalidatedSymbols *invalidated,
  481. ArrayRef<const MemRegion *> Explicits,
  482. ArrayRef<const MemRegion *> Regions,
  483. const LocationContext *LCtx,
  484. const CallEvent *Call) {
  485. return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
  486. Explicits, Regions,
  487. LCtx, Call);
  488. }
  489. static void
  490. printObjectsUnderConstructionJson(raw_ostream &Out, ProgramStateRef State,
  491. const char *NL, const LocationContext *LCtx,
  492. unsigned int Space = 0, bool IsDot = false) {
  493. PrintingPolicy PP =
  494. LCtx->getAnalysisDeclContext()->getASTContext().getPrintingPolicy();
  495. ++Space;
  496. bool HasItem = false;
  497. // Store the last key.
  498. const ConstructedObjectKey *LastKey = nullptr;
  499. for (const auto &I : State->get<ObjectsUnderConstruction>()) {
  500. const ConstructedObjectKey &Key = I.first;
  501. if (Key.getLocationContext() != LCtx)
  502. continue;
  503. if (!HasItem) {
  504. Out << "[" << NL;
  505. HasItem = true;
  506. }
  507. LastKey = &Key;
  508. }
  509. for (const auto &I : State->get<ObjectsUnderConstruction>()) {
  510. const ConstructedObjectKey &Key = I.first;
  511. SVal Value = I.second;
  512. if (Key.getLocationContext() != LCtx)
  513. continue;
  514. Indent(Out, Space, IsDot) << "{ ";
  515. Key.printJson(Out, nullptr, PP);
  516. Out << ", \"value\": \"" << Value << "\" }";
  517. if (&Key != LastKey)
  518. Out << ',';
  519. Out << NL;
  520. }
  521. if (HasItem)
  522. Indent(Out, --Space, IsDot) << ']'; // End of "location_context".
  523. else {
  524. Out << "null ";
  525. }
  526. }
  527. void ExprEngine::printJson(raw_ostream &Out, ProgramStateRef State,
  528. const LocationContext *LCtx, const char *NL,
  529. unsigned int Space, bool IsDot) const {
  530. Indent(Out, Space, IsDot) << "\"constructing_objects\": ";
  531. if (LCtx && !State->get<ObjectsUnderConstruction>().isEmpty()) {
  532. ++Space;
  533. Out << '[' << NL;
  534. LCtx->printJson(Out, NL, Space, IsDot, [&](const LocationContext *LC) {
  535. printObjectsUnderConstructionJson(Out, State, NL, LC, Space, IsDot);
  536. });
  537. --Space;
  538. Indent(Out, Space, IsDot) << "]," << NL; // End of "constructing_objects".
  539. } else {
  540. Out << "null," << NL;
  541. }
  542. getCheckerManager().runCheckersForPrintStateJson(Out, State, NL, Space,
  543. IsDot);
  544. }
  545. void ExprEngine::processEndWorklist() {
  546. getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
  547. }
  548. void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
  549. unsigned StmtIdx, NodeBuilderContext *Ctx) {
  550. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  551. currStmtIdx = StmtIdx;
  552. currBldrCtx = Ctx;
  553. switch (E.getKind()) {
  554. case CFGElement::Statement:
  555. case CFGElement::Constructor:
  556. case CFGElement::CXXRecordTypedCall:
  557. ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred);
  558. return;
  559. case CFGElement::Initializer:
  560. ProcessInitializer(E.castAs<CFGInitializer>(), Pred);
  561. return;
  562. case CFGElement::NewAllocator:
  563. ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
  564. Pred);
  565. return;
  566. case CFGElement::AutomaticObjectDtor:
  567. case CFGElement::DeleteDtor:
  568. case CFGElement::BaseDtor:
  569. case CFGElement::MemberDtor:
  570. case CFGElement::TemporaryDtor:
  571. ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
  572. return;
  573. case CFGElement::LoopExit:
  574. ProcessLoopExit(E.castAs<CFGLoopExit>().getLoopStmt(), Pred);
  575. return;
  576. case CFGElement::LifetimeEnds:
  577. case CFGElement::ScopeBegin:
  578. case CFGElement::ScopeEnd:
  579. return;
  580. }
  581. }
  582. static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
  583. const Stmt *S,
  584. const ExplodedNode *Pred,
  585. const LocationContext *LC) {
  586. // Are we never purging state values?
  587. if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
  588. return false;
  589. // Is this the beginning of a basic block?
  590. if (Pred->getLocation().getAs<BlockEntrance>())
  591. return true;
  592. // Is this on a non-expression?
  593. if (!isa<Expr>(S))
  594. return true;
  595. // Run before processing a call.
  596. if (CallEvent::isCallStmt(S))
  597. return true;
  598. // Is this an expression that is consumed by another expression? If so,
  599. // postpone cleaning out the state.
  600. ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
  601. return !PM.isConsumedExpr(cast<Expr>(S));
  602. }
  603. void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
  604. const Stmt *ReferenceStmt,
  605. const LocationContext *LC,
  606. const Stmt *DiagnosticStmt,
  607. ProgramPoint::Kind K) {
  608. assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
  609. ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
  610. && "PostStmt is not generally supported by the SymbolReaper yet");
  611. assert(LC && "Must pass the current (or expiring) LocationContext");
  612. if (!DiagnosticStmt) {
  613. DiagnosticStmt = ReferenceStmt;
  614. assert(DiagnosticStmt && "Required for clearing a LocationContext");
  615. }
  616. NumRemoveDeadBindings++;
  617. ProgramStateRef CleanedState = Pred->getState();
  618. // LC is the location context being destroyed, but SymbolReaper wants a
  619. // location context that is still live. (If this is the top-level stack
  620. // frame, this will be null.)
  621. if (!ReferenceStmt) {
  622. assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
  623. "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
  624. LC = LC->getParent();
  625. }
  626. const StackFrameContext *SFC = LC ? LC->getStackFrame() : nullptr;
  627. SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
  628. for (auto I : CleanedState->get<ObjectsUnderConstruction>()) {
  629. if (SymbolRef Sym = I.second.getAsSymbol())
  630. SymReaper.markLive(Sym);
  631. if (const MemRegion *MR = I.second.getAsRegion())
  632. SymReaper.markLive(MR);
  633. }
  634. getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
  635. // Create a state in which dead bindings are removed from the environment
  636. // and the store. TODO: The function should just return new env and store,
  637. // not a new state.
  638. CleanedState = StateMgr.removeDeadBindings(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::escapeValue(ProgramStateRef State, SVal V,
  1027. PointerEscapeKind K) const {
  1028. class CollectReachableSymbolsCallback final : public SymbolVisitor {
  1029. InvalidatedSymbols Symbols;
  1030. public:
  1031. explicit CollectReachableSymbolsCallback(ProgramStateRef) {}
  1032. const InvalidatedSymbols &getSymbols() const { return Symbols; }
  1033. bool VisitSymbol(SymbolRef Sym) override {
  1034. Symbols.insert(Sym);
  1035. return true;
  1036. }
  1037. };
  1038. const CollectReachableSymbolsCallback &Scanner =
  1039. State->scanReachableSymbols<CollectReachableSymbolsCallback>(V);
  1040. return getCheckerManager().runCheckersForPointerEscape(
  1041. State, Scanner.getSymbols(), /*CallEvent*/ nullptr, K, nullptr);
  1042. }
  1043. void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
  1044. ExplodedNodeSet &DstTop) {
  1045. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1046. S->getBeginLoc(), "Error evaluating statement");
  1047. ExplodedNodeSet Dst;
  1048. StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
  1049. assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
  1050. switch (S->getStmtClass()) {
  1051. // C++, OpenMP and ARC stuff we don't support yet.
  1052. case Expr::ObjCIndirectCopyRestoreExprClass:
  1053. case Stmt::CXXDependentScopeMemberExprClass:
  1054. case Stmt::CXXInheritedCtorInitExprClass:
  1055. case Stmt::CXXTryStmtClass:
  1056. case Stmt::CXXTypeidExprClass:
  1057. case Stmt::CXXUuidofExprClass:
  1058. case Stmt::CXXFoldExprClass:
  1059. case Stmt::MSPropertyRefExprClass:
  1060. case Stmt::MSPropertySubscriptExprClass:
  1061. case Stmt::CXXUnresolvedConstructExprClass:
  1062. case Stmt::DependentScopeDeclRefExprClass:
  1063. case Stmt::ArrayTypeTraitExprClass:
  1064. case Stmt::ExpressionTraitExprClass:
  1065. case Stmt::UnresolvedLookupExprClass:
  1066. case Stmt::UnresolvedMemberExprClass:
  1067. case Stmt::TypoExprClass:
  1068. case Stmt::CXXNoexceptExprClass:
  1069. case Stmt::PackExpansionExprClass:
  1070. case Stmt::SubstNonTypeTemplateParmPackExprClass:
  1071. case Stmt::FunctionParmPackExprClass:
  1072. case Stmt::CoroutineBodyStmtClass:
  1073. case Stmt::CoawaitExprClass:
  1074. case Stmt::DependentCoawaitExprClass:
  1075. case Stmt::CoreturnStmtClass:
  1076. case Stmt::CoyieldExprClass:
  1077. case Stmt::SEHTryStmtClass:
  1078. case Stmt::SEHExceptStmtClass:
  1079. case Stmt::SEHLeaveStmtClass:
  1080. case Stmt::SEHFinallyStmtClass:
  1081. case Stmt::OMPParallelDirectiveClass:
  1082. case Stmt::OMPSimdDirectiveClass:
  1083. case Stmt::OMPForDirectiveClass:
  1084. case Stmt::OMPForSimdDirectiveClass:
  1085. case Stmt::OMPSectionsDirectiveClass:
  1086. case Stmt::OMPSectionDirectiveClass:
  1087. case Stmt::OMPSingleDirectiveClass:
  1088. case Stmt::OMPMasterDirectiveClass:
  1089. case Stmt::OMPCriticalDirectiveClass:
  1090. case Stmt::OMPParallelForDirectiveClass:
  1091. case Stmt::OMPParallelForSimdDirectiveClass:
  1092. case Stmt::OMPParallelSectionsDirectiveClass:
  1093. case Stmt::OMPTaskDirectiveClass:
  1094. case Stmt::OMPTaskyieldDirectiveClass:
  1095. case Stmt::OMPBarrierDirectiveClass:
  1096. case Stmt::OMPTaskwaitDirectiveClass:
  1097. case Stmt::OMPTaskgroupDirectiveClass:
  1098. case Stmt::OMPFlushDirectiveClass:
  1099. case Stmt::OMPOrderedDirectiveClass:
  1100. case Stmt::OMPAtomicDirectiveClass:
  1101. case Stmt::OMPTargetDirectiveClass:
  1102. case Stmt::OMPTargetDataDirectiveClass:
  1103. case Stmt::OMPTargetEnterDataDirectiveClass:
  1104. case Stmt::OMPTargetExitDataDirectiveClass:
  1105. case Stmt::OMPTargetParallelDirectiveClass:
  1106. case Stmt::OMPTargetParallelForDirectiveClass:
  1107. case Stmt::OMPTargetUpdateDirectiveClass:
  1108. case Stmt::OMPTeamsDirectiveClass:
  1109. case Stmt::OMPCancellationPointDirectiveClass:
  1110. case Stmt::OMPCancelDirectiveClass:
  1111. case Stmt::OMPTaskLoopDirectiveClass:
  1112. case Stmt::OMPTaskLoopSimdDirectiveClass:
  1113. case Stmt::OMPDistributeDirectiveClass:
  1114. case Stmt::OMPDistributeParallelForDirectiveClass:
  1115. case Stmt::OMPDistributeParallelForSimdDirectiveClass:
  1116. case Stmt::OMPDistributeSimdDirectiveClass:
  1117. case Stmt::OMPTargetParallelForSimdDirectiveClass:
  1118. case Stmt::OMPTargetSimdDirectiveClass:
  1119. case Stmt::OMPTeamsDistributeDirectiveClass:
  1120. case Stmt::OMPTeamsDistributeSimdDirectiveClass:
  1121. case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
  1122. case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
  1123. case Stmt::OMPTargetTeamsDirectiveClass:
  1124. case Stmt::OMPTargetTeamsDistributeDirectiveClass:
  1125. case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
  1126. case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
  1127. case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
  1128. case Stmt::CapturedStmtClass: {
  1129. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  1130. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  1131. break;
  1132. }
  1133. case Stmt::ParenExprClass:
  1134. llvm_unreachable("ParenExprs already handled.");
  1135. case Stmt::GenericSelectionExprClass:
  1136. llvm_unreachable("GenericSelectionExprs already handled.");
  1137. // Cases that should never be evaluated simply because they shouldn't
  1138. // appear in the CFG.
  1139. case Stmt::BreakStmtClass:
  1140. case Stmt::CaseStmtClass:
  1141. case Stmt::CompoundStmtClass:
  1142. case Stmt::ContinueStmtClass:
  1143. case Stmt::CXXForRangeStmtClass:
  1144. case Stmt::DefaultStmtClass:
  1145. case Stmt::DoStmtClass:
  1146. case Stmt::ForStmtClass:
  1147. case Stmt::GotoStmtClass:
  1148. case Stmt::IfStmtClass:
  1149. case Stmt::IndirectGotoStmtClass:
  1150. case Stmt::LabelStmtClass:
  1151. case Stmt::NoStmtClass:
  1152. case Stmt::NullStmtClass:
  1153. case Stmt::SwitchStmtClass:
  1154. case Stmt::WhileStmtClass:
  1155. case Expr::MSDependentExistsStmtClass:
  1156. llvm_unreachable("Stmt should not be in analyzer evaluation loop");
  1157. case Stmt::ObjCSubscriptRefExprClass:
  1158. case Stmt::ObjCPropertyRefExprClass:
  1159. llvm_unreachable("These are handled by PseudoObjectExpr");
  1160. case Stmt::GNUNullExprClass: {
  1161. // GNU __null is a pointer-width integer, not an actual pointer.
  1162. ProgramStateRef state = Pred->getState();
  1163. state = state->BindExpr(S, Pred->getLocationContext(),
  1164. svalBuilder.makeIntValWithPtrWidth(0, false));
  1165. Bldr.generateNode(S, Pred, state);
  1166. break;
  1167. }
  1168. case Stmt::ObjCAtSynchronizedStmtClass:
  1169. Bldr.takeNodes(Pred);
  1170. VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
  1171. Bldr.addNodes(Dst);
  1172. break;
  1173. case Expr::ConstantExprClass:
  1174. case Stmt::ExprWithCleanupsClass:
  1175. // Handled due to fully linearised CFG.
  1176. break;
  1177. case Stmt::CXXBindTemporaryExprClass: {
  1178. Bldr.takeNodes(Pred);
  1179. ExplodedNodeSet PreVisit;
  1180. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1181. ExplodedNodeSet Next;
  1182. VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
  1183. getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
  1184. Bldr.addNodes(Dst);
  1185. break;
  1186. }
  1187. // Cases not handled yet; but will handle some day.
  1188. case Stmt::DesignatedInitExprClass:
  1189. case Stmt::DesignatedInitUpdateExprClass:
  1190. case Stmt::ArrayInitLoopExprClass:
  1191. case Stmt::ArrayInitIndexExprClass:
  1192. case Stmt::ExtVectorElementExprClass:
  1193. case Stmt::ImaginaryLiteralClass:
  1194. case Stmt::ObjCAtCatchStmtClass:
  1195. case Stmt::ObjCAtFinallyStmtClass:
  1196. case Stmt::ObjCAtTryStmtClass:
  1197. case Stmt::ObjCAutoreleasePoolStmtClass:
  1198. case Stmt::ObjCEncodeExprClass:
  1199. case Stmt::ObjCIsaExprClass:
  1200. case Stmt::ObjCProtocolExprClass:
  1201. case Stmt::ObjCSelectorExprClass:
  1202. case Stmt::ParenListExprClass:
  1203. case Stmt::ShuffleVectorExprClass:
  1204. case Stmt::ConvertVectorExprClass:
  1205. case Stmt::VAArgExprClass:
  1206. case Stmt::CUDAKernelCallExprClass:
  1207. case Stmt::OpaqueValueExprClass:
  1208. case Stmt::AsTypeExprClass:
  1209. // Fall through.
  1210. // Cases we intentionally don't evaluate, since they don't need
  1211. // to be explicitly evaluated.
  1212. case Stmt::PredefinedExprClass:
  1213. case Stmt::AddrLabelExprClass:
  1214. case Stmt::AttributedStmtClass:
  1215. case Stmt::IntegerLiteralClass:
  1216. case Stmt::FixedPointLiteralClass:
  1217. case Stmt::CharacterLiteralClass:
  1218. case Stmt::ImplicitValueInitExprClass:
  1219. case Stmt::CXXScalarValueInitExprClass:
  1220. case Stmt::CXXBoolLiteralExprClass:
  1221. case Stmt::ObjCBoolLiteralExprClass:
  1222. case Stmt::ObjCAvailabilityCheckExprClass:
  1223. case Stmt::FloatingLiteralClass:
  1224. case Stmt::NoInitExprClass:
  1225. case Stmt::SizeOfPackExprClass:
  1226. case Stmt::StringLiteralClass:
  1227. case Stmt::SourceLocExprClass:
  1228. case Stmt::ObjCStringLiteralClass:
  1229. case Stmt::CXXPseudoDestructorExprClass:
  1230. case Stmt::SubstNonTypeTemplateParmExprClass:
  1231. case Stmt::CXXNullPtrLiteralExprClass:
  1232. case Stmt::OMPArraySectionExprClass:
  1233. case Stmt::TypeTraitExprClass: {
  1234. Bldr.takeNodes(Pred);
  1235. ExplodedNodeSet preVisit;
  1236. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  1237. getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
  1238. Bldr.addNodes(Dst);
  1239. break;
  1240. }
  1241. case Stmt::CXXDefaultArgExprClass:
  1242. case Stmt::CXXDefaultInitExprClass: {
  1243. Bldr.takeNodes(Pred);
  1244. ExplodedNodeSet PreVisit;
  1245. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1246. ExplodedNodeSet Tmp;
  1247. StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
  1248. const Expr *ArgE;
  1249. if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S))
  1250. ArgE = DefE->getExpr();
  1251. else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S))
  1252. ArgE = DefE->getExpr();
  1253. else
  1254. llvm_unreachable("unknown constant wrapper kind");
  1255. bool IsTemporary = false;
  1256. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
  1257. ArgE = MTE->GetTemporaryExpr();
  1258. IsTemporary = true;
  1259. }
  1260. Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
  1261. if (!ConstantVal)
  1262. ConstantVal = UnknownVal();
  1263. const LocationContext *LCtx = Pred->getLocationContext();
  1264. for (const auto I : PreVisit) {
  1265. ProgramStateRef State = I->getState();
  1266. State = State->BindExpr(S, LCtx, *ConstantVal);
  1267. if (IsTemporary)
  1268. State = createTemporaryRegionIfNeeded(State, LCtx,
  1269. cast<Expr>(S),
  1270. cast<Expr>(S));
  1271. Bldr2.generateNode(S, I, State);
  1272. }
  1273. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  1274. Bldr.addNodes(Dst);
  1275. break;
  1276. }
  1277. // Cases we evaluate as opaque expressions, conjuring a symbol.
  1278. case Stmt::CXXStdInitializerListExprClass:
  1279. case Expr::ObjCArrayLiteralClass:
  1280. case Expr::ObjCDictionaryLiteralClass:
  1281. case Expr::ObjCBoxedExprClass: {
  1282. Bldr.takeNodes(Pred);
  1283. ExplodedNodeSet preVisit;
  1284. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  1285. ExplodedNodeSet Tmp;
  1286. StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
  1287. const auto *Ex = cast<Expr>(S);
  1288. QualType resultType = Ex->getType();
  1289. for (const auto N : preVisit) {
  1290. const LocationContext *LCtx = N->getLocationContext();
  1291. SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
  1292. resultType,
  1293. currBldrCtx->blockCount());
  1294. ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
  1295. // Escape pointers passed into the list, unless it's an ObjC boxed
  1296. // expression which is not a boxable C structure.
  1297. if (!(isa<ObjCBoxedExpr>(Ex) &&
  1298. !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
  1299. ->getType()->isRecordType()))
  1300. for (auto Child : Ex->children()) {
  1301. assert(Child);
  1302. SVal Val = State->getSVal(Child, LCtx);
  1303. State = escapeValue(State, Val, PSK_EscapeOther);
  1304. }
  1305. Bldr2.generateNode(S, N, State);
  1306. }
  1307. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  1308. Bldr.addNodes(Dst);
  1309. break;
  1310. }
  1311. case Stmt::ArraySubscriptExprClass:
  1312. Bldr.takeNodes(Pred);
  1313. VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
  1314. Bldr.addNodes(Dst);
  1315. break;
  1316. case Stmt::GCCAsmStmtClass:
  1317. Bldr.takeNodes(Pred);
  1318. VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
  1319. Bldr.addNodes(Dst);
  1320. break;
  1321. case Stmt::MSAsmStmtClass:
  1322. Bldr.takeNodes(Pred);
  1323. VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
  1324. Bldr.addNodes(Dst);
  1325. break;
  1326. case Stmt::BlockExprClass:
  1327. Bldr.takeNodes(Pred);
  1328. VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
  1329. Bldr.addNodes(Dst);
  1330. break;
  1331. case Stmt::LambdaExprClass:
  1332. if (AMgr.options.ShouldInlineLambdas) {
  1333. Bldr.takeNodes(Pred);
  1334. VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
  1335. Bldr.addNodes(Dst);
  1336. } else {
  1337. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  1338. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  1339. }
  1340. break;
  1341. case Stmt::BinaryOperatorClass: {
  1342. const auto *B = cast<BinaryOperator>(S);
  1343. if (B->isLogicalOp()) {
  1344. Bldr.takeNodes(Pred);
  1345. VisitLogicalExpr(B, Pred, Dst);
  1346. Bldr.addNodes(Dst);
  1347. break;
  1348. }
  1349. else if (B->getOpcode() == BO_Comma) {
  1350. ProgramStateRef state = Pred->getState();
  1351. Bldr.generateNode(B, Pred,
  1352. state->BindExpr(B, Pred->getLocationContext(),
  1353. state->getSVal(B->getRHS(),
  1354. Pred->getLocationContext())));
  1355. break;
  1356. }
  1357. Bldr.takeNodes(Pred);
  1358. if (AMgr.options.ShouldEagerlyAssume &&
  1359. (B->isRelationalOp() || B->isEqualityOp())) {
  1360. ExplodedNodeSet Tmp;
  1361. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
  1362. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
  1363. }
  1364. else
  1365. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  1366. Bldr.addNodes(Dst);
  1367. break;
  1368. }
  1369. case Stmt::CXXOperatorCallExprClass: {
  1370. const auto *OCE = cast<CXXOperatorCallExpr>(S);
  1371. // For instance method operators, make sure the 'this' argument has a
  1372. // valid region.
  1373. const Decl *Callee = OCE->getCalleeDecl();
  1374. if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
  1375. if (MD->isInstance()) {
  1376. ProgramStateRef State = Pred->getState();
  1377. const LocationContext *LCtx = Pred->getLocationContext();
  1378. ProgramStateRef NewState =
  1379. createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
  1380. if (NewState != State) {
  1381. Pred = Bldr.generateNode(OCE, Pred, NewState, /*tag=*/nullptr,
  1382. ProgramPoint::PreStmtKind);
  1383. // Did we cache out?
  1384. if (!Pred)
  1385. break;
  1386. }
  1387. }
  1388. }
  1389. // FALLTHROUGH
  1390. LLVM_FALLTHROUGH;
  1391. }
  1392. case Stmt::CallExprClass:
  1393. case Stmt::CXXMemberCallExprClass:
  1394. case Stmt::UserDefinedLiteralClass:
  1395. Bldr.takeNodes(Pred);
  1396. VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
  1397. Bldr.addNodes(Dst);
  1398. break;
  1399. case Stmt::CXXCatchStmtClass:
  1400. Bldr.takeNodes(Pred);
  1401. VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
  1402. Bldr.addNodes(Dst);
  1403. break;
  1404. case Stmt::CXXTemporaryObjectExprClass:
  1405. case Stmt::CXXConstructExprClass:
  1406. Bldr.takeNodes(Pred);
  1407. VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
  1408. Bldr.addNodes(Dst);
  1409. break;
  1410. case Stmt::CXXNewExprClass: {
  1411. Bldr.takeNodes(Pred);
  1412. ExplodedNodeSet PreVisit;
  1413. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1414. ExplodedNodeSet PostVisit;
  1415. for (const auto i : PreVisit)
  1416. VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit);
  1417. getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
  1418. Bldr.addNodes(Dst);
  1419. break;
  1420. }
  1421. case Stmt::CXXDeleteExprClass: {
  1422. Bldr.takeNodes(Pred);
  1423. ExplodedNodeSet PreVisit;
  1424. const auto *CDE = cast<CXXDeleteExpr>(S);
  1425. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1426. for (const auto i : PreVisit)
  1427. VisitCXXDeleteExpr(CDE, i, Dst);
  1428. Bldr.addNodes(Dst);
  1429. break;
  1430. }
  1431. // FIXME: ChooseExpr is really a constant. We need to fix
  1432. // the CFG do not model them as explicit control-flow.
  1433. case Stmt::ChooseExprClass: { // __builtin_choose_expr
  1434. Bldr.takeNodes(Pred);
  1435. const auto *C = cast<ChooseExpr>(S);
  1436. VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
  1437. Bldr.addNodes(Dst);
  1438. break;
  1439. }
  1440. case Stmt::CompoundAssignOperatorClass:
  1441. Bldr.takeNodes(Pred);
  1442. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  1443. Bldr.addNodes(Dst);
  1444. break;
  1445. case Stmt::CompoundLiteralExprClass:
  1446. Bldr.takeNodes(Pred);
  1447. VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
  1448. Bldr.addNodes(Dst);
  1449. break;
  1450. case Stmt::BinaryConditionalOperatorClass:
  1451. case Stmt::ConditionalOperatorClass: { // '?' operator
  1452. Bldr.takeNodes(Pred);
  1453. const auto *C = cast<AbstractConditionalOperator>(S);
  1454. VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
  1455. Bldr.addNodes(Dst);
  1456. break;
  1457. }
  1458. case Stmt::CXXThisExprClass:
  1459. Bldr.takeNodes(Pred);
  1460. VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
  1461. Bldr.addNodes(Dst);
  1462. break;
  1463. case Stmt::DeclRefExprClass: {
  1464. Bldr.takeNodes(Pred);
  1465. const auto *DE = cast<DeclRefExpr>(S);
  1466. VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
  1467. Bldr.addNodes(Dst);
  1468. break;
  1469. }
  1470. case Stmt::DeclStmtClass:
  1471. Bldr.takeNodes(Pred);
  1472. VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
  1473. Bldr.addNodes(Dst);
  1474. break;
  1475. case Stmt::ImplicitCastExprClass:
  1476. case Stmt::CStyleCastExprClass:
  1477. case Stmt::CXXStaticCastExprClass:
  1478. case Stmt::CXXDynamicCastExprClass:
  1479. case Stmt::CXXReinterpretCastExprClass:
  1480. case Stmt::CXXConstCastExprClass:
  1481. case Stmt::CXXFunctionalCastExprClass:
  1482. case Stmt::BuiltinBitCastExprClass:
  1483. case Stmt::ObjCBridgedCastExprClass: {
  1484. Bldr.takeNodes(Pred);
  1485. const auto *C = cast<CastExpr>(S);
  1486. ExplodedNodeSet dstExpr;
  1487. VisitCast(C, C->getSubExpr(), Pred, dstExpr);
  1488. // Handle the postvisit checks.
  1489. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
  1490. Bldr.addNodes(Dst);
  1491. break;
  1492. }
  1493. case Expr::MaterializeTemporaryExprClass: {
  1494. Bldr.takeNodes(Pred);
  1495. const auto *MTE = cast<MaterializeTemporaryExpr>(S);
  1496. ExplodedNodeSet dstPrevisit;
  1497. getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
  1498. ExplodedNodeSet dstExpr;
  1499. for (const auto i : dstPrevisit)
  1500. CreateCXXTemporaryObject(MTE, i, dstExpr);
  1501. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
  1502. Bldr.addNodes(Dst);
  1503. break;
  1504. }
  1505. case Stmt::InitListExprClass:
  1506. Bldr.takeNodes(Pred);
  1507. VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
  1508. Bldr.addNodes(Dst);
  1509. break;
  1510. case Stmt::MemberExprClass:
  1511. Bldr.takeNodes(Pred);
  1512. VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
  1513. Bldr.addNodes(Dst);
  1514. break;
  1515. case Stmt::AtomicExprClass:
  1516. Bldr.takeNodes(Pred);
  1517. VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
  1518. Bldr.addNodes(Dst);
  1519. break;
  1520. case Stmt::ObjCIvarRefExprClass:
  1521. Bldr.takeNodes(Pred);
  1522. VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
  1523. Bldr.addNodes(Dst);
  1524. break;
  1525. case Stmt::ObjCForCollectionStmtClass:
  1526. Bldr.takeNodes(Pred);
  1527. VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
  1528. Bldr.addNodes(Dst);
  1529. break;
  1530. case Stmt::ObjCMessageExprClass:
  1531. Bldr.takeNodes(Pred);
  1532. VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
  1533. Bldr.addNodes(Dst);
  1534. break;
  1535. case Stmt::ObjCAtThrowStmtClass:
  1536. case Stmt::CXXThrowExprClass:
  1537. // FIXME: This is not complete. We basically treat @throw as
  1538. // an abort.
  1539. Bldr.generateSink(S, Pred, Pred->getState());
  1540. break;
  1541. case Stmt::ReturnStmtClass:
  1542. Bldr.takeNodes(Pred);
  1543. VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
  1544. Bldr.addNodes(Dst);
  1545. break;
  1546. case Stmt::OffsetOfExprClass: {
  1547. Bldr.takeNodes(Pred);
  1548. ExplodedNodeSet PreVisit;
  1549. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  1550. ExplodedNodeSet PostVisit;
  1551. for (const auto Node : PreVisit)
  1552. VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit);
  1553. getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
  1554. Bldr.addNodes(Dst);
  1555. break;
  1556. }
  1557. case Stmt::UnaryExprOrTypeTraitExprClass:
  1558. Bldr.takeNodes(Pred);
  1559. VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  1560. Pred, Dst);
  1561. Bldr.addNodes(Dst);
  1562. break;
  1563. case Stmt::StmtExprClass: {
  1564. const auto *SE = cast<StmtExpr>(S);
  1565. if (SE->getSubStmt()->body_empty()) {
  1566. // Empty statement expression.
  1567. assert(SE->getType() == getContext().VoidTy
  1568. && "Empty statement expression must have void type.");
  1569. break;
  1570. }
  1571. if (const auto *LastExpr =
  1572. dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
  1573. ProgramStateRef state = Pred->getState();
  1574. Bldr.generateNode(SE, Pred,
  1575. state->BindExpr(SE, Pred->getLocationContext(),
  1576. state->getSVal(LastExpr,
  1577. Pred->getLocationContext())));
  1578. }
  1579. break;
  1580. }
  1581. case Stmt::UnaryOperatorClass: {
  1582. Bldr.takeNodes(Pred);
  1583. const auto *U = cast<UnaryOperator>(S);
  1584. if (AMgr.options.ShouldEagerlyAssume && (U->getOpcode() == UO_LNot)) {
  1585. ExplodedNodeSet Tmp;
  1586. VisitUnaryOperator(U, Pred, Tmp);
  1587. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
  1588. }
  1589. else
  1590. VisitUnaryOperator(U, Pred, Dst);
  1591. Bldr.addNodes(Dst);
  1592. break;
  1593. }
  1594. case Stmt::PseudoObjectExprClass: {
  1595. Bldr.takeNodes(Pred);
  1596. ProgramStateRef state = Pred->getState();
  1597. const auto *PE = cast<PseudoObjectExpr>(S);
  1598. if (const Expr *Result = PE->getResultExpr()) {
  1599. SVal V = state->getSVal(Result, Pred->getLocationContext());
  1600. Bldr.generateNode(S, Pred,
  1601. state->BindExpr(S, Pred->getLocationContext(), V));
  1602. }
  1603. else
  1604. Bldr.generateNode(S, Pred,
  1605. state->BindExpr(S, Pred->getLocationContext(),
  1606. UnknownVal()));
  1607. Bldr.addNodes(Dst);
  1608. break;
  1609. }
  1610. }
  1611. }
  1612. bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
  1613. const LocationContext *CalleeLC) {
  1614. const StackFrameContext *CalleeSF = CalleeLC->getStackFrame();
  1615. const StackFrameContext *CallerSF = CalleeSF->getParent()->getStackFrame();
  1616. assert(CalleeSF && CallerSF);
  1617. ExplodedNode *BeforeProcessingCall = nullptr;
  1618. const Stmt *CE = CalleeSF->getCallSite();
  1619. // Find the first node before we started processing the call expression.
  1620. while (N) {
  1621. ProgramPoint L = N->getLocation();
  1622. BeforeProcessingCall = N;
  1623. N = N->pred_empty() ? nullptr : *(N->pred_begin());
  1624. // Skip the nodes corresponding to the inlined code.
  1625. if (L.getStackFrame() != CallerSF)
  1626. continue;
  1627. // We reached the caller. Find the node right before we started
  1628. // processing the call.
  1629. if (L.isPurgeKind())
  1630. continue;
  1631. if (L.getAs<PreImplicitCall>())
  1632. continue;
  1633. if (L.getAs<CallEnter>())
  1634. continue;
  1635. if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
  1636. if (SP->getStmt() == CE)
  1637. continue;
  1638. break;
  1639. }
  1640. if (!BeforeProcessingCall)
  1641. return false;
  1642. // TODO: Clean up the unneeded nodes.
  1643. // Build an Epsilon node from which we will restart the analyzes.
  1644. // Note that CE is permitted to be NULL!
  1645. ProgramPoint NewNodeLoc =
  1646. EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
  1647. // Add the special flag to GDM to signal retrying with no inlining.
  1648. // Note, changing the state ensures that we are not going to cache out.
  1649. ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
  1650. NewNodeState =
  1651. NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
  1652. // Make the new node a successor of BeforeProcessingCall.
  1653. bool IsNew = false;
  1654. ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
  1655. // We cached out at this point. Caching out is common due to us backtracking
  1656. // from the inlined function, which might spawn several paths.
  1657. if (!IsNew)
  1658. return true;
  1659. NewNode->addPredecessor(BeforeProcessingCall, G);
  1660. // Add the new node to the work list.
  1661. Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
  1662. CalleeSF->getIndex());
  1663. NumTimesRetriedWithoutInlining++;
  1664. return true;
  1665. }
  1666. /// Block entrance. (Update counters).
  1667. void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
  1668. NodeBuilderWithSinks &nodeBuilder,
  1669. ExplodedNode *Pred) {
  1670. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1671. // If we reach a loop which has a known bound (and meets
  1672. // other constraints) then consider completely unrolling it.
  1673. if(AMgr.options.ShouldUnrollLoops) {
  1674. unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
  1675. const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminatorStmt();
  1676. if (Term) {
  1677. ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
  1678. Pred, maxBlockVisitOnPath);
  1679. if (NewState != Pred->getState()) {
  1680. ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
  1681. if (!UpdatedNode)
  1682. return;
  1683. Pred = UpdatedNode;
  1684. }
  1685. }
  1686. // Is we are inside an unrolled loop then no need the check the counters.
  1687. if(isUnrolledState(Pred->getState()))
  1688. return;
  1689. }
  1690. // If this block is terminated by a loop and it has already been visited the
  1691. // maximum number of times, widen the loop.
  1692. unsigned int BlockCount = nodeBuilder.getContext().blockCount();
  1693. if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
  1694. AMgr.options.ShouldWidenLoops) {
  1695. const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminatorStmt();
  1696. if (!(Term &&
  1697. (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
  1698. return;
  1699. // Widen.
  1700. const LocationContext *LCtx = Pred->getLocationContext();
  1701. ProgramStateRef WidenedState =
  1702. getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
  1703. nodeBuilder.generateNode(WidenedState, Pred);
  1704. return;
  1705. }
  1706. // FIXME: Refactor this into a checker.
  1707. if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
  1708. static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
  1709. const ExplodedNode *Sink =
  1710. nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
  1711. // Check if we stopped at the top level function or not.
  1712. // Root node should have the location context of the top most function.
  1713. const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
  1714. const LocationContext *CalleeSF = CalleeLC->getStackFrame();
  1715. const LocationContext *RootLC =
  1716. (*G.roots_begin())->getLocation().getLocationContext();
  1717. if (RootLC->getStackFrame() != CalleeSF) {
  1718. Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
  1719. // Re-run the call evaluation without inlining it, by storing the
  1720. // no-inlining policy in the state and enqueuing the new work item on
  1721. // the list. Replay should almost never fail. Use the stats to catch it
  1722. // if it does.
  1723. if ((!AMgr.options.NoRetryExhausted &&
  1724. replayWithoutInlining(Pred, CalleeLC)))
  1725. return;
  1726. NumMaxBlockCountReachedInInlined++;
  1727. } else
  1728. NumMaxBlockCountReached++;
  1729. // Make sink nodes as exhausted(for stats) only if retry failed.
  1730. Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
  1731. }
  1732. }
  1733. //===----------------------------------------------------------------------===//
  1734. // Branch processing.
  1735. //===----------------------------------------------------------------------===//
  1736. /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
  1737. /// to try to recover some path-sensitivity for casts of symbolic
  1738. /// integers that promote their values (which are currently not tracked well).
  1739. /// This function returns the SVal bound to Condition->IgnoreCasts if all the
  1740. // cast(s) did was sign-extend the original value.
  1741. static SVal RecoverCastedSymbol(ProgramStateRef state,
  1742. const Stmt *Condition,
  1743. const LocationContext *LCtx,
  1744. ASTContext &Ctx) {
  1745. const auto *Ex = dyn_cast<Expr>(Condition);
  1746. if (!Ex)
  1747. return UnknownVal();
  1748. uint64_t bits = 0;
  1749. bool bitsInit = false;
  1750. while (const auto *CE = dyn_cast<CastExpr>(Ex)) {
  1751. QualType T = CE->getType();
  1752. if (!T->isIntegralOrEnumerationType())
  1753. return UnknownVal();
  1754. uint64_t newBits = Ctx.getTypeSize(T);
  1755. if (!bitsInit || newBits < bits) {
  1756. bitsInit = true;
  1757. bits = newBits;
  1758. }
  1759. Ex = CE->getSubExpr();
  1760. }
  1761. // We reached a non-cast. Is it a symbolic value?
  1762. QualType T = Ex->getType();
  1763. if (!bitsInit || !T->isIntegralOrEnumerationType() ||
  1764. Ctx.getTypeSize(T) > bits)
  1765. return UnknownVal();
  1766. return state->getSVal(Ex, LCtx);
  1767. }
  1768. #ifndef NDEBUG
  1769. static const Stmt *getRightmostLeaf(const Stmt *Condition) {
  1770. while (Condition) {
  1771. const auto *BO = dyn_cast<BinaryOperator>(Condition);
  1772. if (!BO || !BO->isLogicalOp()) {
  1773. return Condition;
  1774. }
  1775. Condition = BO->getRHS()->IgnoreParens();
  1776. }
  1777. return nullptr;
  1778. }
  1779. #endif
  1780. // Returns the condition the branch at the end of 'B' depends on and whose value
  1781. // has been evaluated within 'B'.
  1782. // In most cases, the terminator condition of 'B' will be evaluated fully in
  1783. // the last statement of 'B'; in those cases, the resolved condition is the
  1784. // given 'Condition'.
  1785. // If the condition of the branch is a logical binary operator tree, the CFG is
  1786. // optimized: in that case, we know that the expression formed by all but the
  1787. // rightmost leaf of the logical binary operator tree must be true, and thus
  1788. // the branch condition is at this point equivalent to the truth value of that
  1789. // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
  1790. // expression in its final statement. As the full condition in that case was
  1791. // not evaluated, and is thus not in the SVal cache, we need to use that leaf
  1792. // expression to evaluate the truth value of the condition in the current state
  1793. // space.
  1794. static const Stmt *ResolveCondition(const Stmt *Condition,
  1795. const CFGBlock *B) {
  1796. if (const auto *Ex = dyn_cast<Expr>(Condition))
  1797. Condition = Ex->IgnoreParens();
  1798. const auto *BO = dyn_cast<BinaryOperator>(Condition);
  1799. if (!BO || !BO->isLogicalOp())
  1800. return Condition;
  1801. assert(B->getTerminator().isStmtBranch() &&
  1802. "Other kinds of branches are handled separately!");
  1803. // For logical operations, we still have the case where some branches
  1804. // use the traditional "merge" approach and others sink the branch
  1805. // directly into the basic blocks representing the logical operation.
  1806. // We need to distinguish between those two cases here.
  1807. // The invariants are still shifting, but it is possible that the
  1808. // last element in a CFGBlock is not a CFGStmt. Look for the last
  1809. // CFGStmt as the value of the condition.
  1810. CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
  1811. for (; I != E; ++I) {
  1812. CFGElement Elem = *I;
  1813. Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
  1814. if (!CS)
  1815. continue;
  1816. const Stmt *LastStmt = CS->getStmt();
  1817. assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
  1818. return LastStmt;
  1819. }
  1820. llvm_unreachable("could not resolve condition");
  1821. }
  1822. void ExprEngine::processBranch(const Stmt *Condition,
  1823. NodeBuilderContext& BldCtx,
  1824. ExplodedNode *Pred,
  1825. ExplodedNodeSet &Dst,
  1826. const CFGBlock *DstT,
  1827. const CFGBlock *DstF) {
  1828. assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
  1829. "CXXBindTemporaryExprs are handled by processBindTemporary.");
  1830. const LocationContext *LCtx = Pred->getLocationContext();
  1831. PrettyStackTraceLocationContext StackCrashInfo(LCtx);
  1832. currBldrCtx = &BldCtx;
  1833. // Check for NULL conditions; e.g. "for(;;)"
  1834. if (!Condition) {
  1835. BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
  1836. NullCondBldr.markInfeasible(false);
  1837. NullCondBldr.generateNode(Pred->getState(), true, Pred);
  1838. return;
  1839. }
  1840. if (const auto *Ex = dyn_cast<Expr>(Condition))
  1841. Condition = Ex->IgnoreParens();
  1842. Condition = ResolveCondition(Condition, BldCtx.getBlock());
  1843. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1844. Condition->getBeginLoc(),
  1845. "Error evaluating branch");
  1846. ExplodedNodeSet CheckersOutSet;
  1847. getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
  1848. Pred, *this);
  1849. // We generated only sinks.
  1850. if (CheckersOutSet.empty())
  1851. return;
  1852. BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
  1853. for (const auto PredI : CheckersOutSet) {
  1854. if (PredI->isSink())
  1855. continue;
  1856. ProgramStateRef PrevState = PredI->getState();
  1857. SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
  1858. if (X.isUnknownOrUndef()) {
  1859. // Give it a chance to recover from unknown.
  1860. if (const auto *Ex = dyn_cast<Expr>(Condition)) {
  1861. if (Ex->getType()->isIntegralOrEnumerationType()) {
  1862. // Try to recover some path-sensitivity. Right now casts of symbolic
  1863. // integers that promote their values are currently not tracked well.
  1864. // If 'Condition' is such an expression, try and recover the
  1865. // underlying value and use that instead.
  1866. SVal recovered = RecoverCastedSymbol(PrevState, Condition,
  1867. PredI->getLocationContext(),
  1868. getContext());
  1869. if (!recovered.isUnknown()) {
  1870. X = recovered;
  1871. }
  1872. }
  1873. }
  1874. }
  1875. // If the condition is still unknown, give up.
  1876. if (X.isUnknownOrUndef()) {
  1877. builder.generateNode(PrevState, true, PredI);
  1878. builder.generateNode(PrevState, false, PredI);
  1879. continue;
  1880. }
  1881. DefinedSVal V = X.castAs<DefinedSVal>();
  1882. ProgramStateRef StTrue, StFalse;
  1883. std::tie(StTrue, StFalse) = PrevState->assume(V);
  1884. // Process the true branch.
  1885. if (builder.isFeasible(true)) {
  1886. if (StTrue)
  1887. builder.generateNode(StTrue, true, PredI);
  1888. else
  1889. builder.markInfeasible(true);
  1890. }
  1891. // Process the false branch.
  1892. if (builder.isFeasible(false)) {
  1893. if (StFalse)
  1894. builder.generateNode(StFalse, false, PredI);
  1895. else
  1896. builder.markInfeasible(false);
  1897. }
  1898. }
  1899. currBldrCtx = nullptr;
  1900. }
  1901. /// The GDM component containing the set of global variables which have been
  1902. /// previously initialized with explicit initializers.
  1903. REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
  1904. llvm::ImmutableSet<const VarDecl *>)
  1905. void ExprEngine::processStaticInitializer(const DeclStmt *DS,
  1906. NodeBuilderContext &BuilderCtx,
  1907. ExplodedNode *Pred,
  1908. ExplodedNodeSet &Dst,
  1909. const CFGBlock *DstT,
  1910. const CFGBlock *DstF) {
  1911. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1912. currBldrCtx = &BuilderCtx;
  1913. const auto *VD = cast<VarDecl>(DS->getSingleDecl());
  1914. ProgramStateRef state = Pred->getState();
  1915. bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
  1916. BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
  1917. if (!initHasRun) {
  1918. state = state->add<InitializedGlobalsSet>(VD);
  1919. }
  1920. builder.generateNode(state, initHasRun, Pred);
  1921. builder.markInfeasible(!initHasRun);
  1922. currBldrCtx = nullptr;
  1923. }
  1924. /// processIndirectGoto - Called by CoreEngine. Used to generate successor
  1925. /// nodes by processing the 'effects' of a computed goto jump.
  1926. void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
  1927. ProgramStateRef state = builder.getState();
  1928. SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
  1929. // Three possibilities:
  1930. //
  1931. // (1) We know the computed label.
  1932. // (2) The label is NULL (or some other constant), or Undefined.
  1933. // (3) We have no clue about the label. Dispatch to all targets.
  1934. //
  1935. using iterator = IndirectGotoNodeBuilder::iterator;
  1936. if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
  1937. const LabelDecl *L = LV->getLabel();
  1938. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
  1939. if (I.getLabel() == L) {
  1940. builder.generateNode(I, state);
  1941. return;
  1942. }
  1943. }
  1944. llvm_unreachable("No block with label.");
  1945. }
  1946. if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
  1947. // Dispatch to the first target and mark it as a sink.
  1948. //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
  1949. // FIXME: add checker visit.
  1950. // UndefBranches.insert(N);
  1951. return;
  1952. }
  1953. // This is really a catch-all. We don't support symbolics yet.
  1954. // FIXME: Implement dispatch for symbolic pointers.
  1955. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I)
  1956. builder.generateNode(I, state);
  1957. }
  1958. void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
  1959. ExplodedNode *Pred,
  1960. ExplodedNodeSet &Dst,
  1961. const BlockEdge &L) {
  1962. SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
  1963. getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
  1964. }
  1965. /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
  1966. /// nodes when the control reaches the end of a function.
  1967. void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
  1968. ExplodedNode *Pred,
  1969. const ReturnStmt *RS) {
  1970. ProgramStateRef State = Pred->getState();
  1971. if (!Pred->getStackFrame()->inTopFrame())
  1972. State = finishArgumentConstruction(
  1973. State, *getStateManager().getCallEventManager().getCaller(
  1974. Pred->getStackFrame(), Pred->getState()));
  1975. // FIXME: We currently cannot assert that temporaries are clear, because
  1976. // lifetime extended temporaries are not always modelled correctly. In some
  1977. // cases when we materialize the temporary, we do
  1978. // createTemporaryRegionIfNeeded(), and the region changes, and also the
  1979. // respective destructor becomes automatic from temporary. So for now clean up
  1980. // the state manually before asserting. Ideally, this braced block of code
  1981. // should go away.
  1982. {
  1983. const LocationContext *FromLC = Pred->getLocationContext();
  1984. const LocationContext *ToLC = FromLC->getStackFrame()->getParent();
  1985. const LocationContext *LC = FromLC;
  1986. while (LC != ToLC) {
  1987. assert(LC && "ToLC must be a parent of FromLC!");
  1988. for (auto I : State->get<ObjectsUnderConstruction>())
  1989. if (I.first.getLocationContext() == LC) {
  1990. // The comment above only pardons us for not cleaning up a
  1991. // temporary destructor. If any other statements are found here,
  1992. // it must be a separate problem.
  1993. assert(I.first.getItem().getKind() ==
  1994. ConstructionContextItem::TemporaryDestructorKind ||
  1995. I.first.getItem().getKind() ==
  1996. ConstructionContextItem::ElidedDestructorKind);
  1997. State = State->remove<ObjectsUnderConstruction>(I.first);
  1998. }
  1999. LC = LC->getParent();
  2000. }
  2001. }
  2002. // Perform the transition with cleanups.
  2003. if (State != Pred->getState()) {
  2004. ExplodedNodeSet PostCleanup;
  2005. NodeBuilder Bldr(Pred, PostCleanup, BC);
  2006. Pred = Bldr.generateNode(Pred->getLocation(), State, Pred);
  2007. if (!Pred) {
  2008. // The node with clean temporaries already exists. We might have reached
  2009. // it on a path on which we initialize different temporaries.
  2010. return;
  2011. }
  2012. }
  2013. assert(areAllObjectsFullyConstructed(Pred->getState(),
  2014. Pred->getLocationContext(),
  2015. Pred->getStackFrame()->getParent()));
  2016. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  2017. ExplodedNodeSet Dst;
  2018. if (Pred->getLocationContext()->inTopFrame()) {
  2019. // Remove dead symbols.
  2020. ExplodedNodeSet AfterRemovedDead;
  2021. removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
  2022. // Notify checkers.
  2023. for (const auto I : AfterRemovedDead)
  2024. getCheckerManager().runCheckersForEndFunction(BC, Dst, I, *this, RS);
  2025. } else {
  2026. getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this, RS);
  2027. }
  2028. Engine.enqueueEndOfFunction(Dst, RS);
  2029. }
  2030. /// ProcessSwitch - Called by CoreEngine. Used to generate successor
  2031. /// nodes by processing the 'effects' of a switch statement.
  2032. void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
  2033. using iterator = SwitchNodeBuilder::iterator;
  2034. ProgramStateRef state = builder.getState();
  2035. const Expr *CondE = builder.getCondition();
  2036. SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
  2037. if (CondV_untested.isUndef()) {
  2038. //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
  2039. // FIXME: add checker
  2040. //UndefBranches.insert(N);
  2041. return;
  2042. }
  2043. DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
  2044. ProgramStateRef DefaultSt = state;
  2045. iterator I = builder.begin(), EI = builder.end();
  2046. bool defaultIsFeasible = I == EI;
  2047. for ( ; I != EI; ++I) {
  2048. // Successor may be pruned out during CFG construction.
  2049. if (!I.getBlock())
  2050. continue;
  2051. const CaseStmt *Case = I.getCase();
  2052. // Evaluate the LHS of the case value.
  2053. llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
  2054. assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
  2055. // Get the RHS of the case, if it exists.
  2056. llvm::APSInt V2;
  2057. if (const Expr *E = Case->getRHS())
  2058. V2 = E->EvaluateKnownConstInt(getContext());
  2059. else
  2060. V2 = V1;
  2061. ProgramStateRef StateCase;
  2062. if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
  2063. std::tie(StateCase, DefaultSt) =
  2064. DefaultSt->assumeInclusiveRange(*NL, V1, V2);
  2065. else // UnknownVal
  2066. StateCase = DefaultSt;
  2067. if (StateCase)
  2068. builder.generateCaseStmtNode(I, StateCase);
  2069. // Now "assume" that the case doesn't match. Add this state
  2070. // to the default state (if it is feasible).
  2071. if (DefaultSt)
  2072. defaultIsFeasible = true;
  2073. else {
  2074. defaultIsFeasible = false;
  2075. break;
  2076. }
  2077. }
  2078. if (!defaultIsFeasible)
  2079. return;
  2080. // If we have switch(enum value), the default branch is not
  2081. // feasible if all of the enum constants not covered by 'case:' statements
  2082. // are not feasible values for the switch condition.
  2083. //
  2084. // Note that this isn't as accurate as it could be. Even if there isn't
  2085. // a case for a particular enum value as long as that enum value isn't
  2086. // feasible then it shouldn't be considered for making 'default:' reachable.
  2087. const SwitchStmt *SS = builder.getSwitch();
  2088. const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
  2089. if (CondExpr->getType()->getAs<EnumType>()) {
  2090. if (SS->isAllEnumCasesCovered())
  2091. return;
  2092. }
  2093. builder.generateDefaultCaseNode(DefaultSt);
  2094. }
  2095. //===----------------------------------------------------------------------===//
  2096. // Transfer functions: Loads and stores.
  2097. //===----------------------------------------------------------------------===//
  2098. void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
  2099. ExplodedNode *Pred,
  2100. ExplodedNodeSet &Dst) {
  2101. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2102. ProgramStateRef state = Pred->getState();
  2103. const LocationContext *LCtx = Pred->getLocationContext();
  2104. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  2105. // C permits "extern void v", and if you cast the address to a valid type,
  2106. // you can even do things with it. We simply pretend
  2107. assert(Ex->isGLValue() || VD->getType()->isVoidType());
  2108. const LocationContext *LocCtxt = Pred->getLocationContext();
  2109. const Decl *D = LocCtxt->getDecl();
  2110. const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
  2111. const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
  2112. Optional<std::pair<SVal, QualType>> VInfo;
  2113. if (AMgr.options.ShouldInlineLambdas && DeclRefEx &&
  2114. DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
  2115. MD->getParent()->isLambda()) {
  2116. // Lookup the field of the lambda.
  2117. const CXXRecordDecl *CXXRec = MD->getParent();
  2118. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  2119. FieldDecl *LambdaThisCaptureField;
  2120. CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
  2121. // Sema follows a sequence of complex rules to determine whether the
  2122. // variable should be captured.
  2123. if (const FieldDecl *FD = LambdaCaptureFields[VD]) {
  2124. Loc CXXThis =
  2125. svalBuilder.getCXXThis(MD, LocCtxt->getStackFrame());
  2126. SVal CXXThisVal = state->getSVal(CXXThis);
  2127. VInfo = std::make_pair(state->getLValue(FD, CXXThisVal), FD->getType());
  2128. }
  2129. }
  2130. if (!VInfo)
  2131. VInfo = std::make_pair(state->getLValue(VD, LocCtxt), VD->getType());
  2132. SVal V = VInfo->first;
  2133. bool IsReference = VInfo->second->isReferenceType();
  2134. // For references, the 'lvalue' is the pointer address stored in the
  2135. // reference region.
  2136. if (IsReference) {
  2137. if (const MemRegion *R = V.getAsRegion())
  2138. V = state->getSVal(R);
  2139. else
  2140. V = UnknownVal();
  2141. }
  2142. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  2143. ProgramPoint::PostLValueKind);
  2144. return;
  2145. }
  2146. if (const auto *ED = dyn_cast<EnumConstantDecl>(D)) {
  2147. assert(!Ex->isGLValue());
  2148. SVal V = svalBuilder.makeIntVal(ED->getInitVal());
  2149. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
  2150. return;
  2151. }
  2152. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2153. SVal V = svalBuilder.getFunctionPointer(FD);
  2154. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  2155. ProgramPoint::PostLValueKind);
  2156. return;
  2157. }
  2158. if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
  2159. // FIXME: Compute lvalue of field pointers-to-member.
  2160. // Right now we just use a non-null void pointer, so that it gives proper
  2161. // results in boolean contexts.
  2162. // FIXME: Maybe delegate this to the surrounding operator&.
  2163. // Note how this expression is lvalue, however pointer-to-member is NonLoc.
  2164. SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
  2165. currBldrCtx->blockCount());
  2166. state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
  2167. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
  2168. ProgramPoint::PostLValueKind);
  2169. return;
  2170. }
  2171. if (isa<BindingDecl>(D)) {
  2172. // FIXME: proper support for bound declarations.
  2173. // For now, let's just prevent crashing.
  2174. return;
  2175. }
  2176. llvm_unreachable("Support for this Decl not implemented.");
  2177. }
  2178. /// VisitArraySubscriptExpr - Transfer function for array accesses
  2179. void ExprEngine::VisitArraySubscriptExpr(const ArraySubscriptExpr *A,
  2180. ExplodedNode *Pred,
  2181. ExplodedNodeSet &Dst){
  2182. const Expr *Base = A->getBase()->IgnoreParens();
  2183. const Expr *Idx = A->getIdx()->IgnoreParens();
  2184. ExplodedNodeSet CheckerPreStmt;
  2185. getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
  2186. ExplodedNodeSet EvalSet;
  2187. StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
  2188. bool IsVectorType = A->getBase()->getType()->isVectorType();
  2189. // The "like" case is for situations where C standard prohibits the type to
  2190. // be an lvalue, e.g. taking the address of a subscript of an expression of
  2191. // type "void *".
  2192. bool IsGLValueLike = A->isGLValue() ||
  2193. (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
  2194. for (auto *Node : CheckerPreStmt) {
  2195. const LocationContext *LCtx = Node->getLocationContext();
  2196. ProgramStateRef state = Node->getState();
  2197. if (IsGLValueLike) {
  2198. QualType T = A->getType();
  2199. // One of the forbidden LValue types! We still need to have sensible
  2200. // symbolic locations to represent this stuff. Note that arithmetic on
  2201. // void pointers is a GCC extension.
  2202. if (T->isVoidType())
  2203. T = getContext().CharTy;
  2204. SVal V = state->getLValue(T,
  2205. state->getSVal(Idx, LCtx),
  2206. state->getSVal(Base, LCtx));
  2207. Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
  2208. ProgramPoint::PostLValueKind);
  2209. } else if (IsVectorType) {
  2210. // FIXME: non-glvalue vector reads are not modelled.
  2211. Bldr.generateNode(A, Node, state, nullptr);
  2212. } else {
  2213. llvm_unreachable("Array subscript should be an lValue when not \
  2214. a vector and not a forbidden lvalue type");
  2215. }
  2216. }
  2217. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
  2218. }
  2219. /// VisitMemberExpr - Transfer function for member expressions.
  2220. void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
  2221. ExplodedNodeSet &Dst) {
  2222. // FIXME: Prechecks eventually go in ::Visit().
  2223. ExplodedNodeSet CheckedSet;
  2224. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
  2225. ExplodedNodeSet EvalSet;
  2226. ValueDecl *Member = M->getMemberDecl();
  2227. // Handle static member variables and enum constants accessed via
  2228. // member syntax.
  2229. if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
  2230. for (const auto I : CheckedSet)
  2231. VisitCommonDeclRefExpr(M, Member, I, EvalSet);
  2232. } else {
  2233. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  2234. ExplodedNodeSet Tmp;
  2235. for (const auto I : CheckedSet) {
  2236. ProgramStateRef state = I->getState();
  2237. const LocationContext *LCtx = I->getLocationContext();
  2238. Expr *BaseExpr = M->getBase();
  2239. // Handle C++ method calls.
  2240. if (const auto *MD = dyn_cast<CXXMethodDecl>(Member)) {
  2241. if (MD->isInstance())
  2242. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
  2243. SVal MDVal = svalBuilder.getFunctionPointer(MD);
  2244. state = state->BindExpr(M, LCtx, MDVal);
  2245. Bldr.generateNode(M, I, state);
  2246. continue;
  2247. }
  2248. // Handle regular struct fields / member variables.
  2249. const SubRegion *MR = nullptr;
  2250. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr,
  2251. /*Result=*/nullptr,
  2252. /*OutRegionWithAdjustments=*/&MR);
  2253. SVal baseExprVal =
  2254. MR ? loc::MemRegionVal(MR) : state->getSVal(BaseExpr, LCtx);
  2255. const auto *field = cast<FieldDecl>(Member);
  2256. SVal L = state->getLValue(field, baseExprVal);
  2257. if (M->isGLValue() || M->getType()->isArrayType()) {
  2258. // We special-case rvalues of array type because the analyzer cannot
  2259. // reason about them, since we expect all regions to be wrapped in Locs.
  2260. // We instead treat these as lvalues and assume that they will decay to
  2261. // pointers as soon as they are used.
  2262. if (!M->isGLValue()) {
  2263. assert(M->getType()->isArrayType());
  2264. const auto *PE =
  2265. dyn_cast<ImplicitCastExpr>(I->getParentMap().getParentIgnoreParens(M));
  2266. if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
  2267. llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
  2268. }
  2269. }
  2270. if (field->getType()->isReferenceType()) {
  2271. if (const MemRegion *R = L.getAsRegion())
  2272. L = state->getSVal(R);
  2273. else
  2274. L = UnknownVal();
  2275. }
  2276. Bldr.generateNode(M, I, state->BindExpr(M, LCtx, L), nullptr,
  2277. ProgramPoint::PostLValueKind);
  2278. } else {
  2279. Bldr.takeNodes(I);
  2280. evalLoad(Tmp, M, M, I, state, L);
  2281. Bldr.addNodes(Tmp);
  2282. }
  2283. }
  2284. }
  2285. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
  2286. }
  2287. void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred,
  2288. ExplodedNodeSet &Dst) {
  2289. ExplodedNodeSet AfterPreSet;
  2290. getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
  2291. // For now, treat all the arguments to C11 atomics as escaping.
  2292. // FIXME: Ideally we should model the behavior of the atomics precisely here.
  2293. ExplodedNodeSet AfterInvalidateSet;
  2294. StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
  2295. for (const auto I : AfterPreSet) {
  2296. ProgramStateRef State = I->getState();
  2297. const LocationContext *LCtx = I->getLocationContext();
  2298. SmallVector<SVal, 8> ValuesToInvalidate;
  2299. for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
  2300. const Expr *SubExpr = AE->getSubExprs()[SI];
  2301. SVal SubExprVal = State->getSVal(SubExpr, LCtx);
  2302. ValuesToInvalidate.push_back(SubExprVal);
  2303. }
  2304. State = State->invalidateRegions(ValuesToInvalidate, AE,
  2305. currBldrCtx->blockCount(),
  2306. LCtx,
  2307. /*CausedByPointerEscape*/true,
  2308. /*Symbols=*/nullptr);
  2309. SVal ResultVal = UnknownVal();
  2310. State = State->BindExpr(AE, LCtx, ResultVal);
  2311. Bldr.generateNode(AE, I, State, nullptr,
  2312. ProgramPoint::PostStmtKind);
  2313. }
  2314. getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
  2315. }
  2316. // A value escapes in four possible cases:
  2317. // (1) We are binding to something that is not a memory region.
  2318. // (2) We are binding to a MemRegion that does not have stack storage.
  2319. // (3) We are binding to a top-level parameter region with a non-trivial
  2320. // destructor. We won't see the destructor during analysis, but it's there.
  2321. // (4) We are binding to a MemRegion with stack storage that the store
  2322. // does not understand.
  2323. ProgramStateRef
  2324. ExprEngine::processPointerEscapedOnBind(ProgramStateRef State, SVal Loc,
  2325. SVal Val, const LocationContext *LCtx) {
  2326. // Cases (1) and (2).
  2327. const MemRegion *MR = Loc.getAsRegion();
  2328. if (!MR || !MR->hasStackStorage())
  2329. return escapeValue(State, Val, PSK_EscapeOnBind);
  2330. // Case (3).
  2331. if (const auto *VR = dyn_cast<VarRegion>(MR->getBaseRegion()))
  2332. if (VR->hasStackParametersStorage() && VR->getStackFrame()->inTopFrame())
  2333. if (const auto *RD = VR->getValueType()->getAsCXXRecordDecl())
  2334. if (!RD->hasTrivialDestructor())
  2335. return escapeValue(State, Val, PSK_EscapeOnBind);
  2336. // Case (4): in order to test that, generate a new state with the binding
  2337. // added. If it is the same state, then it escapes (since the store cannot
  2338. // represent the binding).
  2339. // Do this only if we know that the store is not supposed to generate the
  2340. // same state.
  2341. SVal StoredVal = State->getSVal(MR);
  2342. if (StoredVal != Val)
  2343. if (State == (State->bindLoc(loc::MemRegionVal(MR), Val, LCtx)))
  2344. return escapeValue(State, Val, PSK_EscapeOnBind);
  2345. return State;
  2346. }
  2347. ProgramStateRef
  2348. ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
  2349. const InvalidatedSymbols *Invalidated,
  2350. ArrayRef<const MemRegion *> ExplicitRegions,
  2351. const CallEvent *Call,
  2352. RegionAndSymbolInvalidationTraits &ITraits) {
  2353. if (!Invalidated || Invalidated->empty())
  2354. return State;
  2355. if (!Call)
  2356. return getCheckerManager().runCheckersForPointerEscape(State,
  2357. *Invalidated,
  2358. nullptr,
  2359. PSK_EscapeOther,
  2360. &ITraits);
  2361. // If the symbols were invalidated by a call, we want to find out which ones
  2362. // were invalidated directly due to being arguments to the call.
  2363. InvalidatedSymbols SymbolsDirectlyInvalidated;
  2364. for (const auto I : ExplicitRegions) {
  2365. if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>())
  2366. SymbolsDirectlyInvalidated.insert(R->getSymbol());
  2367. }
  2368. InvalidatedSymbols SymbolsIndirectlyInvalidated;
  2369. for (const auto &sym : *Invalidated) {
  2370. if (SymbolsDirectlyInvalidated.count(sym))
  2371. continue;
  2372. SymbolsIndirectlyInvalidated.insert(sym);
  2373. }
  2374. if (!SymbolsDirectlyInvalidated.empty())
  2375. State = getCheckerManager().runCheckersForPointerEscape(State,
  2376. SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
  2377. // Notify about the symbols that get indirectly invalidated by the call.
  2378. if (!SymbolsIndirectlyInvalidated.empty())
  2379. State = getCheckerManager().runCheckersForPointerEscape(State,
  2380. SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
  2381. return State;
  2382. }
  2383. /// evalBind - Handle the semantics of binding a value to a specific location.
  2384. /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
  2385. void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
  2386. ExplodedNode *Pred,
  2387. SVal location, SVal Val,
  2388. bool atDeclInit, const ProgramPoint *PP) {
  2389. const LocationContext *LC = Pred->getLocationContext();
  2390. PostStmt PS(StoreE, LC);
  2391. if (!PP)
  2392. PP = &PS;
  2393. // Do a previsit of the bind.
  2394. ExplodedNodeSet CheckedSet;
  2395. getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
  2396. StoreE, *this, *PP);
  2397. StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
  2398. // If the location is not a 'Loc', it will already be handled by
  2399. // the checkers. There is nothing left to do.
  2400. if (!location.getAs<Loc>()) {
  2401. const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
  2402. /*tag*/nullptr);
  2403. ProgramStateRef state = Pred->getState();
  2404. state = processPointerEscapedOnBind(state, location, Val, LC);
  2405. Bldr.generateNode(L, state, Pred);
  2406. return;
  2407. }
  2408. for (const auto PredI : CheckedSet) {
  2409. ProgramStateRef state = PredI->getState();
  2410. state = processPointerEscapedOnBind(state, location, Val, LC);
  2411. // When binding the value, pass on the hint that this is a initialization.
  2412. // For initializations, we do not need to inform clients of region
  2413. // changes.
  2414. state = state->bindLoc(location.castAs<Loc>(),
  2415. Val, LC, /* notifyChanges = */ !atDeclInit);
  2416. const MemRegion *LocReg = nullptr;
  2417. if (Optional<loc::MemRegionVal> LocRegVal =
  2418. location.getAs<loc::MemRegionVal>()) {
  2419. LocReg = LocRegVal->getRegion();
  2420. }
  2421. const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
  2422. Bldr.generateNode(L, state, PredI);
  2423. }
  2424. }
  2425. /// evalStore - Handle the semantics of a store via an assignment.
  2426. /// @param Dst The node set to store generated state nodes
  2427. /// @param AssignE The assignment expression if the store happens in an
  2428. /// assignment.
  2429. /// @param LocationE The location expression that is stored to.
  2430. /// @param state The current simulation state
  2431. /// @param location The location to store the value
  2432. /// @param Val The value to be stored
  2433. void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
  2434. const Expr *LocationE,
  2435. ExplodedNode *Pred,
  2436. ProgramStateRef state, SVal location, SVal Val,
  2437. const ProgramPointTag *tag) {
  2438. // Proceed with the store. We use AssignE as the anchor for the PostStore
  2439. // ProgramPoint if it is non-NULL, and LocationE otherwise.
  2440. const Expr *StoreE = AssignE ? AssignE : LocationE;
  2441. // Evaluate the location (checks for bad dereferences).
  2442. ExplodedNodeSet Tmp;
  2443. evalLocation(Tmp, AssignE, LocationE, Pred, state, location, false);
  2444. if (Tmp.empty())
  2445. return;
  2446. if (location.isUndef())
  2447. return;
  2448. for (const auto I : Tmp)
  2449. evalBind(Dst, StoreE, I, location, Val, false);
  2450. }
  2451. void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
  2452. const Expr *NodeEx,
  2453. const Expr *BoundEx,
  2454. ExplodedNode *Pred,
  2455. ProgramStateRef state,
  2456. SVal location,
  2457. const ProgramPointTag *tag,
  2458. QualType LoadTy) {
  2459. assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
  2460. assert(NodeEx);
  2461. assert(BoundEx);
  2462. // Evaluate the location (checks for bad dereferences).
  2463. ExplodedNodeSet Tmp;
  2464. evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, true);
  2465. if (Tmp.empty())
  2466. return;
  2467. StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  2468. if (location.isUndef())
  2469. return;
  2470. // Proceed with the load.
  2471. for (const auto I : Tmp) {
  2472. state = I->getState();
  2473. const LocationContext *LCtx = I->getLocationContext();
  2474. SVal V = UnknownVal();
  2475. if (location.isValid()) {
  2476. if (LoadTy.isNull())
  2477. LoadTy = BoundEx->getType();
  2478. V = state->getSVal(location.castAs<Loc>(), LoadTy);
  2479. }
  2480. Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag,
  2481. ProgramPoint::PostLoadKind);
  2482. }
  2483. }
  2484. void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
  2485. const Stmt *NodeEx,
  2486. const Stmt *BoundEx,
  2487. ExplodedNode *Pred,
  2488. ProgramStateRef state,
  2489. SVal location,
  2490. bool isLoad) {
  2491. StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
  2492. // Early checks for performance reason.
  2493. if (location.isUnknown()) {
  2494. return;
  2495. }
  2496. ExplodedNodeSet Src;
  2497. BldrTop.takeNodes(Pred);
  2498. StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
  2499. if (Pred->getState() != state) {
  2500. // Associate this new state with an ExplodedNode.
  2501. // FIXME: If I pass null tag, the graph is incorrect, e.g for
  2502. // int *p;
  2503. // p = 0;
  2504. // *p = 0xDEADBEEF;
  2505. // "p = 0" is not noted as "Null pointer value stored to 'p'" but
  2506. // instead "int *p" is noted as
  2507. // "Variable 'p' initialized to a null pointer value"
  2508. static SimpleProgramPointTag tag(TagProviderName, "Location");
  2509. Bldr.generateNode(NodeEx, Pred, state, &tag);
  2510. }
  2511. ExplodedNodeSet Tmp;
  2512. getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
  2513. NodeEx, BoundEx, *this);
  2514. BldrTop.addNodes(Tmp);
  2515. }
  2516. std::pair<const ProgramPointTag *, const ProgramPointTag*>
  2517. ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
  2518. static SimpleProgramPointTag
  2519. eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
  2520. "Eagerly Assume True"),
  2521. eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
  2522. "Eagerly Assume False");
  2523. return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
  2524. &eagerlyAssumeBinOpBifurcationFalse);
  2525. }
  2526. void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
  2527. ExplodedNodeSet &Src,
  2528. const Expr *Ex) {
  2529. StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
  2530. for (const auto Pred : Src) {
  2531. // Test if the previous node was as the same expression. This can happen
  2532. // when the expression fails to evaluate to anything meaningful and
  2533. // (as an optimization) we don't generate a node.
  2534. ProgramPoint P = Pred->getLocation();
  2535. if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
  2536. continue;
  2537. }
  2538. ProgramStateRef state = Pred->getState();
  2539. SVal V = state->getSVal(Ex, Pred->getLocationContext());
  2540. Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
  2541. if (SEV && SEV->isExpression()) {
  2542. const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
  2543. geteagerlyAssumeBinOpBifurcationTags();
  2544. ProgramStateRef StateTrue, StateFalse;
  2545. std::tie(StateTrue, StateFalse) = state->assume(*SEV);
  2546. // First assume that the condition is true.
  2547. if (StateTrue) {
  2548. SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
  2549. StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
  2550. Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
  2551. }
  2552. // Next, assume that the condition is false.
  2553. if (StateFalse) {
  2554. SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
  2555. StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
  2556. Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
  2557. }
  2558. }
  2559. }
  2560. }
  2561. void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
  2562. ExplodedNodeSet &Dst) {
  2563. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2564. // We have processed both the inputs and the outputs. All of the outputs
  2565. // should evaluate to Locs. Nuke all of their values.
  2566. // FIXME: Some day in the future it would be nice to allow a "plug-in"
  2567. // which interprets the inline asm and stores proper results in the
  2568. // outputs.
  2569. ProgramStateRef state = Pred->getState();
  2570. for (const Expr *O : A->outputs()) {
  2571. SVal X = state->getSVal(O, Pred->getLocationContext());
  2572. assert(!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
  2573. if (Optional<Loc> LV = X.getAs<Loc>())
  2574. state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
  2575. }
  2576. Bldr.generateNode(A, Pred, state);
  2577. }
  2578. void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
  2579. ExplodedNodeSet &Dst) {
  2580. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  2581. Bldr.generateNode(A, Pred, Pred->getState());
  2582. }
  2583. //===----------------------------------------------------------------------===//
  2584. // Visualization.
  2585. //===----------------------------------------------------------------------===//
  2586. #ifndef NDEBUG
  2587. namespace llvm {
  2588. template<>
  2589. struct DOTGraphTraits<ExplodedGraph*> : public DefaultDOTGraphTraits {
  2590. DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  2591. static bool nodeHasBugReport(const ExplodedNode *N) {
  2592. BugReporter &BR = static_cast<ExprEngine &>(
  2593. N->getState()->getStateManager().getOwningEngine()).getBugReporter();
  2594. const auto EQClasses =
  2595. llvm::make_range(BR.EQClasses_begin(), BR.EQClasses_end());
  2596. for (const auto &EQ : EQClasses) {
  2597. for (const BugReport &Report : EQ) {
  2598. if (Report.getErrorNode()->getState() == N->getState() &&
  2599. Report.getErrorNode()->getLocation() == N->getLocation())
  2600. return true;
  2601. }
  2602. }
  2603. return false;
  2604. }
  2605. /// \p PreCallback: callback before break.
  2606. /// \p PostCallback: callback after break.
  2607. /// \p Stop: stop iteration if returns {@code true}
  2608. /// \return Whether {@code Stop} ever returned {@code true}.
  2609. static bool traverseHiddenNodes(
  2610. const ExplodedNode *N,
  2611. llvm::function_ref<void(const ExplodedNode *)> PreCallback,
  2612. llvm::function_ref<void(const ExplodedNode *)> PostCallback,
  2613. llvm::function_ref<bool(const ExplodedNode *)> Stop) {
  2614. const ExplodedNode *FirstHiddenNode = N;
  2615. while (FirstHiddenNode->pred_size() == 1 &&
  2616. isNodeHidden(*FirstHiddenNode->pred_begin())) {
  2617. FirstHiddenNode = *FirstHiddenNode->pred_begin();
  2618. }
  2619. const ExplodedNode *OtherNode = FirstHiddenNode;
  2620. while (true) {
  2621. PreCallback(OtherNode);
  2622. if (Stop(OtherNode))
  2623. return true;
  2624. if (OtherNode == N)
  2625. break;
  2626. PostCallback(OtherNode);
  2627. OtherNode = *OtherNode->succ_begin();
  2628. }
  2629. return false;
  2630. }
  2631. static bool isNodeHidden(const ExplodedNode *N) {
  2632. return N->isTrivial();
  2633. }
  2634. static std::string getNodeLabel(const ExplodedNode *N, ExplodedGraph *G){
  2635. std::string Buf;
  2636. llvm::raw_string_ostream Out(Buf);
  2637. const bool IsDot = true;
  2638. const unsigned int Space = 1;
  2639. ProgramStateRef State = N->getState();
  2640. auto Noop = [](const ExplodedNode*){};
  2641. bool HasReport = traverseHiddenNodes(
  2642. N, Noop, Noop, &nodeHasBugReport);
  2643. bool IsSink = traverseHiddenNodes(
  2644. N, Noop, Noop, [](const ExplodedNode *N) { return N->isSink(); });
  2645. Out << "{ \"node_id\": " << N->getID(G) << ", \"pointer\": \""
  2646. << (const void *)N << "\", \"state_id\": " << State->getID()
  2647. << ", \"has_report\": " << (HasReport ? "true" : "false")
  2648. << ", \"is_sink\": " << (IsSink ? "true" : "false")
  2649. << ",\\l";
  2650. Indent(Out, Space, IsDot) << "\"program_points\": [\\l";
  2651. // Dump program point for all the previously skipped nodes.
  2652. traverseHiddenNodes(
  2653. N,
  2654. [&](const ExplodedNode *OtherNode) {
  2655. Indent(Out, Space + 1, IsDot) << "{ ";
  2656. OtherNode->getLocation().printJson(Out, /*NL=*/"\\l");
  2657. Out << ", \"tag\": ";
  2658. if (const ProgramPointTag *Tag = OtherNode->getLocation().getTag())
  2659. Out << '\"' << Tag->getTagDescription() << "\" }";
  2660. else
  2661. Out << "null }";
  2662. },
  2663. // Adds a comma and a new-line between each program point.
  2664. [&](const ExplodedNode *) { Out << ",\\l"; },
  2665. [&](const ExplodedNode *) { return false; });
  2666. Out << "\\l"; // Adds a new-line to the last program point.
  2667. Indent(Out, Space, IsDot) << "],\\l";
  2668. bool SameAsAllPredecessors =
  2669. std::all_of(N->pred_begin(), N->pred_end(), [&](const ExplodedNode *P) {
  2670. return P->getState() == State;
  2671. });
  2672. if (!SameAsAllPredecessors) {
  2673. State->printDOT(Out, N->getLocationContext(), Space);
  2674. } else {
  2675. Indent(Out, Space, IsDot) << "\"program_state\": null";
  2676. }
  2677. Out << "\\l}\\l";
  2678. return Out.str();
  2679. }
  2680. };
  2681. } // namespace llvm
  2682. #endif
  2683. void ExprEngine::ViewGraph(bool trim) {
  2684. #ifndef NDEBUG
  2685. std::string Filename = DumpGraph(trim);
  2686. llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
  2687. #endif
  2688. llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
  2689. }
  2690. void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
  2691. #ifndef NDEBUG
  2692. std::string Filename = DumpGraph(Nodes);
  2693. llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
  2694. #endif
  2695. llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
  2696. }
  2697. std::string ExprEngine::DumpGraph(bool trim, StringRef Filename) {
  2698. #ifndef NDEBUG
  2699. if (trim) {
  2700. std::vector<const ExplodedNode *> Src;
  2701. // Iterate through the reports and get their nodes.
  2702. for (BugReporter::EQClasses_iterator
  2703. EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
  2704. const auto *N = const_cast<ExplodedNode *>(EI->begin()->getErrorNode());
  2705. if (N) Src.push_back(N);
  2706. }
  2707. return DumpGraph(Src, Filename);
  2708. } else {
  2709. return llvm::WriteGraph(&G, "ExprEngine", /*ShortNames=*/false,
  2710. /*Title=*/"Exploded Graph", /*Filename=*/Filename);
  2711. }
  2712. #endif
  2713. llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
  2714. return "";
  2715. }
  2716. std::string ExprEngine::DumpGraph(ArrayRef<const ExplodedNode*> Nodes,
  2717. StringRef Filename) {
  2718. #ifndef NDEBUG
  2719. std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
  2720. if (!TrimmedG.get()) {
  2721. llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
  2722. } else {
  2723. return llvm::WriteGraph(TrimmedG.get(), "TrimmedExprEngine",
  2724. /*ShortNames=*/false,
  2725. /*Title=*/"Trimmed Exploded Graph",
  2726. /*Filename=*/Filename);
  2727. }
  2728. #endif
  2729. llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
  2730. return "";
  2731. }
  2732. void *ProgramStateTrait<ReplayWithoutInlining>::GDMIndex() {
  2733. static int index = 0;
  2734. return &index;
  2735. }