1 //==- CoreEngine.h - Path-Sensitive Dataflow Engine ----------------*- C++ -*-//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a generic engine for intraprocedural, path-sensitive,
11 // dataflow analysis via graph reachability.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_COREENGINE_H
16 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_COREENGINE_H
18 #include "clang/AST/Expr.h"
19 #include "clang/Analysis/AnalysisContext.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/WorkList.h"
28 class ProgramPointTag;
34 //===----------------------------------------------------------------------===//
35 /// CoreEngine - Implements the core logic of the graph-reachability
36 /// analysis. It traverses the CFG and generates the ExplodedGraph.
37 /// Program "states" are treated as opaque void pointers.
38 /// The template class CoreEngine (which subclasses CoreEngine)
39 /// provides the matching component to the engine that knows the actual types
40 /// for states. Note that this engine only dispatches to transfer functions
41 /// at the statement and block-level. The analyses themselves must implement
42 /// any transfer function logic and the sub-expression level (if any).
44 friend struct NodeBuilderContext;
45 friend class NodeBuilder;
46 friend class ExprEngine;
47 friend class CommonNodeBuilder;
48 friend class IndirectGotoNodeBuilder;
49 friend class SwitchNodeBuilder;
50 friend class EndOfFunctionNodeBuilder;
52 typedef std::vector<std::pair<BlockEdge, const ExplodedNode*> >
55 typedef std::vector<std::pair<const CFGBlock*, const ExplodedNode*> >
62 /// G - The simulation graph. Each node is a (location,state) pair.
63 mutable ExplodedGraph G;
65 /// WList - A set of queued nodes that need to be processed by the
66 /// worklist algorithm. It is up to the implementation of WList to decide
67 /// the order that nodes are processed.
68 std::unique_ptr<WorkList> WList;
70 /// BCounterFactory - A factory object for created BlockCounter objects.
71 /// These are used to record for key nodes in the ExplodedGraph the
72 /// number of times different CFGBlocks have been visited along a path.
73 BlockCounter::Factory BCounterFactory;
75 /// The locations where we stopped doing work because we visited a location
77 BlocksExhausted blocksExhausted;
79 /// The locations where we stopped because the engine aborted analysis,
80 /// usually because it could not reason about something.
81 BlocksAborted blocksAborted;
83 /// The information about functions shared by the whole translation unit.
84 /// (This data is owned by AnalysisConsumer.)
85 FunctionSummariesTy *FunctionSummaries;
87 void generateNode(const ProgramPoint &Loc,
88 ProgramStateRef State,
91 void HandleBlockEdge(const BlockEdge &E, ExplodedNode *Pred);
92 void HandleBlockEntrance(const BlockEntrance &E, ExplodedNode *Pred);
93 void HandleBlockExit(const CFGBlock *B, ExplodedNode *Pred);
95 void HandleCallEnter(const CallEnter &CE, ExplodedNode *Pred);
97 void HandlePostStmt(const CFGBlock *B, unsigned StmtIdx, ExplodedNode *Pred);
99 void HandleBranch(const Stmt *Cond, const Stmt *Term, const CFGBlock *B,
101 void HandleCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
102 const CFGBlock *B, ExplodedNode *Pred);
104 /// Handle conditional logic for running static initializers.
105 void HandleStaticInit(const DeclStmt *DS, const CFGBlock *B,
109 CoreEngine(const CoreEngine &) = delete;
110 void operator=(const CoreEngine &) = delete;
112 ExplodedNode *generateCallExitBeginNode(ExplodedNode *N);
115 /// Construct a CoreEngine object to analyze the provided CFG.
116 CoreEngine(SubEngine &subengine, FunctionSummariesTy *FS)
117 : SubEng(subengine), WList(WorkList::makeDFS()),
118 BCounterFactory(G.getAllocator()), FunctionSummaries(FS) {}
120 /// getGraph - Returns the exploded graph.
121 ExplodedGraph &getGraph() { return G; }
123 /// ExecuteWorkList - Run the worklist algorithm for a maximum number of
124 /// steps. Returns true if there is still simulation state on the worklist.
125 bool ExecuteWorkList(const LocationContext *L, unsigned Steps,
126 ProgramStateRef InitState);
127 /// Returns true if there is still simulation state on the worklist.
128 bool ExecuteWorkListWithInitialState(const LocationContext *L,
130 ProgramStateRef InitState,
131 ExplodedNodeSet &Dst);
133 /// Dispatch the work list item based on the given location information.
134 /// Use Pred parameter as the predecessor state.
135 void dispatchWorkItem(ExplodedNode* Pred, ProgramPoint Loc,
136 const WorkListUnit& WU);
138 // Functions for external checking of whether we have unfinished work
139 bool wasBlockAborted() const { return !blocksAborted.empty(); }
140 bool wasBlocksExhausted() const { return !blocksExhausted.empty(); }
141 bool hasWorkRemaining() const { return wasBlocksExhausted() ||
145 /// Inform the CoreEngine that a basic block was aborted because
146 /// it could not be completely analyzed.
147 void addAbortedBlock(const ExplodedNode *node, const CFGBlock *block) {
148 blocksAborted.push_back(std::make_pair(block, node));
151 WorkList *getWorkList() const { return WList.get(); }
153 BlocksExhausted::const_iterator blocks_exhausted_begin() const {
154 return blocksExhausted.begin();
156 BlocksExhausted::const_iterator blocks_exhausted_end() const {
157 return blocksExhausted.end();
159 BlocksAborted::const_iterator blocks_aborted_begin() const {
160 return blocksAborted.begin();
162 BlocksAborted::const_iterator blocks_aborted_end() const {
163 return blocksAborted.end();
166 /// \brief Enqueue the given set of nodes onto the work list.
167 void enqueue(ExplodedNodeSet &Set);
169 /// \brief Enqueue nodes that were created as a result of processing
170 /// a statement onto the work list.
171 void enqueue(ExplodedNodeSet &Set, const CFGBlock *Block, unsigned Idx);
173 /// \brief enqueue the nodes corresponding to the end of function onto the
174 /// end of path / work list.
175 void enqueueEndOfFunction(ExplodedNodeSet &Set);
177 /// \brief Enqueue a single node created as a result of statement processing.
178 void enqueueStmtNode(ExplodedNode *N, const CFGBlock *Block, unsigned Idx);
181 // TODO: Turn into a calss.
182 struct NodeBuilderContext {
183 const CoreEngine &Eng;
184 const CFGBlock *Block;
185 const LocationContext *LC;
186 NodeBuilderContext(const CoreEngine &E, const CFGBlock *B, ExplodedNode *N)
187 : Eng(E), Block(B), LC(N->getLocationContext()) { assert(B); }
189 /// \brief Return the CFGBlock associated with this builder.
190 const CFGBlock *getBlock() const { return Block; }
192 /// \brief Returns the number of times the current basic block has been
193 /// visited on the exploded graph path.
194 unsigned blockCount() const {
195 return Eng.WList->getBlockCounter().getNumVisited(
196 LC->getCurrentStackFrame(),
197 Block->getBlockID());
201 /// \class NodeBuilder
202 /// \brief This is the simplest builder which generates nodes in the
205 /// The main benefit of the builder is that it automatically tracks the
206 /// frontier nodes (or destination set). This is the set of nodes which should
207 /// be propagated to the next step / builder. They are the nodes which have been
208 /// added to the builder (either as the input node set or as the newly
209 /// constructed nodes) but did not have any outgoing transitions added.
211 virtual void anchor();
213 const NodeBuilderContext &C;
215 /// Specifies if the builder results have been finalized. For example, if it
216 /// is set to false, autotransitions are yet to be generated.
218 bool HasGeneratedNodes;
219 /// \brief The frontier set - a set of nodes which need to be propagated after
220 /// the builder dies.
221 ExplodedNodeSet &Frontier;
223 /// Checkes if the results are ready.
224 virtual bool checkResults() {
230 bool hasNoSinksInFrontier() {
231 for (iterator I = Frontier.begin(), E = Frontier.end(); I != E; ++I) {
238 /// Allow subclasses to finalize results before result_begin() is executed.
239 virtual void finalizeResults() {}
241 ExplodedNode *generateNodeImpl(const ProgramPoint &PP,
242 ProgramStateRef State,
244 bool MarkAsSink = false);
247 NodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet,
248 const NodeBuilderContext &Ctx, bool F = true)
249 : C(Ctx), Finalized(F), HasGeneratedNodes(false), Frontier(DstSet) {
250 Frontier.Add(SrcNode);
253 NodeBuilder(const ExplodedNodeSet &SrcSet, ExplodedNodeSet &DstSet,
254 const NodeBuilderContext &Ctx, bool F = true)
255 : C(Ctx), Finalized(F), HasGeneratedNodes(false), Frontier(DstSet) {
256 Frontier.insert(SrcSet);
257 assert(hasNoSinksInFrontier());
260 virtual ~NodeBuilder() {}
262 /// \brief Generates a node in the ExplodedGraph.
263 ExplodedNode *generateNode(const ProgramPoint &PP,
264 ProgramStateRef State,
265 ExplodedNode *Pred) {
266 return generateNodeImpl(PP, State, Pred, false);
269 /// \brief Generates a sink in the ExplodedGraph.
271 /// When a node is marked as sink, the exploration from the node is stopped -
272 /// the node becomes the last node on the path and certain kinds of bugs are
274 ExplodedNode *generateSink(const ProgramPoint &PP,
275 ProgramStateRef State,
276 ExplodedNode *Pred) {
277 return generateNodeImpl(PP, State, Pred, true);
280 const ExplodedNodeSet &getResults() {
282 assert(checkResults());
286 typedef ExplodedNodeSet::iterator iterator;
287 /// \brief Iterators through the results frontier.
288 inline iterator begin() {
290 assert(checkResults());
291 return Frontier.begin();
293 inline iterator end() {
295 return Frontier.end();
298 const NodeBuilderContext &getContext() { return C; }
299 bool hasGeneratedNodes() { return HasGeneratedNodes; }
301 void takeNodes(const ExplodedNodeSet &S) {
302 for (ExplodedNodeSet::iterator I = S.begin(), E = S.end(); I != E; ++I )
305 void takeNodes(ExplodedNode *N) { Frontier.erase(N); }
306 void addNodes(const ExplodedNodeSet &S) { Frontier.insert(S); }
307 void addNodes(ExplodedNode *N) { Frontier.Add(N); }
310 /// \class NodeBuilderWithSinks
311 /// \brief This node builder keeps track of the generated sink nodes.
312 class NodeBuilderWithSinks: public NodeBuilder {
313 void anchor() override;
315 SmallVector<ExplodedNode*, 2> sinksGenerated;
316 ProgramPoint &Location;
319 NodeBuilderWithSinks(ExplodedNode *Pred, ExplodedNodeSet &DstSet,
320 const NodeBuilderContext &Ctx, ProgramPoint &L)
321 : NodeBuilder(Pred, DstSet, Ctx), Location(L) {}
323 ExplodedNode *generateNode(ProgramStateRef State,
325 const ProgramPointTag *Tag = nullptr) {
326 const ProgramPoint &LocalLoc = (Tag ? Location.withTag(Tag) : Location);
327 return NodeBuilder::generateNode(LocalLoc, State, Pred);
330 ExplodedNode *generateSink(ProgramStateRef State, ExplodedNode *Pred,
331 const ProgramPointTag *Tag = nullptr) {
332 const ProgramPoint &LocalLoc = (Tag ? Location.withTag(Tag) : Location);
333 ExplodedNode *N = NodeBuilder::generateSink(LocalLoc, State, Pred);
334 if (N && N->isSink())
335 sinksGenerated.push_back(N);
339 const SmallVectorImpl<ExplodedNode*> &getSinks() const {
340 return sinksGenerated;
344 /// \class StmtNodeBuilder
345 /// \brief This builder class is useful for generating nodes that resulted from
346 /// visiting a statement. The main difference from its parent NodeBuilder is
347 /// that it creates a statement specific ProgramPoint.
348 class StmtNodeBuilder: public NodeBuilder {
349 NodeBuilder *EnclosingBldr;
352 /// \brief Constructs a StmtNodeBuilder. If the builder is going to process
353 /// nodes currently owned by another builder(with larger scope), use
354 /// Enclosing builder to transfer ownership.
355 StmtNodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet,
356 const NodeBuilderContext &Ctx,
357 NodeBuilder *Enclosing = nullptr)
358 : NodeBuilder(SrcNode, DstSet, Ctx), EnclosingBldr(Enclosing) {
360 EnclosingBldr->takeNodes(SrcNode);
363 StmtNodeBuilder(ExplodedNodeSet &SrcSet, ExplodedNodeSet &DstSet,
364 const NodeBuilderContext &Ctx,
365 NodeBuilder *Enclosing = nullptr)
366 : NodeBuilder(SrcSet, DstSet, Ctx), EnclosingBldr(Enclosing) {
368 for (ExplodedNodeSet::iterator I = SrcSet.begin(),
369 E = SrcSet.end(); I != E; ++I )
370 EnclosingBldr->takeNodes(*I);
373 ~StmtNodeBuilder() override;
375 using NodeBuilder::generateNode;
376 using NodeBuilder::generateSink;
378 ExplodedNode *generateNode(const Stmt *S,
381 const ProgramPointTag *tag = nullptr,
382 ProgramPoint::Kind K = ProgramPoint::PostStmtKind){
383 const ProgramPoint &L = ProgramPoint::getProgramPoint(S, K,
384 Pred->getLocationContext(), tag);
385 return NodeBuilder::generateNode(L, St, Pred);
388 ExplodedNode *generateSink(const Stmt *S,
391 const ProgramPointTag *tag = nullptr,
392 ProgramPoint::Kind K = ProgramPoint::PostStmtKind){
393 const ProgramPoint &L = ProgramPoint::getProgramPoint(S, K,
394 Pred->getLocationContext(), tag);
395 return NodeBuilder::generateSink(L, St, Pred);
399 /// \brief BranchNodeBuilder is responsible for constructing the nodes
400 /// corresponding to the two branches of the if statement - true and false.
401 class BranchNodeBuilder: public NodeBuilder {
402 void anchor() override;
403 const CFGBlock *DstT;
404 const CFGBlock *DstF;
407 bool InFeasibleFalse;
410 BranchNodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet,
411 const NodeBuilderContext &C,
412 const CFGBlock *dstT, const CFGBlock *dstF)
413 : NodeBuilder(SrcNode, DstSet, C), DstT(dstT), DstF(dstF),
414 InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) {
415 // The branch node builder does not generate autotransitions.
416 // If there are no successors it means that both branches are infeasible.
420 BranchNodeBuilder(const ExplodedNodeSet &SrcSet, ExplodedNodeSet &DstSet,
421 const NodeBuilderContext &C,
422 const CFGBlock *dstT, const CFGBlock *dstF)
423 : NodeBuilder(SrcSet, DstSet, C), DstT(dstT), DstF(dstF),
424 InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) {
428 ExplodedNode *generateNode(ProgramStateRef State, bool branch,
431 const CFGBlock *getTargetBlock(bool branch) const {
432 return branch ? DstT : DstF;
435 void markInfeasible(bool branch) {
437 InFeasibleTrue = true;
439 InFeasibleFalse = true;
442 bool isFeasible(bool branch) {
443 return branch ? !InFeasibleTrue : !InFeasibleFalse;
447 class IndirectGotoNodeBuilder {
450 const CFGBlock &DispatchBlock;
455 IndirectGotoNodeBuilder(ExplodedNode *pred, const CFGBlock *src,
456 const Expr *e, const CFGBlock *dispatch, CoreEngine* eng)
457 : Eng(*eng), Src(src), DispatchBlock(*dispatch), E(e), Pred(pred) {}
460 CFGBlock::const_succ_iterator I;
462 friend class IndirectGotoNodeBuilder;
463 iterator(CFGBlock::const_succ_iterator i) : I(i) {}
466 iterator &operator++() { ++I; return *this; }
467 bool operator!=(const iterator &X) const { return I != X.I; }
469 const LabelDecl *getLabel() const {
470 return cast<LabelStmt>((*I)->getLabel())->getDecl();
473 const CFGBlock *getBlock() const {
478 iterator begin() { return iterator(DispatchBlock.succ_begin()); }
479 iterator end() { return iterator(DispatchBlock.succ_end()); }
481 ExplodedNode *generateNode(const iterator &I,
482 ProgramStateRef State,
483 bool isSink = false);
485 const Expr *getTarget() const { return E; }
487 ProgramStateRef getState() const { return Pred->State; }
489 const LocationContext *getLocationContext() const {
490 return Pred->getLocationContext();
494 class SwitchNodeBuilder {
497 const Expr *Condition;
501 SwitchNodeBuilder(ExplodedNode *pred, const CFGBlock *src,
502 const Expr *condition, CoreEngine* eng)
503 : Eng(*eng), Src(src), Condition(condition), Pred(pred) {}
506 CFGBlock::const_succ_reverse_iterator I;
508 friend class SwitchNodeBuilder;
509 iterator(CFGBlock::const_succ_reverse_iterator i) : I(i) {}
512 iterator &operator++() { ++I; return *this; }
513 bool operator!=(const iterator &X) const { return I != X.I; }
514 bool operator==(const iterator &X) const { return I == X.I; }
516 const CaseStmt *getCase() const {
517 return cast<CaseStmt>((*I)->getLabel());
520 const CFGBlock *getBlock() const {
525 iterator begin() { return iterator(Src->succ_rbegin()+1); }
526 iterator end() { return iterator(Src->succ_rend()); }
528 const SwitchStmt *getSwitch() const {
529 return cast<SwitchStmt>(Src->getTerminator());
532 ExplodedNode *generateCaseStmtNode(const iterator &I,
533 ProgramStateRef State);
535 ExplodedNode *generateDefaultCaseNode(ProgramStateRef State,
536 bool isSink = false);
538 const Expr *getCondition() const { return Condition; }
540 ProgramStateRef getState() const { return Pred->State; }
542 const LocationContext *getLocationContext() const {
543 return Pred->getLocationContext();
547 } // end ento namespace
548 } // end clang namespace