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