Home | History | Annotate | Download | only in Core
      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"
     23 using namespace clang;
     24 using namespace ento;
     25 
     26 //===----------------------------------------------------------------------===//
     27 // Worklist classes for exploration of reachable states.
     28 //===----------------------------------------------------------------------===//
     29 
     30 WorkList::Visitor::~Visitor() {}
     31 
     32 namespace {
     33 class DFS : public WorkList {
     34   SmallVector<WorkListUnit,20> Stack;
     35 public:
     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 
     61 class BFS : public WorkList {
     62   std::deque<WorkListUnit> Queue;
     63 public:
     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.
     92 WorkList::~WorkList() {}
     93 
     94 WorkList *WorkList::makeDFS() { return new DFS(); }
     95 WorkList *WorkList::makeBFS() { return new BFS(); }
     96 
     97 namespace {
     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 
    145 WorkList* 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.
    154 bool 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 
    238 void 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 
    249 void 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 
    256 void CoreEngine::HandleCallExit(const CallExit &L, ExplodedNode *Pred) {
    257   CallExitNodeBuilder Builder(*this, Pred);
    258   SubEng.processCallExit(Builder);
    259 }
    260 
    261 void 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 
    305 void 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(), Pred);
    318     StmtNodeBuilder Builder(Pred, 0, Ctx);
    319     SubEng.processCFGElement(E, Builder, Pred);
    320   }
    321   else
    322     HandleBlockExit(L.getBlock(), Pred);
    323 }
    324 
    325 void 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 
    418 void 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, Pred);
    422   SubEng.processBranch(Cond, Term, Ctx, Pred,
    423                        *(B->succ_begin()), *(B->succ_begin()+1));
    424 }
    425 
    426 void 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, Pred);
    435     StmtNodeBuilder Builder(Pred, StmtIdx, Ctx);
    436     SubEng.processCFGElement((*B)[StmtIdx], Builder, Pred);
    437   }
    438 }
    439 
    440 /// generateNode - Utility method to generate nodes, hook up successors,
    441 ///  and add nodes to the worklist.
    442 void 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 
    460 void 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 
    467 ExplodedNode *
    468 GenericNodeBuilderImpl::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 
    488 ExplodedNode* NodeBuilder::generateNodeImpl(const ProgramPoint &Loc,
    489                                             const ProgramState *State,
    490                                             ExplodedNode *FromN,
    491                                             bool MarkAsSink) {
    492   HasGeneratedNodes = true;
    493 
    494   bool IsNew;
    495   ExplodedNode *N = C.Eng.G->getNode(Loc, State, &IsNew);
    496   N->addPredecessor(FromN, *C.Eng.G);
    497   Deferred.erase(FromN);
    498 
    499   if (MarkAsSink)
    500     N->markAsSink();
    501 
    502   if (IsNew && !N->isSink())
    503     Deferred.insert(N);
    504 
    505   return (IsNew ? N : 0);
    506 }
    507 
    508 
    509 StmtNodeBuilder::StmtNodeBuilder(ExplodedNode *N, unsigned idx,
    510                                  NodeBuilderContext &Ctx)
    511   : NodeBuilder(Ctx), Idx(idx),
    512     PurgingDeadSymbols(false), BuildSinks(false), hasGeneratedNode(false),
    513     PointKind(ProgramPoint::PostStmtKind), Tag(0) {
    514   Deferred.insert(N);
    515 }
    516 
    517 StmtNodeBuilder::~StmtNodeBuilder() {
    518   for (DeferredTy::iterator I=Deferred.begin(), E=Deferred.end(); I!=E; ++I)
    519     if (!(*I)->isSink())
    520       GenerateAutoTransition(*I);
    521 }
    522 
    523 void StmtNodeBuilder::GenerateAutoTransition(ExplodedNode *N) {
    524   assert (!N->isSink());
    525 
    526   // Check if this node entered a callee.
    527   if (isa<CallEnter>(N->getLocation())) {
    528     // Still use the index of the CallExpr. It's needed to create the callee
    529     // StackFrameContext.
    530     C.Eng.WList->enqueue(N, C.Block, Idx);
    531     return;
    532   }
    533 
    534   // Do not create extra nodes. Move to the next CFG element.
    535   if (isa<PostInitializer>(N->getLocation())) {
    536     C.Eng.WList->enqueue(N, C.Block, Idx+1);
    537     return;
    538   }
    539 
    540   PostStmt Loc(getStmt(), N->getLocationContext());
    541 
    542   if (Loc == N->getLocation()) {
    543     // Note: 'N' should be a fresh node because otherwise it shouldn't be
    544     // a member of Deferred.
    545     C.Eng.WList->enqueue(N, C.Block, Idx+1);
    546     return;
    547   }
    548 
    549   bool IsNew;
    550   ExplodedNode *Succ = C.Eng.G->getNode(Loc, N->State, &IsNew);
    551   Succ->addPredecessor(N, *C.Eng.G);
    552 
    553   if (IsNew)
    554     C.Eng.WList->enqueue(Succ, C.Block, Idx+1);
    555 }
    556 
    557 ExplodedNode *StmtNodeBuilder::MakeNode(ExplodedNodeSet &Dst,
    558                                         const Stmt *S,
    559                                         ExplodedNode *Pred,
    560                                         const ProgramState *St,
    561                                         ProgramPoint::Kind K) {
    562   ExplodedNode *N = generateNode(S, St, Pred, K, 0, BuildSinks);
    563   if (N && !BuildSinks){
    564       Dst.Add(N);
    565   }
    566   return N;
    567 }
    568 
    569 ExplodedNode *BranchNodeBuilder::generateNode(const ProgramState *State,
    570                                               bool branch,
    571                                               ExplodedNode *NodePred) {
    572   // If the branch has been marked infeasible we should not generate a node.
    573   if (!isFeasible(branch))
    574     return NULL;
    575 
    576   ProgramPoint Loc = BlockEdge(C.Block, branch ? DstT:DstF,
    577                                NodePred->getLocationContext());
    578   ExplodedNode *Succ = generateNodeImpl(Loc, State, NodePred);
    579   return Succ;
    580 }
    581 
    582 ExplodedNode*
    583 IndirectGotoNodeBuilder::generateNode(const iterator &I,
    584                                       const ProgramState *St,
    585                                       bool isSink) {
    586   bool IsNew;
    587 
    588   ExplodedNode *Succ = Eng.G->getNode(BlockEdge(Src, I.getBlock(),
    589                                       Pred->getLocationContext()), St, &IsNew);
    590 
    591   Succ->addPredecessor(Pred, *Eng.G);
    592 
    593   if (IsNew) {
    594 
    595     if (isSink)
    596       Succ->markAsSink();
    597     else
    598       Eng.WList->enqueue(Succ);
    599 
    600     return Succ;
    601   }
    602 
    603   return NULL;
    604 }
    605 
    606 
    607 ExplodedNode*
    608 SwitchNodeBuilder::generateCaseStmtNode(const iterator &I,
    609                                         const ProgramState *St) {
    610 
    611   bool IsNew;
    612   ExplodedNode *Succ = Eng.G->getNode(BlockEdge(Src, I.getBlock(),
    613                                       Pred->getLocationContext()),
    614                                       St, &IsNew);
    615   Succ->addPredecessor(Pred, *Eng.G);
    616   if (IsNew) {
    617     Eng.WList->enqueue(Succ);
    618     return Succ;
    619   }
    620   return NULL;
    621 }
    622 
    623 
    624 ExplodedNode*
    625 SwitchNodeBuilder::generateDefaultCaseNode(const ProgramState *St,
    626                                            bool isSink) {
    627   // Get the block for the default case.
    628   assert(Src->succ_rbegin() != Src->succ_rend());
    629   CFGBlock *DefaultBlock = *Src->succ_rbegin();
    630 
    631   // Sanity check for default blocks that are unreachable and not caught
    632   // by earlier stages.
    633   if (!DefaultBlock)
    634     return NULL;
    635 
    636   bool IsNew;
    637 
    638   ExplodedNode *Succ = Eng.G->getNode(BlockEdge(Src, DefaultBlock,
    639                                       Pred->getLocationContext()), St, &IsNew);
    640   Succ->addPredecessor(Pred, *Eng.G);
    641 
    642   if (IsNew) {
    643     if (isSink)
    644       Succ->markAsSink();
    645     else
    646       Eng.WList->enqueue(Succ);
    647 
    648     return Succ;
    649   }
    650 
    651   return NULL;
    652 }
    653 
    654 EndOfFunctionNodeBuilder::~EndOfFunctionNodeBuilder() {
    655   // Auto-generate an EOP node if one has not been generated.
    656   if (!hasGeneratedNode) {
    657     // If we are in an inlined call, generate CallExit node.
    658     if (Pred->getLocationContext()->getParent())
    659       GenerateCallExitNode(Pred->State);
    660     else
    661       generateNode(Pred->State);
    662   }
    663 }
    664 
    665 ExplodedNode*
    666 EndOfFunctionNodeBuilder::generateNode(const ProgramState *State,
    667                                        ExplodedNode *P,
    668                                        const ProgramPointTag *tag) {
    669   hasGeneratedNode = true;
    670   bool IsNew;
    671 
    672   ExplodedNode *Node = Eng.G->getNode(BlockEntrance(&B,
    673                                Pred->getLocationContext(), tag ? tag : Tag),
    674                                State, &IsNew);
    675 
    676   Node->addPredecessor(P ? P : Pred, *Eng.G);
    677 
    678   if (IsNew) {
    679     Eng.G->addEndOfPath(Node);
    680     return Node;
    681   }
    682 
    683   return NULL;
    684 }
    685 
    686 void EndOfFunctionNodeBuilder::GenerateCallExitNode(const ProgramState *state) {
    687   hasGeneratedNode = true;
    688   // Create a CallExit node and enqueue it.
    689   const StackFrameContext *LocCtx
    690                          = cast<StackFrameContext>(Pred->getLocationContext());
    691   const Stmt *CE = LocCtx->getCallSite();
    692 
    693   // Use the the callee location context.
    694   CallExit Loc(CE, LocCtx);
    695 
    696   bool isNew;
    697   ExplodedNode *Node = Eng.G->getNode(Loc, state, &isNew);
    698   Node->addPredecessor(Pred, *Eng.G);
    699 
    700   if (isNew)
    701     Eng.WList->enqueue(Node);
    702 }
    703 
    704 
    705 void CallEnterNodeBuilder::generateNode(const ProgramState *state) {
    706   // Check if the callee is in the same translation unit.
    707   if (CalleeCtx->getTranslationUnit() !=
    708       Pred->getLocationContext()->getTranslationUnit()) {
    709     // Create a new engine. We must be careful that the new engine should not
    710     // reference data structures owned by the old engine.
    711 
    712     AnalysisManager &OldMgr = Eng.SubEng.getAnalysisManager();
    713 
    714     // Get the callee's translation unit.
    715     idx::TranslationUnit *TU = CalleeCtx->getTranslationUnit();
    716 
    717     // Create a new AnalysisManager with components of the callee's
    718     // TranslationUnit.
    719     // The Diagnostic is  actually shared when we create ASTUnits from AST files.
    720     AnalysisManager AMgr(TU->getASTContext(), TU->getDiagnostic(), OldMgr);
    721 
    722     // Create the new engine.
    723     // FIXME: This cast isn't really safe.
    724     bool GCEnabled = static_cast<ExprEngine&>(Eng.SubEng).isObjCGCEnabled();
    725     ExprEngine NewEng(AMgr, GCEnabled);
    726 
    727     // Create the new LocationContext.
    728     AnalysisContext *NewAnaCtx = AMgr.getAnalysisContext(CalleeCtx->getDecl(),
    729                                                CalleeCtx->getTranslationUnit());
    730     const StackFrameContext *OldLocCtx = CalleeCtx;
    731     const StackFrameContext *NewLocCtx = AMgr.getStackFrame(NewAnaCtx,
    732                                                OldLocCtx->getParent(),
    733                                                OldLocCtx->getCallSite(),
    734                                                OldLocCtx->getCallSiteBlock(),
    735                                                OldLocCtx->getIndex());
    736 
    737     // Now create an initial state for the new engine.
    738     const ProgramState *NewState =
    739       NewEng.getStateManager().MarshalState(state, NewLocCtx);
    740     ExplodedNodeSet ReturnNodes;
    741     NewEng.ExecuteWorkListWithInitialState(NewLocCtx, AMgr.getMaxNodes(),
    742                                            NewState, ReturnNodes);
    743     return;
    744   }
    745 
    746   // Get the callee entry block.
    747   const CFGBlock *Entry = &(CalleeCtx->getCFG()->getEntry());
    748   assert(Entry->empty());
    749   assert(Entry->succ_size() == 1);
    750 
    751   // Get the solitary successor.
    752   const CFGBlock *SuccB = *(Entry->succ_begin());
    753 
    754   // Construct an edge representing the starting location in the callee.
    755   BlockEdge Loc(Entry, SuccB, CalleeCtx);
    756 
    757   bool isNew;
    758   ExplodedNode *Node = Eng.G->getNode(Loc, state, &isNew);
    759   Node->addPredecessor(const_cast<ExplodedNode*>(Pred), *Eng.G);
    760 
    761   if (isNew)
    762     Eng.WList->enqueue(Node);
    763 }
    764 
    765 void CallExitNodeBuilder::generateNode(const ProgramState *state) {
    766   // Get the callee's location context.
    767   const StackFrameContext *LocCtx
    768                          = cast<StackFrameContext>(Pred->getLocationContext());
    769   // When exiting an implicit automatic obj dtor call, the callsite is the Stmt
    770   // that triggers the dtor.
    771   PostStmt Loc(LocCtx->getCallSite(), LocCtx->getParent());
    772   bool isNew;
    773   ExplodedNode *Node = Eng.G->getNode(Loc, state, &isNew);
    774   Node->addPredecessor(const_cast<ExplodedNode*>(Pred), *Eng.G);
    775   if (isNew)
    776     Eng.WList->enqueue(Node, LocCtx->getCallSiteBlock(),
    777                        LocCtx->getIndex() + 1);
    778 }
    779