ExprEngine.h revision 66c486f275531df6362b3511fc3af6563561801b
1//===-- ExprEngine.h - 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 CoreEngine, but provides the boilerplate to execute transfer 12// functions and build the ExplodedGraph at the expression level. 13// 14//===----------------------------------------------------------------------===// 15 16#ifndef LLVM_CLANG_GR_EXPRENGINE 17#define LLVM_CLANG_GR_EXPRENGINE 18 19#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 20#include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h" 21#include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h" 22#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 23#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" 24#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 25#include "clang/AST/Expr.h" 26#include "clang/AST/Type.h" 27 28namespace clang { 29 30class AnalysisDeclContextManager; 31class CXXCatchStmt; 32class CXXConstructExpr; 33class CXXDeleteExpr; 34class CXXNewExpr; 35class CXXTemporaryObjectExpr; 36class CXXThisExpr; 37class MaterializeTemporaryExpr; 38class ObjCAtSynchronizedStmt; 39class ObjCForCollectionStmt; 40 41namespace ento { 42 43class AnalysisManager; 44class CallEvent; 45class SimpleCall; 46 47class ExprEngine : public SubEngine { 48 AnalysisManager &AMgr; 49 50 AnalysisDeclContextManager &AnalysisDeclContexts; 51 52 CoreEngine Engine; 53 54 /// G - the simulation graph. 55 ExplodedGraph& G; 56 57 /// StateMgr - Object that manages the data for all created states. 58 ProgramStateManager StateMgr; 59 60 /// SymMgr - Object that manages the symbol information. 61 SymbolManager& SymMgr; 62 63 /// svalBuilder - SValBuilder object that creates SVals from expressions. 64 SValBuilder &svalBuilder; 65 66 /// EntryNode - The immediate predecessor node. 67 ExplodedNode *EntryNode; 68 69 /// CleanedState - The state for EntryNode "cleaned" of all dead 70 /// variables and symbols (as determined by a liveness analysis). 71 ProgramStateRef CleanedState; 72 73 /// currStmt - The current block-level statement. 74 const Stmt *currStmt; 75 unsigned int currStmtIdx; 76 const NodeBuilderContext *currBldrCtx; 77 78 /// Obj-C Class Identifiers. 79 IdentifierInfo* NSExceptionII; 80 81 /// Obj-C Selectors. 82 Selector* NSExceptionInstanceRaiseSelectors; 83 Selector RaiseSel; 84 85 /// Whether or not GC is enabled in this analysis. 86 bool ObjCGCEnabled; 87 88 /// The BugReporter associated with this engine. It is important that 89 /// this object be placed at the very end of member variables so that its 90 /// destructor is called before the rest of the ExprEngine is destroyed. 91 GRBugReporter BR; 92 93public: 94 ExprEngine(AnalysisManager &mgr, bool gcEnabled, 95 SetOfConstDecls *VisitedCallees, 96 FunctionSummariesTy *FS); 97 98 ~ExprEngine(); 99 100 /// Returns true if there is still simulation state on the worklist. 101 bool ExecuteWorkList(const LocationContext *L, unsigned Steps = 150000) { 102 return Engine.ExecuteWorkList(L, Steps, 0); 103 } 104 105 /// Execute the work list with an initial state. Nodes that reaches the exit 106 /// of the function are added into the Dst set, which represent the exit 107 /// state of the function call. Returns true if there is still simulation 108 /// state on the worklist. 109 bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned Steps, 110 ProgramStateRef InitState, 111 ExplodedNodeSet &Dst) { 112 return Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst); 113 } 114 115 /// getContext - Return the ASTContext associated with this analysis. 116 ASTContext &getContext() const { return AMgr.getASTContext(); } 117 118 virtual AnalysisManager &getAnalysisManager() { return AMgr; } 119 120 CheckerManager &getCheckerManager() const { 121 return *AMgr.getCheckerManager(); 122 } 123 124 SValBuilder &getSValBuilder() { return svalBuilder; } 125 126 BugReporter& getBugReporter() { return BR; } 127 128 const NodeBuilderContext &getBuilderContext() { 129 assert(currBldrCtx); 130 return *currBldrCtx; 131 } 132 133 bool isObjCGCEnabled() { return ObjCGCEnabled; } 134 135 const Stmt *getStmt() const; 136 137 void GenerateAutoTransition(ExplodedNode *N); 138 void enqueueEndOfPath(ExplodedNodeSet &S); 139 void GenerateCallExitNode(ExplodedNode *N); 140 141 /// ViewGraph - Visualize the ExplodedGraph created by executing the 142 /// simulation. 143 void ViewGraph(bool trim = false); 144 145 void ViewGraph(ExplodedNode** Beg, ExplodedNode** End); 146 147 /// getInitialState - Return the initial state used for the root vertex 148 /// in the ExplodedGraph. 149 ProgramStateRef getInitialState(const LocationContext *InitLoc); 150 151 ExplodedGraph& getGraph() { return G; } 152 const ExplodedGraph& getGraph() const { return G; } 153 154 /// \brief Run the analyzer's garbage collection - remove dead symbols and 155 /// bindings. 156 /// 157 /// \param Node - The predecessor node, from which the processing should 158 /// start. 159 /// \param Out - The returned set of output nodes. 160 /// \param ReferenceStmt - Run garbage collection using the symbols, 161 /// which are live before the given statement. 162 /// \param LC - The location context of the ReferenceStmt. 163 /// \param DiagnosticStmt - the statement used to associate the diagnostic 164 /// message, if any warnings should occur while removing the dead (leaks 165 /// are usually reported here). 166 /// \param K - In some cases it is possible to use PreStmt kind. (Do 167 /// not use it unless you know what you are doing.) 168 void removeDead(ExplodedNode *Node, ExplodedNodeSet &Out, 169 const Stmt *ReferenceStmt, const LocationContext *LC, 170 const Stmt *DiagnosticStmt, 171 ProgramPoint::Kind K = ProgramPoint::PreStmtPurgeDeadSymbolsKind); 172 173 /// processCFGElement - Called by CoreEngine. Used to generate new successor 174 /// nodes by processing the 'effects' of a CFG element. 175 void processCFGElement(const CFGElement E, ExplodedNode *Pred, 176 unsigned StmtIdx, NodeBuilderContext *Ctx); 177 178 void ProcessStmt(const CFGStmt S, ExplodedNode *Pred); 179 180 void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred); 181 182 void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred); 183 184 void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D, 185 ExplodedNode *Pred, ExplodedNodeSet &Dst); 186 void ProcessBaseDtor(const CFGBaseDtor D, 187 ExplodedNode *Pred, ExplodedNodeSet &Dst); 188 void ProcessMemberDtor(const CFGMemberDtor D, 189 ExplodedNode *Pred, ExplodedNodeSet &Dst); 190 void ProcessTemporaryDtor(const CFGTemporaryDtor D, 191 ExplodedNode *Pred, ExplodedNodeSet &Dst); 192 193 /// Called by CoreEngine when processing the entrance of a CFGBlock. 194 virtual void processCFGBlockEntrance(const BlockEdge &L, 195 NodeBuilderWithSinks &nodeBuilder); 196 197 /// ProcessBranch - Called by CoreEngine. Used to generate successor 198 /// nodes by processing the 'effects' of a branch condition. 199 void processBranch(const Stmt *Condition, const Stmt *Term, 200 NodeBuilderContext& BuilderCtx, 201 ExplodedNode *Pred, 202 ExplodedNodeSet &Dst, 203 const CFGBlock *DstT, 204 const CFGBlock *DstF); 205 206 /// processIndirectGoto - Called by CoreEngine. Used to generate successor 207 /// nodes by processing the 'effects' of a computed goto jump. 208 void processIndirectGoto(IndirectGotoNodeBuilder& builder); 209 210 /// ProcessSwitch - Called by CoreEngine. Used to generate successor 211 /// nodes by processing the 'effects' of a switch statement. 212 void processSwitch(SwitchNodeBuilder& builder); 213 214 /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path 215 /// nodes when the control reaches the end of a function. 216 void processEndOfFunction(NodeBuilderContext& BC); 217 218 /// Generate the entry node of the callee. 219 void processCallEnter(CallEnter CE, ExplodedNode *Pred); 220 221 /// Generate the sequence of nodes that simulate the call exit and the post 222 /// visit for CallExpr. 223 void processCallExit(ExplodedNode *Pred); 224 225 /// Called by CoreEngine when the analysis worklist has terminated. 226 void processEndWorklist(bool hasWorkRemaining); 227 228 /// evalAssume - Callback function invoked by the ConstraintManager when 229 /// making assumptions about state values. 230 ProgramStateRef processAssume(ProgramStateRef state, SVal cond,bool assumption); 231 232 /// wantsRegionChangeUpdate - Called by ProgramStateManager to determine if a 233 /// region change should trigger a processRegionChanges update. 234 bool wantsRegionChangeUpdate(ProgramStateRef state); 235 236 /// processRegionChanges - Called by ProgramStateManager whenever a change is made 237 /// to the store. Used to update checkers that track region values. 238 ProgramStateRef 239 processRegionChanges(ProgramStateRef state, 240 const StoreManager::InvalidatedSymbols *invalidated, 241 ArrayRef<const MemRegion *> ExplicitRegions, 242 ArrayRef<const MemRegion *> Regions, 243 const CallEvent *Call); 244 245 /// printState - Called by ProgramStateManager to print checker-specific data. 246 void printState(raw_ostream &Out, ProgramStateRef State, 247 const char *NL, const char *Sep); 248 249 virtual ProgramStateManager& getStateManager() { return StateMgr; } 250 251 StoreManager& getStoreManager() { return StateMgr.getStoreManager(); } 252 253 ConstraintManager& getConstraintManager() { 254 return StateMgr.getConstraintManager(); 255 } 256 257 // FIXME: Remove when we migrate over to just using SValBuilder. 258 BasicValueFactory& getBasicVals() { 259 return StateMgr.getBasicVals(); 260 } 261 const BasicValueFactory& getBasicVals() const { 262 return StateMgr.getBasicVals(); 263 } 264 265 // FIXME: Remove when we migrate over to just using ValueManager. 266 SymbolManager& getSymbolManager() { return SymMgr; } 267 const SymbolManager& getSymbolManager() const { return SymMgr; } 268 269 // Functions for external checking of whether we have unfinished work 270 bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); } 271 bool hasEmptyWorkList() const { return !Engine.getWorkList()->hasWork(); } 272 bool hasWorkRemaining() const { return Engine.hasWorkRemaining(); } 273 274 const CoreEngine &getCoreEngine() const { return Engine; } 275 276public: 277 /// Visit - Transfer function logic for all statements. Dispatches to 278 /// other functions that handle specific kinds of statements. 279 void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst); 280 281 /// VisitArraySubscriptExpr - Transfer function for array accesses. 282 void VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *Ex, 283 ExplodedNode *Pred, 284 ExplodedNodeSet &Dst); 285 286 /// VisitAsmStmt - Transfer function logic for inline asm. 287 void VisitAsmStmt(const AsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet &Dst); 288 289 /// VisitMSAsmStmt - Transfer function logic for MS inline asm. 290 void VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred, 291 ExplodedNodeSet &Dst); 292 293 /// VisitBlockExpr - Transfer function logic for BlockExprs. 294 void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, 295 ExplodedNodeSet &Dst); 296 297 /// VisitBinaryOperator - Transfer function logic for binary operators. 298 void VisitBinaryOperator(const BinaryOperator* B, ExplodedNode *Pred, 299 ExplodedNodeSet &Dst); 300 301 302 /// VisitCall - Transfer function for function calls. 303 void VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, 304 ExplodedNodeSet &Dst); 305 306 /// VisitCast - Transfer function logic for all casts (implicit and explicit). 307 void VisitCast(const CastExpr *CastE, const Expr *Ex, ExplodedNode *Pred, 308 ExplodedNodeSet &Dst); 309 310 /// VisitCompoundLiteralExpr - Transfer function logic for compound literals. 311 void VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, 312 ExplodedNode *Pred, ExplodedNodeSet &Dst); 313 314 /// Transfer function logic for DeclRefExprs and BlockDeclRefExprs. 315 void VisitCommonDeclRefExpr(const Expr *DR, const NamedDecl *D, 316 ExplodedNode *Pred, ExplodedNodeSet &Dst); 317 318 /// VisitDeclStmt - Transfer function logic for DeclStmts. 319 void VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, 320 ExplodedNodeSet &Dst); 321 322 /// VisitGuardedExpr - Transfer function logic for ?, __builtin_choose 323 void VisitGuardedExpr(const Expr *Ex, const Expr *L, const Expr *R, 324 ExplodedNode *Pred, ExplodedNodeSet &Dst); 325 326 void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred, 327 ExplodedNodeSet &Dst); 328 329 /// VisitLogicalExpr - Transfer function logic for '&&', '||' 330 void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred, 331 ExplodedNodeSet &Dst); 332 333 /// VisitMemberExpr - Transfer function for member expressions. 334 void VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred, 335 ExplodedNodeSet &Dst); 336 337 /// Transfer function logic for ObjCAtSynchronizedStmts. 338 void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, 339 ExplodedNode *Pred, ExplodedNodeSet &Dst); 340 341 /// Transfer function logic for computing the lvalue of an Objective-C ivar. 342 void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred, 343 ExplodedNodeSet &Dst); 344 345 /// VisitObjCForCollectionStmt - Transfer function logic for 346 /// ObjCForCollectionStmt. 347 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, 348 ExplodedNode *Pred, ExplodedNodeSet &Dst); 349 350 void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred, 351 ExplodedNodeSet &Dst); 352 353 /// VisitReturnStmt - Transfer function logic for return statements. 354 void VisitReturnStmt(const ReturnStmt *R, ExplodedNode *Pred, 355 ExplodedNodeSet &Dst); 356 357 /// VisitOffsetOfExpr - Transfer function for offsetof. 358 void VisitOffsetOfExpr(const OffsetOfExpr *Ex, ExplodedNode *Pred, 359 ExplodedNodeSet &Dst); 360 361 /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof. 362 void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, 363 ExplodedNode *Pred, ExplodedNodeSet &Dst); 364 365 /// VisitUnaryOperator - Transfer function logic for unary operators. 366 void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred, 367 ExplodedNodeSet &Dst); 368 369 /// Handle ++ and -- (both pre- and post-increment). 370 void VisitIncrementDecrementOperator(const UnaryOperator* U, 371 ExplodedNode *Pred, 372 ExplodedNodeSet &Dst); 373 374 void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, 375 ExplodedNodeSet &Dst); 376 377 void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, 378 ExplodedNodeSet & Dst); 379 380 void VisitCXXConstructExpr(const CXXConstructExpr *E, ExplodedNode *Pred, 381 ExplodedNodeSet &Dst); 382 383 void VisitCXXDestructor(QualType ObjectType, 384 const MemRegion *Dest, const Stmt *S, 385 ExplodedNode *Pred, ExplodedNodeSet &Dst); 386 387 void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, 388 ExplodedNodeSet &Dst); 389 390 void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, 391 ExplodedNodeSet &Dst); 392 393 /// Create a C++ temporary object for an rvalue. 394 void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, 395 ExplodedNode *Pred, 396 ExplodedNodeSet &Dst); 397 398 /// evalEagerlyAssume - Given the nodes in 'Src', eagerly assume symbolic 399 /// expressions of the form 'x != 0' and generate new nodes (stored in Dst) 400 /// with those assumptions. 401 void evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, 402 const Expr *Ex); 403 404 std::pair<const ProgramPointTag *, const ProgramPointTag*> 405 getEagerlyAssumeTags(); 406 407 SVal evalMinus(SVal X) { 408 return X.isValid() ? svalBuilder.evalMinus(cast<NonLoc>(X)) : X; 409 } 410 411 SVal evalComplement(SVal X) { 412 return X.isValid() ? svalBuilder.evalComplement(cast<NonLoc>(X)) : X; 413 } 414 415public: 416 417 SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, 418 NonLoc L, NonLoc R, QualType T) { 419 return svalBuilder.evalBinOpNN(state, op, L, R, T); 420 } 421 422 SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, 423 NonLoc L, SVal R, QualType T) { 424 return R.isValid() ? svalBuilder.evalBinOpNN(state,op,L, cast<NonLoc>(R), T) : R; 425 } 426 427 SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op, 428 SVal LHS, SVal RHS, QualType T) { 429 return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T); 430 } 431 432protected: 433 /// evalBind - Handle the semantics of binding a value to a specific location. 434 /// This method is used by evalStore, VisitDeclStmt, and others. 435 void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred, 436 SVal location, SVal Val, bool atDeclInit = false); 437 438public: 439 // FIXME: 'tag' should be removed, and a LocationContext should be used 440 // instead. 441 // FIXME: Comment on the meaning of the arguments, when 'St' may not 442 // be the same as Pred->state, and when 'location' may not be the 443 // same as state->getLValue(Ex). 444 /// Simulate a read of the result of Ex. 445 void evalLoad(ExplodedNodeSet &Dst, 446 const Expr *NodeEx, /* Eventually will be a CFGStmt */ 447 const Expr *BoundExpr, 448 ExplodedNode *Pred, 449 ProgramStateRef St, 450 SVal location, 451 const ProgramPointTag *tag = 0, 452 QualType LoadTy = QualType()); 453 454 // FIXME: 'tag' should be removed, and a LocationContext should be used 455 // instead. 456 void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE, 457 ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val, 458 const ProgramPointTag *tag = 0); 459 460 /// \brief Create a new state in which the call return value is binded to the 461 /// call origin expression. 462 ProgramStateRef bindReturnValue(const CallEvent &Call, 463 const LocationContext *LCtx, 464 ProgramStateRef State); 465 466 /// Evaluate a call, running pre- and post-call checks and allowing checkers 467 /// to be responsible for handling the evaluation of the call itself. 468 void evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred, 469 const CallEvent &Call); 470 471 /// \brief Default implementation of call evaluation. 472 void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred, 473 const CallEvent &Call); 474private: 475 void evalLoadCommon(ExplodedNodeSet &Dst, 476 const Expr *NodeEx, /* Eventually will be a CFGStmt */ 477 const Expr *BoundEx, 478 ExplodedNode *Pred, 479 ProgramStateRef St, 480 SVal location, 481 const ProgramPointTag *tag, 482 QualType LoadTy); 483 484 // FIXME: 'tag' should be removed, and a LocationContext should be used 485 // instead. 486 void evalLocation(ExplodedNodeSet &Dst, 487 const Stmt *NodeEx, /* This will eventually be a CFGStmt */ 488 const Stmt *BoundEx, 489 ExplodedNode *Pred, 490 ProgramStateRef St, SVal location, 491 const ProgramPointTag *tag, bool isLoad); 492 493 bool shouldInlineDecl(const Decl *D, ExplodedNode *Pred); 494 bool inlineCall(const CallEvent &Call, const Decl *D, NodeBuilder &Bldr, 495 ExplodedNode *Pred, ProgramStateRef State); 496 497 /// \brief Conservatively evaluate call by invalidating regions and binding 498 /// a conjured return value. 499 void conservativeEvalCall(const CallEvent &Call, NodeBuilder &Bldr, 500 ExplodedNode *Pred, ProgramStateRef State); 501 502 /// \brief Either inline or process the call conservatively (or both), based 503 /// on DynamicDispatchBifurcation data. 504 void BifurcateCall(const MemRegion *BifurReg, 505 const CallEvent &Call, const Decl *D, NodeBuilder &Bldr, 506 ExplodedNode *Pred); 507 508 bool replayWithoutInlining(ExplodedNode *P, const LocationContext *CalleeLC); 509}; 510 511/// Traits for storing the call processing policy inside GDM. 512/// The GDM stores the corresponding CallExpr pointer. 513struct ReplayWithoutInlining{}; 514template <> 515struct ProgramStateTrait<ReplayWithoutInlining> : 516 public ProgramStatePartialTrait<void*> { 517 static void *GDMIndex() { static int index = 0; return &index; } 518}; 519 520} // end ento namespace 521 522} // end clang namespace 523 524#endif 525