CoreEngine.h revision a19f4af7a94835ce4693bfe12d6270754e79eb56
1//==- CoreEngine.h - Path-Sensitive Dataflow Engine ----------------*- 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 generic engine for intraprocedural, path-sensitive, 11// dataflow analysis via graph reachability. 12// 13//===----------------------------------------------------------------------===// 14 15#ifndef LLVM_CLANG_GR_COREENGINE 16#define LLVM_CLANG_GR_COREENGINE 17 18#include "clang/AST/Expr.h" 19#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h" 20#include "clang/StaticAnalyzer/Core/PathSensitive/WorkList.h" 21#include "clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h" 22#include "llvm/ADT/OwningPtr.h" 23 24namespace clang { 25 26class ProgramPointTag; 27 28namespace ento { 29 30class NodeBuilder; 31 32//===----------------------------------------------------------------------===// 33/// CoreEngine - Implements the core logic of the graph-reachability 34/// analysis. It traverses the CFG and generates the ExplodedGraph. 35/// Program "states" are treated as opaque void pointers. 36/// The template class CoreEngine (which subclasses CoreEngine) 37/// provides the matching component to the engine that knows the actual types 38/// for states. Note that this engine only dispatches to transfer functions 39/// at the statement and block-level. The analyses themselves must implement 40/// any transfer function logic and the sub-expression level (if any). 41class CoreEngine { 42 friend class CommonNodeBuilder; 43 friend class NodeBuilder; 44 friend class StmtNodeBuilder; 45 friend class GenericNodeBuilderImpl; 46 friend class BranchNodeBuilder; 47 friend class IndirectGotoNodeBuilder; 48 friend class SwitchNodeBuilder; 49 friend class EndOfFunctionNodeBuilder; 50 friend class CallEnterNodeBuilder; 51 friend class CallExitNodeBuilder; 52 53public: 54 typedef std::vector<std::pair<BlockEdge, const ExplodedNode*> > 55 BlocksExhausted; 56 57 typedef std::vector<std::pair<const CFGBlock*, const ExplodedNode*> > 58 BlocksAborted; 59 60private: 61 62 SubEngine& SubEng; 63 64 /// G - The simulation graph. Each node is a (location,state) pair. 65 llvm::OwningPtr<ExplodedGraph> G; 66 67 /// WList - A set of queued nodes that need to be processed by the 68 /// worklist algorithm. It is up to the implementation of WList to decide 69 /// the order that nodes are processed. 70 WorkList* WList; 71 72 /// BCounterFactory - A factory object for created BlockCounter objects. 73 /// These are used to record for key nodes in the ExplodedGraph the 74 /// number of times different CFGBlocks have been visited along a path. 75 BlockCounter::Factory BCounterFactory; 76 77 /// The locations where we stopped doing work because we visited a location 78 /// too many times. 79 BlocksExhausted blocksExhausted; 80 81 /// The locations where we stopped because the engine aborted analysis, 82 /// usually because it could not reason about something. 83 BlocksAborted blocksAborted; 84 85 void generateNode(const ProgramPoint &Loc, 86 const ProgramState *State, 87 ExplodedNode *Pred); 88 89 void HandleBlockEdge(const BlockEdge &E, ExplodedNode *Pred); 90 void HandleBlockEntrance(const BlockEntrance &E, ExplodedNode *Pred); 91 void HandleBlockExit(const CFGBlock *B, ExplodedNode *Pred); 92 void HandlePostStmt(const CFGBlock *B, unsigned StmtIdx, ExplodedNode *Pred); 93 94 void HandleBranch(const Stmt *Cond, const Stmt *Term, const CFGBlock *B, 95 ExplodedNode *Pred); 96 void HandleCallEnter(const CallEnter &L, const CFGBlock *Block, 97 unsigned Index, ExplodedNode *Pred); 98 void HandleCallExit(const CallExit &L, ExplodedNode *Pred); 99 100private: 101 CoreEngine(const CoreEngine&); // Do not implement. 102 CoreEngine& operator=(const CoreEngine&); 103 104public: 105 /// Construct a CoreEngine object to analyze the provided CFG using 106 /// a DFS exploration of the exploded graph. 107 CoreEngine(SubEngine& subengine) 108 : SubEng(subengine), G(new ExplodedGraph()), 109 WList(WorkList::makeBFS()), 110 BCounterFactory(G->getAllocator()) {} 111 112 /// Construct a CoreEngine object to analyze the provided CFG and to 113 /// use the provided worklist object to execute the worklist algorithm. 114 /// The CoreEngine object assumes ownership of 'wlist'. 115 CoreEngine(WorkList* wlist, SubEngine& subengine) 116 : SubEng(subengine), G(new ExplodedGraph()), WList(wlist), 117 BCounterFactory(G->getAllocator()) {} 118 119 ~CoreEngine() { 120 delete WList; 121 } 122 123 /// getGraph - Returns the exploded graph. 124 ExplodedGraph& getGraph() { return *G.get(); } 125 126 /// takeGraph - Returns the exploded graph. Ownership of the graph is 127 /// transferred to the caller. 128 ExplodedGraph* takeGraph() { return G.take(); } 129 130 /// ExecuteWorkList - Run the worklist algorithm for a maximum number of 131 /// steps. Returns true if there is still simulation state on the worklist. 132 bool ExecuteWorkList(const LocationContext *L, unsigned Steps, 133 const ProgramState *InitState); 134 void ExecuteWorkListWithInitialState(const LocationContext *L, 135 unsigned Steps, 136 const ProgramState *InitState, 137 ExplodedNodeSet &Dst); 138 139 // Functions for external checking of whether we have unfinished work 140 bool wasBlockAborted() const { return !blocksAborted.empty(); } 141 bool wasBlocksExhausted() const { return !blocksExhausted.empty(); } 142 bool hasWorkRemaining() const { return wasBlocksExhausted() || 143 WList->hasWork() || 144 wasBlockAborted(); } 145 146 /// Inform the CoreEngine that a basic block was aborted because 147 /// it could not be completely analyzed. 148 void addAbortedBlock(const ExplodedNode *node, const CFGBlock *block) { 149 blocksAborted.push_back(std::make_pair(block, node)); 150 } 151 152 WorkList *getWorkList() const { return WList; } 153 154 BlocksExhausted::const_iterator blocks_exhausted_begin() const { 155 return blocksExhausted.begin(); 156 } 157 BlocksExhausted::const_iterator blocks_exhausted_end() const { 158 return blocksExhausted.end(); 159 } 160 BlocksAborted::const_iterator blocks_aborted_begin() const { 161 return blocksAborted.begin(); 162 } 163 BlocksAborted::const_iterator blocks_aborted_end() const { 164 return blocksAborted.end(); 165 } 166 167 /// Enqueue the results of the node builder onto the work list. 168 void enqueue(NodeBuilder &NB); 169}; 170 171struct NodeBuilderContext { 172 CoreEngine &Eng; 173 ExplodedNode *Pred; 174 const CFGBlock *Block; 175 NodeBuilderContext(CoreEngine &E, ExplodedNode *N, const CFGBlock *B) 176 : Eng(E), Pred(N), Block(B) { assert(B); assert(!N->isSink()); } 177}; 178 179/// This is the simplest builder which generates nodes in the ExplodedGraph. 180class NodeBuilder { 181protected: 182 friend class StmtNodeBuilder; 183 184 NodeBuilderContext &C; 185 bool Finalized; 186 187 /// \brief The frontier set - a set of nodes which need to be propagated after 188 /// the builder dies. 189 typedef llvm::SmallPtrSet<ExplodedNode*,5> DeferredTy; 190 DeferredTy Deferred; 191 192 BlockCounter getBlockCounter() const { return C.Eng.WList->getBlockCounter();} 193 194 bool checkResults() { 195 if (!Finalized) 196 return false; 197 for (DeferredTy::iterator I=Deferred.begin(), E=Deferred.end(); I!=E; ++I) 198 if ((*I)->isSink()) 199 return false; 200 return true; 201 } 202 203 virtual void finalizeResults() { 204 if (!Finalized) { 205 Finalized = true; 206 } 207 } 208 209 ExplodedNode *generateNodeImpl(const ProgramPoint &PP, 210 const ProgramState *State, 211 ExplodedNode *Pred, 212 bool MarkAsSink = false); 213 214public: 215 NodeBuilder(NodeBuilderContext &Ctx) 216 : C(Ctx), Finalized(false) { Deferred.insert(C.Pred); } 217 218 virtual ~NodeBuilder() {} 219 220 /// \brief Generates a node in the ExplodedGraph. 221 /// 222 /// When a node is marked as sink, the exploration from the node is stopped - 223 /// the node becomes the last node on the path. 224 ExplodedNode *generateNode(const ProgramPoint &PP, 225 const ProgramState *State, 226 ExplodedNode *Pred, 227 bool MarkAsSink = false) { 228 return generateNodeImpl(PP, State, Pred, MarkAsSink); 229 } 230 231 // \brief Get the builder's predecessor - the parent to all the other nodes. 232 const ExplodedNode *getPred() const { return C.Pred; } 233 234 bool hasGeneratedNodes() const { 235 return (!Deferred.count(C.Pred)); 236 } 237 238 typedef DeferredTy::iterator iterator; 239 /// \brief Iterators through the results frontier. 240 inline iterator results_begin() { 241 finalizeResults(); 242 assert(checkResults()); 243 return Deferred.begin(); 244 } 245 inline iterator results_end() { 246 finalizeResults(); 247 return Deferred.end(); 248 } 249 250 /// \brief Returns the number of times the current basic block has been 251 /// visited on the exploded graph path. 252 unsigned getCurrentBlockCount() const { 253 return getBlockCounter().getNumVisited( 254 C.Pred->getLocationContext()->getCurrentStackFrame(), 255 C.Block->getBlockID()); 256 } 257 258 ExplodedNode *getPredecessor() const { return C.Pred; } 259}; 260 261class CommonNodeBuilder { 262protected: 263 ExplodedNode *Pred; 264public: 265 // TODO: make protected. 266 CoreEngine& Eng; 267 268 CommonNodeBuilder(CoreEngine* E, ExplodedNode *P) : Pred(P), Eng(*E) {} 269 BlockCounter getBlockCounter() const { return Eng.WList->getBlockCounter(); } 270}; 271 272 273class StmtNodeBuilder: public CommonNodeBuilder { 274 const CFGBlock &B; 275 const unsigned Idx; 276 277public: 278 bool PurgingDeadSymbols; 279 bool BuildSinks; 280 bool hasGeneratedNode; 281 ProgramPoint::Kind PointKind; 282 const ProgramPointTag *Tag; 283 284 typedef llvm::SmallPtrSet<ExplodedNode*,5> DeferredTy; 285 DeferredTy Deferred; 286 287 void GenerateAutoTransition(ExplodedNode *N); 288 289public: 290 StmtNodeBuilder(const CFGBlock *b, 291 unsigned idx, 292 ExplodedNode *N, 293 CoreEngine* e); 294 295 ~StmtNodeBuilder(); 296 297 ExplodedNode *getPredecessor() const { return Pred; } 298 299 unsigned getCurrentBlockCount() const { 300 return getBlockCounter().getNumVisited( 301 Pred->getLocationContext()->getCurrentStackFrame(), 302 B.getBlockID()); 303 } 304 305 ExplodedNode *generateNode(const Stmt *S, 306 const ProgramState *St, 307 ExplodedNode *Pred, 308 ProgramPoint::Kind K, 309 const ProgramPointTag *tag = 0) { 310 hasGeneratedNode = true; 311 312 if (PurgingDeadSymbols) 313 K = ProgramPoint::PostPurgeDeadSymbolsKind; 314 315 return generateNodeInternal(S, St, Pred, K, tag ? tag : Tag); 316 } 317 318 ExplodedNode *generateNode(const Stmt *S, 319 const ProgramState *St, 320 ExplodedNode *Pred, 321 const ProgramPointTag *tag = 0) { 322 return generateNode(S, St, Pred, PointKind, tag); 323 } 324 325 ExplodedNode *generateNode(const ProgramPoint &PP, 326 const ProgramState *State, 327 ExplodedNode *Pred) { 328 hasGeneratedNode = true; 329 return generateNodeInternal(PP, State, Pred); 330 } 331 332 ExplodedNode* 333 generateNodeInternal(const ProgramPoint &PP, 334 const ProgramState *State, 335 ExplodedNode *Pred); 336 337 ExplodedNode* 338 generateNodeInternal(const Stmt *S, 339 const ProgramState *State, 340 ExplodedNode *Pred, 341 ProgramPoint::Kind K, 342 const ProgramPointTag *tag = 0); 343 344 /// getStmt - Return the current block-level expression associated with 345 /// this builder. 346 const Stmt *getStmt() const { 347 const CFGStmt *CS = B[Idx].getAs<CFGStmt>(); 348 return CS ? CS->getStmt() : 0; 349 } 350 351 /// getBlock - Return the CFGBlock associated with the block-level expression 352 /// of this builder. 353 const CFGBlock *getBlock() const { return &B; } 354 355 unsigned getIndex() const { return Idx; } 356 357 ExplodedNode *MakeNode(ExplodedNodeSet &Dst, 358 const Stmt *S, 359 ExplodedNode *Pred, 360 const ProgramState *St) { 361 return MakeNode(Dst, S, Pred, St, PointKind); 362 } 363 364 ExplodedNode *MakeNode(ExplodedNodeSet &Dst, 365 const Stmt *S, 366 ExplodedNode *Pred, 367 const ProgramState *St, 368 ProgramPoint::Kind K); 369 370 ExplodedNode *MakeSinkNode(ExplodedNodeSet &Dst, 371 const Stmt *S, 372 ExplodedNode *Pred, 373 const ProgramState *St) { 374 bool Tmp = BuildSinks; 375 BuildSinks = true; 376 ExplodedNode *N = MakeNode(Dst, S, Pred, St); 377 BuildSinks = Tmp; 378 return N; 379 } 380 381 void importNodesFromBuilder(const NodeBuilder &NB) { 382 ExplodedNode *NBPred = const_cast<ExplodedNode*>(NB.getPred()); 383 if (NB.hasGeneratedNodes()) { 384 Deferred.erase(NBPred); 385 Deferred.insert(NB.Deferred.begin(), NB.Deferred.end()); 386 hasGeneratedNode = true; 387 } 388 } 389}; 390 391class BranchNodeBuilder: public NodeBuilder { 392 const CFGBlock *DstT; 393 const CFGBlock *DstF; 394 395 bool GeneratedTrue; 396 bool GeneratedFalse; 397 bool InFeasibleTrue; 398 bool InFeasibleFalse; 399 400 void finalizeResults() { 401 if (Finalized) 402 return; 403 if (!GeneratedTrue) generateNode(C.Pred->State, true); 404 if (!GeneratedFalse) generateNode(C.Pred->State, false); 405 Finalized = true; 406 } 407 408public: 409 BranchNodeBuilder(NodeBuilderContext &C, const CFGBlock *dstT, 410 const CFGBlock *dstF) 411 : NodeBuilder(C), DstT(dstT), DstF(dstF), 412 GeneratedTrue(false), GeneratedFalse(false), 413 InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) { 414 } 415 416 /// This function generate a new ExplodedNode but not a new 417 /// branch(block edge). Creates a transition from the Builder's top 418 /// predecessor. 419 ExplodedNode *generateNode(const Stmt *Condition, const ProgramState *State, 420 const ProgramPointTag *Tag = 0, 421 bool MarkAsSink = false); 422 423 ExplodedNode *generateNode(const ProgramState *State, bool branch, 424 ExplodedNode *Pred = 0); 425 426 const CFGBlock *getTargetBlock(bool branch) const { 427 return branch ? DstT : DstF; 428 } 429 430 void markInfeasible(bool branch) { 431 if (branch) 432 InFeasibleTrue = GeneratedTrue = true; 433 else 434 InFeasibleFalse = GeneratedFalse = true; 435 } 436 437 bool isFeasible(bool branch) { 438 return branch ? !InFeasibleTrue : !InFeasibleFalse; 439 } 440 441 const ProgramState *getState() const { 442 return getPredecessor()->getState(); 443 } 444}; 445 446class IndirectGotoNodeBuilder { 447 CoreEngine& Eng; 448 const CFGBlock *Src; 449 const CFGBlock &DispatchBlock; 450 const Expr *E; 451 ExplodedNode *Pred; 452 453public: 454 IndirectGotoNodeBuilder(ExplodedNode *pred, const CFGBlock *src, 455 const Expr *e, const CFGBlock *dispatch, CoreEngine* eng) 456 : Eng(*eng), Src(src), DispatchBlock(*dispatch), E(e), Pred(pred) {} 457 458 class iterator { 459 CFGBlock::const_succ_iterator I; 460 461 friend class IndirectGotoNodeBuilder; 462 iterator(CFGBlock::const_succ_iterator i) : I(i) {} 463 public: 464 465 iterator &operator++() { ++I; return *this; } 466 bool operator!=(const iterator &X) const { return I != X.I; } 467 468 const LabelDecl *getLabel() const { 469 return llvm::cast<LabelStmt>((*I)->getLabel())->getDecl(); 470 } 471 472 const CFGBlock *getBlock() const { 473 return *I; 474 } 475 }; 476 477 iterator begin() { return iterator(DispatchBlock.succ_begin()); } 478 iterator end() { return iterator(DispatchBlock.succ_end()); } 479 480 ExplodedNode *generateNode(const iterator &I, 481 const ProgramState *State, 482 bool isSink = false); 483 484 const Expr *getTarget() const { return E; } 485 486 const ProgramState *getState() const { return Pred->State; } 487}; 488 489class SwitchNodeBuilder { 490 CoreEngine& Eng; 491 const CFGBlock *Src; 492 const Expr *Condition; 493 ExplodedNode *Pred; 494 495public: 496 SwitchNodeBuilder(ExplodedNode *pred, const CFGBlock *src, 497 const Expr *condition, CoreEngine* eng) 498 : Eng(*eng), Src(src), Condition(condition), Pred(pred) {} 499 500 class iterator { 501 CFGBlock::const_succ_reverse_iterator I; 502 503 friend class SwitchNodeBuilder; 504 iterator(CFGBlock::const_succ_reverse_iterator i) : I(i) {} 505 506 public: 507 iterator &operator++() { ++I; return *this; } 508 bool operator!=(const iterator &X) const { return I != X.I; } 509 bool operator==(const iterator &X) const { return I == X.I; } 510 511 const CaseStmt *getCase() const { 512 return llvm::cast<CaseStmt>((*I)->getLabel()); 513 } 514 515 const CFGBlock *getBlock() const { 516 return *I; 517 } 518 }; 519 520 iterator begin() { return iterator(Src->succ_rbegin()+1); } 521 iterator end() { return iterator(Src->succ_rend()); } 522 523 const SwitchStmt *getSwitch() const { 524 return llvm::cast<SwitchStmt>(Src->getTerminator()); 525 } 526 527 ExplodedNode *generateCaseStmtNode(const iterator &I, 528 const ProgramState *State); 529 530 ExplodedNode *generateDefaultCaseNode(const ProgramState *State, 531 bool isSink = false); 532 533 const Expr *getCondition() const { return Condition; } 534 535 const ProgramState *getState() const { return Pred->State; } 536}; 537 538class GenericNodeBuilderImpl { 539protected: 540 CoreEngine &engine; 541 ExplodedNode *pred; 542 ProgramPoint pp; 543 SmallVector<ExplodedNode*, 2> sinksGenerated; 544 545 ExplodedNode *generateNodeImpl(const ProgramState *state, 546 ExplodedNode *pred, 547 ProgramPoint programPoint, 548 bool asSink); 549 550 GenericNodeBuilderImpl(CoreEngine &eng, ExplodedNode *pr, ProgramPoint p) 551 : engine(eng), pred(pr), pp(p), hasGeneratedNode(false) {} 552 553public: 554 bool hasGeneratedNode; 555 556 WorkList &getWorkList() { return *engine.WList; } 557 558 ExplodedNode *getPredecessor() const { return pred; } 559 560 BlockCounter getBlockCounter() const { 561 return engine.WList->getBlockCounter(); 562 } 563 564 const SmallVectorImpl<ExplodedNode*> &sinks() const { 565 return sinksGenerated; 566 } 567}; 568 569template <typename PP_T> 570class GenericNodeBuilder : public GenericNodeBuilderImpl { 571public: 572 GenericNodeBuilder(CoreEngine &eng, ExplodedNode *pr, const PP_T &p) 573 : GenericNodeBuilderImpl(eng, pr, p) {} 574 575 ExplodedNode *generateNode(const ProgramState *state, ExplodedNode *pred, 576 const ProgramPointTag *tag, bool asSink) { 577 return generateNodeImpl(state, pred, cast<PP_T>(pp).withTag(tag), 578 asSink); 579 } 580 581 const PP_T &getProgramPoint() const { return cast<PP_T>(pp); } 582}; 583 584class EndOfFunctionNodeBuilder : public CommonNodeBuilder { 585 const CFGBlock &B; 586 const ProgramPointTag *Tag; 587 588public: 589 bool hasGeneratedNode; 590 591public: 592 EndOfFunctionNodeBuilder(const CFGBlock *b, ExplodedNode *N, CoreEngine* e, 593 const ProgramPointTag *tag = 0) 594 : CommonNodeBuilder(e, N), B(*b), Tag(tag), hasGeneratedNode(false) {} 595 596 ~EndOfFunctionNodeBuilder(); 597 598 EndOfFunctionNodeBuilder withCheckerTag(const ProgramPointTag *tag) { 599 return EndOfFunctionNodeBuilder(&B, Pred, &Eng, tag); 600 } 601 602 WorkList &getWorkList() { return *Eng.WList; } 603 604 ExplodedNode *getPredecessor() const { return Pred; } 605 606 unsigned getCurrentBlockCount() const { 607 return getBlockCounter().getNumVisited( 608 Pred->getLocationContext()->getCurrentStackFrame(), 609 B.getBlockID()); 610 } 611 612 ExplodedNode *generateNode(const ProgramState *State, 613 ExplodedNode *P = 0, 614 const ProgramPointTag *tag = 0); 615 616 void GenerateCallExitNode(const ProgramState *state); 617 618 const CFGBlock *getBlock() const { return &B; } 619 620 const ProgramState *getState() const { 621 return getPredecessor()->getState(); 622 } 623}; 624 625class CallEnterNodeBuilder { 626 CoreEngine &Eng; 627 628 const ExplodedNode *Pred; 629 630 // The call site. For implicit automatic object dtor, this is the trigger 631 // statement. 632 const Stmt *CE; 633 634 // The context of the callee. 635 const StackFrameContext *CalleeCtx; 636 637 // The parent block of the CallExpr. 638 const CFGBlock *Block; 639 640 // The CFGBlock index of the CallExpr. 641 unsigned Index; 642 643public: 644 CallEnterNodeBuilder(CoreEngine &eng, const ExplodedNode *pred, 645 const Stmt *s, const StackFrameContext *callee, 646 const CFGBlock *blk, unsigned idx) 647 : Eng(eng), Pred(pred), CE(s), CalleeCtx(callee), Block(blk), Index(idx) {} 648 649 const ProgramState *getState() const { return Pred->getState(); } 650 651 const LocationContext *getLocationContext() const { 652 return Pred->getLocationContext(); 653 } 654 655 const Stmt *getCallExpr() const { return CE; } 656 657 const StackFrameContext *getCalleeContext() const { return CalleeCtx; } 658 659 const CFGBlock *getBlock() const { return Block; } 660 661 unsigned getIndex() const { return Index; } 662 663 void generateNode(const ProgramState *state); 664}; 665 666class CallExitNodeBuilder { 667 CoreEngine &Eng; 668 const ExplodedNode *Pred; 669 670public: 671 CallExitNodeBuilder(CoreEngine &eng, const ExplodedNode *pred) 672 : Eng(eng), Pred(pred) {} 673 674 const ExplodedNode *getPredecessor() const { return Pred; } 675 676 const ProgramState *getState() const { return Pred->getState(); } 677 678 void generateNode(const ProgramState *state); 679}; 680 681} // end GR namespace 682 683} // end clang namespace 684 685#endif 686