CoreEngine.h revision 3152b3cb5b6a2f797d0972c81a5eb3fd69c0d620
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 const CFGBlock *Block; 174 NodeBuilderContext(CoreEngine &E, const CFGBlock *B) 175 : Eng(E), Block(B) { assert(B); } 176}; 177 178/// This is the simplest builder which generates nodes in the ExplodedGraph. 179class NodeBuilder { 180protected: 181 friend class StmtNodeBuilder; 182 183 ExplodedNode *BuilderPred; 184 185// TODO: Context should become protected after refactoring is done. 186public: 187 const NodeBuilderContext &C; 188protected: 189 190 /// Specifies if the builder results have been finalized. For example, if it 191 /// is set to false, autotransitions are yet to be generated. 192 bool Finalized; 193 194 /// \brief The frontier set - a set of nodes which need to be propagated after 195 /// the builder dies. 196 typedef llvm::SmallPtrSet<ExplodedNode*,5> DeferredTy; 197 DeferredTy Deferred; 198 199 BlockCounter getBlockCounter() const { return C.Eng.WList->getBlockCounter();} 200 201 /// Checkes if the results are ready. 202 virtual bool checkResults() { 203 if (!Finalized) 204 return false; 205 for (DeferredTy::iterator I=Deferred.begin(), E=Deferred.end(); I!=E; ++I) 206 if ((*I)->isSink()) 207 return false; 208 return true; 209 } 210 211 /// Allow subclasses to finalize results before result_begin() is executed. 212 virtual void finalizeResults() {} 213 214 ExplodedNode *generateNodeImpl(const ProgramPoint &PP, 215 const ProgramState *State, 216 ExplodedNode *Pred, 217 bool MarkAsSink = false); 218 219public: 220 NodeBuilder(ExplodedNode *N, NodeBuilderContext &Ctx, bool F = true) 221 : BuilderPred(N), C(Ctx), Finalized(F) { 222 assert(!N->isSink()); 223 Deferred.insert(N); 224 } 225 226 /// Create a new builder using the parent builder's context. 227 NodeBuilder(ExplodedNode *N, const NodeBuilder &ParentBldr, bool F = true) 228 : BuilderPred(N), C(ParentBldr.C), Finalized(F) { 229 assert(!N->isSink()); 230 Deferred.insert(N); 231 } 232 233 virtual ~NodeBuilder() {} 234 235 /// \brief Generates a node in the ExplodedGraph. 236 /// 237 /// When a node is marked as sink, the exploration from the node is stopped - 238 /// the node becomes the last node on the path. 239 ExplodedNode *generateNode(const ProgramPoint &PP, 240 const ProgramState *State, 241 ExplodedNode *Pred, 242 bool MarkAsSink = false) { 243 return generateNodeImpl(PP, State, Pred, MarkAsSink); 244 } 245 246 bool hasGeneratedNodes() const { 247 return (!Deferred.count(BuilderPred)); 248 } 249 250 typedef DeferredTy::iterator iterator; 251 /// \brief Iterators through the results frontier. 252 inline iterator results_begin() { 253 finalizeResults(); 254 assert(checkResults()); 255 return Deferred.begin(); 256 } 257 inline iterator results_end() { 258 finalizeResults(); 259 return Deferred.end(); 260 } 261 262 /// \brief Return the CFGBlock associated with this builder. 263 const CFGBlock *getBlock() const { return C.Block; } 264 265 /// \brief Returns the number of times the current basic block has been 266 /// visited on the exploded graph path. 267 unsigned getCurrentBlockCount() const { 268 return getBlockCounter().getNumVisited( 269 BuilderPred->getLocationContext()->getCurrentStackFrame(), 270 C.Block->getBlockID()); 271 } 272 273 // \brief Get the builder's predecessor - the parent to all the other nodes. 274 ExplodedNode *getPredecessor() const { return BuilderPred; } 275 276 // \brief Returns state of the predecessor. 277 const ProgramState *getState() const { return BuilderPred->getState(); } 278}; 279 280class CommonNodeBuilder { 281protected: 282 ExplodedNode *Pred; 283 CoreEngine& Eng; 284 285 CommonNodeBuilder(CoreEngine* E, ExplodedNode *P) : Pred(P), Eng(*E) {} 286 BlockCounter getBlockCounter() const { return Eng.WList->getBlockCounter(); } 287}; 288 289 290class StmtNodeBuilder: public NodeBuilder { 291 const unsigned Idx; 292 293public: 294 bool PurgingDeadSymbols; 295 bool BuildSinks; 296 // TODO: Remove the flag. We should be able to use the method in the parent. 297 bool hasGeneratedNode; 298 ProgramPoint::Kind PointKind; 299 const ProgramPointTag *Tag; 300 301 void GenerateAutoTransition(ExplodedNode *N); 302 303public: 304 StmtNodeBuilder(ExplodedNode *N, unsigned idx, NodeBuilderContext &Ctx); 305 306 ~StmtNodeBuilder(); 307 308 ExplodedNode *generateNode(const Stmt *S, 309 const ProgramState *St, 310 ExplodedNode *Pred, 311 ProgramPoint::Kind K, 312 const ProgramPointTag *tag = 0, 313 bool MarkAsSink = false) { 314 if (PurgingDeadSymbols) 315 K = ProgramPoint::PostPurgeDeadSymbolsKind; 316 317 const ProgramPoint &L = ProgramPoint::getProgramPoint(S, K, 318 Pred->getLocationContext(), tag ? tag : Tag); 319 return generateNodeImpl(L, St, Pred, MarkAsSink); 320 } 321 322 ExplodedNode *generateNode(const Stmt *S, 323 const ProgramState *St, 324 ExplodedNode *Pred, 325 const ProgramPointTag *tag = 0) { 326 return generateNode(S, St, Pred, PointKind, tag); 327 } 328 329 ExplodedNode *generateNode(const ProgramPoint &PP, 330 const ProgramState *State, 331 ExplodedNode *Pred) { 332 return generateNodeImpl(PP, State, Pred, false); 333 } 334 335 /// getStmt - Return the current block-level expression associated with 336 /// this builder. 337 const Stmt *getStmt() const { 338 const CFGStmt *CS = (*C.Block)[Idx].getAs<CFGStmt>(); 339 return CS ? CS->getStmt() : 0; 340 } 341 342 unsigned getIndex() const { return Idx; } 343 344 ExplodedNode *MakeNode(ExplodedNodeSet &Dst, 345 const Stmt *S, 346 ExplodedNode *Pred, 347 const ProgramState *St) { 348 return MakeNode(Dst, S, Pred, St, PointKind); 349 } 350 351 ExplodedNode *MakeNode(ExplodedNodeSet &Dst, 352 const Stmt *S, 353 ExplodedNode *Pred, 354 const ProgramState *St, 355 ProgramPoint::Kind K); 356 357 ExplodedNode *MakeSinkNode(ExplodedNodeSet &Dst, 358 const Stmt *S, 359 ExplodedNode *Pred, 360 const ProgramState *St) { 361 bool Tmp = BuildSinks; 362 BuildSinks = true; 363 ExplodedNode *N = MakeNode(Dst, S, Pred, St); 364 BuildSinks = Tmp; 365 return N; 366 } 367 368 void importNodesFromBuilder(const NodeBuilder &NB) { 369 ExplodedNode *NBPred = const_cast<ExplodedNode*>(NB.getPredecessor()); 370 if (NB.hasGeneratedNodes()) { 371 Deferred.erase(NBPred); 372 Deferred.insert(NB.Deferred.begin(), NB.Deferred.end()); 373 } 374 } 375}; 376 377class BranchNodeBuilder: public NodeBuilder { 378 const CFGBlock *DstT; 379 const CFGBlock *DstF; 380 381 bool GeneratedTrue; 382 bool GeneratedFalse; 383 bool InFeasibleTrue; 384 bool InFeasibleFalse; 385 386 /// Generate default branching transitions of none were generated or 387 /// suppressed. 388 void finalizeResults() { 389 if (Finalized) 390 return; 391 if (!GeneratedTrue) generateNode(BuilderPred->State, true); 392 if (!GeneratedFalse) generateNode(BuilderPred->State, false); 393 Finalized = true; 394 } 395 396public: 397 BranchNodeBuilder(ExplodedNode *Pred, NodeBuilderContext &C, 398 const CFGBlock *dstT, const CFGBlock *dstF) 399 : NodeBuilder(Pred, C, false), DstT(dstT), DstF(dstF), 400 GeneratedTrue(false), GeneratedFalse(false), 401 InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) { 402 } 403 404 /// Create a new builder using the parent builder's context. 405 BranchNodeBuilder(ExplodedNode *Pred, BranchNodeBuilder &ParentBldr) 406 : NodeBuilder(Pred, ParentBldr, false), DstT(ParentBldr.DstT), 407 DstF(ParentBldr.DstF), GeneratedTrue(false), GeneratedFalse(false), 408 InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) { 409 } 410 411 ExplodedNode *generateNode(const ProgramState *State, bool branch, 412 ExplodedNode *Pred = 0); 413 414 const CFGBlock *getTargetBlock(bool branch) const { 415 return branch ? DstT : DstF; 416 } 417 418 void markInfeasible(bool branch) { 419 if (branch) 420 InFeasibleTrue = GeneratedTrue = true; 421 else 422 InFeasibleFalse = GeneratedFalse = true; 423 } 424 425 bool isFeasible(bool branch) { 426 return branch ? !InFeasibleTrue : !InFeasibleFalse; 427 } 428}; 429 430class IndirectGotoNodeBuilder { 431 CoreEngine& Eng; 432 const CFGBlock *Src; 433 const CFGBlock &DispatchBlock; 434 const Expr *E; 435 ExplodedNode *Pred; 436 437public: 438 IndirectGotoNodeBuilder(ExplodedNode *pred, const CFGBlock *src, 439 const Expr *e, const CFGBlock *dispatch, CoreEngine* eng) 440 : Eng(*eng), Src(src), DispatchBlock(*dispatch), E(e), Pred(pred) {} 441 442 class iterator { 443 CFGBlock::const_succ_iterator I; 444 445 friend class IndirectGotoNodeBuilder; 446 iterator(CFGBlock::const_succ_iterator i) : I(i) {} 447 public: 448 449 iterator &operator++() { ++I; return *this; } 450 bool operator!=(const iterator &X) const { return I != X.I; } 451 452 const LabelDecl *getLabel() const { 453 return llvm::cast<LabelStmt>((*I)->getLabel())->getDecl(); 454 } 455 456 const CFGBlock *getBlock() const { 457 return *I; 458 } 459 }; 460 461 iterator begin() { return iterator(DispatchBlock.succ_begin()); } 462 iterator end() { return iterator(DispatchBlock.succ_end()); } 463 464 ExplodedNode *generateNode(const iterator &I, 465 const ProgramState *State, 466 bool isSink = false); 467 468 const Expr *getTarget() const { return E; } 469 470 const ProgramState *getState() const { return Pred->State; } 471}; 472 473class SwitchNodeBuilder { 474 CoreEngine& Eng; 475 const CFGBlock *Src; 476 const Expr *Condition; 477 ExplodedNode *Pred; 478 479public: 480 SwitchNodeBuilder(ExplodedNode *pred, const CFGBlock *src, 481 const Expr *condition, CoreEngine* eng) 482 : Eng(*eng), Src(src), Condition(condition), Pred(pred) {} 483 484 class iterator { 485 CFGBlock::const_succ_reverse_iterator I; 486 487 friend class SwitchNodeBuilder; 488 iterator(CFGBlock::const_succ_reverse_iterator i) : I(i) {} 489 490 public: 491 iterator &operator++() { ++I; return *this; } 492 bool operator!=(const iterator &X) const { return I != X.I; } 493 bool operator==(const iterator &X) const { return I == X.I; } 494 495 const CaseStmt *getCase() const { 496 return llvm::cast<CaseStmt>((*I)->getLabel()); 497 } 498 499 const CFGBlock *getBlock() const { 500 return *I; 501 } 502 }; 503 504 iterator begin() { return iterator(Src->succ_rbegin()+1); } 505 iterator end() { return iterator(Src->succ_rend()); } 506 507 const SwitchStmt *getSwitch() const { 508 return llvm::cast<SwitchStmt>(Src->getTerminator()); 509 } 510 511 ExplodedNode *generateCaseStmtNode(const iterator &I, 512 const ProgramState *State); 513 514 ExplodedNode *generateDefaultCaseNode(const ProgramState *State, 515 bool isSink = false); 516 517 const Expr *getCondition() const { return Condition; } 518 519 const ProgramState *getState() const { return Pred->State; } 520}; 521 522class GenericNodeBuilderImpl { 523protected: 524 CoreEngine &engine; 525 ExplodedNode *pred; 526 ProgramPoint pp; 527 SmallVector<ExplodedNode*, 2> sinksGenerated; 528 529 ExplodedNode *generateNodeImpl(const ProgramState *state, 530 ExplodedNode *pred, 531 ProgramPoint programPoint, 532 bool asSink); 533 534 GenericNodeBuilderImpl(CoreEngine &eng, ExplodedNode *pr, ProgramPoint p) 535 : engine(eng), pred(pr), pp(p), hasGeneratedNode(false) {} 536 537public: 538 bool hasGeneratedNode; 539 540 WorkList &getWorkList() { return *engine.WList; } 541 542 ExplodedNode *getPredecessor() const { return pred; } 543 544 BlockCounter getBlockCounter() const { 545 return engine.WList->getBlockCounter(); 546 } 547 548 const SmallVectorImpl<ExplodedNode*> &sinks() const { 549 return sinksGenerated; 550 } 551}; 552 553template <typename PP_T> 554class GenericNodeBuilder : public GenericNodeBuilderImpl { 555public: 556 GenericNodeBuilder(CoreEngine &eng, ExplodedNode *pr, const PP_T &p) 557 : GenericNodeBuilderImpl(eng, pr, p) {} 558 559 ExplodedNode *generateNode(const ProgramState *state, ExplodedNode *pred, 560 const ProgramPointTag *tag, bool asSink) { 561 return generateNodeImpl(state, pred, cast<PP_T>(pp).withTag(tag), 562 asSink); 563 } 564 565 const PP_T &getProgramPoint() const { return cast<PP_T>(pp); } 566}; 567 568class EndOfFunctionNodeBuilder : public CommonNodeBuilder { 569 const CFGBlock &B; 570 const ProgramPointTag *Tag; 571 572public: 573 bool hasGeneratedNode; 574 575public: 576 EndOfFunctionNodeBuilder(const CFGBlock *b, ExplodedNode *N, CoreEngine* e, 577 const ProgramPointTag *tag = 0) 578 : CommonNodeBuilder(e, N), B(*b), Tag(tag), hasGeneratedNode(false) {} 579 580 ~EndOfFunctionNodeBuilder(); 581 582 EndOfFunctionNodeBuilder withCheckerTag(const ProgramPointTag *tag) { 583 return EndOfFunctionNodeBuilder(&B, Pred, &Eng, tag); 584 } 585 586 WorkList &getWorkList() { return *Eng.WList; } 587 588 ExplodedNode *getPredecessor() const { return Pred; } 589 590 unsigned getCurrentBlockCount() const { 591 return getBlockCounter().getNumVisited( 592 Pred->getLocationContext()->getCurrentStackFrame(), 593 B.getBlockID()); 594 } 595 596 ExplodedNode *generateNode(const ProgramState *State, 597 ExplodedNode *P = 0, 598 const ProgramPointTag *tag = 0); 599 600 void GenerateCallExitNode(const ProgramState *state); 601 602 const CFGBlock *getBlock() const { return &B; } 603 604 const ProgramState *getState() const { 605 return getPredecessor()->getState(); 606 } 607}; 608 609class CallEnterNodeBuilder { 610 CoreEngine &Eng; 611 612 const ExplodedNode *Pred; 613 614 // The call site. For implicit automatic object dtor, this is the trigger 615 // statement. 616 const Stmt *CE; 617 618 // The context of the callee. 619 const StackFrameContext *CalleeCtx; 620 621 // The parent block of the CallExpr. 622 const CFGBlock *Block; 623 624 // The CFGBlock index of the CallExpr. 625 unsigned Index; 626 627public: 628 CallEnterNodeBuilder(CoreEngine &eng, const ExplodedNode *pred, 629 const Stmt *s, const StackFrameContext *callee, 630 const CFGBlock *blk, unsigned idx) 631 : Eng(eng), Pred(pred), CE(s), CalleeCtx(callee), Block(blk), Index(idx) {} 632 633 const ProgramState *getState() const { return Pred->getState(); } 634 635 const LocationContext *getLocationContext() const { 636 return Pred->getLocationContext(); 637 } 638 639 const Stmt *getCallExpr() const { return CE; } 640 641 const StackFrameContext *getCalleeContext() const { return CalleeCtx; } 642 643 const CFGBlock *getBlock() const { return Block; } 644 645 unsigned getIndex() const { return Index; } 646 647 void generateNode(const ProgramState *state); 648}; 649 650class CallExitNodeBuilder { 651 CoreEngine &Eng; 652 const ExplodedNode *Pred; 653 654public: 655 CallExitNodeBuilder(CoreEngine &eng, const ExplodedNode *pred) 656 : Eng(eng), Pred(pred) {} 657 658 const ExplodedNode *getPredecessor() const { return Pred; } 659 660 const ProgramState *getState() const { return Pred->getState(); } 661 662 void generateNode(const ProgramState *state); 663}; 664 665} // end GR namespace 666 667} // end clang namespace 668 669#endif 670