ExprEngine.cpp 144 KB

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