CoreEngine.cpp revision 3152b3cb5b6a2f797d0972c81a5eb3fd69c0d620
1//==- CoreEngine.cpp - 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 engine.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
16#include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
17#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
18#include "clang/Index/TranslationUnit.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/StmtCXX.h"
21#include "llvm/Support/Casting.h"
22#include "llvm/ADT/DenseMap.h"
23using namespace clang;
24using namespace ento;
25
26//===----------------------------------------------------------------------===//
27// Worklist classes for exploration of reachable states.
28//===----------------------------------------------------------------------===//
29
30WorkList::Visitor::~Visitor() {}
31
32namespace {
33class DFS : public WorkList {
34  SmallVector<WorkListUnit,20> Stack;
35public:
36  virtual bool hasWork() const {
37    return !Stack.empty();
38  }
39
40  virtual void enqueue(const WorkListUnit& U) {
41    Stack.push_back(U);
42  }
43
44  virtual WorkListUnit dequeue() {
45    assert (!Stack.empty());
46    const WorkListUnit& U = Stack.back();
47    Stack.pop_back(); // This technically "invalidates" U, but we are fine.
48    return U;
49  }
50
51  virtual bool visitItemsInWorkList(Visitor &V) {
52    for (SmallVectorImpl<WorkListUnit>::iterator
53         I = Stack.begin(), E = Stack.end(); I != E; ++I) {
54      if (V.visit(*I))
55        return true;
56    }
57    return false;
58  }
59};
60
61class BFS : public WorkList {
62  std::deque<WorkListUnit> Queue;
63public:
64  virtual bool hasWork() const {
65    return !Queue.empty();
66  }
67
68  virtual void enqueue(const WorkListUnit& U) {
69    Queue.push_front(U);
70  }
71
72  virtual WorkListUnit dequeue() {
73    WorkListUnit U = Queue.front();
74    Queue.pop_front();
75    return U;
76  }
77
78  virtual bool visitItemsInWorkList(Visitor &V) {
79    for (std::deque<WorkListUnit>::iterator
80         I = Queue.begin(), E = Queue.end(); I != E; ++I) {
81      if (V.visit(*I))
82        return true;
83    }
84    return false;
85  }
86};
87
88} // end anonymous namespace
89
90// Place the dstor for WorkList here because it contains virtual member
91// functions, and we the code for the dstor generated in one compilation unit.
92WorkList::~WorkList() {}
93
94WorkList *WorkList::makeDFS() { return new DFS(); }
95WorkList *WorkList::makeBFS() { return new BFS(); }
96
97namespace {
98  class BFSBlockDFSContents : public WorkList {
99    std::deque<WorkListUnit> Queue;
100    SmallVector<WorkListUnit,20> Stack;
101  public:
102    virtual bool hasWork() const {
103      return !Queue.empty() || !Stack.empty();
104    }
105
106    virtual void enqueue(const WorkListUnit& U) {
107      if (isa<BlockEntrance>(U.getNode()->getLocation()))
108        Queue.push_front(U);
109      else
110        Stack.push_back(U);
111    }
112
113    virtual WorkListUnit dequeue() {
114      // Process all basic blocks to completion.
115      if (!Stack.empty()) {
116        const WorkListUnit& U = Stack.back();
117        Stack.pop_back(); // This technically "invalidates" U, but we are fine.
118        return U;
119      }
120
121      assert(!Queue.empty());
122      // Don't use const reference.  The subsequent pop_back() might make it
123      // unsafe.
124      WorkListUnit U = Queue.front();
125      Queue.pop_front();
126      return U;
127    }
128    virtual bool visitItemsInWorkList(Visitor &V) {
129      for (SmallVectorImpl<WorkListUnit>::iterator
130           I = Stack.begin(), E = Stack.end(); I != E; ++I) {
131        if (V.visit(*I))
132          return true;
133      }
134      for (std::deque<WorkListUnit>::iterator
135           I = Queue.begin(), E = Queue.end(); I != E; ++I) {
136        if (V.visit(*I))
137          return true;
138      }
139      return false;
140    }
141
142  };
143} // end anonymous namespace
144
145WorkList* WorkList::makeBFSBlockDFSContents() {
146  return new BFSBlockDFSContents();
147}
148
149//===----------------------------------------------------------------------===//
150// Core analysis engine.
151//===----------------------------------------------------------------------===//
152
153/// ExecuteWorkList - Run the worklist algorithm for a maximum number of steps.
154bool CoreEngine::ExecuteWorkList(const LocationContext *L, unsigned Steps,
155                                   const ProgramState *InitState) {
156
157  if (G->num_roots() == 0) { // Initialize the analysis by constructing
158    // the root if none exists.
159
160    const CFGBlock *Entry = &(L->getCFG()->getEntry());
161
162    assert (Entry->empty() &&
163            "Entry block must be empty.");
164
165    assert (Entry->succ_size() == 1 &&
166            "Entry block must have 1 successor.");
167
168    // Get the solitary successor.
169    const CFGBlock *Succ = *(Entry->succ_begin());
170
171    // Construct an edge representing the
172    // starting location in the function.
173    BlockEdge StartLoc(Entry, Succ, L);
174
175    // Set the current block counter to being empty.
176    WList->setBlockCounter(BCounterFactory.GetEmptyCounter());
177
178    if (!InitState)
179      // Generate the root.
180      generateNode(StartLoc, SubEng.getInitialState(L), 0);
181    else
182      generateNode(StartLoc, InitState, 0);
183  }
184
185  // Check if we have a steps limit
186  bool UnlimitedSteps = Steps == 0;
187
188  while (WList->hasWork()) {
189    if (!UnlimitedSteps) {
190      if (Steps == 0)
191        break;
192      --Steps;
193    }
194
195    const WorkListUnit& WU = WList->dequeue();
196
197    // Set the current block counter.
198    WList->setBlockCounter(WU.getBlockCounter());
199
200    // Retrieve the node.
201    ExplodedNode *Node = WU.getNode();
202
203    // Dispatch on the location type.
204    switch (Node->getLocation().getKind()) {
205      case ProgramPoint::BlockEdgeKind:
206        HandleBlockEdge(cast<BlockEdge>(Node->getLocation()), Node);
207        break;
208
209      case ProgramPoint::BlockEntranceKind:
210        HandleBlockEntrance(cast<BlockEntrance>(Node->getLocation()), Node);
211        break;
212
213      case ProgramPoint::BlockExitKind:
214        assert (false && "BlockExit location never occur in forward analysis.");
215        break;
216
217      case ProgramPoint::CallEnterKind:
218        HandleCallEnter(cast<CallEnter>(Node->getLocation()), WU.getBlock(),
219                        WU.getIndex(), Node);
220        break;
221
222      case ProgramPoint::CallExitKind:
223        HandleCallExit(cast<CallExit>(Node->getLocation()), Node);
224        break;
225
226      default:
227        assert(isa<PostStmt>(Node->getLocation()) ||
228               isa<PostInitializer>(Node->getLocation()));
229        HandlePostStmt(WU.getBlock(), WU.getIndex(), Node);
230        break;
231    }
232  }
233
234  SubEng.processEndWorklist(hasWorkRemaining());
235  return WList->hasWork();
236}
237
238void CoreEngine::ExecuteWorkListWithInitialState(const LocationContext *L,
239                                                 unsigned Steps,
240                                                 const ProgramState *InitState,
241                                                 ExplodedNodeSet &Dst) {
242  ExecuteWorkList(L, Steps, InitState);
243  for (SmallVectorImpl<ExplodedNode*>::iterator I = G->EndNodes.begin(),
244                                           E = G->EndNodes.end(); I != E; ++I) {
245    Dst.Add(*I);
246  }
247}
248
249void CoreEngine::HandleCallEnter(const CallEnter &L, const CFGBlock *Block,
250                                   unsigned Index, ExplodedNode *Pred) {
251  CallEnterNodeBuilder Builder(*this, Pred, L.getCallExpr(),
252                                 L.getCalleeContext(), Block, Index);
253  SubEng.processCallEnter(Builder);
254}
255
256void CoreEngine::HandleCallExit(const CallExit &L, ExplodedNode *Pred) {
257  CallExitNodeBuilder Builder(*this, Pred);
258  SubEng.processCallExit(Builder);
259}
260
261void CoreEngine::HandleBlockEdge(const BlockEdge &L, ExplodedNode *Pred) {
262
263  const CFGBlock *Blk = L.getDst();
264
265  // Check if we are entering the EXIT block.
266  if (Blk == &(L.getLocationContext()->getCFG()->getExit())) {
267
268    assert (L.getLocationContext()->getCFG()->getExit().size() == 0
269            && "EXIT block cannot contain Stmts.");
270
271    // Process the final state transition.
272    EndOfFunctionNodeBuilder Builder(Blk, Pred, this);
273    SubEng.processEndOfFunction(Builder);
274
275    // This path is done. Don't enqueue any more nodes.
276    return;
277  }
278
279  // Call into the subengine to process entering the CFGBlock.
280  ExplodedNodeSet dstNodes;
281  BlockEntrance BE(Blk, Pred->getLocationContext());
282  GenericNodeBuilder<BlockEntrance> nodeBuilder(*this, Pred, BE);
283  SubEng.processCFGBlockEntrance(dstNodes, nodeBuilder);
284
285  if (dstNodes.empty()) {
286    if (!nodeBuilder.hasGeneratedNode) {
287      // Auto-generate a node and enqueue it to the worklist.
288      generateNode(BE, Pred->State, Pred);
289    }
290  }
291  else {
292    for (ExplodedNodeSet::iterator I = dstNodes.begin(), E = dstNodes.end();
293         I != E; ++I) {
294      WList->enqueue(*I);
295    }
296  }
297
298  for (SmallVectorImpl<ExplodedNode*>::const_iterator
299       I = nodeBuilder.sinks().begin(), E = nodeBuilder.sinks().end();
300       I != E; ++I) {
301    blocksExhausted.push_back(std::make_pair(L, *I));
302  }
303}
304
305void CoreEngine::HandleBlockEntrance(const BlockEntrance &L,
306                                       ExplodedNode *Pred) {
307
308  // Increment the block counter.
309  BlockCounter Counter = WList->getBlockCounter();
310  Counter = BCounterFactory.IncrementCount(Counter,
311                             Pred->getLocationContext()->getCurrentStackFrame(),
312                                           L.getBlock()->getBlockID());
313  WList->setBlockCounter(Counter);
314
315  // Process the entrance of the block.
316  if (CFGElement E = L.getFirstElement()) {
317    NodeBuilderContext Ctx(*this, L.getBlock());
318    StmtNodeBuilder Builder(Pred, 0, Ctx);
319    SubEng.processCFGElement(E, Builder);
320  }
321  else
322    HandleBlockExit(L.getBlock(), Pred);
323}
324
325void CoreEngine::HandleBlockExit(const CFGBlock * B, ExplodedNode *Pred) {
326
327  if (const Stmt *Term = B->getTerminator()) {
328    switch (Term->getStmtClass()) {
329      default:
330        llvm_unreachable("Analysis for this terminator not implemented.");
331
332      case Stmt::BinaryOperatorClass: // '&&' and '||'
333        HandleBranch(cast<BinaryOperator>(Term)->getLHS(), Term, B, Pred);
334        return;
335
336      case Stmt::BinaryConditionalOperatorClass:
337      case Stmt::ConditionalOperatorClass:
338        HandleBranch(cast<AbstractConditionalOperator>(Term)->getCond(),
339                     Term, B, Pred);
340        return;
341
342        // FIXME: Use constant-folding in CFG construction to simplify this
343        // case.
344
345      case Stmt::ChooseExprClass:
346        HandleBranch(cast<ChooseExpr>(Term)->getCond(), Term, B, Pred);
347        return;
348
349      case Stmt::DoStmtClass:
350        HandleBranch(cast<DoStmt>(Term)->getCond(), Term, B, Pred);
351        return;
352
353      case Stmt::CXXForRangeStmtClass:
354        HandleBranch(cast<CXXForRangeStmt>(Term)->getCond(), Term, B, Pred);
355        return;
356
357      case Stmt::ForStmtClass:
358        HandleBranch(cast<ForStmt>(Term)->getCond(), Term, B, Pred);
359        return;
360
361      case Stmt::ContinueStmtClass:
362      case Stmt::BreakStmtClass:
363      case Stmt::GotoStmtClass:
364        break;
365
366      case Stmt::IfStmtClass:
367        HandleBranch(cast<IfStmt>(Term)->getCond(), Term, B, Pred);
368        return;
369
370      case Stmt::IndirectGotoStmtClass: {
371        // Only 1 successor: the indirect goto dispatch block.
372        assert (B->succ_size() == 1);
373
374        IndirectGotoNodeBuilder
375           builder(Pred, B, cast<IndirectGotoStmt>(Term)->getTarget(),
376                   *(B->succ_begin()), this);
377
378        SubEng.processIndirectGoto(builder);
379        return;
380      }
381
382      case Stmt::ObjCForCollectionStmtClass: {
383        // In the case of ObjCForCollectionStmt, it appears twice in a CFG:
384        //
385        //  (1) inside a basic block, which represents the binding of the
386        //      'element' variable to a value.
387        //  (2) in a terminator, which represents the branch.
388        //
389        // For (1), subengines will bind a value (i.e., 0 or 1) indicating
390        // whether or not collection contains any more elements.  We cannot
391        // just test to see if the element is nil because a container can
392        // contain nil elements.
393        HandleBranch(Term, Term, B, Pred);
394        return;
395      }
396
397      case Stmt::SwitchStmtClass: {
398        SwitchNodeBuilder builder(Pred, B, cast<SwitchStmt>(Term)->getCond(),
399                                    this);
400
401        SubEng.processSwitch(builder);
402        return;
403      }
404
405      case Stmt::WhileStmtClass:
406        HandleBranch(cast<WhileStmt>(Term)->getCond(), Term, B, Pred);
407        return;
408    }
409  }
410
411  assert (B->succ_size() == 1 &&
412          "Blocks with no terminator should have at most 1 successor.");
413
414  generateNode(BlockEdge(B, *(B->succ_begin()), Pred->getLocationContext()),
415               Pred->State, Pred);
416}
417
418void CoreEngine::HandleBranch(const Stmt *Cond, const Stmt *Term,
419                                const CFGBlock * B, ExplodedNode *Pred) {
420  assert(B->succ_size() == 2);
421  NodeBuilderContext Ctx(*this, B);
422  SubEng.processBranch(Cond, Term, Ctx, Pred,
423                       *(B->succ_begin()), *(B->succ_begin()+1));
424}
425
426void CoreEngine::HandlePostStmt(const CFGBlock *B, unsigned StmtIdx,
427                                  ExplodedNode *Pred) {
428  assert(B);
429  assert(!B->empty());
430
431  if (StmtIdx == B->size())
432    HandleBlockExit(B, Pred);
433  else {
434    NodeBuilderContext Ctx(*this, B);
435    StmtNodeBuilder Builder(Pred, StmtIdx, Ctx);
436    SubEng.processCFGElement((*B)[StmtIdx], Builder);
437  }
438}
439
440/// generateNode - Utility method to generate nodes, hook up successors,
441///  and add nodes to the worklist.
442void CoreEngine::generateNode(const ProgramPoint &Loc,
443                              const ProgramState *State,
444                              ExplodedNode *Pred) {
445
446  bool IsNew;
447  ExplodedNode *Node = G->getNode(Loc, State, &IsNew);
448
449  if (Pred)
450    Node->addPredecessor(Pred, *G);  // Link 'Node' with its predecessor.
451  else {
452    assert (IsNew);
453    G->addRoot(Node);  // 'Node' has no predecessor.  Make it a root.
454  }
455
456  // Only add 'Node' to the worklist if it was freshly generated.
457  if (IsNew) WList->enqueue(Node);
458}
459
460void CoreEngine::enqueue(NodeBuilder &NB) {
461  for (NodeBuilder::iterator I = NB.results_begin(),
462                               E = NB.results_end(); I != E; ++I) {
463    WList->enqueue(*I);
464  }
465}
466
467ExplodedNode *
468GenericNodeBuilderImpl::generateNodeImpl(const ProgramState *state,
469                                         ExplodedNode *pred,
470                                         ProgramPoint programPoint,
471                                         bool asSink) {
472
473  hasGeneratedNode = true;
474  bool isNew;
475  ExplodedNode *node = engine.getGraph().getNode(programPoint, state, &isNew);
476  if (pred)
477    node->addPredecessor(pred, engine.getGraph());
478  if (isNew) {
479    if (asSink) {
480      node->markAsSink();
481      sinksGenerated.push_back(node);
482    }
483    return node;
484  }
485  return 0;
486}
487
488ExplodedNode* NodeBuilder::generateNodeImpl(const ProgramPoint &Loc,
489                                            const ProgramState *State,
490                                            ExplodedNode *FromN,
491                                            bool MarkAsSink) {
492  bool IsNew;
493  ExplodedNode *N = C.Eng.G->getNode(Loc, State, &IsNew);
494  N->addPredecessor(FromN, *C.Eng.G);
495  Deferred.erase(FromN);
496
497  if (MarkAsSink)
498    N->markAsSink();
499
500  if (IsNew && !N->isSink())
501    Deferred.insert(N);
502
503  return (IsNew ? N : 0);
504}
505
506
507StmtNodeBuilder::StmtNodeBuilder(ExplodedNode *N, unsigned idx,
508                                 NodeBuilderContext &Ctx)
509  : NodeBuilder(N, Ctx), Idx(idx),
510    PurgingDeadSymbols(false), BuildSinks(false), hasGeneratedNode(false),
511    PointKind(ProgramPoint::PostStmtKind), Tag(0) {
512  Deferred.insert(N);
513}
514
515StmtNodeBuilder::~StmtNodeBuilder() {
516  for (DeferredTy::iterator I=Deferred.begin(), E=Deferred.end(); I!=E; ++I)
517    if (!(*I)->isSink())
518      GenerateAutoTransition(*I);
519}
520
521void StmtNodeBuilder::GenerateAutoTransition(ExplodedNode *N) {
522  assert (!N->isSink());
523
524  // Check if this node entered a callee.
525  if (isa<CallEnter>(N->getLocation())) {
526    // Still use the index of the CallExpr. It's needed to create the callee
527    // StackFrameContext.
528    C.Eng.WList->enqueue(N, C.Block, Idx);
529    return;
530  }
531
532  // Do not create extra nodes. Move to the next CFG element.
533  if (isa<PostInitializer>(N->getLocation())) {
534    C.Eng.WList->enqueue(N, C.Block, Idx+1);
535    return;
536  }
537
538  PostStmt Loc(getStmt(), N->getLocationContext());
539
540  if (Loc == N->getLocation()) {
541    // Note: 'N' should be a fresh node because otherwise it shouldn't be
542    // a member of Deferred.
543    C.Eng.WList->enqueue(N, C.Block, Idx+1);
544    return;
545  }
546
547  bool IsNew;
548  ExplodedNode *Succ = C.Eng.G->getNode(Loc, N->State, &IsNew);
549  Succ->addPredecessor(N, *C.Eng.G);
550
551  if (IsNew)
552    C.Eng.WList->enqueue(Succ, C.Block, Idx+1);
553}
554
555ExplodedNode *StmtNodeBuilder::MakeNode(ExplodedNodeSet &Dst,
556                                        const Stmt *S,
557                                        ExplodedNode *Pred,
558                                        const ProgramState *St,
559                                        ProgramPoint::Kind K) {
560  ExplodedNode *N = generateNode(S, St, Pred, K, 0, BuildSinks);
561  if (N && !BuildSinks){
562      Dst.Add(N);
563  }
564  return N;
565}
566
567ExplodedNode *BranchNodeBuilder::generateNode(const ProgramState *State,
568                                              bool branch,
569                                              ExplodedNode *NodePred) {
570  assert(Finalized == false &&
571         "We cannot create new nodes after the results have been finalized.");
572
573  // If the branch has been marked infeasible we should not generate a node.
574  if (!isFeasible(branch))
575    return NULL;
576
577  if (!NodePred)
578    NodePred = BuilderPred;
579  ProgramPoint Loc = BlockEdge(C.Block, branch ? DstT:DstF,
580                               NodePred->getLocationContext());
581  ExplodedNode *Succ = generateNodeImpl(Loc, State, NodePred);
582
583  if (branch)
584    GeneratedTrue = true;
585  else
586    GeneratedFalse = true;
587
588  return Succ;
589}
590
591ExplodedNode*
592IndirectGotoNodeBuilder::generateNode(const iterator &I,
593                                      const ProgramState *St,
594                                      bool isSink) {
595  bool IsNew;
596
597  ExplodedNode *Succ = Eng.G->getNode(BlockEdge(Src, I.getBlock(),
598                                      Pred->getLocationContext()), St, &IsNew);
599
600  Succ->addPredecessor(Pred, *Eng.G);
601
602  if (IsNew) {
603
604    if (isSink)
605      Succ->markAsSink();
606    else
607      Eng.WList->enqueue(Succ);
608
609    return Succ;
610  }
611
612  return NULL;
613}
614
615
616ExplodedNode*
617SwitchNodeBuilder::generateCaseStmtNode(const iterator &I,
618                                        const ProgramState *St) {
619
620  bool IsNew;
621  ExplodedNode *Succ = Eng.G->getNode(BlockEdge(Src, I.getBlock(),
622                                      Pred->getLocationContext()),
623                                      St, &IsNew);
624  Succ->addPredecessor(Pred, *Eng.G);
625  if (IsNew) {
626    Eng.WList->enqueue(Succ);
627    return Succ;
628  }
629  return NULL;
630}
631
632
633ExplodedNode*
634SwitchNodeBuilder::generateDefaultCaseNode(const ProgramState *St,
635                                           bool isSink) {
636  // Get the block for the default case.
637  assert(Src->succ_rbegin() != Src->succ_rend());
638  CFGBlock *DefaultBlock = *Src->succ_rbegin();
639
640  // Sanity check for default blocks that are unreachable and not caught
641  // by earlier stages.
642  if (!DefaultBlock)
643    return NULL;
644
645  bool IsNew;
646
647  ExplodedNode *Succ = Eng.G->getNode(BlockEdge(Src, DefaultBlock,
648                                      Pred->getLocationContext()), St, &IsNew);
649  Succ->addPredecessor(Pred, *Eng.G);
650
651  if (IsNew) {
652    if (isSink)
653      Succ->markAsSink();
654    else
655      Eng.WList->enqueue(Succ);
656
657    return Succ;
658  }
659
660  return NULL;
661}
662
663EndOfFunctionNodeBuilder::~EndOfFunctionNodeBuilder() {
664  // Auto-generate an EOP node if one has not been generated.
665  if (!hasGeneratedNode) {
666    // If we are in an inlined call, generate CallExit node.
667    if (Pred->getLocationContext()->getParent())
668      GenerateCallExitNode(Pred->State);
669    else
670      generateNode(Pred->State);
671  }
672}
673
674ExplodedNode*
675EndOfFunctionNodeBuilder::generateNode(const ProgramState *State,
676                                       ExplodedNode *P,
677                                       const ProgramPointTag *tag) {
678  hasGeneratedNode = true;
679  bool IsNew;
680
681  ExplodedNode *Node = Eng.G->getNode(BlockEntrance(&B,
682                               Pred->getLocationContext(), tag ? tag : Tag),
683                               State, &IsNew);
684
685  Node->addPredecessor(P ? P : Pred, *Eng.G);
686
687  if (IsNew) {
688    Eng.G->addEndOfPath(Node);
689    return Node;
690  }
691
692  return NULL;
693}
694
695void EndOfFunctionNodeBuilder::GenerateCallExitNode(const ProgramState *state) {
696  hasGeneratedNode = true;
697  // Create a CallExit node and enqueue it.
698  const StackFrameContext *LocCtx
699                         = cast<StackFrameContext>(Pred->getLocationContext());
700  const Stmt *CE = LocCtx->getCallSite();
701
702  // Use the the callee location context.
703  CallExit Loc(CE, LocCtx);
704
705  bool isNew;
706  ExplodedNode *Node = Eng.G->getNode(Loc, state, &isNew);
707  Node->addPredecessor(Pred, *Eng.G);
708
709  if (isNew)
710    Eng.WList->enqueue(Node);
711}
712
713
714void CallEnterNodeBuilder::generateNode(const ProgramState *state) {
715  // Check if the callee is in the same translation unit.
716  if (CalleeCtx->getTranslationUnit() !=
717      Pred->getLocationContext()->getTranslationUnit()) {
718    // Create a new engine. We must be careful that the new engine should not
719    // reference data structures owned by the old engine.
720
721    AnalysisManager &OldMgr = Eng.SubEng.getAnalysisManager();
722
723    // Get the callee's translation unit.
724    idx::TranslationUnit *TU = CalleeCtx->getTranslationUnit();
725
726    // Create a new AnalysisManager with components of the callee's
727    // TranslationUnit.
728    // The Diagnostic is  actually shared when we create ASTUnits from AST files.
729    AnalysisManager AMgr(TU->getASTContext(), TU->getDiagnostic(), OldMgr);
730
731    // Create the new engine.
732    // FIXME: This cast isn't really safe.
733    bool GCEnabled = static_cast<ExprEngine&>(Eng.SubEng).isObjCGCEnabled();
734    ExprEngine NewEng(AMgr, GCEnabled);
735
736    // Create the new LocationContext.
737    AnalysisContext *NewAnaCtx = AMgr.getAnalysisContext(CalleeCtx->getDecl(),
738                                               CalleeCtx->getTranslationUnit());
739    const StackFrameContext *OldLocCtx = CalleeCtx;
740    const StackFrameContext *NewLocCtx = AMgr.getStackFrame(NewAnaCtx,
741                                               OldLocCtx->getParent(),
742                                               OldLocCtx->getCallSite(),
743                                               OldLocCtx->getCallSiteBlock(),
744                                               OldLocCtx->getIndex());
745
746    // Now create an initial state for the new engine.
747    const ProgramState *NewState =
748      NewEng.getStateManager().MarshalState(state, NewLocCtx);
749    ExplodedNodeSet ReturnNodes;
750    NewEng.ExecuteWorkListWithInitialState(NewLocCtx, AMgr.getMaxNodes(),
751                                           NewState, ReturnNodes);
752    return;
753  }
754
755  // Get the callee entry block.
756  const CFGBlock *Entry = &(CalleeCtx->getCFG()->getEntry());
757  assert(Entry->empty());
758  assert(Entry->succ_size() == 1);
759
760  // Get the solitary successor.
761  const CFGBlock *SuccB = *(Entry->succ_begin());
762
763  // Construct an edge representing the starting location in the callee.
764  BlockEdge Loc(Entry, SuccB, CalleeCtx);
765
766  bool isNew;
767  ExplodedNode *Node = Eng.G->getNode(Loc, state, &isNew);
768  Node->addPredecessor(const_cast<ExplodedNode*>(Pred), *Eng.G);
769
770  if (isNew)
771    Eng.WList->enqueue(Node);
772}
773
774void CallExitNodeBuilder::generateNode(const ProgramState *state) {
775  // Get the callee's location context.
776  const StackFrameContext *LocCtx
777                         = cast<StackFrameContext>(Pred->getLocationContext());
778  // When exiting an implicit automatic obj dtor call, the callsite is the Stmt
779  // that triggers the dtor.
780  PostStmt Loc(LocCtx->getCallSite(), LocCtx->getParent());
781  bool isNew;
782  ExplodedNode *Node = Eng.G->getNode(Loc, state, &isNew);
783  Node->addPredecessor(const_cast<ExplodedNode*>(Pred), *Eng.G);
784  if (isNew)
785    Eng.WList->enqueue(Node, LocCtx->getCallSiteBlock(),
786                       LocCtx->getIndex() + 1);
787}
788