ExprEngine.cpp 106 KB

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