ExprEngine.h revision cde8cdbd6a662c636164465ad309b5f17ff01064
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 ObjCMethodCall; 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 /// currentStmt - The current block-level statement. 74 const Stmt *currentStmt; 75 unsigned int currentStmtIdx; 76 const NodeBuilderContext *currentBuilderContext; 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(currentBuilderContext); 130 return *currentBuilderContext; 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 ObjCMethodCall &Msg, 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 VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *expr, 381 ExplodedNode *Pred, ExplodedNodeSet &Dst); 382 383 void VisitCXXConstructExpr(const CXXConstructExpr *E, const MemRegion *Dest, 384 ExplodedNode *Pred, ExplodedNodeSet &Dst); 385 386 void VisitCXXDestructor(const CXXDestructorDecl *DD, 387 const MemRegion *Dest, const Stmt *S, 388 ExplodedNode *Pred, ExplodedNodeSet &Dst); 389 390 void VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, 391 ExplodedNodeSet &Dst); 392 393 void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred, 394 ExplodedNodeSet &Dst); 395 396 /// Create a C++ temporary object for an rvalue. 397 void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, 398 ExplodedNode *Pred, 399 ExplodedNodeSet &Dst); 400 401 /// evalEagerlyAssume - Given the nodes in 'Src', eagerly assume symbolic 402 /// expressions of the form 'x != 0' and generate new nodes (stored in Dst) 403 /// with those assumptions. 404 void evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src, 405 const Expr *Ex); 406 407 std::pair<const ProgramPointTag *, const ProgramPointTag*> 408 getEagerlyAssumeTags(); 409 410 SVal evalMinus(SVal X) { 411 return X.isValid() ? svalBuilder.evalMinus(cast<NonLoc>(X)) : X; 412 } 413 414 SVal evalComplement(SVal X) { 415 return X.isValid() ? svalBuilder.evalComplement(cast<NonLoc>(X)) : X; 416 } 417 418public: 419 420 SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, 421 NonLoc L, NonLoc R, QualType T) { 422 return svalBuilder.evalBinOpNN(state, op, L, R, T); 423 } 424 425 SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, 426 NonLoc L, SVal R, QualType T) { 427 return R.isValid() ? svalBuilder.evalBinOpNN(state,op,L, cast<NonLoc>(R), T) : R; 428 } 429 430 SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op, 431 SVal LHS, SVal RHS, QualType T) { 432 return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T); 433 } 434 435protected: 436 void evalObjCMessage(StmtNodeBuilder &Bldr, const ObjCMethodCall &Msg, 437 ExplodedNode *Pred, ProgramStateRef state, 438 bool GenSink); 439 440 ProgramStateRef MarkBranch(ProgramStateRef state, 441 const Stmt *Terminator, 442 const LocationContext *LCtx, 443 bool branchTaken); 444 445 /// evalBind - Handle the semantics of binding a value to a specific location. 446 /// This method is used by evalStore, VisitDeclStmt, and others. 447 void evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE, ExplodedNode *Pred, 448 SVal location, SVal Val, bool atDeclInit = false); 449 450public: 451 // FIXME: 'tag' should be removed, and a LocationContext should be used 452 // instead. 453 // FIXME: Comment on the meaning of the arguments, when 'St' may not 454 // be the same as Pred->state, and when 'location' may not be the 455 // same as state->getLValue(Ex). 456 /// Simulate a read of the result of Ex. 457 void evalLoad(ExplodedNodeSet &Dst, 458 const Expr *NodeEx, /* Eventually will be a CFGStmt */ 459 const Expr *BoundExpr, 460 ExplodedNode *Pred, 461 ProgramStateRef St, 462 SVal location, 463 const ProgramPointTag *tag = 0, 464 QualType LoadTy = QualType()); 465 466 // FIXME: 'tag' should be removed, and a LocationContext should be used 467 // instead. 468 void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *StoreE, 469 ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SVal Val, 470 const ProgramPointTag *tag = 0); 471private: 472 void evalLoadCommon(ExplodedNodeSet &Dst, 473 const Expr *NodeEx, /* Eventually will be a CFGStmt */ 474 const Expr *BoundEx, 475 ExplodedNode *Pred, 476 ProgramStateRef St, 477 SVal location, 478 const ProgramPointTag *tag, 479 QualType LoadTy); 480 481 // FIXME: 'tag' should be removed, and a LocationContext should be used 482 // instead. 483 void evalLocation(ExplodedNodeSet &Dst, 484 const Stmt *NodeEx, /* This will eventually be a CFGStmt */ 485 const Stmt *BoundEx, 486 ExplodedNode *Pred, 487 ProgramStateRef St, SVal location, 488 const ProgramPointTag *tag, bool isLoad); 489 490 bool shouldInlineDecl(const Decl *D, ExplodedNode *Pred); 491 bool InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE, ExplodedNode *Pred); 492 493 bool replayWithoutInlining(ExplodedNode *P, const LocationContext *CalleeLC); 494}; 495 496/// Traits for storing the call processing policy inside GDM. 497/// The GDM stores the corresponding CallExpr pointer. 498struct ReplayWithoutInlining{}; 499template <> 500struct ProgramStateTrait<ReplayWithoutInlining> : 501 public ProgramStatePartialTrait<void*> { 502 static void *GDMIndex() { static int index = 0; return &index; } 503}; 504 505} // end ento namespace 506 507} // end clang namespace 508 509#endif 510