ExprEngine.cpp 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646
  1. //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-=
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines a meta-engine for path-sensitive dataflow analysis that
  11. // is built on GREngine, but provides the boilerplate to execute transfer
  12. // functions and build the ExplodedGraph at the expression level.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. // FIXME: Restructure checker registration.
  16. #include "InternalChecks.h"
  17. #include "clang/StaticAnalyzer/BugReporter/BugType.h"
  18. #include "clang/StaticAnalyzer/PathSensitive/AnalysisManager.h"
  19. #include "clang/StaticAnalyzer/PathSensitive/ExprEngine.h"
  20. #include "clang/StaticAnalyzer/PathSensitive/ExprEngineBuilders.h"
  21. #include "clang/StaticAnalyzer/PathSensitive/Checker.h"
  22. #include "clang/AST/CharUnits.h"
  23. #include "clang/AST/ParentMap.h"
  24. #include "clang/AST/StmtObjC.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/Basic/Builtins.h"
  27. #include "clang/Basic/SourceManager.h"
  28. #include "clang/Basic/SourceManager.h"
  29. #include "clang/Basic/PrettyStackTrace.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include "llvm/ADT/ImmutableList.h"
  32. #ifndef NDEBUG
  33. #include "llvm/Support/GraphWriter.h"
  34. #endif
  35. using namespace clang;
  36. using namespace ento;
  37. using llvm::dyn_cast;
  38. using llvm::dyn_cast_or_null;
  39. using llvm::cast;
  40. using llvm::APSInt;
  41. namespace {
  42. // Trait class for recording returned expression in the state.
  43. struct ReturnExpr {
  44. static int TagInt;
  45. typedef const Stmt *data_type;
  46. };
  47. int ReturnExpr::TagInt;
  48. }
  49. //===----------------------------------------------------------------------===//
  50. // Utility functions.
  51. //===----------------------------------------------------------------------===//
  52. static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
  53. IdentifierInfo* II = &Ctx.Idents.get(name);
  54. return Ctx.Selectors.getSelector(0, &II);
  55. }
  56. //===----------------------------------------------------------------------===//
  57. // Checker worklist routines.
  58. //===----------------------------------------------------------------------===//
  59. void ExprEngine::CheckerVisit(const Stmt *S, ExplodedNodeSet &Dst,
  60. ExplodedNodeSet &Src, CallbackKind Kind) {
  61. // Determine if we already have a cached 'CheckersOrdered' vector
  62. // specifically tailored for the provided <CallbackKind, Stmt kind>. This
  63. // can reduce the number of checkers actually called.
  64. CheckersOrdered *CO = &Checkers;
  65. llvm::OwningPtr<CheckersOrdered> NewCO;
  66. // The cache key is made up of the and the callback kind (pre- or post-visit)
  67. // and the statement kind.
  68. CallbackTag K = GetCallbackTag(Kind, S->getStmtClass());
  69. CheckersOrdered *& CO_Ref = COCache[K];
  70. if (!CO_Ref) {
  71. // If we have no previously cached CheckersOrdered vector for this
  72. // statement kind, then create one.
  73. NewCO.reset(new CheckersOrdered);
  74. }
  75. else {
  76. // Use the already cached set.
  77. CO = CO_Ref;
  78. }
  79. if (CO->empty()) {
  80. // If there are no checkers, return early without doing any
  81. // more work.
  82. Dst.insert(Src);
  83. return;
  84. }
  85. ExplodedNodeSet Tmp;
  86. ExplodedNodeSet *PrevSet = &Src;
  87. unsigned checkersEvaluated = 0;
  88. for (CheckersOrdered::iterator I=CO->begin(), E=CO->end(); I!=E; ++I) {
  89. // If all nodes are sunk, bail out early.
  90. if (PrevSet->empty())
  91. break;
  92. ExplodedNodeSet *CurrSet = 0;
  93. if (I+1 == E)
  94. CurrSet = &Dst;
  95. else {
  96. CurrSet = (PrevSet == &Tmp) ? &Src : &Tmp;
  97. CurrSet->clear();
  98. }
  99. void *tag = I->first;
  100. Checker *checker = I->second;
  101. bool respondsToCallback = true;
  102. for (ExplodedNodeSet::iterator NI = PrevSet->begin(), NE = PrevSet->end();
  103. NI != NE; ++NI) {
  104. checker->GR_Visit(*CurrSet, *Builder, *this, S, *NI, tag,
  105. Kind == PreVisitStmtCallback, respondsToCallback);
  106. }
  107. PrevSet = CurrSet;
  108. if (NewCO.get()) {
  109. ++checkersEvaluated;
  110. if (respondsToCallback)
  111. NewCO->push_back(*I);
  112. }
  113. }
  114. // If we built NewCO, check if we called all the checkers. This is important
  115. // so that we know that we accurately determined the entire set of checkers
  116. // that responds to this callback. Note that 'checkersEvaluated' might
  117. // not be the same as Checkers.size() if one of the Checkers generates
  118. // a sink node.
  119. if (NewCO.get() && checkersEvaluated == Checkers.size())
  120. CO_Ref = NewCO.take();
  121. // Don't autotransition. The CheckerContext objects should do this
  122. // automatically.
  123. }
  124. void ExprEngine::CheckerVisitObjCMessage(const ObjCMessage &msg,
  125. ExplodedNodeSet &Dst,
  126. ExplodedNodeSet &Src,
  127. bool isPrevisit) {
  128. if (Checkers.empty()) {
  129. Dst.insert(Src);
  130. return;
  131. }
  132. ExplodedNodeSet Tmp;
  133. ExplodedNodeSet *PrevSet = &Src;
  134. for (CheckersOrdered::iterator I=Checkers.begin(),E=Checkers.end(); I!=E; ++I)
  135. {
  136. ExplodedNodeSet *CurrSet = 0;
  137. if (I+1 == E)
  138. CurrSet = &Dst;
  139. else {
  140. CurrSet = (PrevSet == &Tmp) ? &Src : &Tmp;
  141. CurrSet->clear();
  142. }
  143. void *tag = I->first;
  144. Checker *checker = I->second;
  145. for (ExplodedNodeSet::iterator NI = PrevSet->begin(), NE = PrevSet->end();
  146. NI != NE; ++NI)
  147. checker->GR_visitObjCMessage(*CurrSet, *Builder, *this, msg,
  148. *NI, tag, isPrevisit);
  149. // Update which NodeSet is the current one.
  150. PrevSet = CurrSet;
  151. }
  152. // Don't autotransition. The CheckerContext objects should do this
  153. // automatically.
  154. }
  155. void ExprEngine::CheckerEvalNilReceiver(const ObjCMessage &msg,
  156. ExplodedNodeSet &Dst,
  157. const GRState *state,
  158. ExplodedNode *Pred) {
  159. bool evaluated = false;
  160. ExplodedNodeSet DstTmp;
  161. for (CheckersOrdered::iterator I=Checkers.begin(),E=Checkers.end();I!=E;++I) {
  162. void *tag = I->first;
  163. Checker *checker = I->second;
  164. if (checker->GR_evalNilReceiver(DstTmp, *Builder, *this, msg, Pred, state,
  165. tag)) {
  166. evaluated = true;
  167. break;
  168. } else
  169. // The checker didn't evaluate the expr. Restore the Dst.
  170. DstTmp.clear();
  171. }
  172. if (evaluated)
  173. Dst.insert(DstTmp);
  174. else
  175. Dst.insert(Pred);
  176. }
  177. // CheckerEvalCall returns true if one of the checkers processed the node.
  178. // This may return void when all call evaluation logic goes to some checker
  179. // in the future.
  180. bool ExprEngine::CheckerEvalCall(const CallExpr *CE,
  181. ExplodedNodeSet &Dst,
  182. ExplodedNode *Pred) {
  183. bool evaluated = false;
  184. ExplodedNodeSet DstTmp;
  185. for (CheckersOrdered::iterator I=Checkers.begin(),E=Checkers.end();I!=E;++I) {
  186. void *tag = I->first;
  187. Checker *checker = I->second;
  188. if (checker->GR_evalCallExpr(DstTmp, *Builder, *this, CE, Pred, tag)) {
  189. evaluated = true;
  190. break;
  191. } else
  192. // The checker didn't evaluate the expr. Restore the DstTmp set.
  193. DstTmp.clear();
  194. }
  195. if (evaluated)
  196. Dst.insert(DstTmp);
  197. else
  198. Dst.insert(Pred);
  199. return evaluated;
  200. }
  201. // FIXME: This is largely copy-paste from CheckerVisit(). Need to
  202. // unify.
  203. void ExprEngine::CheckerVisitBind(const Stmt *StoreE, ExplodedNodeSet &Dst,
  204. ExplodedNodeSet &Src, SVal location,
  205. SVal val, bool isPrevisit) {
  206. if (Checkers.empty()) {
  207. Dst.insert(Src);
  208. return;
  209. }
  210. ExplodedNodeSet Tmp;
  211. ExplodedNodeSet *PrevSet = &Src;
  212. for (CheckersOrdered::iterator I=Checkers.begin(),E=Checkers.end(); I!=E; ++I)
  213. {
  214. ExplodedNodeSet *CurrSet = 0;
  215. if (I+1 == E)
  216. CurrSet = &Dst;
  217. else {
  218. CurrSet = (PrevSet == &Tmp) ? &Src : &Tmp;
  219. CurrSet->clear();
  220. }
  221. void *tag = I->first;
  222. Checker *checker = I->second;
  223. for (ExplodedNodeSet::iterator NI = PrevSet->begin(), NE = PrevSet->end();
  224. NI != NE; ++NI)
  225. checker->GR_VisitBind(*CurrSet, *Builder, *this, StoreE,
  226. *NI, tag, location, val, isPrevisit);
  227. // Update which NodeSet is the current one.
  228. PrevSet = CurrSet;
  229. }
  230. // Don't autotransition. The CheckerContext objects should do this
  231. // automatically.
  232. }
  233. //===----------------------------------------------------------------------===//
  234. // Engine construction and deletion.
  235. //===----------------------------------------------------------------------===//
  236. static void RegisterInternalChecks(ExprEngine &Eng) {
  237. // Register internal "built-in" BugTypes with the BugReporter. These BugTypes
  238. // are different than what probably many checks will do since they don't
  239. // create BugReports on-the-fly but instead wait until ExprEngine finishes
  240. // analyzing a function. Generation of BugReport objects is done via a call
  241. // to 'FlushReports' from BugReporter.
  242. // The following checks do not need to have their associated BugTypes
  243. // explicitly registered with the BugReporter. If they issue any BugReports,
  244. // their associated BugType will get registered with the BugReporter
  245. // automatically. Note that the check itself is owned by the ExprEngine
  246. // object.
  247. RegisterAdjustedReturnValueChecker(Eng);
  248. // CallAndMessageChecker should be registered before AttrNonNullChecker,
  249. // where we assume arguments are not undefined.
  250. RegisterCallAndMessageChecker(Eng);
  251. RegisterAttrNonNullChecker(Eng);
  252. RegisterDereferenceChecker(Eng);
  253. RegisterVLASizeChecker(Eng);
  254. RegisterDivZeroChecker(Eng);
  255. RegisterReturnUndefChecker(Eng);
  256. RegisterUndefinedArraySubscriptChecker(Eng);
  257. RegisterUndefinedAssignmentChecker(Eng);
  258. RegisterUndefBranchChecker(Eng);
  259. RegisterUndefCapturedBlockVarChecker(Eng);
  260. RegisterUndefResultChecker(Eng);
  261. RegisterStackAddrLeakChecker(Eng);
  262. RegisterObjCAtSyncChecker(Eng);
  263. // This is not a checker yet.
  264. RegisterNoReturnFunctionChecker(Eng);
  265. RegisterBuiltinFunctionChecker(Eng);
  266. RegisterOSAtomicChecker(Eng);
  267. RegisterUnixAPIChecker(Eng);
  268. RegisterMacOSXAPIChecker(Eng);
  269. }
  270. ExprEngine::ExprEngine(AnalysisManager &mgr, TransferFuncs *tf)
  271. : AMgr(mgr),
  272. Engine(*this),
  273. G(Engine.getGraph()),
  274. Builder(NULL),
  275. StateMgr(getContext(), mgr.getStoreManagerCreator(),
  276. mgr.getConstraintManagerCreator(), G.getAllocator(),
  277. *this),
  278. SymMgr(StateMgr.getSymbolManager()),
  279. svalBuilder(StateMgr.getSValBuilder()),
  280. EntryNode(NULL), currentStmt(NULL),
  281. NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL),
  282. RaiseSel(GetNullarySelector("raise", getContext())),
  283. BR(mgr, *this), TF(tf) {
  284. // Register internal checks.
  285. RegisterInternalChecks(*this);
  286. // FIXME: Eventually remove the TF object entirely.
  287. TF->RegisterChecks(*this);
  288. TF->RegisterPrinters(getStateManager().Printers);
  289. }
  290. ExprEngine::~ExprEngine() {
  291. BR.FlushReports();
  292. delete [] NSExceptionInstanceRaiseSelectors;
  293. // Delete the set of checkers.
  294. for (CheckersOrdered::iterator I=Checkers.begin(), E=Checkers.end(); I!=E;++I)
  295. delete I->second;
  296. for (CheckersOrderedCache::iterator I=COCache.begin(), E=COCache.end();
  297. I!=E;++I)
  298. delete I->second;
  299. }
  300. //===----------------------------------------------------------------------===//
  301. // Utility methods.
  302. //===----------------------------------------------------------------------===//
  303. const GRState* ExprEngine::getInitialState(const LocationContext *InitLoc) {
  304. const GRState *state = StateMgr.getInitialState(InitLoc);
  305. // Preconditions.
  306. // FIXME: It would be nice if we had a more general mechanism to add
  307. // such preconditions. Some day.
  308. do {
  309. const Decl *D = InitLoc->getDecl();
  310. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  311. // Precondition: the first argument of 'main' is an integer guaranteed
  312. // to be > 0.
  313. const IdentifierInfo *II = FD->getIdentifier();
  314. if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
  315. break;
  316. const ParmVarDecl *PD = FD->getParamDecl(0);
  317. QualType T = PD->getType();
  318. if (!T->isIntegerType())
  319. break;
  320. const MemRegion *R = state->getRegion(PD, InitLoc);
  321. if (!R)
  322. break;
  323. SVal V = state->getSVal(loc::MemRegionVal(R));
  324. SVal Constraint_untested = evalBinOp(state, BO_GT, V,
  325. svalBuilder.makeZeroVal(T),
  326. getContext().IntTy);
  327. DefinedOrUnknownSVal *Constraint =
  328. dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested);
  329. if (!Constraint)
  330. break;
  331. if (const GRState *newState = state->assume(*Constraint, true))
  332. state = newState;
  333. break;
  334. }
  335. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  336. // Precondition: 'self' is always non-null upon entry to an Objective-C
  337. // method.
  338. const ImplicitParamDecl *SelfD = MD->getSelfDecl();
  339. const MemRegion *R = state->getRegion(SelfD, InitLoc);
  340. SVal V = state->getSVal(loc::MemRegionVal(R));
  341. if (const Loc *LV = dyn_cast<Loc>(&V)) {
  342. // Assume that the pointer value in 'self' is non-null.
  343. state = state->assume(*LV, true);
  344. assert(state && "'self' cannot be null");
  345. }
  346. }
  347. } while (0);
  348. return state;
  349. }
  350. //===----------------------------------------------------------------------===//
  351. // Top-level transfer function logic (Dispatcher).
  352. //===----------------------------------------------------------------------===//
  353. /// evalAssume - Called by ConstraintManager. Used to call checker-specific
  354. /// logic for handling assumptions on symbolic values.
  355. const GRState *ExprEngine::processAssume(const GRState *state, SVal cond,
  356. bool assumption) {
  357. // Determine if we already have a cached 'CheckersOrdered' vector
  358. // specifically tailored for processing assumptions. This
  359. // can reduce the number of checkers actually called.
  360. CheckersOrdered *CO = &Checkers;
  361. llvm::OwningPtr<CheckersOrdered> NewCO;
  362. CallbackTag K = GetCallbackTag(processAssumeCallback);
  363. CheckersOrdered *& CO_Ref = COCache[K];
  364. if (!CO_Ref) {
  365. // If we have no previously cached CheckersOrdered vector for this
  366. // statement kind, then create one.
  367. NewCO.reset(new CheckersOrdered);
  368. }
  369. else {
  370. // Use the already cached set.
  371. CO = CO_Ref;
  372. }
  373. if (!CO->empty()) {
  374. // Let the checkers have a crack at the assume before the transfer functions
  375. // get their turn.
  376. for (CheckersOrdered::iterator I = CO->begin(), E = CO->end(); I!=E; ++I) {
  377. // If any checker declares the state infeasible (or if it starts that
  378. // way), bail out.
  379. if (!state)
  380. return NULL;
  381. Checker *C = I->second;
  382. bool respondsToCallback = true;
  383. state = C->evalAssume(state, cond, assumption, &respondsToCallback);
  384. // Check if we're building the cache of checkers that care about
  385. // assumptions.
  386. if (NewCO.get() && respondsToCallback)
  387. NewCO->push_back(*I);
  388. }
  389. // If we got through all the checkers, and we built a list of those that
  390. // care about assumptions, save it.
  391. if (NewCO.get())
  392. CO_Ref = NewCO.take();
  393. }
  394. // If the state is infeasible at this point, bail out.
  395. if (!state)
  396. return NULL;
  397. return TF->evalAssume(state, cond, assumption);
  398. }
  399. bool ExprEngine::wantsRegionChangeUpdate(const GRState* state) {
  400. CallbackTag K = GetCallbackTag(EvalRegionChangesCallback);
  401. CheckersOrdered *CO = COCache[K];
  402. if (!CO)
  403. CO = &Checkers;
  404. for (CheckersOrdered::iterator I = CO->begin(), E = CO->end(); I != E; ++I) {
  405. Checker *C = I->second;
  406. if (C->wantsRegionChangeUpdate(state))
  407. return true;
  408. }
  409. return false;
  410. }
  411. const GRState *
  412. ExprEngine::processRegionChanges(const GRState *state,
  413. const MemRegion * const *Begin,
  414. const MemRegion * const *End) {
  415. // FIXME: Most of this method is copy-pasted from processAssume.
  416. // Determine if we already have a cached 'CheckersOrdered' vector
  417. // specifically tailored for processing region changes. This
  418. // can reduce the number of checkers actually called.
  419. CheckersOrdered *CO = &Checkers;
  420. llvm::OwningPtr<CheckersOrdered> NewCO;
  421. CallbackTag K = GetCallbackTag(EvalRegionChangesCallback);
  422. CheckersOrdered *& CO_Ref = COCache[K];
  423. if (!CO_Ref) {
  424. // If we have no previously cached CheckersOrdered vector for this
  425. // callback, then create one.
  426. NewCO.reset(new CheckersOrdered);
  427. }
  428. else {
  429. // Use the already cached set.
  430. CO = CO_Ref;
  431. }
  432. // If there are no checkers, just return the state as is.
  433. if (CO->empty())
  434. return state;
  435. for (CheckersOrdered::iterator I = CO->begin(), E = CO->end(); I != E; ++I) {
  436. // If any checker declares the state infeasible (or if it starts that way),
  437. // bail out.
  438. if (!state)
  439. return NULL;
  440. Checker *C = I->second;
  441. bool respondsToCallback = true;
  442. state = C->EvalRegionChanges(state, Begin, End, &respondsToCallback);
  443. // See if we're building a cache of checkers that care about region changes.
  444. if (NewCO.get() && respondsToCallback)
  445. NewCO->push_back(*I);
  446. }
  447. // If we got through all the checkers, and we built a list of those that
  448. // care about region changes, save it.
  449. if (NewCO.get())
  450. CO_Ref = NewCO.take();
  451. return state;
  452. }
  453. void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
  454. for (CheckersOrdered::iterator I = Checkers.begin(), E = Checkers.end();
  455. I != E; ++I) {
  456. I->second->VisitEndAnalysis(G, BR, *this);
  457. }
  458. }
  459. void ExprEngine::processCFGElement(const CFGElement E,
  460. StmtNodeBuilder& builder) {
  461. switch (E.getKind()) {
  462. case CFGElement::Statement:
  463. ProcessStmt(E.getAs<CFGStmt>(), builder);
  464. break;
  465. case CFGElement::Initializer:
  466. ProcessInitializer(E.getAs<CFGInitializer>(), builder);
  467. break;
  468. case CFGElement::ImplicitDtor:
  469. ProcessImplicitDtor(E.getAs<CFGImplicitDtor>(), builder);
  470. break;
  471. default:
  472. // Suppress compiler warning.
  473. llvm_unreachable("Unexpected CFGElement kind.");
  474. }
  475. }
  476. void ExprEngine::ProcessStmt(const CFGStmt S, StmtNodeBuilder& builder) {
  477. // Recycle any unused states in the GRStateManager.
  478. StateMgr.recycleUnusedStates();
  479. currentStmt = S.getStmt();
  480. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  481. currentStmt->getLocStart(),
  482. "Error evaluating statement");
  483. Builder = &builder;
  484. EntryNode = builder.getPredecessor();
  485. // Create the cleaned state.
  486. const LocationContext *LC = EntryNode->getLocationContext();
  487. SymbolReaper SymReaper(LC, currentStmt, SymMgr);
  488. if (AMgr.shouldPurgeDead()) {
  489. const GRState *St = EntryNode->getState();
  490. for (CheckersOrdered::iterator I = Checkers.begin(), E = Checkers.end();
  491. I != E; ++I) {
  492. Checker *checker = I->second;
  493. checker->MarkLiveSymbols(St, SymReaper);
  494. }
  495. const StackFrameContext *SFC = LC->getCurrentStackFrame();
  496. CleanedState = StateMgr.removeDeadBindings(St, SFC, SymReaper);
  497. } else {
  498. CleanedState = EntryNode->getState();
  499. }
  500. // Process any special transfer function for dead symbols.
  501. ExplodedNodeSet Tmp;
  502. if (!SymReaper.hasDeadSymbols())
  503. Tmp.Add(EntryNode);
  504. else {
  505. SaveAndRestore<bool> OldSink(Builder->BuildSinks);
  506. SaveOr OldHasGen(Builder->hasGeneratedNode);
  507. SaveAndRestore<bool> OldPurgeDeadSymbols(Builder->PurgingDeadSymbols);
  508. Builder->PurgingDeadSymbols = true;
  509. // FIXME: This should soon be removed.
  510. ExplodedNodeSet Tmp2;
  511. getTF().evalDeadSymbols(Tmp2, *this, *Builder, EntryNode,
  512. CleanedState, SymReaper);
  513. if (Checkers.empty())
  514. Tmp.insert(Tmp2);
  515. else {
  516. ExplodedNodeSet Tmp3;
  517. ExplodedNodeSet *SrcSet = &Tmp2;
  518. for (CheckersOrdered::iterator I = Checkers.begin(), E = Checkers.end();
  519. I != E; ++I) {
  520. ExplodedNodeSet *DstSet = 0;
  521. if (I+1 == E)
  522. DstSet = &Tmp;
  523. else {
  524. DstSet = (SrcSet == &Tmp2) ? &Tmp3 : &Tmp2;
  525. DstSet->clear();
  526. }
  527. void *tag = I->first;
  528. Checker *checker = I->second;
  529. for (ExplodedNodeSet::iterator NI = SrcSet->begin(), NE = SrcSet->end();
  530. NI != NE; ++NI)
  531. checker->GR_evalDeadSymbols(*DstSet, *Builder, *this, currentStmt,
  532. *NI, SymReaper, tag);
  533. SrcSet = DstSet;
  534. }
  535. }
  536. if (!Builder->BuildSinks && !Builder->hasGeneratedNode)
  537. Tmp.Add(EntryNode);
  538. }
  539. bool HasAutoGenerated = false;
  540. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
  541. ExplodedNodeSet Dst;
  542. // Set the cleaned state.
  543. Builder->SetCleanedState(*I == EntryNode ? CleanedState : GetState(*I));
  544. // Visit the statement.
  545. Visit(currentStmt, *I, Dst);
  546. // Do we need to auto-generate a node? We only need to do this to generate
  547. // a node with a "cleaned" state; CoreEngine will actually handle
  548. // auto-transitions for other cases.
  549. if (Dst.size() == 1 && *Dst.begin() == EntryNode
  550. && !Builder->hasGeneratedNode && !HasAutoGenerated) {
  551. HasAutoGenerated = true;
  552. builder.generateNode(currentStmt, GetState(EntryNode), *I);
  553. }
  554. }
  555. // NULL out these variables to cleanup.
  556. CleanedState = NULL;
  557. EntryNode = NULL;
  558. currentStmt = 0;
  559. Builder = NULL;
  560. }
  561. void ExprEngine::ProcessInitializer(const CFGInitializer Init,
  562. StmtNodeBuilder &builder) {
  563. // We don't set EntryNode and currentStmt. And we don't clean up state.
  564. const CXXCtorInitializer *BMI = Init.getInitializer();
  565. ExplodedNode *pred = builder.getPredecessor();
  566. const StackFrameContext *stackFrame = cast<StackFrameContext>(pred->getLocationContext());
  567. const CXXConstructorDecl *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
  568. const CXXThisRegion *thisReg = getCXXThisRegion(decl, stackFrame);
  569. SVal thisVal = pred->getState()->getSVal(thisReg);
  570. if (BMI->isAnyMemberInitializer()) {
  571. ExplodedNodeSet Dst;
  572. // Evaluate the initializer.
  573. Visit(BMI->getInit(), pred, Dst);
  574. for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end(); I != E; ++I){
  575. ExplodedNode *Pred = *I;
  576. const GRState *state = Pred->getState();
  577. const FieldDecl *FD = BMI->getAnyMember();
  578. SVal FieldLoc = state->getLValue(FD, thisVal);
  579. SVal InitVal = state->getSVal(BMI->getInit());
  580. state = state->bindLoc(FieldLoc, InitVal);
  581. // Use a custom node building process.
  582. PostInitializer PP(BMI, stackFrame);
  583. // Builder automatically add the generated node to the deferred set,
  584. // which are processed in the builder's dtor.
  585. builder.generateNode(PP, state, Pred);
  586. }
  587. return;
  588. }
  589. assert(BMI->isBaseInitializer());
  590. // Get the base class declaration.
  591. const CXXConstructExpr *ctorExpr = cast<CXXConstructExpr>(BMI->getInit());
  592. // Create the base object region.
  593. SVal baseVal =
  594. getStoreManager().evalDerivedToBase(thisVal, ctorExpr->getType());
  595. const MemRegion *baseReg = baseVal.getAsRegion();
  596. assert(baseReg);
  597. Builder = &builder;
  598. ExplodedNodeSet dst;
  599. VisitCXXConstructExpr(ctorExpr, baseReg, pred, dst);
  600. }
  601. void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
  602. StmtNodeBuilder &builder) {
  603. Builder = &builder;
  604. switch (D.getDtorKind()) {
  605. case CFGElement::AutomaticObjectDtor:
  606. ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), builder);
  607. break;
  608. case CFGElement::BaseDtor:
  609. ProcessBaseDtor(cast<CFGBaseDtor>(D), builder);
  610. break;
  611. case CFGElement::MemberDtor:
  612. ProcessMemberDtor(cast<CFGMemberDtor>(D), builder);
  613. break;
  614. case CFGElement::TemporaryDtor:
  615. ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), builder);
  616. break;
  617. default:
  618. llvm_unreachable("Unexpected dtor kind.");
  619. }
  620. }
  621. void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor dtor,
  622. StmtNodeBuilder &builder) {
  623. ExplodedNode *pred = builder.getPredecessor();
  624. const GRState *state = pred->getState();
  625. const VarDecl *varDecl = dtor.getVarDecl();
  626. QualType varType = varDecl->getType();
  627. if (const ReferenceType *refType = varType->getAs<ReferenceType>())
  628. varType = refType->getPointeeType();
  629. const CXXRecordDecl *recordDecl = varType->getAsCXXRecordDecl();
  630. assert(recordDecl && "get CXXRecordDecl fail");
  631. const CXXDestructorDecl *dtorDecl = recordDecl->getDestructor();
  632. Loc dest = state->getLValue(varDecl, pred->getLocationContext());
  633. ExplodedNodeSet dstSet;
  634. VisitCXXDestructor(dtorDecl, cast<loc::MemRegionVal>(dest).getRegion(),
  635. dtor.getTriggerStmt(), pred, dstSet);
  636. }
  637. void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
  638. StmtNodeBuilder &builder) {
  639. }
  640. void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
  641. StmtNodeBuilder &builder) {
  642. }
  643. void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
  644. StmtNodeBuilder &builder) {
  645. }
  646. void ExprEngine::Visit(const Stmt* S, ExplodedNode* Pred,
  647. ExplodedNodeSet& Dst) {
  648. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  649. S->getLocStart(),
  650. "Error evaluating statement");
  651. // Expressions to ignore.
  652. if (const Expr *Ex = dyn_cast<Expr>(S))
  653. S = Ex->IgnoreParens();
  654. // FIXME: add metadata to the CFG so that we can disable
  655. // this check when we KNOW that there is no block-level subexpression.
  656. // The motivation is that this check requires a hashtable lookup.
  657. if (S != currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(S)) {
  658. Dst.Add(Pred);
  659. return;
  660. }
  661. switch (S->getStmtClass()) {
  662. // C++ stuff we don't support yet.
  663. case Stmt::CXXBindTemporaryExprClass:
  664. case Stmt::CXXCatchStmtClass:
  665. case Stmt::CXXDefaultArgExprClass:
  666. case Stmt::CXXDependentScopeMemberExprClass:
  667. case Stmt::ExprWithCleanupsClass:
  668. case Stmt::CXXNullPtrLiteralExprClass:
  669. case Stmt::CXXPseudoDestructorExprClass:
  670. case Stmt::CXXTemporaryObjectExprClass:
  671. case Stmt::CXXThrowExprClass:
  672. case Stmt::CXXTryStmtClass:
  673. case Stmt::CXXTypeidExprClass:
  674. case Stmt::CXXUuidofExprClass:
  675. case Stmt::CXXUnresolvedConstructExprClass:
  676. case Stmt::CXXScalarValueInitExprClass:
  677. case Stmt::DependentScopeDeclRefExprClass:
  678. case Stmt::UnaryTypeTraitExprClass:
  679. case Stmt::BinaryTypeTraitExprClass:
  680. case Stmt::UnresolvedLookupExprClass:
  681. case Stmt::UnresolvedMemberExprClass:
  682. case Stmt::CXXNoexceptExprClass:
  683. case Stmt::PackExpansionExprClass:
  684. case Stmt::SubstNonTypeTemplateParmPackExprClass:
  685. {
  686. SaveAndRestore<bool> OldSink(Builder->BuildSinks);
  687. Builder->BuildSinks = true;
  688. MakeNode(Dst, S, Pred, GetState(Pred));
  689. break;
  690. }
  691. case Stmt::ParenExprClass:
  692. llvm_unreachable("ParenExprs already handled.");
  693. // Cases that should never be evaluated simply because they shouldn't
  694. // appear in the CFG.
  695. case Stmt::BreakStmtClass:
  696. case Stmt::CaseStmtClass:
  697. case Stmt::CompoundStmtClass:
  698. case Stmt::ContinueStmtClass:
  699. case Stmt::DefaultStmtClass:
  700. case Stmt::DoStmtClass:
  701. case Stmt::GotoStmtClass:
  702. case Stmt::IndirectGotoStmtClass:
  703. case Stmt::LabelStmtClass:
  704. case Stmt::NoStmtClass:
  705. case Stmt::NullStmtClass:
  706. case Stmt::SwitchCaseClass:
  707. case Stmt::OpaqueValueExprClass:
  708. llvm_unreachable("Stmt should not be in analyzer evaluation loop");
  709. break;
  710. case Stmt::GNUNullExprClass: {
  711. MakeNode(Dst, S, Pred, GetState(Pred)->BindExpr(S, svalBuilder.makeNull()));
  712. break;
  713. }
  714. case Stmt::ObjCAtSynchronizedStmtClass:
  715. VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
  716. break;
  717. case Stmt::ObjCPropertyRefExprClass:
  718. VisitObjCPropertyRefExpr(cast<ObjCPropertyRefExpr>(S), Pred, Dst);
  719. break;
  720. // Cases not handled yet; but will handle some day.
  721. case Stmt::DesignatedInitExprClass:
  722. case Stmt::ExtVectorElementExprClass:
  723. case Stmt::ImaginaryLiteralClass:
  724. case Stmt::ImplicitValueInitExprClass:
  725. case Stmt::ObjCAtCatchStmtClass:
  726. case Stmt::ObjCAtFinallyStmtClass:
  727. case Stmt::ObjCAtTryStmtClass:
  728. case Stmt::ObjCEncodeExprClass:
  729. case Stmt::ObjCIsaExprClass:
  730. case Stmt::ObjCProtocolExprClass:
  731. case Stmt::ObjCSelectorExprClass:
  732. case Stmt::ObjCStringLiteralClass:
  733. case Stmt::ParenListExprClass:
  734. case Stmt::PredefinedExprClass:
  735. case Stmt::ShuffleVectorExprClass:
  736. case Stmt::VAArgExprClass:
  737. // Fall through.
  738. // Cases we intentionally don't evaluate, since they don't need
  739. // to be explicitly evaluated.
  740. case Stmt::AddrLabelExprClass:
  741. case Stmt::IntegerLiteralClass:
  742. case Stmt::CharacterLiteralClass:
  743. case Stmt::CXXBoolLiteralExprClass:
  744. case Stmt::FloatingLiteralClass:
  745. case Stmt::SizeOfPackExprClass:
  746. Dst.Add(Pred); // No-op. Simply propagate the current state unchanged.
  747. break;
  748. case Stmt::ArraySubscriptExprClass:
  749. VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
  750. break;
  751. case Stmt::AsmStmtClass:
  752. VisitAsmStmt(cast<AsmStmt>(S), Pred, Dst);
  753. break;
  754. case Stmt::BlockDeclRefExprClass: {
  755. const BlockDeclRefExpr *BE = cast<BlockDeclRefExpr>(S);
  756. VisitCommonDeclRefExpr(BE, BE->getDecl(), Pred, Dst);
  757. break;
  758. }
  759. case Stmt::BlockExprClass:
  760. VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
  761. break;
  762. case Stmt::BinaryOperatorClass: {
  763. const BinaryOperator* B = cast<BinaryOperator>(S);
  764. if (B->isLogicalOp()) {
  765. VisitLogicalExpr(B, Pred, Dst);
  766. break;
  767. }
  768. else if (B->getOpcode() == BO_Comma) {
  769. const GRState* state = GetState(Pred);
  770. MakeNode(Dst, B, Pred, state->BindExpr(B, state->getSVal(B->getRHS())));
  771. break;
  772. }
  773. if (AMgr.shouldEagerlyAssume() &&
  774. (B->isRelationalOp() || B->isEqualityOp())) {
  775. ExplodedNodeSet Tmp;
  776. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
  777. evalEagerlyAssume(Dst, Tmp, cast<Expr>(S));
  778. }
  779. else
  780. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  781. break;
  782. }
  783. case Stmt::CallExprClass: {
  784. const CallExpr* C = cast<CallExpr>(S);
  785. VisitCall(C, Pred, C->arg_begin(), C->arg_end(), Dst);
  786. break;
  787. }
  788. case Stmt::CXXConstructExprClass: {
  789. const CXXConstructExpr *C = cast<CXXConstructExpr>(S);
  790. // For block-level CXXConstructExpr, we don't have a destination region.
  791. // Let VisitCXXConstructExpr() create one.
  792. VisitCXXConstructExpr(C, 0, Pred, Dst);
  793. break;
  794. }
  795. case Stmt::CXXMemberCallExprClass: {
  796. const CXXMemberCallExpr *MCE = cast<CXXMemberCallExpr>(S);
  797. VisitCXXMemberCallExpr(MCE, Pred, Dst);
  798. break;
  799. }
  800. case Stmt::CXXOperatorCallExprClass: {
  801. const CXXOperatorCallExpr *C = cast<CXXOperatorCallExpr>(S);
  802. VisitCXXOperatorCallExpr(C, Pred, Dst);
  803. break;
  804. }
  805. case Stmt::CXXNewExprClass: {
  806. const CXXNewExpr *NE = cast<CXXNewExpr>(S);
  807. VisitCXXNewExpr(NE, Pred, Dst);
  808. break;
  809. }
  810. case Stmt::CXXDeleteExprClass: {
  811. const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
  812. VisitCXXDeleteExpr(CDE, Pred, Dst);
  813. break;
  814. }
  815. // FIXME: ChooseExpr is really a constant. We need to fix
  816. // the CFG do not model them as explicit control-flow.
  817. case Stmt::ChooseExprClass: { // __builtin_choose_expr
  818. const ChooseExpr* C = cast<ChooseExpr>(S);
  819. VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
  820. break;
  821. }
  822. case Stmt::CompoundAssignOperatorClass:
  823. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  824. break;
  825. case Stmt::CompoundLiteralExprClass:
  826. VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
  827. break;
  828. case Stmt::ConditionalOperatorClass: { // '?' operator
  829. const ConditionalOperator* C = cast<ConditionalOperator>(S);
  830. VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
  831. break;
  832. }
  833. case Stmt::CXXThisExprClass:
  834. VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
  835. break;
  836. case Stmt::DeclRefExprClass: {
  837. const DeclRefExpr *DE = cast<DeclRefExpr>(S);
  838. VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
  839. break;
  840. }
  841. case Stmt::DeclStmtClass:
  842. VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
  843. break;
  844. case Stmt::ForStmtClass:
  845. // This case isn't for branch processing, but for handling the
  846. // initialization of a condition variable.
  847. VisitCondInit(cast<ForStmt>(S)->getConditionVariable(), S, Pred, Dst);
  848. break;
  849. case Stmt::ImplicitCastExprClass:
  850. case Stmt::CStyleCastExprClass:
  851. case Stmt::CXXStaticCastExprClass:
  852. case Stmt::CXXDynamicCastExprClass:
  853. case Stmt::CXXReinterpretCastExprClass:
  854. case Stmt::CXXConstCastExprClass:
  855. case Stmt::CXXFunctionalCastExprClass: {
  856. const CastExpr* C = cast<CastExpr>(S);
  857. VisitCast(C, C->getSubExpr(), Pred, Dst);
  858. break;
  859. }
  860. case Stmt::IfStmtClass:
  861. // This case isn't for branch processing, but for handling the
  862. // initialization of a condition variable.
  863. VisitCondInit(cast<IfStmt>(S)->getConditionVariable(), S, Pred, Dst);
  864. break;
  865. case Stmt::InitListExprClass:
  866. VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
  867. break;
  868. case Stmt::MemberExprClass:
  869. VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
  870. break;
  871. case Stmt::ObjCIvarRefExprClass:
  872. VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
  873. break;
  874. case Stmt::ObjCForCollectionStmtClass:
  875. VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
  876. break;
  877. case Stmt::ObjCMessageExprClass:
  878. VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), Pred, Dst);
  879. break;
  880. case Stmt::ObjCAtThrowStmtClass: {
  881. // FIXME: This is not complete. We basically treat @throw as
  882. // an abort.
  883. SaveAndRestore<bool> OldSink(Builder->BuildSinks);
  884. Builder->BuildSinks = true;
  885. MakeNode(Dst, S, Pred, GetState(Pred));
  886. break;
  887. }
  888. case Stmt::ReturnStmtClass:
  889. VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
  890. break;
  891. case Stmt::OffsetOfExprClass:
  892. VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
  893. break;
  894. case Stmt::SizeOfAlignOfExprClass:
  895. VisitSizeOfAlignOfExpr(cast<SizeOfAlignOfExpr>(S), Pred, Dst);
  896. break;
  897. case Stmt::StmtExprClass: {
  898. const StmtExpr* SE = cast<StmtExpr>(S);
  899. if (SE->getSubStmt()->body_empty()) {
  900. // Empty statement expression.
  901. assert(SE->getType() == getContext().VoidTy
  902. && "Empty statement expression must have void type.");
  903. Dst.Add(Pred);
  904. break;
  905. }
  906. if (Expr* LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
  907. const GRState* state = GetState(Pred);
  908. MakeNode(Dst, SE, Pred, state->BindExpr(SE, state->getSVal(LastExpr)));
  909. }
  910. else
  911. Dst.Add(Pred);
  912. break;
  913. }
  914. case Stmt::StringLiteralClass: {
  915. const GRState* state = GetState(Pred);
  916. SVal V = state->getLValue(cast<StringLiteral>(S));
  917. MakeNode(Dst, S, Pred, state->BindExpr(S, V));
  918. return;
  919. }
  920. case Stmt::SwitchStmtClass:
  921. // This case isn't for branch processing, but for handling the
  922. // initialization of a condition variable.
  923. VisitCondInit(cast<SwitchStmt>(S)->getConditionVariable(), S, Pred, Dst);
  924. break;
  925. case Stmt::UnaryOperatorClass: {
  926. const UnaryOperator *U = cast<UnaryOperator>(S);
  927. if (AMgr.shouldEagerlyAssume()&&(U->getOpcode() == UO_LNot)) {
  928. ExplodedNodeSet Tmp;
  929. VisitUnaryOperator(U, Pred, Tmp);
  930. evalEagerlyAssume(Dst, Tmp, U);
  931. }
  932. else
  933. VisitUnaryOperator(U, Pred, Dst);
  934. break;
  935. }
  936. case Stmt::WhileStmtClass:
  937. // This case isn't for branch processing, but for handling the
  938. // initialization of a condition variable.
  939. VisitCondInit(cast<WhileStmt>(S)->getConditionVariable(), S, Pred, Dst);
  940. break;
  941. }
  942. }
  943. //===----------------------------------------------------------------------===//
  944. // Block entrance. (Update counters).
  945. //===----------------------------------------------------------------------===//
  946. void ExprEngine::processCFGBlockEntrance(ExplodedNodeSet &dstNodes,
  947. GenericNodeBuilder<BlockEntrance> &nodeBuilder){
  948. // FIXME: Refactor this into a checker.
  949. const CFGBlock *block = nodeBuilder.getProgramPoint().getBlock();
  950. ExplodedNode *pred = nodeBuilder.getPredecessor();
  951. if (nodeBuilder.getBlockCounter().getNumVisited(
  952. pred->getLocationContext()->getCurrentStackFrame(),
  953. block->getBlockID()) >= AMgr.getMaxVisit()) {
  954. static int tag = 0;
  955. nodeBuilder.generateNode(pred->getState(), pred, &tag, true);
  956. }
  957. }
  958. //===----------------------------------------------------------------------===//
  959. // Generic node creation.
  960. //===----------------------------------------------------------------------===//
  961. ExplodedNode* ExprEngine::MakeNode(ExplodedNodeSet& Dst, const Stmt* S,
  962. ExplodedNode* Pred, const GRState* St,
  963. ProgramPoint::Kind K, const void *tag) {
  964. assert (Builder && "StmtNodeBuilder not present.");
  965. SaveAndRestore<const void*> OldTag(Builder->Tag);
  966. Builder->Tag = tag;
  967. return Builder->MakeNode(Dst, S, Pred, St, K);
  968. }
  969. //===----------------------------------------------------------------------===//
  970. // Branch processing.
  971. //===----------------------------------------------------------------------===//
  972. const GRState* ExprEngine::MarkBranch(const GRState* state,
  973. const Stmt* Terminator,
  974. bool branchTaken) {
  975. switch (Terminator->getStmtClass()) {
  976. default:
  977. return state;
  978. case Stmt::BinaryOperatorClass: { // '&&' and '||'
  979. const BinaryOperator* B = cast<BinaryOperator>(Terminator);
  980. BinaryOperator::Opcode Op = B->getOpcode();
  981. assert (Op == BO_LAnd || Op == BO_LOr);
  982. // For &&, if we take the true branch, then the value of the whole
  983. // expression is that of the RHS expression.
  984. //
  985. // For ||, if we take the false branch, then the value of the whole
  986. // expression is that of the RHS expression.
  987. const Expr* Ex = (Op == BO_LAnd && branchTaken) ||
  988. (Op == BO_LOr && !branchTaken)
  989. ? B->getRHS() : B->getLHS();
  990. return state->BindExpr(B, UndefinedVal(Ex));
  991. }
  992. case Stmt::ConditionalOperatorClass: { // ?:
  993. const ConditionalOperator* C = cast<ConditionalOperator>(Terminator);
  994. // For ?, if branchTaken == true then the value is either the LHS or
  995. // the condition itself. (GNU extension).
  996. const Expr* Ex;
  997. if (branchTaken)
  998. Ex = C->getLHS() ? C->getLHS() : C->getCond();
  999. else
  1000. Ex = C->getRHS();
  1001. return state->BindExpr(C, UndefinedVal(Ex));
  1002. }
  1003. case Stmt::ChooseExprClass: { // ?:
  1004. const ChooseExpr* C = cast<ChooseExpr>(Terminator);
  1005. const Expr* Ex = branchTaken ? C->getLHS() : C->getRHS();
  1006. return state->BindExpr(C, UndefinedVal(Ex));
  1007. }
  1008. }
  1009. }
  1010. /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
  1011. /// to try to recover some path-sensitivity for casts of symbolic
  1012. /// integers that promote their values (which are currently not tracked well).
  1013. /// This function returns the SVal bound to Condition->IgnoreCasts if all the
  1014. // cast(s) did was sign-extend the original value.
  1015. static SVal RecoverCastedSymbol(GRStateManager& StateMgr, const GRState* state,
  1016. const Stmt* Condition, ASTContext& Ctx) {
  1017. const Expr *Ex = dyn_cast<Expr>(Condition);
  1018. if (!Ex)
  1019. return UnknownVal();
  1020. uint64_t bits = 0;
  1021. bool bitsInit = false;
  1022. while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
  1023. QualType T = CE->getType();
  1024. if (!T->isIntegerType())
  1025. return UnknownVal();
  1026. uint64_t newBits = Ctx.getTypeSize(T);
  1027. if (!bitsInit || newBits < bits) {
  1028. bitsInit = true;
  1029. bits = newBits;
  1030. }
  1031. Ex = CE->getSubExpr();
  1032. }
  1033. // We reached a non-cast. Is it a symbolic value?
  1034. QualType T = Ex->getType();
  1035. if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits)
  1036. return UnknownVal();
  1037. return state->getSVal(Ex);
  1038. }
  1039. void ExprEngine::processBranch(const Stmt* Condition, const Stmt* Term,
  1040. BranchNodeBuilder& builder) {
  1041. // Check for NULL conditions; e.g. "for(;;)"
  1042. if (!Condition) {
  1043. builder.markInfeasible(false);
  1044. return;
  1045. }
  1046. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1047. Condition->getLocStart(),
  1048. "Error evaluating branch");
  1049. for (CheckersOrdered::iterator I=Checkers.begin(),E=Checkers.end();I!=E;++I) {
  1050. void *tag = I->first;
  1051. Checker *checker = I->second;
  1052. checker->VisitBranchCondition(builder, *this, Condition, tag);
  1053. }
  1054. // If the branch condition is undefined, return;
  1055. if (!builder.isFeasible(true) && !builder.isFeasible(false))
  1056. return;
  1057. const GRState* PrevState = builder.getState();
  1058. SVal X = PrevState->getSVal(Condition);
  1059. if (X.isUnknown()) {
  1060. // Give it a chance to recover from unknown.
  1061. if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
  1062. if (Ex->getType()->isIntegerType()) {
  1063. // Try to recover some path-sensitivity. Right now casts of symbolic
  1064. // integers that promote their values are currently not tracked well.
  1065. // If 'Condition' is such an expression, try and recover the
  1066. // underlying value and use that instead.
  1067. SVal recovered = RecoverCastedSymbol(getStateManager(),
  1068. builder.getState(), Condition,
  1069. getContext());
  1070. if (!recovered.isUnknown()) {
  1071. X = recovered;
  1072. }
  1073. }
  1074. }
  1075. // If the condition is still unknown, give up.
  1076. if (X.isUnknown()) {
  1077. builder.generateNode(MarkBranch(PrevState, Term, true), true);
  1078. builder.generateNode(MarkBranch(PrevState, Term, false), false);
  1079. return;
  1080. }
  1081. }
  1082. DefinedSVal V = cast<DefinedSVal>(X);
  1083. // Process the true branch.
  1084. if (builder.isFeasible(true)) {
  1085. if (const GRState *state = PrevState->assume(V, true))
  1086. builder.generateNode(MarkBranch(state, Term, true), true);
  1087. else
  1088. builder.markInfeasible(true);
  1089. }
  1090. // Process the false branch.
  1091. if (builder.isFeasible(false)) {
  1092. if (const GRState *state = PrevState->assume(V, false))
  1093. builder.generateNode(MarkBranch(state, Term, false), false);
  1094. else
  1095. builder.markInfeasible(false);
  1096. }
  1097. }
  1098. /// processIndirectGoto - Called by CoreEngine. Used to generate successor
  1099. /// nodes by processing the 'effects' of a computed goto jump.
  1100. void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder& builder) {
  1101. const GRState *state = builder.getState();
  1102. SVal V = state->getSVal(builder.getTarget());
  1103. // Three possibilities:
  1104. //
  1105. // (1) We know the computed label.
  1106. // (2) The label is NULL (or some other constant), or Undefined.
  1107. // (3) We have no clue about the label. Dispatch to all targets.
  1108. //
  1109. typedef IndirectGotoNodeBuilder::iterator iterator;
  1110. if (isa<loc::GotoLabel>(V)) {
  1111. const LabelStmt* L = cast<loc::GotoLabel>(V).getLabel();
  1112. for (iterator I=builder.begin(), E=builder.end(); I != E; ++I) {
  1113. if (I.getLabel() == L) {
  1114. builder.generateNode(I, state);
  1115. return;
  1116. }
  1117. }
  1118. assert (false && "No block with label.");
  1119. return;
  1120. }
  1121. if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) {
  1122. // Dispatch to the first target and mark it as a sink.
  1123. //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
  1124. // FIXME: add checker visit.
  1125. // UndefBranches.insert(N);
  1126. return;
  1127. }
  1128. // This is really a catch-all. We don't support symbolics yet.
  1129. // FIXME: Implement dispatch for symbolic pointers.
  1130. for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
  1131. builder.generateNode(I, state);
  1132. }
  1133. void ExprEngine::VisitGuardedExpr(const Expr* Ex, const Expr* L,
  1134. const Expr* R,
  1135. ExplodedNode* Pred, ExplodedNodeSet& Dst) {
  1136. assert(Ex == currentStmt &&
  1137. Pred->getLocationContext()->getCFG()->isBlkExpr(Ex));
  1138. const GRState* state = GetState(Pred);
  1139. SVal X = state->getSVal(Ex);
  1140. assert (X.isUndef());
  1141. const Expr *SE = (Expr*) cast<UndefinedVal>(X).getData();
  1142. assert(SE);
  1143. X = state->getSVal(SE);
  1144. // Make sure that we invalidate the previous binding.
  1145. MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, X, true));
  1146. }
  1147. /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
  1148. /// nodes when the control reaches the end of a function.
  1149. void ExprEngine::processEndOfFunction(EndOfFunctionNodeBuilder& builder) {
  1150. getTF().evalEndPath(*this, builder);
  1151. StateMgr.EndPath(builder.getState());
  1152. for (CheckersOrdered::iterator I=Checkers.begin(),E=Checkers.end(); I!=E;++I){
  1153. void *tag = I->first;
  1154. Checker *checker = I->second;
  1155. checker->evalEndPath(builder, tag, *this);
  1156. }
  1157. }
  1158. /// ProcessSwitch - Called by CoreEngine. Used to generate successor
  1159. /// nodes by processing the 'effects' of a switch statement.
  1160. void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
  1161. typedef SwitchNodeBuilder::iterator iterator;
  1162. const GRState* state = builder.getState();
  1163. const Expr* CondE = builder.getCondition();
  1164. SVal CondV_untested = state->getSVal(CondE);
  1165. if (CondV_untested.isUndef()) {
  1166. //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
  1167. // FIXME: add checker
  1168. //UndefBranches.insert(N);
  1169. return;
  1170. }
  1171. DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested);
  1172. const GRState *DefaultSt = state;
  1173. iterator I = builder.begin(), EI = builder.end();
  1174. bool defaultIsFeasible = I == EI;
  1175. for ( ; I != EI; ++I) {
  1176. const CaseStmt* Case = I.getCase();
  1177. // Evaluate the LHS of the case value.
  1178. Expr::EvalResult V1;
  1179. bool b = Case->getLHS()->Evaluate(V1, getContext());
  1180. // Sanity checks. These go away in Release builds.
  1181. assert(b && V1.Val.isInt() && !V1.HasSideEffects
  1182. && "Case condition must evaluate to an integer constant.");
  1183. (void)b; // silence unused variable warning
  1184. assert(V1.Val.getInt().getBitWidth() ==
  1185. getContext().getTypeSize(CondE->getType()));
  1186. // Get the RHS of the case, if it exists.
  1187. Expr::EvalResult V2;
  1188. if (const Expr* E = Case->getRHS()) {
  1189. b = E->Evaluate(V2, getContext());
  1190. assert(b && V2.Val.isInt() && !V2.HasSideEffects
  1191. && "Case condition must evaluate to an integer constant.");
  1192. (void)b; // silence unused variable warning
  1193. }
  1194. else
  1195. V2 = V1;
  1196. // FIXME: Eventually we should replace the logic below with a range
  1197. // comparison, rather than concretize the values within the range.
  1198. // This should be easy once we have "ranges" for NonLVals.
  1199. do {
  1200. nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1.Val.getInt()));
  1201. DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
  1202. CondV, CaseVal);
  1203. // Now "assume" that the case matches.
  1204. if (const GRState* stateNew = state->assume(Res, true)) {
  1205. builder.generateCaseStmtNode(I, stateNew);
  1206. // If CondV evaluates to a constant, then we know that this
  1207. // is the *only* case that we can take, so stop evaluating the
  1208. // others.
  1209. if (isa<nonloc::ConcreteInt>(CondV))
  1210. return;
  1211. }
  1212. // Now "assume" that the case doesn't match. Add this state
  1213. // to the default state (if it is feasible).
  1214. if (DefaultSt) {
  1215. if (const GRState *stateNew = DefaultSt->assume(Res, false)) {
  1216. defaultIsFeasible = true;
  1217. DefaultSt = stateNew;
  1218. }
  1219. else {
  1220. defaultIsFeasible = false;
  1221. DefaultSt = NULL;
  1222. }
  1223. }
  1224. // Concretize the next value in the range.
  1225. if (V1.Val.getInt() == V2.Val.getInt())
  1226. break;
  1227. ++V1.Val.getInt();
  1228. assert (V1.Val.getInt() <= V2.Val.getInt());
  1229. } while (true);
  1230. }
  1231. if (!defaultIsFeasible)
  1232. return;
  1233. // If we have switch(enum value), the default branch is not
  1234. // feasible if all of the enum constants not covered by 'case:' statements
  1235. // are not feasible values for the switch condition.
  1236. //
  1237. // Note that this isn't as accurate as it could be. Even if there isn't
  1238. // a case for a particular enum value as long as that enum value isn't
  1239. // feasible then it shouldn't be considered for making 'default:' reachable.
  1240. const SwitchStmt *SS = builder.getSwitch();
  1241. const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
  1242. if (CondExpr->getType()->getAs<EnumType>()) {
  1243. if (SS->isAllEnumCasesCovered())
  1244. return;
  1245. }
  1246. builder.generateDefaultCaseNode(DefaultSt);
  1247. }
  1248. void ExprEngine::processCallEnter(CallEnterNodeBuilder &B) {
  1249. const GRState *state = B.getState()->enterStackFrame(B.getCalleeContext());
  1250. B.generateNode(state);
  1251. }
  1252. void ExprEngine::processCallExit(CallExitNodeBuilder &B) {
  1253. const GRState *state = B.getState();
  1254. const ExplodedNode *Pred = B.getPredecessor();
  1255. const StackFrameContext *calleeCtx =
  1256. cast<StackFrameContext>(Pred->getLocationContext());
  1257. const Stmt *CE = calleeCtx->getCallSite();
  1258. // If the callee returns an expression, bind its value to CallExpr.
  1259. const Stmt *ReturnedExpr = state->get<ReturnExpr>();
  1260. if (ReturnedExpr) {
  1261. SVal RetVal = state->getSVal(ReturnedExpr);
  1262. state = state->BindExpr(CE, RetVal);
  1263. // Clear the return expr GDM.
  1264. state = state->remove<ReturnExpr>();
  1265. }
  1266. // Bind the constructed object value to CXXConstructExpr.
  1267. if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) {
  1268. const CXXThisRegion *ThisR =
  1269. getCXXThisRegion(CCE->getConstructor()->getParent(), calleeCtx);
  1270. SVal ThisV = state->getSVal(ThisR);
  1271. // Always bind the region to the CXXConstructExpr.
  1272. state = state->BindExpr(CCE, ThisV);
  1273. }
  1274. B.generateNode(state);
  1275. }
  1276. //===----------------------------------------------------------------------===//
  1277. // Transfer functions: logical operations ('&&', '||').
  1278. //===----------------------------------------------------------------------===//
  1279. void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode* Pred,
  1280. ExplodedNodeSet& Dst) {
  1281. assert(B->getOpcode() == BO_LAnd ||
  1282. B->getOpcode() == BO_LOr);
  1283. assert(B==currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(B));
  1284. const GRState* state = GetState(Pred);
  1285. SVal X = state->getSVal(B);
  1286. assert(X.isUndef());
  1287. const Expr *Ex = (const Expr*) cast<UndefinedVal>(X).getData();
  1288. assert(Ex);
  1289. if (Ex == B->getRHS()) {
  1290. X = state->getSVal(Ex);
  1291. // Handle undefined values.
  1292. if (X.isUndef()) {
  1293. MakeNode(Dst, B, Pred, state->BindExpr(B, X));
  1294. return;
  1295. }
  1296. DefinedOrUnknownSVal XD = cast<DefinedOrUnknownSVal>(X);
  1297. // We took the RHS. Because the value of the '&&' or '||' expression must
  1298. // evaluate to 0 or 1, we must assume the value of the RHS evaluates to 0
  1299. // or 1. Alternatively, we could take a lazy approach, and calculate this
  1300. // value later when necessary. We don't have the machinery in place for
  1301. // this right now, and since most logical expressions are used for branches,
  1302. // the payoff is not likely to be large. Instead, we do eager evaluation.
  1303. if (const GRState *newState = state->assume(XD, true))
  1304. MakeNode(Dst, B, Pred,
  1305. newState->BindExpr(B, svalBuilder.makeIntVal(1U, B->getType())));
  1306. if (const GRState *newState = state->assume(XD, false))
  1307. MakeNode(Dst, B, Pred,
  1308. newState->BindExpr(B, svalBuilder.makeIntVal(0U, B->getType())));
  1309. }
  1310. else {
  1311. // We took the LHS expression. Depending on whether we are '&&' or
  1312. // '||' we know what the value of the expression is via properties of
  1313. // the short-circuiting.
  1314. X = svalBuilder.makeIntVal(B->getOpcode() == BO_LAnd ? 0U : 1U,
  1315. B->getType());
  1316. MakeNode(Dst, B, Pred, state->BindExpr(B, X));
  1317. }
  1318. }
  1319. //===----------------------------------------------------------------------===//
  1320. // Transfer functions: Loads and stores.
  1321. //===----------------------------------------------------------------------===//
  1322. void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
  1323. ExplodedNodeSet &Dst) {
  1324. ExplodedNodeSet Tmp;
  1325. CanQualType T = getContext().getCanonicalType(BE->getType());
  1326. SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T,
  1327. Pred->getLocationContext());
  1328. MakeNode(Tmp, BE, Pred, GetState(Pred)->BindExpr(BE, V),
  1329. ProgramPoint::PostLValueKind);
  1330. // Post-visit the BlockExpr.
  1331. CheckerVisit(BE, Dst, Tmp, PostVisitStmtCallback);
  1332. }
  1333. void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
  1334. ExplodedNode *Pred,
  1335. ExplodedNodeSet &Dst) {
  1336. const GRState *state = GetState(Pred);
  1337. if (const VarDecl* VD = dyn_cast<VarDecl>(D)) {
  1338. assert(Ex->isLValue());
  1339. SVal V = state->getLValue(VD, Pred->getLocationContext());
  1340. // For references, the 'lvalue' is the pointer address stored in the
  1341. // reference region.
  1342. if (VD->getType()->isReferenceType()) {
  1343. if (const MemRegion *R = V.getAsRegion())
  1344. V = state->getSVal(R);
  1345. else
  1346. V = UnknownVal();
  1347. }
  1348. MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V),
  1349. ProgramPoint::PostLValueKind);
  1350. return;
  1351. }
  1352. if (const EnumConstantDecl* ED = dyn_cast<EnumConstantDecl>(D)) {
  1353. assert(!Ex->isLValue());
  1354. SVal V = svalBuilder.makeIntVal(ED->getInitVal());
  1355. MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V));
  1356. return;
  1357. }
  1358. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) {
  1359. SVal V = svalBuilder.getFunctionPointer(FD);
  1360. MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V),
  1361. ProgramPoint::PostLValueKind);
  1362. return;
  1363. }
  1364. assert (false &&
  1365. "ValueDecl support for this ValueDecl not implemented.");
  1366. }
  1367. /// VisitArraySubscriptExpr - Transfer function for array accesses
  1368. void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr* A,
  1369. ExplodedNode* Pred,
  1370. ExplodedNodeSet& Dst){
  1371. const Expr* Base = A->getBase()->IgnoreParens();
  1372. const Expr* Idx = A->getIdx()->IgnoreParens();
  1373. // Evaluate the base.
  1374. ExplodedNodeSet Tmp;
  1375. Visit(Base, Pred, Tmp);
  1376. for (ExplodedNodeSet::iterator I1=Tmp.begin(), E1=Tmp.end(); I1!=E1; ++I1) {
  1377. ExplodedNodeSet Tmp2;
  1378. Visit(Idx, *I1, Tmp2); // Evaluate the index.
  1379. ExplodedNodeSet Tmp3;
  1380. CheckerVisit(A, Tmp3, Tmp2, PreVisitStmtCallback);
  1381. for (ExplodedNodeSet::iterator I2=Tmp3.begin(),E2=Tmp3.end();I2!=E2; ++I2) {
  1382. const GRState* state = GetState(*I2);
  1383. SVal V = state->getLValue(A->getType(), state->getSVal(Idx),
  1384. state->getSVal(Base));
  1385. assert(A->isLValue());
  1386. MakeNode(Dst, A, *I2, state->BindExpr(A, V), ProgramPoint::PostLValueKind);
  1387. }
  1388. }
  1389. }
  1390. /// VisitMemberExpr - Transfer function for member expressions.
  1391. void ExprEngine::VisitMemberExpr(const MemberExpr* M, ExplodedNode* Pred,
  1392. ExplodedNodeSet& Dst) {
  1393. Expr *baseExpr = M->getBase()->IgnoreParens();
  1394. ExplodedNodeSet dstBase;
  1395. Visit(baseExpr, Pred, dstBase);
  1396. FieldDecl *field = dyn_cast<FieldDecl>(M->getMemberDecl());
  1397. if (!field) // FIXME: skipping member expressions for non-fields
  1398. return;
  1399. for (ExplodedNodeSet::iterator I = dstBase.begin(), E = dstBase.end();
  1400. I != E; ++I) {
  1401. const GRState* state = GetState(*I);
  1402. SVal baseExprVal = state->getSVal(baseExpr);
  1403. if (isa<nonloc::LazyCompoundVal>(baseExprVal) ||
  1404. isa<nonloc::CompoundVal>(baseExprVal) ||
  1405. // FIXME: This can originate by conjuring a symbol for an unknown
  1406. // temporary struct object, see test/Analysis/fields.c:
  1407. // (p = getit()).x
  1408. isa<nonloc::SymbolVal>(baseExprVal)) {
  1409. MakeNode(Dst, M, *I, state->BindExpr(M, UnknownVal()));
  1410. continue;
  1411. }
  1412. // FIXME: Should we insert some assumption logic in here to determine
  1413. // if "Base" is a valid piece of memory? Before we put this assumption
  1414. // later when using FieldOffset lvals (which we no longer have).
  1415. // For all other cases, compute an lvalue.
  1416. SVal L = state->getLValue(field, baseExprVal);
  1417. if (M->isLValue())
  1418. MakeNode(Dst, M, *I, state->BindExpr(M, L), ProgramPoint::PostLValueKind);
  1419. else
  1420. evalLoad(Dst, M, *I, state, L);
  1421. }
  1422. }
  1423. /// evalBind - Handle the semantics of binding a value to a specific location.
  1424. /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
  1425. void ExprEngine::evalBind(ExplodedNodeSet& Dst, const Stmt* StoreE,
  1426. ExplodedNode* Pred, const GRState* state,
  1427. SVal location, SVal Val, bool atDeclInit) {
  1428. // Do a previsit of the bind.
  1429. ExplodedNodeSet CheckedSet, Src;
  1430. Src.Add(Pred);
  1431. CheckerVisitBind(StoreE, CheckedSet, Src, location, Val, true);
  1432. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  1433. I!=E; ++I) {
  1434. if (Pred != *I)
  1435. state = GetState(*I);
  1436. const GRState* newState = 0;
  1437. if (atDeclInit) {
  1438. const VarRegion *VR =
  1439. cast<VarRegion>(cast<loc::MemRegionVal>(location).getRegion());
  1440. newState = state->bindDecl(VR, Val);
  1441. }
  1442. else {
  1443. if (location.isUnknown()) {
  1444. // We know that the new state will be the same as the old state since
  1445. // the location of the binding is "unknown". Consequently, there
  1446. // is no reason to just create a new node.
  1447. newState = state;
  1448. }
  1449. else {
  1450. // We are binding to a value other than 'unknown'. Perform the binding
  1451. // using the StoreManager.
  1452. newState = state->bindLoc(cast<Loc>(location), Val);
  1453. }
  1454. }
  1455. // The next thing to do is check if the TransferFuncs object wants to
  1456. // update the state based on the new binding. If the GRTransferFunc object
  1457. // doesn't do anything, just auto-propagate the current state.
  1458. // NOTE: We use 'AssignE' for the location of the PostStore if 'AssignE'
  1459. // is non-NULL. Checkers typically care about
  1460. StmtNodeBuilderRef BuilderRef(Dst, *Builder, *this, *I, newState, StoreE,
  1461. true);
  1462. getTF().evalBind(BuilderRef, location, Val);
  1463. }
  1464. }
  1465. /// evalStore - Handle the semantics of a store via an assignment.
  1466. /// @param Dst The node set to store generated state nodes
  1467. /// @param AssignE The assignment expression if the store happens in an
  1468. /// assignment.
  1469. /// @param LocatioinE The location expression that is stored to.
  1470. /// @param state The current simulation state
  1471. /// @param location The location to store the value
  1472. /// @param Val The value to be stored
  1473. void ExprEngine::evalStore(ExplodedNodeSet& Dst, const Expr *AssignE,
  1474. const Expr* LocationE,
  1475. ExplodedNode* Pred,
  1476. const GRState* state, SVal location, SVal Val,
  1477. const void *tag) {
  1478. assert(Builder && "StmtNodeBuilder must be defined.");
  1479. // Proceed with the store. We use AssignE as the anchor for the PostStore
  1480. // ProgramPoint if it is non-NULL, and LocationE otherwise.
  1481. const Expr *StoreE = AssignE ? AssignE : LocationE;
  1482. if (isa<loc::ObjCPropRef>(location)) {
  1483. loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location);
  1484. ExplodedNodeSet src = Pred;
  1485. return VisitObjCMessage(ObjCPropertySetter(prop.getPropRefExpr(),
  1486. StoreE, Val), src, Dst);
  1487. }
  1488. // Evaluate the location (checks for bad dereferences).
  1489. ExplodedNodeSet Tmp;
  1490. evalLocation(Tmp, LocationE, Pred, state, location, tag, false);
  1491. if (Tmp.empty())
  1492. return;
  1493. assert(!location.isUndef());
  1494. SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind,
  1495. ProgramPoint::PostStoreKind);
  1496. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
  1497. evalBind(Dst, StoreE, *NI, GetState(*NI), location, Val);
  1498. }
  1499. void ExprEngine::evalLoad(ExplodedNodeSet& Dst, const Expr *Ex,
  1500. ExplodedNode* Pred,
  1501. const GRState* state, SVal location,
  1502. const void *tag, QualType LoadTy) {
  1503. assert(!isa<NonLoc>(location) && "location cannot be a NonLoc.");
  1504. if (isa<loc::ObjCPropRef>(location)) {
  1505. loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location);
  1506. ExplodedNodeSet src = Pred;
  1507. return VisitObjCMessage(ObjCPropertyGetter(prop.getPropRefExpr(), Ex),
  1508. src, Dst);
  1509. }
  1510. // Are we loading from a region? This actually results in two loads; one
  1511. // to fetch the address of the referenced value and one to fetch the
  1512. // referenced value.
  1513. if (const TypedRegion *TR =
  1514. dyn_cast_or_null<TypedRegion>(location.getAsRegion())) {
  1515. QualType ValTy = TR->getValueType();
  1516. if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
  1517. static int loadReferenceTag = 0;
  1518. ExplodedNodeSet Tmp;
  1519. evalLoadCommon(Tmp, Ex, Pred, state, location, &loadReferenceTag,
  1520. getContext().getPointerType(RT->getPointeeType()));
  1521. // Perform the load from the referenced value.
  1522. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
  1523. state = GetState(*I);
  1524. location = state->getSVal(Ex);
  1525. evalLoadCommon(Dst, Ex, *I, state, location, tag, LoadTy);
  1526. }
  1527. return;
  1528. }
  1529. }
  1530. evalLoadCommon(Dst, Ex, Pred, state, location, tag, LoadTy);
  1531. }
  1532. void ExprEngine::evalLoadCommon(ExplodedNodeSet& Dst, const Expr *Ex,
  1533. ExplodedNode* Pred,
  1534. const GRState* state, SVal location,
  1535. const void *tag, QualType LoadTy) {
  1536. // Evaluate the location (checks for bad dereferences).
  1537. ExplodedNodeSet Tmp;
  1538. evalLocation(Tmp, Ex, Pred, state, location, tag, true);
  1539. if (Tmp.empty())
  1540. return;
  1541. assert(!location.isUndef());
  1542. SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind);
  1543. // Proceed with the load.
  1544. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
  1545. state = GetState(*NI);
  1546. if (location.isUnknown()) {
  1547. // This is important. We must nuke the old binding.
  1548. MakeNode(Dst, Ex, *NI, state->BindExpr(Ex, UnknownVal()),
  1549. ProgramPoint::PostLoadKind, tag);
  1550. }
  1551. else {
  1552. if (LoadTy.isNull())
  1553. LoadTy = Ex->getType();
  1554. SVal V = state->getSVal(cast<Loc>(location), LoadTy);
  1555. MakeNode(Dst, Ex, *NI, state->bindExprAndLocation(Ex, location, V),
  1556. ProgramPoint::PostLoadKind, tag);
  1557. }
  1558. }
  1559. }
  1560. void ExprEngine::evalLocation(ExplodedNodeSet &Dst, const Stmt *S,
  1561. ExplodedNode* Pred,
  1562. const GRState* state, SVal location,
  1563. const void *tag, bool isLoad) {
  1564. // Early checks for performance reason.
  1565. if (location.isUnknown() || Checkers.empty()) {
  1566. Dst.Add(Pred);
  1567. return;
  1568. }
  1569. ExplodedNodeSet Src, Tmp;
  1570. Src.Add(Pred);
  1571. ExplodedNodeSet *PrevSet = &Src;
  1572. for (CheckersOrdered::iterator I=Checkers.begin(),E=Checkers.end(); I!=E; ++I)
  1573. {
  1574. ExplodedNodeSet *CurrSet = 0;
  1575. if (I+1 == E)
  1576. CurrSet = &Dst;
  1577. else {
  1578. CurrSet = (PrevSet == &Tmp) ? &Src : &Tmp;
  1579. CurrSet->clear();
  1580. }
  1581. void *tag = I->first;
  1582. Checker *checker = I->second;
  1583. for (ExplodedNodeSet::iterator NI = PrevSet->begin(), NE = PrevSet->end();
  1584. NI != NE; ++NI) {
  1585. // Use the 'state' argument only when the predecessor node is the
  1586. // same as Pred. This allows us to catch updates to the state.
  1587. checker->GR_visitLocation(*CurrSet, *Builder, *this, S, *NI,
  1588. *NI == Pred ? state : GetState(*NI),
  1589. location, tag, isLoad);
  1590. }
  1591. // Update which NodeSet is the current one.
  1592. PrevSet = CurrSet;
  1593. }
  1594. }
  1595. bool ExprEngine::InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE,
  1596. ExplodedNode *Pred) {
  1597. const GRState *state = GetState(Pred);
  1598. const Expr *Callee = CE->getCallee();
  1599. SVal L = state->getSVal(Callee);
  1600. const FunctionDecl *FD = L.getAsFunctionDecl();
  1601. if (!FD)
  1602. return false;
  1603. // Check if the function definition is in the same translation unit.
  1604. if (FD->hasBody(FD)) {
  1605. const StackFrameContext *stackFrame =
  1606. AMgr.getStackFrame(AMgr.getAnalysisContext(FD),
  1607. Pred->getLocationContext(),
  1608. CE, Builder->getBlock(), Builder->getIndex());
  1609. // Now we have the definition of the callee, create a CallEnter node.
  1610. CallEnter Loc(CE, stackFrame, Pred->getLocationContext());
  1611. ExplodedNode *N = Builder->generateNode(Loc, state, Pred);
  1612. Dst.Add(N);
  1613. return true;
  1614. }
  1615. // Check if we can find the function definition in other translation units.
  1616. if (AMgr.hasIndexer()) {
  1617. AnalysisContext *C = AMgr.getAnalysisContextInAnotherTU(FD);
  1618. if (C == 0)
  1619. return false;
  1620. const StackFrameContext *stackFrame =
  1621. AMgr.getStackFrame(C, Pred->getLocationContext(),
  1622. CE, Builder->getBlock(), Builder->getIndex());
  1623. CallEnter Loc(CE, stackFrame, Pred->getLocationContext());
  1624. ExplodedNode *N = Builder->generateNode(Loc, state, Pred);
  1625. Dst.Add(N);
  1626. return true;
  1627. }
  1628. return false;
  1629. }
  1630. void ExprEngine::VisitCall(const CallExpr* CE, ExplodedNode* Pred,
  1631. CallExpr::const_arg_iterator AI,
  1632. CallExpr::const_arg_iterator AE,
  1633. ExplodedNodeSet& Dst) {
  1634. // Determine the type of function we're calling (if available).
  1635. const FunctionProtoType *Proto = NULL;
  1636. QualType FnType = CE->getCallee()->IgnoreParens()->getType();
  1637. if (const PointerType *FnTypePtr = FnType->getAs<PointerType>())
  1638. Proto = FnTypePtr->getPointeeType()->getAs<FunctionProtoType>();
  1639. // Evaluate the arguments.
  1640. ExplodedNodeSet ArgsEvaluated;
  1641. evalArguments(CE->arg_begin(), CE->arg_end(), Proto, Pred, ArgsEvaluated);
  1642. // Now process the call itself.
  1643. ExplodedNodeSet DstTmp;
  1644. const Expr* Callee = CE->getCallee()->IgnoreParens();
  1645. for (ExplodedNodeSet::iterator NI=ArgsEvaluated.begin(),
  1646. NE=ArgsEvaluated.end(); NI != NE; ++NI) {
  1647. // Evaluate the callee.
  1648. ExplodedNodeSet DstTmp2;
  1649. Visit(Callee, *NI, DstTmp2);
  1650. // Perform the previsit of the CallExpr, storing the results in DstTmp.
  1651. CheckerVisit(CE, DstTmp, DstTmp2, PreVisitStmtCallback);
  1652. }
  1653. // Finally, evaluate the function call. We try each of the checkers
  1654. // to see if the can evaluate the function call.
  1655. ExplodedNodeSet DstTmp3;
  1656. for (ExplodedNodeSet::iterator DI = DstTmp.begin(), DE = DstTmp.end();
  1657. DI != DE; ++DI) {
  1658. const GRState* state = GetState(*DI);
  1659. SVal L = state->getSVal(Callee);
  1660. // FIXME: Add support for symbolic function calls (calls involving
  1661. // function pointer values that are symbolic).
  1662. SaveAndRestore<bool> OldSink(Builder->BuildSinks);
  1663. ExplodedNodeSet DstChecker;
  1664. // If the callee is processed by a checker, skip the rest logic.
  1665. if (CheckerEvalCall(CE, DstChecker, *DI))
  1666. DstTmp3.insert(DstChecker);
  1667. else if (AMgr.shouldInlineCall() && InlineCall(Dst, CE, *DI)) {
  1668. // Callee is inlined. We shouldn't do post call checking.
  1669. return;
  1670. }
  1671. else {
  1672. for (ExplodedNodeSet::iterator DI_Checker = DstChecker.begin(),
  1673. DE_Checker = DstChecker.end();
  1674. DI_Checker != DE_Checker; ++DI_Checker) {
  1675. // Dispatch to the plug-in transfer function.
  1676. unsigned oldSize = DstTmp3.size();
  1677. SaveOr OldHasGen(Builder->hasGeneratedNode);
  1678. Pred = *DI_Checker;
  1679. // Dispatch to transfer function logic to handle the call itself.
  1680. // FIXME: Allow us to chain together transfer functions.
  1681. assert(Builder && "StmtNodeBuilder must be defined.");
  1682. getTF().evalCall(DstTmp3, *this, *Builder, CE, L, Pred);
  1683. // Handle the case where no nodes where generated. Auto-generate that
  1684. // contains the updated state if we aren't generating sinks.
  1685. if (!Builder->BuildSinks && DstTmp3.size() == oldSize &&
  1686. !Builder->hasGeneratedNode)
  1687. MakeNode(DstTmp3, CE, Pred, state);
  1688. }
  1689. }
  1690. }
  1691. // Finally, perform the post-condition check of the CallExpr and store
  1692. // the created nodes in 'Dst'.
  1693. CheckerVisit(CE, Dst, DstTmp3, PostVisitStmtCallback);
  1694. }
  1695. //===----------------------------------------------------------------------===//
  1696. // Transfer function: Objective-C dot-syntax to access a property.
  1697. //===----------------------------------------------------------------------===//
  1698. void ExprEngine::VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Ex,
  1699. ExplodedNode *Pred,
  1700. ExplodedNodeSet &Dst) {
  1701. ExplodedNodeSet dstBase;
  1702. // Visit the receiver (if any).
  1703. if (Ex->isObjectReceiver())
  1704. Visit(Ex->getBase(), Pred, dstBase);
  1705. else
  1706. dstBase = Pred;
  1707. ExplodedNodeSet dstPropRef;
  1708. // Using the base, compute the lvalue of the instance variable.
  1709. for (ExplodedNodeSet::iterator I = dstBase.begin(), E = dstBase.end();
  1710. I!=E; ++I) {
  1711. ExplodedNode *nodeBase = *I;
  1712. const GRState *state = GetState(nodeBase);
  1713. MakeNode(dstPropRef, Ex, *I, state->BindExpr(Ex, loc::ObjCPropRef(Ex)));
  1714. }
  1715. Dst.insert(dstPropRef);
  1716. }
  1717. //===----------------------------------------------------------------------===//
  1718. // Transfer function: Objective-C ivar references.
  1719. //===----------------------------------------------------------------------===//
  1720. static std::pair<const void*,const void*> EagerlyAssumeTag
  1721. = std::pair<const void*,const void*>(&EagerlyAssumeTag,static_cast<void*>(0));
  1722. void ExprEngine::evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
  1723. const Expr *Ex) {
  1724. for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
  1725. ExplodedNode *Pred = *I;
  1726. // Test if the previous node was as the same expression. This can happen
  1727. // when the expression fails to evaluate to anything meaningful and
  1728. // (as an optimization) we don't generate a node.
  1729. ProgramPoint P = Pred->getLocation();
  1730. if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) {
  1731. Dst.Add(Pred);
  1732. continue;
  1733. }
  1734. const GRState* state = GetState(Pred);
  1735. SVal V = state->getSVal(Ex);
  1736. if (nonloc::SymExprVal *SEV = dyn_cast<nonloc::SymExprVal>(&V)) {
  1737. // First assume that the condition is true.
  1738. if (const GRState *stateTrue = state->assume(*SEV, true)) {
  1739. stateTrue = stateTrue->BindExpr(Ex,
  1740. svalBuilder.makeIntVal(1U, Ex->getType()));
  1741. Dst.Add(Builder->generateNode(PostStmtCustom(Ex,
  1742. &EagerlyAssumeTag, Pred->getLocationContext()),
  1743. stateTrue, Pred));
  1744. }
  1745. // Next, assume that the condition is false.
  1746. if (const GRState *stateFalse = state->assume(*SEV, false)) {
  1747. stateFalse = stateFalse->BindExpr(Ex,
  1748. svalBuilder.makeIntVal(0U, Ex->getType()));
  1749. Dst.Add(Builder->generateNode(PostStmtCustom(Ex, &EagerlyAssumeTag,
  1750. Pred->getLocationContext()),
  1751. stateFalse, Pred));
  1752. }
  1753. }
  1754. else
  1755. Dst.Add(Pred);
  1756. }
  1757. }
  1758. //===----------------------------------------------------------------------===//
  1759. // Transfer function: Objective-C @synchronized.
  1760. //===----------------------------------------------------------------------===//
  1761. void ExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
  1762. ExplodedNode *Pred,
  1763. ExplodedNodeSet &Dst) {
  1764. // The mutex expression is a CFGElement, so we don't need to explicitly
  1765. // visit it since it will already be processed.
  1766. // Pre-visit the ObjCAtSynchronizedStmt.
  1767. ExplodedNodeSet Tmp;
  1768. Tmp.Add(Pred);
  1769. CheckerVisit(S, Dst, Tmp, PreVisitStmtCallback);
  1770. }
  1771. //===----------------------------------------------------------------------===//
  1772. // Transfer function: Objective-C ivar references.
  1773. //===----------------------------------------------------------------------===//
  1774. void ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr* Ex,
  1775. ExplodedNode* Pred,
  1776. ExplodedNodeSet& Dst) {
  1777. // Visit the base expression, which is needed for computing the lvalue
  1778. // of the ivar.
  1779. ExplodedNodeSet dstBase;
  1780. const Expr *baseExpr = Ex->getBase();
  1781. Visit(baseExpr, Pred, dstBase);
  1782. ExplodedNodeSet dstIvar;
  1783. // Using the base, compute the lvalue of the instance variable.
  1784. for (ExplodedNodeSet::iterator I = dstBase.begin(), E = dstBase.end();
  1785. I!=E; ++I) {
  1786. ExplodedNode *nodeBase = *I;
  1787. const GRState *state = GetState(nodeBase);
  1788. SVal baseVal = state->getSVal(baseExpr);
  1789. SVal location = state->getLValue(Ex->getDecl(), baseVal);
  1790. MakeNode(dstIvar, Ex, *I, state->BindExpr(Ex, location));
  1791. }
  1792. // Perform the post-condition check of the ObjCIvarRefExpr and store
  1793. // the created nodes in 'Dst'.
  1794. CheckerVisit(Ex, Dst, dstIvar, PostVisitStmtCallback);
  1795. }
  1796. //===----------------------------------------------------------------------===//
  1797. // Transfer function: Objective-C fast enumeration 'for' statements.
  1798. //===----------------------------------------------------------------------===//
  1799. void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt* S,
  1800. ExplodedNode* Pred, ExplodedNodeSet& Dst) {
  1801. // ObjCForCollectionStmts are processed in two places. This method
  1802. // handles the case where an ObjCForCollectionStmt* occurs as one of the
  1803. // statements within a basic block. This transfer function does two things:
  1804. //
  1805. // (1) binds the next container value to 'element'. This creates a new
  1806. // node in the ExplodedGraph.
  1807. //
  1808. // (2) binds the value 0/1 to the ObjCForCollectionStmt* itself, indicating
  1809. // whether or not the container has any more elements. This value
  1810. // will be tested in ProcessBranch. We need to explicitly bind
  1811. // this value because a container can contain nil elements.
  1812. //
  1813. // FIXME: Eventually this logic should actually do dispatches to
  1814. // 'countByEnumeratingWithState:objects:count:' (NSFastEnumeration).
  1815. // This will require simulating a temporary NSFastEnumerationState, either
  1816. // through an SVal or through the use of MemRegions. This value can
  1817. // be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop
  1818. // terminates we reclaim the temporary (it goes out of scope) and we
  1819. // we can test if the SVal is 0 or if the MemRegion is null (depending
  1820. // on what approach we take).
  1821. //
  1822. // For now: simulate (1) by assigning either a symbol or nil if the
  1823. // container is empty. Thus this transfer function will by default
  1824. // result in state splitting.
  1825. const Stmt* elem = S->getElement();
  1826. SVal ElementV;
  1827. if (const DeclStmt* DS = dyn_cast<DeclStmt>(elem)) {
  1828. const VarDecl* ElemD = cast<VarDecl>(DS->getSingleDecl());
  1829. assert (ElemD->getInit() == 0);
  1830. ElementV = GetState(Pred)->getLValue(ElemD, Pred->getLocationContext());
  1831. VisitObjCForCollectionStmtAux(S, Pred, Dst, ElementV);
  1832. return;
  1833. }
  1834. ExplodedNodeSet Tmp;
  1835. Visit(cast<Expr>(elem), Pred, Tmp);
  1836. for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) {
  1837. const GRState* state = GetState(*I);
  1838. VisitObjCForCollectionStmtAux(S, *I, Dst, state->getSVal(elem));
  1839. }
  1840. }
  1841. void ExprEngine::VisitObjCForCollectionStmtAux(const ObjCForCollectionStmt* S,
  1842. ExplodedNode* Pred, ExplodedNodeSet& Dst,
  1843. SVal ElementV) {
  1844. // Check if the location we are writing back to is a null pointer.
  1845. const Stmt* elem = S->getElement();
  1846. ExplodedNodeSet Tmp;
  1847. evalLocation(Tmp, elem, Pred, GetState(Pred), ElementV, NULL, false);
  1848. if (Tmp.empty())
  1849. return;
  1850. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
  1851. Pred = *NI;
  1852. const GRState *state = GetState(Pred);
  1853. // Handle the case where the container still has elements.
  1854. SVal TrueV = svalBuilder.makeTruthVal(1);
  1855. const GRState *hasElems = state->BindExpr(S, TrueV);
  1856. // Handle the case where the container has no elements.
  1857. SVal FalseV = svalBuilder.makeTruthVal(0);
  1858. const GRState *noElems = state->BindExpr(S, FalseV);
  1859. if (loc::MemRegionVal* MV = dyn_cast<loc::MemRegionVal>(&ElementV))
  1860. if (const TypedRegion* R = dyn_cast<TypedRegion>(MV->getRegion())) {
  1861. // FIXME: The proper thing to do is to really iterate over the
  1862. // container. We will do this with dispatch logic to the store.
  1863. // For now, just 'conjure' up a symbolic value.
  1864. QualType T = R->getValueType();
  1865. assert(Loc::IsLocType(T));
  1866. unsigned Count = Builder->getCurrentBlockCount();
  1867. SymbolRef Sym = SymMgr.getConjuredSymbol(elem, T, Count);
  1868. SVal V = svalBuilder.makeLoc(Sym);
  1869. hasElems = hasElems->bindLoc(ElementV, V);
  1870. // Bind the location to 'nil' on the false branch.
  1871. SVal nilV = svalBuilder.makeIntVal(0, T);
  1872. noElems = noElems->bindLoc(ElementV, nilV);
  1873. }
  1874. // Create the new nodes.
  1875. MakeNode(Dst, S, Pred, hasElems);
  1876. MakeNode(Dst, S, Pred, noElems);
  1877. }
  1878. }
  1879. //===----------------------------------------------------------------------===//
  1880. // Transfer function: Objective-C message expressions.
  1881. //===----------------------------------------------------------------------===//
  1882. namespace {
  1883. class ObjCMsgWLItem {
  1884. public:
  1885. ObjCMessageExpr::const_arg_iterator I;
  1886. ExplodedNode *N;
  1887. ObjCMsgWLItem(const ObjCMessageExpr::const_arg_iterator &i, ExplodedNode *n)
  1888. : I(i), N(n) {}
  1889. };
  1890. } // end anonymous namespace
  1891. void ExprEngine::VisitObjCMessageExpr(const ObjCMessageExpr* ME,
  1892. ExplodedNode* Pred,
  1893. ExplodedNodeSet& Dst){
  1894. // Create a worklist to process both the arguments.
  1895. llvm::SmallVector<ObjCMsgWLItem, 20> WL;
  1896. // But first evaluate the receiver (if any).
  1897. ObjCMessageExpr::const_arg_iterator AI = ME->arg_begin(), AE = ME->arg_end();
  1898. if (const Expr *Receiver = ME->getInstanceReceiver()) {
  1899. ExplodedNodeSet Tmp;
  1900. Visit(Receiver, Pred, Tmp);
  1901. if (Tmp.empty())
  1902. return;
  1903. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I)
  1904. WL.push_back(ObjCMsgWLItem(AI, *I));
  1905. }
  1906. else
  1907. WL.push_back(ObjCMsgWLItem(AI, Pred));
  1908. // Evaluate the arguments.
  1909. ExplodedNodeSet ArgsEvaluated;
  1910. while (!WL.empty()) {
  1911. ObjCMsgWLItem Item = WL.back();
  1912. WL.pop_back();
  1913. if (Item.I == AE) {
  1914. ArgsEvaluated.insert(Item.N);
  1915. continue;
  1916. }
  1917. // Evaluate the subexpression.
  1918. ExplodedNodeSet Tmp;
  1919. // FIXME: [Objective-C++] handle arguments that are references
  1920. Visit(*Item.I, Item.N, Tmp);
  1921. // Enqueue evaluating the next argument on the worklist.
  1922. ++(Item.I);
  1923. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
  1924. WL.push_back(ObjCMsgWLItem(Item.I, *NI));
  1925. }
  1926. // Now that the arguments are processed, handle the ObjC message.
  1927. VisitObjCMessage(ME, ArgsEvaluated, Dst);
  1928. }
  1929. void ExprEngine::VisitObjCMessage(const ObjCMessage &msg,
  1930. ExplodedNodeSet &Src, ExplodedNodeSet& Dst) {
  1931. // Handle the previsits checks.
  1932. ExplodedNodeSet DstPrevisit;
  1933. CheckerVisitObjCMessage(msg, DstPrevisit, Src, /*isPreVisit=*/true);
  1934. // Proceed with evaluate the message expression.
  1935. ExplodedNodeSet dstEval;
  1936. for (ExplodedNodeSet::iterator DI = DstPrevisit.begin(),
  1937. DE = DstPrevisit.end(); DI != DE; ++DI) {
  1938. ExplodedNode *Pred = *DI;
  1939. bool RaisesException = false;
  1940. unsigned oldSize = dstEval.size();
  1941. SaveAndRestore<bool> OldSink(Builder->BuildSinks);
  1942. SaveOr OldHasGen(Builder->hasGeneratedNode);
  1943. if (const Expr *Receiver = msg.getInstanceReceiver()) {
  1944. const GRState *state = GetState(Pred);
  1945. // Bifurcate the state into nil and non-nil ones.
  1946. DefinedOrUnknownSVal receiverVal =
  1947. cast<DefinedOrUnknownSVal>(state->getSVal(Receiver));
  1948. const GRState *notNilState, *nilState;
  1949. llvm::tie(notNilState, nilState) = state->assume(receiverVal);
  1950. // There are three cases: can be nil or non-nil, must be nil, must be
  1951. // non-nil. We handle must be nil, and merge the rest two into non-nil.
  1952. if (nilState && !notNilState) {
  1953. CheckerEvalNilReceiver(msg, dstEval, nilState, Pred);
  1954. continue;
  1955. }
  1956. // Check if the "raise" message was sent.
  1957. assert(notNilState);
  1958. if (msg.getSelector() == RaiseSel)
  1959. RaisesException = true;
  1960. // Check if we raise an exception. For now treat these as sinks.
  1961. // Eventually we will want to handle exceptions properly.
  1962. if (RaisesException)
  1963. Builder->BuildSinks = true;
  1964. // Dispatch to plug-in transfer function.
  1965. evalObjCMessage(dstEval, msg, Pred, notNilState);
  1966. }
  1967. else if (const ObjCInterfaceDecl *Iface = msg.getReceiverInterface()) {
  1968. IdentifierInfo* ClsName = Iface->getIdentifier();
  1969. Selector S = msg.getSelector();
  1970. // Check for special instance methods.
  1971. if (!NSExceptionII) {
  1972. ASTContext& Ctx = getContext();
  1973. NSExceptionII = &Ctx.Idents.get("NSException");
  1974. }
  1975. if (ClsName == NSExceptionII) {
  1976. enum { NUM_RAISE_SELECTORS = 2 };
  1977. // Lazily create a cache of the selectors.
  1978. if (!NSExceptionInstanceRaiseSelectors) {
  1979. ASTContext& Ctx = getContext();
  1980. NSExceptionInstanceRaiseSelectors =
  1981. new Selector[NUM_RAISE_SELECTORS];
  1982. llvm::SmallVector<IdentifierInfo*, NUM_RAISE_SELECTORS> II;
  1983. unsigned idx = 0;
  1984. // raise:format:
  1985. II.push_back(&Ctx.Idents.get("raise"));
  1986. II.push_back(&Ctx.Idents.get("format"));
  1987. NSExceptionInstanceRaiseSelectors[idx++] =
  1988. Ctx.Selectors.getSelector(II.size(), &II[0]);
  1989. // raise:format::arguments:
  1990. II.push_back(&Ctx.Idents.get("arguments"));
  1991. NSExceptionInstanceRaiseSelectors[idx++] =
  1992. Ctx.Selectors.getSelector(II.size(), &II[0]);
  1993. }
  1994. for (unsigned i = 0; i < NUM_RAISE_SELECTORS; ++i)
  1995. if (S == NSExceptionInstanceRaiseSelectors[i]) {
  1996. RaisesException = true;
  1997. break;
  1998. }
  1999. }
  2000. // Check if we raise an exception. For now treat these as sinks.
  2001. // Eventually we will want to handle exceptions properly.
  2002. if (RaisesException)
  2003. Builder->BuildSinks = true;
  2004. // Dispatch to plug-in transfer function.
  2005. evalObjCMessage(dstEval, msg, Pred, Builder->GetState(Pred));
  2006. }
  2007. // Handle the case where no nodes where generated. Auto-generate that
  2008. // contains the updated state if we aren't generating sinks.
  2009. if (!Builder->BuildSinks && dstEval.size() == oldSize &&
  2010. !Builder->hasGeneratedNode)
  2011. MakeNode(dstEval, msg.getOriginExpr(), Pred, GetState(Pred));
  2012. }
  2013. // Finally, perform the post-condition check of the ObjCMessageExpr and store
  2014. // the created nodes in 'Dst'.
  2015. CheckerVisitObjCMessage(msg, Dst, dstEval, /*isPreVisit=*/false);
  2016. }
  2017. //===----------------------------------------------------------------------===//
  2018. // Transfer functions: Miscellaneous statements.
  2019. //===----------------------------------------------------------------------===//
  2020. void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
  2021. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  2022. ExplodedNodeSet S1;
  2023. Visit(Ex, Pred, S1);
  2024. ExplodedNodeSet S2;
  2025. CheckerVisit(CastE, S2, S1, PreVisitStmtCallback);
  2026. if (CastE->getCastKind() == CK_LValueToRValue ||
  2027. CastE->getCastKind() == CK_GetObjCProperty) {
  2028. for (ExplodedNodeSet::iterator I = S2.begin(), E = S2.end(); I!=E; ++I) {
  2029. ExplodedNode *subExprNode = *I;
  2030. const GRState *state = GetState(subExprNode);
  2031. evalLoad(Dst, CastE, subExprNode, state, state->getSVal(Ex));
  2032. }
  2033. return;
  2034. }
  2035. // All other casts.
  2036. QualType T = CastE->getType();
  2037. QualType ExTy = Ex->getType();
  2038. if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
  2039. T = ExCast->getTypeAsWritten();
  2040. #if 0
  2041. // If we are evaluating the cast in an lvalue context, we implicitly want
  2042. // the cast to evaluate to a location.
  2043. if (asLValue) {
  2044. ASTContext &Ctx = getContext();
  2045. T = Ctx.getPointerType(Ctx.getCanonicalType(T));
  2046. ExTy = Ctx.getPointerType(Ctx.getCanonicalType(ExTy));
  2047. }
  2048. #endif
  2049. switch (CastE->getCastKind()) {
  2050. case CK_ToVoid:
  2051. for (ExplodedNodeSet::iterator I = S2.begin(), E = S2.end(); I != E; ++I)
  2052. Dst.Add(*I);
  2053. return;
  2054. case CK_LValueToRValue:
  2055. case CK_NoOp:
  2056. case CK_FunctionToPointerDecay:
  2057. for (ExplodedNodeSet::iterator I = S2.begin(), E = S2.end(); I != E; ++I) {
  2058. // Copy the SVal of Ex to CastE.
  2059. ExplodedNode *N = *I;
  2060. const GRState *state = GetState(N);
  2061. SVal V = state->getSVal(Ex);
  2062. state = state->BindExpr(CastE, V);
  2063. MakeNode(Dst, CastE, N, state);
  2064. }
  2065. return;
  2066. case CK_GetObjCProperty:
  2067. case CK_Dependent:
  2068. case CK_ArrayToPointerDecay:
  2069. case CK_BitCast:
  2070. case CK_LValueBitCast:
  2071. case CK_IntegralCast:
  2072. case CK_NullToPointer:
  2073. case CK_IntegralToPointer:
  2074. case CK_PointerToIntegral:
  2075. case CK_PointerToBoolean:
  2076. case CK_IntegralToBoolean:
  2077. case CK_IntegralToFloating:
  2078. case CK_FloatingToIntegral:
  2079. case CK_FloatingToBoolean:
  2080. case CK_FloatingCast:
  2081. case CK_FloatingRealToComplex:
  2082. case CK_FloatingComplexToReal:
  2083. case CK_FloatingComplexToBoolean:
  2084. case CK_FloatingComplexCast:
  2085. case CK_FloatingComplexToIntegralComplex:
  2086. case CK_IntegralRealToComplex:
  2087. case CK_IntegralComplexToReal:
  2088. case CK_IntegralComplexToBoolean:
  2089. case CK_IntegralComplexCast:
  2090. case CK_IntegralComplexToFloatingComplex:
  2091. case CK_AnyPointerToObjCPointerCast:
  2092. case CK_AnyPointerToBlockPointerCast:
  2093. case CK_ObjCObjectLValueCast: {
  2094. // Delegate to SValBuilder to process.
  2095. for (ExplodedNodeSet::iterator I = S2.begin(), E = S2.end(); I != E; ++I) {
  2096. ExplodedNode* N = *I;
  2097. const GRState* state = GetState(N);
  2098. SVal V = state->getSVal(Ex);
  2099. V = svalBuilder.evalCast(V, T, ExTy);
  2100. state = state->BindExpr(CastE, V);
  2101. MakeNode(Dst, CastE, N, state);
  2102. }
  2103. return;
  2104. }
  2105. case CK_DerivedToBase:
  2106. case CK_UncheckedDerivedToBase:
  2107. // For DerivedToBase cast, delegate to the store manager.
  2108. for (ExplodedNodeSet::iterator I = S2.begin(), E = S2.end(); I != E; ++I) {
  2109. ExplodedNode *node = *I;
  2110. const GRState *state = GetState(node);
  2111. SVal val = state->getSVal(Ex);
  2112. val = getStoreManager().evalDerivedToBase(val, T);
  2113. state = state->BindExpr(CastE, val);
  2114. MakeNode(Dst, CastE, node, state);
  2115. }
  2116. return;
  2117. // Various C++ casts that are not handled yet.
  2118. case CK_Dynamic:
  2119. case CK_ToUnion:
  2120. case CK_BaseToDerived:
  2121. case CK_NullToMemberPointer:
  2122. case CK_BaseToDerivedMemberPointer:
  2123. case CK_DerivedToBaseMemberPointer:
  2124. case CK_UserDefinedConversion:
  2125. case CK_ConstructorConversion:
  2126. case CK_VectorSplat:
  2127. case CK_MemberPointerToBoolean: {
  2128. SaveAndRestore<bool> OldSink(Builder->BuildSinks);
  2129. Builder->BuildSinks = true;
  2130. MakeNode(Dst, CastE, Pred, GetState(Pred));
  2131. return;
  2132. }
  2133. }
  2134. }
  2135. void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr* CL,
  2136. ExplodedNode* Pred,
  2137. ExplodedNodeSet& Dst) {
  2138. const InitListExpr* ILE
  2139. = cast<InitListExpr>(CL->getInitializer()->IgnoreParens());
  2140. ExplodedNodeSet Tmp;
  2141. Visit(ILE, Pred, Tmp);
  2142. for (ExplodedNodeSet::iterator I = Tmp.begin(), EI = Tmp.end(); I!=EI; ++I) {
  2143. const GRState* state = GetState(*I);
  2144. SVal ILV = state->getSVal(ILE);
  2145. const LocationContext *LC = (*I)->getLocationContext();
  2146. state = state->bindCompoundLiteral(CL, LC, ILV);
  2147. if (CL->isLValue()) {
  2148. MakeNode(Dst, CL, *I, state->BindExpr(CL, state->getLValue(CL, LC)));
  2149. }
  2150. else
  2151. MakeNode(Dst, CL, *I, state->BindExpr(CL, ILV));
  2152. }
  2153. }
  2154. void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
  2155. ExplodedNodeSet& Dst) {
  2156. // The CFG has one DeclStmt per Decl.
  2157. const Decl* D = *DS->decl_begin();
  2158. if (!D || !isa<VarDecl>(D))
  2159. return;
  2160. const VarDecl* VD = dyn_cast<VarDecl>(D);
  2161. const Expr* InitEx = VD->getInit();
  2162. // FIXME: static variables may have an initializer, but the second
  2163. // time a function is called those values may not be current.
  2164. ExplodedNodeSet Tmp;
  2165. if (InitEx) {
  2166. if (VD->getType()->isReferenceType() && !InitEx->isLValue()) {
  2167. // If the initializer is C++ record type, it should already has a
  2168. // temp object.
  2169. if (!InitEx->getType()->isRecordType())
  2170. CreateCXXTemporaryObject(InitEx, Pred, Tmp);
  2171. else
  2172. Tmp.Add(Pred);
  2173. } else
  2174. Visit(InitEx, Pred, Tmp);
  2175. } else
  2176. Tmp.Add(Pred);
  2177. ExplodedNodeSet Tmp2;
  2178. CheckerVisit(DS, Tmp2, Tmp, PreVisitStmtCallback);
  2179. for (ExplodedNodeSet::iterator I=Tmp2.begin(), E=Tmp2.end(); I!=E; ++I) {
  2180. ExplodedNode *N = *I;
  2181. const GRState *state = GetState(N);
  2182. // Decls without InitExpr are not initialized explicitly.
  2183. const LocationContext *LC = N->getLocationContext();
  2184. if (InitEx) {
  2185. SVal InitVal = state->getSVal(InitEx);
  2186. // We bound the temp obj region to the CXXConstructExpr. Now recover
  2187. // the lazy compound value when the variable is not a reference.
  2188. if (AMgr.getLangOptions().CPlusPlus && VD->getType()->isRecordType() &&
  2189. !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(InitVal)){
  2190. InitVal = state->getSVal(cast<loc::MemRegionVal>(InitVal).getRegion());
  2191. assert(isa<nonloc::LazyCompoundVal>(InitVal));
  2192. }
  2193. // Recover some path-sensitivity if a scalar value evaluated to
  2194. // UnknownVal.
  2195. if ((InitVal.isUnknown() ||
  2196. !getConstraintManager().canReasonAbout(InitVal)) &&
  2197. !VD->getType()->isReferenceType()) {
  2198. InitVal = svalBuilder.getConjuredSymbolVal(NULL, InitEx,
  2199. Builder->getCurrentBlockCount());
  2200. }
  2201. evalBind(Dst, DS, *I, state,
  2202. loc::MemRegionVal(state->getRegion(VD, LC)), InitVal, true);
  2203. }
  2204. else {
  2205. state = state->bindDeclWithNoInit(state->getRegion(VD, LC));
  2206. MakeNode(Dst, DS, *I, state);
  2207. }
  2208. }
  2209. }
  2210. void ExprEngine::VisitCondInit(const VarDecl *VD, const Stmt *S,
  2211. ExplodedNode *Pred, ExplodedNodeSet& Dst) {
  2212. const Expr* InitEx = VD->getInit();
  2213. ExplodedNodeSet Tmp;
  2214. Visit(InitEx, Pred, Tmp);
  2215. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
  2216. ExplodedNode *N = *I;
  2217. const GRState *state = GetState(N);
  2218. const LocationContext *LC = N->getLocationContext();
  2219. SVal InitVal = state->getSVal(InitEx);
  2220. // Recover some path-sensitivity if a scalar value evaluated to
  2221. // UnknownVal.
  2222. if (InitVal.isUnknown() ||
  2223. !getConstraintManager().canReasonAbout(InitVal)) {
  2224. InitVal = svalBuilder.getConjuredSymbolVal(NULL, InitEx,
  2225. Builder->getCurrentBlockCount());
  2226. }
  2227. evalBind(Dst, S, N, state,
  2228. loc::MemRegionVal(state->getRegion(VD, LC)), InitVal, true);
  2229. }
  2230. }
  2231. namespace {
  2232. // This class is used by VisitInitListExpr as an item in a worklist
  2233. // for processing the values contained in an InitListExpr.
  2234. class InitListWLItem {
  2235. public:
  2236. llvm::ImmutableList<SVal> Vals;
  2237. ExplodedNode* N;
  2238. InitListExpr::const_reverse_iterator Itr;
  2239. InitListWLItem(ExplodedNode* n, llvm::ImmutableList<SVal> vals,
  2240. InitListExpr::const_reverse_iterator itr)
  2241. : Vals(vals), N(n), Itr(itr) {}
  2242. };
  2243. }
  2244. void ExprEngine::VisitInitListExpr(const InitListExpr* E, ExplodedNode* Pred,
  2245. ExplodedNodeSet& Dst) {
  2246. const GRState* state = GetState(Pred);
  2247. QualType T = getContext().getCanonicalType(E->getType());
  2248. unsigned NumInitElements = E->getNumInits();
  2249. if (T->isArrayType() || T->isRecordType() || T->isVectorType()) {
  2250. llvm::ImmutableList<SVal> StartVals = getBasicVals().getEmptySValList();
  2251. // Handle base case where the initializer has no elements.
  2252. // e.g: static int* myArray[] = {};
  2253. if (NumInitElements == 0) {
  2254. SVal V = svalBuilder.makeCompoundVal(T, StartVals);
  2255. MakeNode(Dst, E, Pred, state->BindExpr(E, V));
  2256. return;
  2257. }
  2258. // Create a worklist to process the initializers.
  2259. llvm::SmallVector<InitListWLItem, 10> WorkList;
  2260. WorkList.reserve(NumInitElements);
  2261. WorkList.push_back(InitListWLItem(Pred, StartVals, E->rbegin()));
  2262. InitListExpr::const_reverse_iterator ItrEnd = E->rend();
  2263. assert(!(E->rbegin() == E->rend()));
  2264. // Process the worklist until it is empty.
  2265. while (!WorkList.empty()) {
  2266. InitListWLItem X = WorkList.back();
  2267. WorkList.pop_back();
  2268. ExplodedNodeSet Tmp;
  2269. Visit(*X.Itr, X.N, Tmp);
  2270. InitListExpr::const_reverse_iterator NewItr = X.Itr + 1;
  2271. for (ExplodedNodeSet::iterator NI=Tmp.begin(),NE=Tmp.end();NI!=NE;++NI) {
  2272. // Get the last initializer value.
  2273. state = GetState(*NI);
  2274. SVal InitV = state->getSVal(cast<Expr>(*X.Itr));
  2275. // Construct the new list of values by prepending the new value to
  2276. // the already constructed list.
  2277. llvm::ImmutableList<SVal> NewVals =
  2278. getBasicVals().consVals(InitV, X.Vals);
  2279. if (NewItr == ItrEnd) {
  2280. // Now we have a list holding all init values. Make CompoundValData.
  2281. SVal V = svalBuilder.makeCompoundVal(T, NewVals);
  2282. // Make final state and node.
  2283. MakeNode(Dst, E, *NI, state->BindExpr(E, V));
  2284. }
  2285. else {
  2286. // Still some initializer values to go. Push them onto the worklist.
  2287. WorkList.push_back(InitListWLItem(*NI, NewVals, NewItr));
  2288. }
  2289. }
  2290. }
  2291. return;
  2292. }
  2293. if (Loc::IsLocType(T) || T->isIntegerType()) {
  2294. assert (E->getNumInits() == 1);
  2295. ExplodedNodeSet Tmp;
  2296. const Expr* Init = E->getInit(0);
  2297. Visit(Init, Pred, Tmp);
  2298. for (ExplodedNodeSet::iterator I=Tmp.begin(), EI=Tmp.end(); I != EI; ++I) {
  2299. state = GetState(*I);
  2300. MakeNode(Dst, E, *I, state->BindExpr(E, state->getSVal(Init)));
  2301. }
  2302. return;
  2303. }
  2304. assert(0 && "unprocessed InitListExpr type");
  2305. }
  2306. /// VisitSizeOfAlignOfExpr - Transfer function for sizeof(type).
  2307. void ExprEngine::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr* Ex,
  2308. ExplodedNode* Pred,
  2309. ExplodedNodeSet& Dst) {
  2310. QualType T = Ex->getTypeOfArgument();
  2311. CharUnits amt;
  2312. if (Ex->isSizeOf()) {
  2313. if (T == getContext().VoidTy) {
  2314. // sizeof(void) == 1 byte.
  2315. amt = CharUnits::One();
  2316. }
  2317. else if (!T->isConstantSizeType()) {
  2318. assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
  2319. // FIXME: Add support for VLA type arguments, not just VLA expressions.
  2320. // When that happens, we should probably refactor VLASizeChecker's code.
  2321. if (Ex->isArgumentType()) {
  2322. Dst.Add(Pred);
  2323. return;
  2324. }
  2325. // Get the size by getting the extent of the sub-expression.
  2326. // First, visit the sub-expression to find its region.
  2327. const Expr *Arg = Ex->getArgumentExpr();
  2328. ExplodedNodeSet Tmp;
  2329. Visit(Arg, Pred, Tmp);
  2330. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
  2331. const GRState* state = GetState(*I);
  2332. const MemRegion *MR = state->getSVal(Arg).getAsRegion();
  2333. // If the subexpression can't be resolved to a region, we don't know
  2334. // anything about its size. Just leave the state as is and continue.
  2335. if (!MR) {
  2336. Dst.Add(*I);
  2337. continue;
  2338. }
  2339. // The result is the extent of the VLA.
  2340. SVal Extent = cast<SubRegion>(MR)->getExtent(svalBuilder);
  2341. MakeNode(Dst, Ex, *I, state->BindExpr(Ex, Extent));
  2342. }
  2343. return;
  2344. }
  2345. else if (T->getAs<ObjCObjectType>()) {
  2346. // Some code tries to take the sizeof an ObjCObjectType, relying that
  2347. // the compiler has laid out its representation. Just report Unknown
  2348. // for these.
  2349. Dst.Add(Pred);
  2350. return;
  2351. }
  2352. else {
  2353. // All other cases.
  2354. amt = getContext().getTypeSizeInChars(T);
  2355. }
  2356. }
  2357. else // Get alignment of the type.
  2358. amt = getContext().getTypeAlignInChars(T);
  2359. MakeNode(Dst, Ex, Pred,
  2360. GetState(Pred)->BindExpr(Ex,
  2361. svalBuilder.makeIntVal(amt.getQuantity(), Ex->getType())));
  2362. }
  2363. void ExprEngine::VisitOffsetOfExpr(const OffsetOfExpr* OOE,
  2364. ExplodedNode* Pred, ExplodedNodeSet& Dst) {
  2365. Expr::EvalResult Res;
  2366. if (OOE->Evaluate(Res, getContext()) && Res.Val.isInt()) {
  2367. const APSInt &IV = Res.Val.getInt();
  2368. assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
  2369. assert(OOE->getType()->isIntegerType());
  2370. assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
  2371. SVal X = svalBuilder.makeIntVal(IV);
  2372. MakeNode(Dst, OOE, Pred, GetState(Pred)->BindExpr(OOE, X));
  2373. return;
  2374. }
  2375. // FIXME: Handle the case where __builtin_offsetof is not a constant.
  2376. Dst.Add(Pred);
  2377. }
  2378. void ExprEngine::VisitUnaryOperator(const UnaryOperator* U,
  2379. ExplodedNode* Pred,
  2380. ExplodedNodeSet& Dst) {
  2381. switch (U->getOpcode()) {
  2382. default:
  2383. break;
  2384. case UO_Real: {
  2385. const Expr* Ex = U->getSubExpr()->IgnoreParens();
  2386. ExplodedNodeSet Tmp;
  2387. Visit(Ex, Pred, Tmp);
  2388. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
  2389. // FIXME: We don't have complex SValues yet.
  2390. if (Ex->getType()->isAnyComplexType()) {
  2391. // Just report "Unknown."
  2392. Dst.Add(*I);
  2393. continue;
  2394. }
  2395. // For all other types, UO_Real is an identity operation.
  2396. assert (U->getType() == Ex->getType());
  2397. const GRState* state = GetState(*I);
  2398. MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex)));
  2399. }
  2400. return;
  2401. }
  2402. case UO_Imag: {
  2403. const Expr* Ex = U->getSubExpr()->IgnoreParens();
  2404. ExplodedNodeSet Tmp;
  2405. Visit(Ex, Pred, Tmp);
  2406. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
  2407. // FIXME: We don't have complex SValues yet.
  2408. if (Ex->getType()->isAnyComplexType()) {
  2409. // Just report "Unknown."
  2410. Dst.Add(*I);
  2411. continue;
  2412. }
  2413. // For all other types, UO_Imag returns 0.
  2414. const GRState* state = GetState(*I);
  2415. SVal X = svalBuilder.makeZeroVal(Ex->getType());
  2416. MakeNode(Dst, U, *I, state->BindExpr(U, X));
  2417. }
  2418. return;
  2419. }
  2420. case UO_Plus:
  2421. assert(!U->isLValue());
  2422. // FALL-THROUGH.
  2423. case UO_Deref:
  2424. case UO_AddrOf:
  2425. case UO_Extension: {
  2426. // Unary "+" is a no-op, similar to a parentheses. We still have places
  2427. // where it may be a block-level expression, so we need to
  2428. // generate an extra node that just propagates the value of the
  2429. // subexpression.
  2430. const Expr* Ex = U->getSubExpr()->IgnoreParens();
  2431. ExplodedNodeSet Tmp;
  2432. Visit(Ex, Pred, Tmp);
  2433. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
  2434. const GRState* state = GetState(*I);
  2435. MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex)));
  2436. }
  2437. return;
  2438. }
  2439. case UO_LNot:
  2440. case UO_Minus:
  2441. case UO_Not: {
  2442. assert (!U->isLValue());
  2443. const Expr* Ex = U->getSubExpr()->IgnoreParens();
  2444. ExplodedNodeSet Tmp;
  2445. Visit(Ex, Pred, Tmp);
  2446. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
  2447. const GRState* state = GetState(*I);
  2448. // Get the value of the subexpression.
  2449. SVal V = state->getSVal(Ex);
  2450. if (V.isUnknownOrUndef()) {
  2451. MakeNode(Dst, U, *I, state->BindExpr(U, V));
  2452. continue;
  2453. }
  2454. // QualType DstT = getContext().getCanonicalType(U->getType());
  2455. // QualType SrcT = getContext().getCanonicalType(Ex->getType());
  2456. //
  2457. // if (DstT != SrcT) // Perform promotions.
  2458. // V = evalCast(V, DstT);
  2459. //
  2460. // if (V.isUnknownOrUndef()) {
  2461. // MakeNode(Dst, U, *I, BindExpr(St, U, V));
  2462. // continue;
  2463. // }
  2464. switch (U->getOpcode()) {
  2465. default:
  2466. assert(false && "Invalid Opcode.");
  2467. break;
  2468. case UO_Not:
  2469. // FIXME: Do we need to handle promotions?
  2470. state = state->BindExpr(U, evalComplement(cast<NonLoc>(V)));
  2471. break;
  2472. case UO_Minus:
  2473. // FIXME: Do we need to handle promotions?
  2474. state = state->BindExpr(U, evalMinus(cast<NonLoc>(V)));
  2475. break;
  2476. case UO_LNot:
  2477. // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
  2478. //
  2479. // Note: technically we do "E == 0", but this is the same in the
  2480. // transfer functions as "0 == E".
  2481. SVal Result;
  2482. if (isa<Loc>(V)) {
  2483. Loc X = svalBuilder.makeNull();
  2484. Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X,
  2485. U->getType());
  2486. }
  2487. else {
  2488. nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
  2489. Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X,
  2490. U->getType());
  2491. }
  2492. state = state->BindExpr(U, Result);
  2493. break;
  2494. }
  2495. MakeNode(Dst, U, *I, state);
  2496. }
  2497. return;
  2498. }
  2499. }
  2500. // Handle ++ and -- (both pre- and post-increment).
  2501. assert (U->isIncrementDecrementOp());
  2502. ExplodedNodeSet Tmp;
  2503. const Expr* Ex = U->getSubExpr()->IgnoreParens();
  2504. Visit(Ex, Pred, Tmp);
  2505. for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) {
  2506. const GRState* state = GetState(*I);
  2507. SVal loc = state->getSVal(Ex);
  2508. // Perform a load.
  2509. ExplodedNodeSet Tmp2;
  2510. evalLoad(Tmp2, Ex, *I, state, loc);
  2511. for (ExplodedNodeSet::iterator I2=Tmp2.begin(), E2=Tmp2.end();I2!=E2;++I2) {
  2512. state = GetState(*I2);
  2513. SVal V2_untested = state->getSVal(Ex);
  2514. // Propagate unknown and undefined values.
  2515. if (V2_untested.isUnknownOrUndef()) {
  2516. MakeNode(Dst, U, *I2, state->BindExpr(U, V2_untested));
  2517. continue;
  2518. }
  2519. DefinedSVal V2 = cast<DefinedSVal>(V2_untested);
  2520. // Handle all other values.
  2521. BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add
  2522. : BO_Sub;
  2523. // If the UnaryOperator has non-location type, use its type to create the
  2524. // constant value. If the UnaryOperator has location type, create the
  2525. // constant with int type and pointer width.
  2526. SVal RHS;
  2527. if (U->getType()->isAnyPointerType())
  2528. RHS = svalBuilder.makeArrayIndex(1);
  2529. else
  2530. RHS = svalBuilder.makeIntVal(1, U->getType());
  2531. SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
  2532. // Conjure a new symbol if necessary to recover precision.
  2533. if (Result.isUnknown() || !getConstraintManager().canReasonAbout(Result)){
  2534. DefinedOrUnknownSVal SymVal =
  2535. svalBuilder.getConjuredSymbolVal(NULL, Ex,
  2536. Builder->getCurrentBlockCount());
  2537. Result = SymVal;
  2538. // If the value is a location, ++/-- should always preserve
  2539. // non-nullness. Check if the original value was non-null, and if so
  2540. // propagate that constraint.
  2541. if (Loc::IsLocType(U->getType())) {
  2542. DefinedOrUnknownSVal Constraint =
  2543. svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
  2544. if (!state->assume(Constraint, true)) {
  2545. // It isn't feasible for the original value to be null.
  2546. // Propagate this constraint.
  2547. Constraint = svalBuilder.evalEQ(state, SymVal,
  2548. svalBuilder.makeZeroVal(U->getType()));
  2549. state = state->assume(Constraint, false);
  2550. assert(state);
  2551. }
  2552. }
  2553. }
  2554. // Since the lvalue-to-rvalue conversion is explicit in the AST,
  2555. // we bind an l-value if the operator is prefix and an lvalue (in C++).
  2556. if (U->isLValue())
  2557. state = state->BindExpr(U, loc);
  2558. else
  2559. state = state->BindExpr(U, V2);
  2560. // Perform the store.
  2561. evalStore(Dst, NULL, U, *I2, state, loc, Result);
  2562. }
  2563. }
  2564. }
  2565. void ExprEngine::VisitAsmStmt(const AsmStmt* A, ExplodedNode* Pred,
  2566. ExplodedNodeSet& Dst) {
  2567. VisitAsmStmtHelperOutputs(A, A->begin_outputs(), A->end_outputs(), Pred, Dst);
  2568. }
  2569. void ExprEngine::VisitAsmStmtHelperOutputs(const AsmStmt* A,
  2570. AsmStmt::const_outputs_iterator I,
  2571. AsmStmt::const_outputs_iterator E,
  2572. ExplodedNode* Pred, ExplodedNodeSet& Dst) {
  2573. if (I == E) {
  2574. VisitAsmStmtHelperInputs(A, A->begin_inputs(), A->end_inputs(), Pred, Dst);
  2575. return;
  2576. }
  2577. ExplodedNodeSet Tmp;
  2578. Visit(*I, Pred, Tmp);
  2579. ++I;
  2580. for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end();NI != NE;++NI)
  2581. VisitAsmStmtHelperOutputs(A, I, E, *NI, Dst);
  2582. }
  2583. void ExprEngine::VisitAsmStmtHelperInputs(const AsmStmt* A,
  2584. AsmStmt::const_inputs_iterator I,
  2585. AsmStmt::const_inputs_iterator E,
  2586. ExplodedNode* Pred,
  2587. ExplodedNodeSet& Dst) {
  2588. if (I == E) {
  2589. // We have processed both the inputs and the outputs. All of the outputs
  2590. // should evaluate to Locs. Nuke all of their values.
  2591. // FIXME: Some day in the future it would be nice to allow a "plug-in"
  2592. // which interprets the inline asm and stores proper results in the
  2593. // outputs.
  2594. const GRState* state = GetState(Pred);
  2595. for (AsmStmt::const_outputs_iterator OI = A->begin_outputs(),
  2596. OE = A->end_outputs(); OI != OE; ++OI) {
  2597. SVal X = state->getSVal(*OI);
  2598. assert (!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef.
  2599. if (isa<Loc>(X))
  2600. state = state->bindLoc(cast<Loc>(X), UnknownVal());
  2601. }
  2602. MakeNode(Dst, A, Pred, state);
  2603. return;
  2604. }
  2605. ExplodedNodeSet Tmp;
  2606. Visit(*I, Pred, Tmp);
  2607. ++I;
  2608. for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI!=NE; ++NI)
  2609. VisitAsmStmtHelperInputs(A, I, E, *NI, Dst);
  2610. }
  2611. void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred,
  2612. ExplodedNodeSet &Dst) {
  2613. ExplodedNodeSet Src;
  2614. if (const Expr *RetE = RS->getRetValue()) {
  2615. // Record the returned expression in the state. It will be used in
  2616. // processCallExit to bind the return value to the call expr.
  2617. {
  2618. static int tag = 0;
  2619. const GRState *state = GetState(Pred);
  2620. state = state->set<ReturnExpr>(RetE);
  2621. Pred = Builder->generateNode(RetE, state, Pred, &tag);
  2622. }
  2623. // We may get a NULL Pred because we generated a cached node.
  2624. if (Pred)
  2625. Visit(RetE, Pred, Src);
  2626. }
  2627. else {
  2628. Src.Add(Pred);
  2629. }
  2630. ExplodedNodeSet CheckedSet;
  2631. CheckerVisit(RS, CheckedSet, Src, PreVisitStmtCallback);
  2632. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  2633. I != E; ++I) {
  2634. assert(Builder && "StmtNodeBuilder must be defined.");
  2635. Pred = *I;
  2636. unsigned size = Dst.size();
  2637. SaveAndRestore<bool> OldSink(Builder->BuildSinks);
  2638. SaveOr OldHasGen(Builder->hasGeneratedNode);
  2639. getTF().evalReturn(Dst, *this, *Builder, RS, Pred);
  2640. // Handle the case where no nodes where generated.
  2641. if (!Builder->BuildSinks && Dst.size() == size &&
  2642. !Builder->hasGeneratedNode)
  2643. MakeNode(Dst, RS, Pred, GetState(Pred));
  2644. }
  2645. }
  2646. //===----------------------------------------------------------------------===//
  2647. // Transfer functions: Binary operators.
  2648. //===----------------------------------------------------------------------===//
  2649. void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
  2650. ExplodedNode* Pred,
  2651. ExplodedNodeSet& Dst) {
  2652. ExplodedNodeSet Tmp1;
  2653. Expr* LHS = B->getLHS()->IgnoreParens();
  2654. Expr* RHS = B->getRHS()->IgnoreParens();
  2655. Visit(LHS, Pred, Tmp1);
  2656. ExplodedNodeSet Tmp3;
  2657. for (ExplodedNodeSet::iterator I1=Tmp1.begin(), E1=Tmp1.end(); I1!=E1; ++I1) {
  2658. SVal LeftV = GetState(*I1)->getSVal(LHS);
  2659. ExplodedNodeSet Tmp2;
  2660. Visit(RHS, *I1, Tmp2);
  2661. ExplodedNodeSet CheckedSet;
  2662. CheckerVisit(B, CheckedSet, Tmp2, PreVisitStmtCallback);
  2663. // With both the LHS and RHS evaluated, process the operation itself.
  2664. for (ExplodedNodeSet::iterator I2=CheckedSet.begin(), E2=CheckedSet.end();
  2665. I2 != E2; ++I2) {
  2666. const GRState *state = GetState(*I2);
  2667. SVal RightV = state->getSVal(RHS);
  2668. BinaryOperator::Opcode Op = B->getOpcode();
  2669. if (Op == BO_Assign) {
  2670. // EXPERIMENTAL: "Conjured" symbols.
  2671. // FIXME: Handle structs.
  2672. if (RightV.isUnknown() ||!getConstraintManager().canReasonAbout(RightV))
  2673. {
  2674. unsigned Count = Builder->getCurrentBlockCount();
  2675. RightV = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), Count);
  2676. }
  2677. SVal ExprVal = B->isLValue() ? LeftV : RightV;
  2678. // Simulate the effects of a "store": bind the value of the RHS
  2679. // to the L-Value represented by the LHS.
  2680. evalStore(Tmp3, B, LHS, *I2, state->BindExpr(B, ExprVal), LeftV,RightV);
  2681. continue;
  2682. }
  2683. if (!B->isAssignmentOp()) {
  2684. // Process non-assignments except commas or short-circuited
  2685. // logical expressions (LAnd and LOr).
  2686. SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
  2687. if (Result.isUnknown()) {
  2688. MakeNode(Tmp3, B, *I2, state);
  2689. continue;
  2690. }
  2691. state = state->BindExpr(B, Result);
  2692. MakeNode(Tmp3, B, *I2, state);
  2693. continue;
  2694. }
  2695. assert (B->isCompoundAssignmentOp());
  2696. switch (Op) {
  2697. default:
  2698. assert(0 && "Invalid opcode for compound assignment.");
  2699. case BO_MulAssign: Op = BO_Mul; break;
  2700. case BO_DivAssign: Op = BO_Div; break;
  2701. case BO_RemAssign: Op = BO_Rem; break;
  2702. case BO_AddAssign: Op = BO_Add; break;
  2703. case BO_SubAssign: Op = BO_Sub; break;
  2704. case BO_ShlAssign: Op = BO_Shl; break;
  2705. case BO_ShrAssign: Op = BO_Shr; break;
  2706. case BO_AndAssign: Op = BO_And; break;
  2707. case BO_XorAssign: Op = BO_Xor; break;
  2708. case BO_OrAssign: Op = BO_Or; break;
  2709. }
  2710. // Perform a load (the LHS). This performs the checks for
  2711. // null dereferences, and so on.
  2712. ExplodedNodeSet Tmp4;
  2713. SVal location = state->getSVal(LHS);
  2714. evalLoad(Tmp4, LHS, *I2, state, location);
  2715. for (ExplodedNodeSet::iterator I4=Tmp4.begin(), E4=Tmp4.end(); I4!=E4;
  2716. ++I4) {
  2717. state = GetState(*I4);
  2718. SVal V = state->getSVal(LHS);
  2719. // Get the computation type.
  2720. QualType CTy =
  2721. cast<CompoundAssignOperator>(B)->getComputationResultType();
  2722. CTy = getContext().getCanonicalType(CTy);
  2723. QualType CLHSTy =
  2724. cast<CompoundAssignOperator>(B)->getComputationLHSType();
  2725. CLHSTy = getContext().getCanonicalType(CLHSTy);
  2726. QualType LTy = getContext().getCanonicalType(LHS->getType());
  2727. // Promote LHS.
  2728. V = svalBuilder.evalCast(V, CLHSTy, LTy);
  2729. // Compute the result of the operation.
  2730. SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
  2731. B->getType(), CTy);
  2732. // EXPERIMENTAL: "Conjured" symbols.
  2733. // FIXME: Handle structs.
  2734. SVal LHSVal;
  2735. if (Result.isUnknown() ||
  2736. !getConstraintManager().canReasonAbout(Result)) {
  2737. unsigned Count = Builder->getCurrentBlockCount();
  2738. // The symbolic value is actually for the type of the left-hand side
  2739. // expression, not the computation type, as this is the value the
  2740. // LValue on the LHS will bind to.
  2741. LHSVal = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LTy, Count);
  2742. // However, we need to convert the symbol to the computation type.
  2743. Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
  2744. }
  2745. else {
  2746. // The left-hand side may bind to a different value then the
  2747. // computation type.
  2748. LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
  2749. }
  2750. // In C++, assignment and compound assignment operators return an
  2751. // lvalue.
  2752. if (B->isLValue())
  2753. state = state->BindExpr(B, location);
  2754. else
  2755. state = state->BindExpr(B, Result);
  2756. evalStore(Tmp3, B, LHS, *I4, state, location, LHSVal);
  2757. }
  2758. }
  2759. }
  2760. CheckerVisit(B, Dst, Tmp3, PostVisitStmtCallback);
  2761. }
  2762. //===----------------------------------------------------------------------===//
  2763. // Checker registration/lookup.
  2764. //===----------------------------------------------------------------------===//
  2765. Checker *ExprEngine::lookupChecker(void *tag) const {
  2766. CheckerMap::const_iterator I = CheckerM.find(tag);
  2767. return (I == CheckerM.end()) ? NULL : Checkers[I->second].second;
  2768. }
  2769. //===----------------------------------------------------------------------===//
  2770. // Visualization.
  2771. //===----------------------------------------------------------------------===//
  2772. #ifndef NDEBUG
  2773. static ExprEngine* GraphPrintCheckerState;
  2774. static SourceManager* GraphPrintSourceManager;
  2775. namespace llvm {
  2776. template<>
  2777. struct DOTGraphTraits<ExplodedNode*> :
  2778. public DefaultDOTGraphTraits {
  2779. DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
  2780. // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
  2781. // work.
  2782. static std::string getNodeAttributes(const ExplodedNode* N, void*) {
  2783. #if 0
  2784. // FIXME: Replace with a general scheme to tell if the node is
  2785. // an error node.
  2786. if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
  2787. GraphPrintCheckerState->isExplicitNullDeref(N) ||
  2788. GraphPrintCheckerState->isUndefDeref(N) ||
  2789. GraphPrintCheckerState->isUndefStore(N) ||
  2790. GraphPrintCheckerState->isUndefControlFlow(N) ||
  2791. GraphPrintCheckerState->isUndefResult(N) ||
  2792. GraphPrintCheckerState->isBadCall(N) ||
  2793. GraphPrintCheckerState->isUndefArg(N))
  2794. return "color=\"red\",style=\"filled\"";
  2795. if (GraphPrintCheckerState->isNoReturnCall(N))
  2796. return "color=\"blue\",style=\"filled\"";
  2797. #endif
  2798. return "";
  2799. }
  2800. static std::string getNodeLabel(const ExplodedNode* N, void*){
  2801. std::string sbuf;
  2802. llvm::raw_string_ostream Out(sbuf);
  2803. // Program Location.
  2804. ProgramPoint Loc = N->getLocation();
  2805. switch (Loc.getKind()) {
  2806. case ProgramPoint::BlockEntranceKind:
  2807. Out << "Block Entrance: B"
  2808. << cast<BlockEntrance>(Loc).getBlock()->getBlockID();
  2809. break;
  2810. case ProgramPoint::BlockExitKind:
  2811. assert (false);
  2812. break;
  2813. case ProgramPoint::CallEnterKind:
  2814. Out << "CallEnter";
  2815. break;
  2816. case ProgramPoint::CallExitKind:
  2817. Out << "CallExit";
  2818. break;
  2819. default: {
  2820. if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) {
  2821. const Stmt* S = L->getStmt();
  2822. SourceLocation SLoc = S->getLocStart();
  2823. Out << S->getStmtClassName() << ' ' << (void*) S << ' ';
  2824. LangOptions LO; // FIXME.
  2825. S->printPretty(Out, 0, PrintingPolicy(LO));
  2826. if (SLoc.isFileID()) {
  2827. Out << "\\lline="
  2828. << GraphPrintSourceManager->getInstantiationLineNumber(SLoc)
  2829. << " col="
  2830. << GraphPrintSourceManager->getInstantiationColumnNumber(SLoc)
  2831. << "\\l";
  2832. }
  2833. if (isa<PreStmt>(Loc))
  2834. Out << "\\lPreStmt\\l;";
  2835. else if (isa<PostLoad>(Loc))
  2836. Out << "\\lPostLoad\\l;";
  2837. else if (isa<PostStore>(Loc))
  2838. Out << "\\lPostStore\\l";
  2839. else if (isa<PostLValue>(Loc))
  2840. Out << "\\lPostLValue\\l";
  2841. #if 0
  2842. // FIXME: Replace with a general scheme to determine
  2843. // the name of the check.
  2844. if (GraphPrintCheckerState->isImplicitNullDeref(N))
  2845. Out << "\\|Implicit-Null Dereference.\\l";
  2846. else if (GraphPrintCheckerState->isExplicitNullDeref(N))
  2847. Out << "\\|Explicit-Null Dereference.\\l";
  2848. else if (GraphPrintCheckerState->isUndefDeref(N))
  2849. Out << "\\|Dereference of undefialied value.\\l";
  2850. else if (GraphPrintCheckerState->isUndefStore(N))
  2851. Out << "\\|Store to Undefined Loc.";
  2852. else if (GraphPrintCheckerState->isUndefResult(N))
  2853. Out << "\\|Result of operation is undefined.";
  2854. else if (GraphPrintCheckerState->isNoReturnCall(N))
  2855. Out << "\\|Call to function marked \"noreturn\".";
  2856. else if (GraphPrintCheckerState->isBadCall(N))
  2857. Out << "\\|Call to NULL/Undefined.";
  2858. else if (GraphPrintCheckerState->isUndefArg(N))
  2859. Out << "\\|Argument in call is undefined";
  2860. #endif
  2861. break;
  2862. }
  2863. const BlockEdge& E = cast<BlockEdge>(Loc);
  2864. Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
  2865. << E.getDst()->getBlockID() << ')';
  2866. if (const Stmt* T = E.getSrc()->getTerminator()) {
  2867. SourceLocation SLoc = T->getLocStart();
  2868. Out << "\\|Terminator: ";
  2869. LangOptions LO; // FIXME.
  2870. E.getSrc()->printTerminator(Out, LO);
  2871. if (SLoc.isFileID()) {
  2872. Out << "\\lline="
  2873. << GraphPrintSourceManager->getInstantiationLineNumber(SLoc)
  2874. << " col="
  2875. << GraphPrintSourceManager->getInstantiationColumnNumber(SLoc);
  2876. }
  2877. if (isa<SwitchStmt>(T)) {
  2878. const Stmt* Label = E.getDst()->getLabel();
  2879. if (Label) {
  2880. if (const CaseStmt* C = dyn_cast<CaseStmt>(Label)) {
  2881. Out << "\\lcase ";
  2882. LangOptions LO; // FIXME.
  2883. C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO));
  2884. if (const Stmt* RHS = C->getRHS()) {
  2885. Out << " .. ";
  2886. RHS->printPretty(Out, 0, PrintingPolicy(LO));
  2887. }
  2888. Out << ":";
  2889. }
  2890. else {
  2891. assert (isa<DefaultStmt>(Label));
  2892. Out << "\\ldefault:";
  2893. }
  2894. }
  2895. else
  2896. Out << "\\l(implicit) default:";
  2897. }
  2898. else if (isa<IndirectGotoStmt>(T)) {
  2899. // FIXME
  2900. }
  2901. else {
  2902. Out << "\\lCondition: ";
  2903. if (*E.getSrc()->succ_begin() == E.getDst())
  2904. Out << "true";
  2905. else
  2906. Out << "false";
  2907. }
  2908. Out << "\\l";
  2909. }
  2910. #if 0
  2911. // FIXME: Replace with a general scheme to determine
  2912. // the name of the check.
  2913. if (GraphPrintCheckerState->isUndefControlFlow(N)) {
  2914. Out << "\\|Control-flow based on\\lUndefined value.\\l";
  2915. }
  2916. #endif
  2917. }
  2918. }
  2919. const GRState *state = N->getState();
  2920. Out << "\\|StateID: " << (void*) state
  2921. << " NodeID: " << (void*) N << "\\|";
  2922. state->printDOT(Out, *N->getLocationContext()->getCFG());
  2923. Out << "\\l";
  2924. return Out.str();
  2925. }
  2926. };
  2927. } // end llvm namespace
  2928. #endif
  2929. #ifndef NDEBUG
  2930. template <typename ITERATOR>
  2931. ExplodedNode* GetGraphNode(ITERATOR I) { return *I; }
  2932. template <> ExplodedNode*
  2933. GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
  2934. (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
  2935. return I->first;
  2936. }
  2937. #endif
  2938. void ExprEngine::ViewGraph(bool trim) {
  2939. #ifndef NDEBUG
  2940. if (trim) {
  2941. std::vector<ExplodedNode*> Src;
  2942. // Flush any outstanding reports to make sure we cover all the nodes.
  2943. // This does not cause them to get displayed.
  2944. for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
  2945. const_cast<BugType*>(*I)->FlushReports(BR);
  2946. // Iterate through the reports and get their nodes.
  2947. for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I) {
  2948. for (BugType::const_iterator I2=(*I)->begin(), E2=(*I)->end();
  2949. I2!=E2; ++I2) {
  2950. const BugReportEquivClass& EQ = *I2;
  2951. const BugReport &R = **EQ.begin();
  2952. ExplodedNode *N = const_cast<ExplodedNode*>(R.getErrorNode());
  2953. if (N) Src.push_back(N);
  2954. }
  2955. }
  2956. ViewGraph(&Src[0], &Src[0]+Src.size());
  2957. }
  2958. else {
  2959. GraphPrintCheckerState = this;
  2960. GraphPrintSourceManager = &getContext().getSourceManager();
  2961. llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
  2962. GraphPrintCheckerState = NULL;
  2963. GraphPrintSourceManager = NULL;
  2964. }
  2965. #endif
  2966. }
  2967. void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) {
  2968. #ifndef NDEBUG
  2969. GraphPrintCheckerState = this;
  2970. GraphPrintSourceManager = &getContext().getSourceManager();
  2971. std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first);
  2972. if (!TrimmedG.get())
  2973. llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
  2974. else
  2975. llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
  2976. GraphPrintCheckerState = NULL;
  2977. GraphPrintSourceManager = NULL;
  2978. #endif
  2979. }