1   //===--- CFG.cpp - Classes for representing and building CFGs----*- 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 the CFG and CFGBuilder classes for representing and
11 //  building Control-Flow Graphs (CFGs) from ASTs.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Analysis/CFG.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/PrettyPrinter.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/Basic/Builtins.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/OwningPtr.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Format.h"
28 #include "llvm/Support/GraphWriter.h"
29 #include "llvm/Support/SaveAndRestore.h"
30 
31 using namespace clang;
32 
33 namespace {
34 
35 static SourceLocation GetEndLoc(Decl *D) {
36   if (VarDecl *VD = dyn_cast<VarDecl>(D))
37     if (Expr *Ex = VD->getInit())
38       return Ex->getSourceRange().getEnd();
39   return D->getLocation();
40 }
41 
42 class CFGBuilder;
43 
44 /// The CFG builder uses a recursive algorithm to build the CFG.  When
45 ///  we process an expression, sometimes we know that we must add the
46 ///  subexpressions as block-level expressions.  For example:
47 ///
48 ///    exp1 || exp2
49 ///
50 ///  When processing the '||' expression, we know that exp1 and exp2
51 ///  need to be added as block-level expressions, even though they
52 ///  might not normally need to be.  AddStmtChoice records this
53 ///  contextual information.  If AddStmtChoice is 'NotAlwaysAdd', then
54 ///  the builder has an option not to add a subexpression as a
55 ///  block-level expression.
56 ///
57 class AddStmtChoice {
58 public:
59   enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
60 
61   AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
62 
63   bool alwaysAdd(CFGBuilder &builder,
64                  const Stmt *stmt) const;
65 
66   /// Return a copy of this object, except with the 'always-add' bit
67   ///  set as specified.
68   AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
69     return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
70   }
71 
72 private:
73   Kind kind;
74 };
75 
76 /// LocalScope - Node in tree of local scopes created for C++ implicit
77 /// destructor calls generation. It contains list of automatic variables
78 /// declared in the scope and link to position in previous scope this scope
79 /// began in.
80 ///
81 /// The process of creating local scopes is as follows:
82 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
83 /// - Before processing statements in scope (e.g. CompoundStmt) create
84 ///   LocalScope object using CFGBuilder::ScopePos as link to previous scope
85 ///   and set CFGBuilder::ScopePos to the end of new scope,
86 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
87 ///   at this VarDecl,
88 /// - For every normal (without jump) end of scope add to CFGBlock destructors
89 ///   for objects in the current scope,
90 /// - For every jump add to CFGBlock destructors for objects
91 ///   between CFGBuilder::ScopePos and local scope position saved for jump
92 ///   target. Thanks to C++ restrictions on goto jumps we can be sure that
93 ///   jump target position will be on the path to root from CFGBuilder::ScopePos
94 ///   (adding any variable that doesn't need constructor to be called to
95 ///   LocalScope can break this assumption),
96 ///
97 class LocalScope {
98 public:
99   typedef BumpVector<VarDecl*> AutomaticVarsTy;
100 
101   /// const_iterator - Iterates local scope backwards and jumps to previous
102   /// scope on reaching the beginning of currently iterated scope.
103   class const_iterator {
104     const LocalScope* Scope;
105 
106     /// VarIter is guaranteed to be greater then 0 for every valid iterator.
107     /// Invalid iterator (with null Scope) has VarIter equal to 0.
108     unsigned VarIter;
109 
110   public:
111     /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
112     /// Incrementing invalid iterator is allowed and will result in invalid
113     /// iterator.
114     const_iterator()
115         : Scope(NULL), VarIter(0) {}
116 
117     /// Create valid iterator. In case when S.Prev is an invalid iterator and
118     /// I is equal to 0, this will create invalid iterator.
119     const_iterator(const LocalScope& S, unsigned I)
120         : Scope(&S), VarIter(I) {
121       // Iterator to "end" of scope is not allowed. Handle it by going up
122       // in scopes tree possibly up to invalid iterator in the root.
123       if (VarIter == 0 && Scope)
124         *this = Scope->Prev;
125     }
126 
127     VarDecl *const* operator->() const {
128       assert (Scope && "Dereferencing invalid iterator is not allowed");
129       assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
130       return &Scope->Vars[VarIter - 1];
131     }
132     VarDecl *operator*() const {
133       return *this->operator->();
134     }
135 
136     const_iterator &operator++() {
137       if (!Scope)
138         return *this;
139 
140       assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
141       --VarIter;
142       if (VarIter == 0)
143         *this = Scope->Prev;
144       return *this;
145     }
146     const_iterator operator++(int) {
147       const_iterator P = *this;
148       ++*this;
149       return P;
150     }
151 
152     bool operator==(const const_iterator &rhs) const {
153       return Scope == rhs.Scope && VarIter == rhs.VarIter;
154     }
155     bool operator!=(const const_iterator &rhs) const {
156       return !(*this == rhs);
157     }
158 
159     LLVM_EXPLICIT operator bool() const {
160       return *this != const_iterator();
161     }
162 
163     int distance(const_iterator L);
164   };
165 
166   friend class const_iterator;
167 
168 private:
169   BumpVectorContext ctx;
170 
171   /// Automatic variables in order of declaration.
172   AutomaticVarsTy Vars;
173   /// Iterator to variable in previous scope that was declared just before
174   /// begin of this scope.
175   const_iterator Prev;
176 
177 public:
178   /// Constructs empty scope linked to previous scope in specified place.
179   LocalScope(BumpVectorContext &ctx, const_iterator P)
180       : ctx(ctx), Vars(ctx, 4), Prev(P) {}
181 
182   /// Begin of scope in direction of CFG building (backwards).
183   const_iterator begin() const { return const_iterator(*this, Vars.size()); }
184 
185   void addVar(VarDecl *VD) {
186     Vars.push_back(VD, ctx);
187   }
188 };
189 
190 /// distance - Calculates distance from this to L. L must be reachable from this
191 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
192 /// number of scopes between this and L.
193 int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
194   int D = 0;
195   const_iterator F = *this;
196   while (F.Scope != L.Scope) {
197     assert (F != const_iterator()
198         && "L iterator is not reachable from F iterator.");
199     D += F.VarIter;
200     F = F.Scope->Prev;
201   }
202   D += F.VarIter - L.VarIter;
203   return D;
204 }
205 
206 /// BlockScopePosPair - Structure for specifying position in CFG during its
207 /// build process. It consists of CFGBlock that specifies position in CFG graph
208 /// and  LocalScope::const_iterator that specifies position in LocalScope graph.
209 struct BlockScopePosPair {
210   BlockScopePosPair() : block(0) {}
211   BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
212       : block(b), scopePosition(scopePos) {}
213 
214   CFGBlock *block;
215   LocalScope::const_iterator scopePosition;
216 };
217 
218 /// TryResult - a class representing a variant over the values
219 ///  'true', 'false', or 'unknown'.  This is returned by tryEvaluateBool,
220 ///  and is used by the CFGBuilder to decide if a branch condition
221 ///  can be decided up front during CFG construction.
222 class TryResult {
223   int X;
224 public:
225   TryResult(bool b) : X(b ? 1 : 0) {}
226   TryResult() : X(-1) {}
227 
228   bool isTrue() const { return X == 1; }
229   bool isFalse() const { return X == 0; }
230   bool isKnown() const { return X >= 0; }
231   void negate() {
232     assert(isKnown());
233     X ^= 0x1;
234   }
235 };
236 
237 class reverse_children {
238   llvm::SmallVector<Stmt *, 12> childrenBuf;
239   ArrayRef<Stmt*> children;
240 public:
241   reverse_children(Stmt *S);
242 
243   typedef ArrayRef<Stmt*>::reverse_iterator iterator;
244   iterator begin() const { return children.rbegin(); }
245   iterator end() const { return children.rend(); }
246 };
247 
248 
249 reverse_children::reverse_children(Stmt *S) {
250   if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
251     children = CE->getRawSubExprs();
252     return;
253   }
254   switch (S->getStmtClass()) {
255     // Note: Fill in this switch with more cases we want to optimize.
256     case Stmt::InitListExprClass: {
257       InitListExpr *IE = cast<InitListExpr>(S);
258       children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
259                                     IE->getNumInits());
260       return;
261     }
262     default:
263       break;
264   }
265 
266   // Default case for all other statements.
267   for (Stmt::child_range I = S->children(); I; ++I) {
268     childrenBuf.push_back(*I);
269   }
270 
271   // This needs to be done *after* childrenBuf has been populated.
272   children = childrenBuf;
273 }
274 
275 /// CFGBuilder - This class implements CFG construction from an AST.
276 ///   The builder is stateful: an instance of the builder should be used to only
277 ///   construct a single CFG.
278 ///
279 ///   Example usage:
280 ///
281 ///     CFGBuilder builder;
282 ///     CFG* cfg = builder.BuildAST(stmt1);
283 ///
284 ///  CFG construction is done via a recursive walk of an AST.  We actually parse
285 ///  the AST in reverse order so that the successor of a basic block is
286 ///  constructed prior to its predecessor.  This allows us to nicely capture
287 ///  implicit fall-throughs without extra basic blocks.
288 ///
289 class CFGBuilder {
290   typedef BlockScopePosPair JumpTarget;
291   typedef BlockScopePosPair JumpSource;
292 
293   ASTContext *Context;
294   OwningPtr<CFG> cfg;
295 
296   CFGBlock *Block;
297   CFGBlock *Succ;
298   JumpTarget ContinueJumpTarget;
299   JumpTarget BreakJumpTarget;
300   CFGBlock *SwitchTerminatedBlock;
301   CFGBlock *DefaultCaseBlock;
302   CFGBlock *TryTerminatedBlock;
303 
304   // Current position in local scope.
305   LocalScope::const_iterator ScopePos;
306 
307   // LabelMap records the mapping from Label expressions to their jump targets.
308   typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy;
309   LabelMapTy LabelMap;
310 
311   // A list of blocks that end with a "goto" that must be backpatched to their
312   // resolved targets upon completion of CFG construction.
313   typedef std::vector<JumpSource> BackpatchBlocksTy;
314   BackpatchBlocksTy BackpatchBlocks;
315 
316   // A list of labels whose address has been taken (for indirect gotos).
317   typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy;
318   LabelSetTy AddressTakenLabels;
319 
320   bool badCFG;
321   const CFG::BuildOptions &BuildOpts;
322 
323   // State to track for building switch statements.
324   bool switchExclusivelyCovered;
325   Expr::EvalResult *switchCond;
326 
327   CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry;
328   const Stmt *lastLookup;
329 
330   // Caches boolean evaluations of expressions to avoid multiple re-evaluations
331   // during construction of branches for chained logical operators.
332   typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy;
333   CachedBoolEvalsTy CachedBoolEvals;
334 
335 public:
336   explicit CFGBuilder(ASTContext *astContext,
337                       const CFG::BuildOptions &buildOpts)
338     : Context(astContext), cfg(new CFG()), // crew a new CFG
339       Block(NULL), Succ(NULL),
340       SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL),
341       TryTerminatedBlock(NULL), badCFG(false), BuildOpts(buildOpts),
342       switchExclusivelyCovered(false), switchCond(0),
343       cachedEntry(0), lastLookup(0) {}
344 
345   // buildCFG - Used by external clients to construct the CFG.
346   CFG* buildCFG(const Decl *D, Stmt *Statement);
347 
348   bool alwaysAdd(const Stmt *stmt);
349 
350 private:
351   // Visitors to walk an AST and construct the CFG.
352   CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
353   CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
354   CFGBlock *VisitBreakStmt(BreakStmt *B);
355   CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
356   CFGBlock *VisitCaseStmt(CaseStmt *C);
357   CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
358   CFGBlock *VisitCompoundStmt(CompoundStmt *C);
359   CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
360                                      AddStmtChoice asc);
361   CFGBlock *VisitContinueStmt(ContinueStmt *C);
362   CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
363                                       AddStmtChoice asc);
364   CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
365   CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
366   CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
367   CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
368   CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
369                                        AddStmtChoice asc);
370   CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
371                                         AddStmtChoice asc);
372   CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
373   CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
374   CFGBlock *VisitDeclStmt(DeclStmt *DS);
375   CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
376   CFGBlock *VisitDefaultStmt(DefaultStmt *D);
377   CFGBlock *VisitDoStmt(DoStmt *D);
378   CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
379   CFGBlock *VisitForStmt(ForStmt *F);
380   CFGBlock *VisitGotoStmt(GotoStmt *G);
381   CFGBlock *VisitIfStmt(IfStmt *I);
382   CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
383   CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
384   CFGBlock *VisitLabelStmt(LabelStmt *L);
385   CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
386   CFGBlock *VisitLogicalOperator(BinaryOperator *B);
387   std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
388                                                          Stmt *Term,
389                                                          CFGBlock *TrueBlock,
390                                                          CFGBlock *FalseBlock);
391   CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
392   CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
393   CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
394   CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
395   CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
396   CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
397   CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
398   CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
399   CFGBlock *VisitReturnStmt(ReturnStmt *R);
400   CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
401   CFGBlock *VisitSwitchStmt(SwitchStmt *S);
402   CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
403                                           AddStmtChoice asc);
404   CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
405   CFGBlock *VisitWhileStmt(WhileStmt *W);
406 
407   CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
408   CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
409   CFGBlock *VisitChildren(Stmt *S);
410   CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
411 
412   // Visitors to walk an AST and generate destructors of temporaries in
413   // full expression.
414   CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary = false);
415   CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E);
416   CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E);
417   CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(CXXBindTemporaryExpr *E,
418       bool BindToTemporary);
419   CFGBlock *
420   VisitConditionalOperatorForTemporaryDtors(AbstractConditionalOperator *E,
421                                             bool BindToTemporary);
422 
423   // NYS == Not Yet Supported
424   CFGBlock *NYS() {
425     badCFG = true;
426     return Block;
427   }
428 
429   void autoCreateBlock() { if (!Block) Block = createBlock(); }
430   CFGBlock *createBlock(bool add_successor = true);
431   CFGBlock *createNoReturnBlock();
432 
433   CFGBlock *addStmt(Stmt *S) {
434     return Visit(S, AddStmtChoice::AlwaysAdd);
435   }
436   CFGBlock *addInitializer(CXXCtorInitializer *I);
437   void addAutomaticObjDtors(LocalScope::const_iterator B,
438                             LocalScope::const_iterator E, Stmt *S);
439   void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
440 
441   // Local scopes creation.
442   LocalScope* createOrReuseLocalScope(LocalScope* Scope);
443 
444   void addLocalScopeForStmt(Stmt *S);
445   LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS, LocalScope* Scope = NULL);
446   LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = NULL);
447 
448   void addLocalScopeAndDtors(Stmt *S);
449 
450   // Interface to CFGBlock - adding CFGElements.
451   void appendStmt(CFGBlock *B, const Stmt *S) {
452     if (alwaysAdd(S) && cachedEntry)
453       cachedEntry->second = B;
454 
455     // All block-level expressions should have already been IgnoreParens()ed.
456     assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
457     B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
458   }
459   void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
460     B->appendInitializer(I, cfg->getBumpVectorContext());
461   }
462   void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
463     B->appendBaseDtor(BS, cfg->getBumpVectorContext());
464   }
465   void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
466     B->appendMemberDtor(FD, cfg->getBumpVectorContext());
467   }
468   void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
469     B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
470   }
471   void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
472     B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
473   }
474 
475   void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
476     B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
477   }
478 
479   void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
480       LocalScope::const_iterator B, LocalScope::const_iterator E);
481 
482   void addSuccessor(CFGBlock *B, CFGBlock *S) {
483     B->addSuccessor(S, cfg->getBumpVectorContext());
484   }
485 
486   /// Try and evaluate an expression to an integer constant.
487   bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
488     if (!BuildOpts.PruneTriviallyFalseEdges)
489       return false;
490     return !S->isTypeDependent() &&
491            !S->isValueDependent() &&
492            S->EvaluateAsRValue(outResult, *Context);
493   }
494 
495   /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
496   /// if we can evaluate to a known value, otherwise return -1.
497   TryResult tryEvaluateBool(Expr *S) {
498     if (!BuildOpts.PruneTriviallyFalseEdges ||
499         S->isTypeDependent() || S->isValueDependent())
500       return TryResult();
501 
502     if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
503       if (Bop->isLogicalOp()) {
504         // Check the cache first.
505         CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
506         if (I != CachedBoolEvals.end())
507           return I->second; // already in map;
508 
509         // Retrieve result at first, or the map might be updated.
510         TryResult Result = evaluateAsBooleanConditionNoCache(S);
511         CachedBoolEvals[S] = Result; // update or insert
512         return Result;
513       }
514       else {
515         switch (Bop->getOpcode()) {
516           default: break;
517           // For 'x & 0' and 'x * 0', we can determine that
518           // the value is always false.
519           case BO_Mul:
520           case BO_And: {
521             // If either operand is zero, we know the value
522             // must be false.
523             llvm::APSInt IntVal;
524             if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
525               if (IntVal.getBoolValue() == false) {
526                 return TryResult(false);
527               }
528             }
529             if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
530               if (IntVal.getBoolValue() == false) {
531                 return TryResult(false);
532               }
533             }
534           }
535           break;
536         }
537       }
538     }
539 
540     return evaluateAsBooleanConditionNoCache(S);
541   }
542 
543   /// \brief Evaluate as boolean \param E without using the cache.
544   TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
545     if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
546       if (Bop->isLogicalOp()) {
547         TryResult LHS = tryEvaluateBool(Bop->getLHS());
548         if (LHS.isKnown()) {
549           // We were able to evaluate the LHS, see if we can get away with not
550           // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
551           if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
552             return LHS.isTrue();
553 
554           TryResult RHS = tryEvaluateBool(Bop->getRHS());
555           if (RHS.isKnown()) {
556             if (Bop->getOpcode() == BO_LOr)
557               return LHS.isTrue() || RHS.isTrue();
558             else
559               return LHS.isTrue() && RHS.isTrue();
560           }
561         } else {
562           TryResult RHS = tryEvaluateBool(Bop->getRHS());
563           if (RHS.isKnown()) {
564             // We can't evaluate the LHS; however, sometimes the result
565             // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
566             if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
567               return RHS.isTrue();
568           }
569         }
570 
571         return TryResult();
572       }
573     }
574 
575     bool Result;
576     if (E->EvaluateAsBooleanCondition(Result, *Context))
577       return Result;
578 
579     return TryResult();
580   }
581 
582 };
583 
584 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
585                                      const Stmt *stmt) const {
586   return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
587 }
588 
589 bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
590   bool shouldAdd = BuildOpts.alwaysAdd(stmt);
591 
592   if (!BuildOpts.forcedBlkExprs)
593     return shouldAdd;
594 
595   if (lastLookup == stmt) {
596     if (cachedEntry) {
597       assert(cachedEntry->first == stmt);
598       return true;
599     }
600     return shouldAdd;
601   }
602 
603   lastLookup = stmt;
604 
605   // Perform the lookup!
606   CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
607 
608   if (!fb) {
609     // No need to update 'cachedEntry', since it will always be null.
610     assert(cachedEntry == 0);
611     return shouldAdd;
612   }
613 
614   CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
615   if (itr == fb->end()) {
616     cachedEntry = 0;
617     return shouldAdd;
618   }
619 
620   cachedEntry = &*itr;
621   return true;
622 }
623 
624 // FIXME: Add support for dependent-sized array types in C++?
625 // Does it even make sense to build a CFG for an uninstantiated template?
626 static const VariableArrayType *FindVA(const Type *t) {
627   while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
628     if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
629       if (vat->getSizeExpr())
630         return vat;
631 
632     t = vt->getElementType().getTypePtr();
633   }
634 
635   return 0;
636 }
637 
638 /// BuildCFG - Constructs a CFG from an AST (a Stmt*).  The AST can represent an
639 ///  arbitrary statement.  Examples include a single expression or a function
640 ///  body (compound statement).  The ownership of the returned CFG is
641 ///  transferred to the caller.  If CFG construction fails, this method returns
642 ///  NULL.
643 CFG* CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
644   assert(cfg.get());
645   if (!Statement)
646     return NULL;
647 
648   // Create an empty block that will serve as the exit block for the CFG.  Since
649   // this is the first block added to the CFG, it will be implicitly registered
650   // as the exit block.
651   Succ = createBlock();
652   assert(Succ == &cfg->getExit());
653   Block = NULL;  // the EXIT block is empty.  Create all other blocks lazily.
654 
655   if (BuildOpts.AddImplicitDtors)
656     if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
657       addImplicitDtorsForDestructor(DD);
658 
659   // Visit the statements and create the CFG.
660   CFGBlock *B = addStmt(Statement);
661 
662   if (badCFG)
663     return NULL;
664 
665   // For C++ constructor add initializers to CFG.
666   if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
667     for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(),
668         E = CD->init_rend(); I != E; ++I) {
669       B = addInitializer(*I);
670       if (badCFG)
671         return NULL;
672     }
673   }
674 
675   if (B)
676     Succ = B;
677 
678   // Backpatch the gotos whose label -> block mappings we didn't know when we
679   // encountered them.
680   for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
681                                    E = BackpatchBlocks.end(); I != E; ++I ) {
682 
683     CFGBlock *B = I->block;
684     const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
685     LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
686 
687     // If there is no target for the goto, then we are looking at an
688     // incomplete AST.  Handle this by not registering a successor.
689     if (LI == LabelMap.end()) continue;
690 
691     JumpTarget JT = LI->second;
692     prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
693                                            JT.scopePosition);
694     addSuccessor(B, JT.block);
695   }
696 
697   // Add successors to the Indirect Goto Dispatch block (if we have one).
698   if (CFGBlock *B = cfg->getIndirectGotoBlock())
699     for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
700                               E = AddressTakenLabels.end(); I != E; ++I ) {
701 
702       // Lookup the target block.
703       LabelMapTy::iterator LI = LabelMap.find(*I);
704 
705       // If there is no target block that contains label, then we are looking
706       // at an incomplete AST.  Handle this by not registering a successor.
707       if (LI == LabelMap.end()) continue;
708 
709       addSuccessor(B, LI->second.block);
710     }
711 
712   // Create an empty entry block that has no predecessors.
713   cfg->setEntry(createBlock());
714 
715   return cfg.take();
716 }
717 
718 /// createBlock - Used to lazily create blocks that are connected
719 ///  to the current (global) succcessor.
720 CFGBlock *CFGBuilder::createBlock(bool add_successor) {
721   CFGBlock *B = cfg->createBlock();
722   if (add_successor && Succ)
723     addSuccessor(B, Succ);
724   return B;
725 }
726 
727 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
728 /// CFG. It is *not* connected to the current (global) successor, and instead
729 /// directly tied to the exit block in order to be reachable.
730 CFGBlock *CFGBuilder::createNoReturnBlock() {
731   CFGBlock *B = createBlock(false);
732   B->setHasNoReturnElement();
733   addSuccessor(B, &cfg->getExit());
734   return B;
735 }
736 
737 /// addInitializer - Add C++ base or member initializer element to CFG.
738 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
739   if (!BuildOpts.AddInitializers)
740     return Block;
741 
742   bool IsReference = false;
743   bool HasTemporaries = false;
744 
745   // Destructors of temporaries in initialization expression should be called
746   // after initialization finishes.
747   Expr *Init = I->getInit();
748   if (Init) {
749     if (FieldDecl *FD = I->getAnyMember())
750       IsReference = FD->getType()->isReferenceType();
751     HasTemporaries = isa<ExprWithCleanups>(Init);
752 
753     if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
754       // Generate destructors for temporaries in initialization expression.
755       VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
756           IsReference);
757     }
758   }
759 
760   autoCreateBlock();
761   appendInitializer(Block, I);
762 
763   if (Init) {
764     if (HasTemporaries) {
765       // For expression with temporaries go directly to subexpression to omit
766       // generating destructors for the second time.
767       return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
768     }
769     return Visit(Init);
770   }
771 
772   return Block;
773 }
774 
775 /// \brief Retrieve the type of the temporary object whose lifetime was
776 /// extended by a local reference with the given initializer.
777 static QualType getReferenceInitTemporaryType(ASTContext &Context,
778                                               const Expr *Init) {
779   while (true) {
780     // Skip parentheses.
781     Init = Init->IgnoreParens();
782 
783     // Skip through cleanups.
784     if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
785       Init = EWC->getSubExpr();
786       continue;
787     }
788 
789     // Skip through the temporary-materialization expression.
790     if (const MaterializeTemporaryExpr *MTE
791           = dyn_cast<MaterializeTemporaryExpr>(Init)) {
792       Init = MTE->GetTemporaryExpr();
793       continue;
794     }
795 
796     // Skip derived-to-base and no-op casts.
797     if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
798       if ((CE->getCastKind() == CK_DerivedToBase ||
799            CE->getCastKind() == CK_UncheckedDerivedToBase ||
800            CE->getCastKind() == CK_NoOp) &&
801           Init->getType()->isRecordType()) {
802         Init = CE->getSubExpr();
803         continue;
804       }
805     }
806 
807     // Skip member accesses into rvalues.
808     if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
809       if (!ME->isArrow() && ME->getBase()->isRValue()) {
810         Init = ME->getBase();
811         continue;
812       }
813     }
814 
815     break;
816   }
817 
818   return Init->getType();
819 }
820 
821 /// addAutomaticObjDtors - Add to current block automatic objects destructors
822 /// for objects in range of local scope positions. Use S as trigger statement
823 /// for destructors.
824 void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
825                                       LocalScope::const_iterator E, Stmt *S) {
826   if (!BuildOpts.AddImplicitDtors)
827     return;
828 
829   if (B == E)
830     return;
831 
832   // We need to append the destructors in reverse order, but any one of them
833   // may be a no-return destructor which changes the CFG. As a result, buffer
834   // this sequence up and replay them in reverse order when appending onto the
835   // CFGBlock(s).
836   SmallVector<VarDecl*, 10> Decls;
837   Decls.reserve(B.distance(E));
838   for (LocalScope::const_iterator I = B; I != E; ++I)
839     Decls.push_back(*I);
840 
841   for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
842                                                    E = Decls.rend();
843        I != E; ++I) {
844     // If this destructor is marked as a no-return destructor, we need to
845     // create a new block for the destructor which does not have as a successor
846     // anything built thus far: control won't flow out of this block.
847     QualType Ty = (*I)->getType();
848     if (Ty->isReferenceType()) {
849       Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
850     }
851     Ty = Context->getBaseElementType(Ty);
852 
853     const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
854     if (Dtor->isNoReturn())
855       Block = createNoReturnBlock();
856     else
857       autoCreateBlock();
858 
859     appendAutomaticObjDtor(Block, *I, S);
860   }
861 }
862 
863 /// addImplicitDtorsForDestructor - Add implicit destructors generated for
864 /// base and member objects in destructor.
865 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
866   assert (BuildOpts.AddImplicitDtors
867       && "Can be called only when dtors should be added");
868   const CXXRecordDecl *RD = DD->getParent();
869 
870   // At the end destroy virtual base objects.
871   for (CXXRecordDecl::base_class_const_iterator VI = RD->vbases_begin(),
872       VE = RD->vbases_end(); VI != VE; ++VI) {
873     const CXXRecordDecl *CD = VI->getType()->getAsCXXRecordDecl();
874     if (!CD->hasTrivialDestructor()) {
875       autoCreateBlock();
876       appendBaseDtor(Block, VI);
877     }
878   }
879 
880   // Before virtual bases destroy direct base objects.
881   for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
882       BE = RD->bases_end(); BI != BE; ++BI) {
883     if (!BI->isVirtual()) {
884       const CXXRecordDecl *CD = BI->getType()->getAsCXXRecordDecl();
885       if (!CD->hasTrivialDestructor()) {
886         autoCreateBlock();
887         appendBaseDtor(Block, BI);
888       }
889     }
890   }
891 
892   // First destroy member objects.
893   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
894       FE = RD->field_end(); FI != FE; ++FI) {
895     // Check for constant size array. Set type to array element type.
896     QualType QT = FI->getType();
897     if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
898       if (AT->getSize() == 0)
899         continue;
900       QT = AT->getElementType();
901     }
902 
903     if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
904       if (!CD->hasTrivialDestructor()) {
905         autoCreateBlock();
906         appendMemberDtor(Block, *FI);
907       }
908   }
909 }
910 
911 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
912 /// way return valid LocalScope object.
913 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
914   if (!Scope) {
915     llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
916     Scope = alloc.Allocate<LocalScope>();
917     BumpVectorContext ctx(alloc);
918     new (Scope) LocalScope(ctx, ScopePos);
919   }
920   return Scope;
921 }
922 
923 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
924 /// that should create implicit scope (e.g. if/else substatements).
925 void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
926   if (!BuildOpts.AddImplicitDtors)
927     return;
928 
929   LocalScope *Scope = 0;
930 
931   // For compound statement we will be creating explicit scope.
932   if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
933     for (CompoundStmt::body_iterator BI = CS->body_begin(), BE = CS->body_end()
934         ; BI != BE; ++BI) {
935       Stmt *SI = (*BI)->stripLabelLikeStatements();
936       if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
937         Scope = addLocalScopeForDeclStmt(DS, Scope);
938     }
939     return;
940   }
941 
942   // For any other statement scope will be implicit and as such will be
943   // interesting only for DeclStmt.
944   if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
945     addLocalScopeForDeclStmt(DS);
946 }
947 
948 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
949 /// reuse Scope if not NULL.
950 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
951                                                  LocalScope* Scope) {
952   if (!BuildOpts.AddImplicitDtors)
953     return Scope;
954 
955   for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end()
956       ; DI != DE; ++DI) {
957     if (VarDecl *VD = dyn_cast<VarDecl>(*DI))
958       Scope = addLocalScopeForVarDecl(VD, Scope);
959   }
960   return Scope;
961 }
962 
963 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
964 /// create add scope for automatic objects and temporary objects bound to
965 /// const reference. Will reuse Scope if not NULL.
966 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
967                                                 LocalScope* Scope) {
968   if (!BuildOpts.AddImplicitDtors)
969     return Scope;
970 
971   // Check if variable is local.
972   switch (VD->getStorageClass()) {
973   case SC_None:
974   case SC_Auto:
975   case SC_Register:
976     break;
977   default: return Scope;
978   }
979 
980   // Check for const references bound to temporary. Set type to pointee.
981   QualType QT = VD->getType();
982   if (QT.getTypePtr()->isReferenceType()) {
983     // Attempt to determine whether this declaration lifetime-extends a
984     // temporary.
985     //
986     // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
987     // temporaries, and a single declaration can extend multiple temporaries.
988     // We should look at the storage duration on each nested
989     // MaterializeTemporaryExpr instead.
990     const Expr *Init = VD->getInit();
991     if (!Init)
992       return Scope;
993     if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init))
994       Init = EWC->getSubExpr();
995     if (!isa<MaterializeTemporaryExpr>(Init))
996       return Scope;
997 
998     // Lifetime-extending a temporary.
999     QT = getReferenceInitTemporaryType(*Context, Init);
1000   }
1001 
1002   // Check for constant size array. Set type to array element type.
1003   while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1004     if (AT->getSize() == 0)
1005       return Scope;
1006     QT = AT->getElementType();
1007   }
1008 
1009   // Check if type is a C++ class with non-trivial destructor.
1010   if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1011     if (!CD->hasTrivialDestructor()) {
1012       // Add the variable to scope
1013       Scope = createOrReuseLocalScope(Scope);
1014       Scope->addVar(VD);
1015       ScopePos = Scope->begin();
1016     }
1017   return Scope;
1018 }
1019 
1020 /// addLocalScopeAndDtors - For given statement add local scope for it and
1021 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
1022 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
1023   if (!BuildOpts.AddImplicitDtors)
1024     return;
1025 
1026   LocalScope::const_iterator scopeBeginPos = ScopePos;
1027   addLocalScopeForStmt(S);
1028   addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
1029 }
1030 
1031 /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1032 /// variables with automatic storage duration to CFGBlock's elements vector.
1033 /// Elements will be prepended to physical beginning of the vector which
1034 /// happens to be logical end. Use blocks terminator as statement that specifies
1035 /// destructors call site.
1036 /// FIXME: This mechanism for adding automatic destructors doesn't handle
1037 /// no-return destructors properly.
1038 void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
1039     LocalScope::const_iterator B, LocalScope::const_iterator E) {
1040   BumpVectorContext &C = cfg->getBumpVectorContext();
1041   CFGBlock::iterator InsertPos
1042     = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1043   for (LocalScope::const_iterator I = B; I != E; ++I)
1044     InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1045                                             Blk->getTerminator());
1046 }
1047 
1048 /// Visit - Walk the subtree of a statement and add extra
1049 ///   blocks for ternary operators, &&, and ||.  We also process "," and
1050 ///   DeclStmts (which may contain nested control-flow).
1051 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
1052   if (!S) {
1053     badCFG = true;
1054     return 0;
1055   }
1056 
1057   if (Expr *E = dyn_cast<Expr>(S))
1058     S = E->IgnoreParens();
1059 
1060   switch (S->getStmtClass()) {
1061     default:
1062       return VisitStmt(S, asc);
1063 
1064     case Stmt::AddrLabelExprClass:
1065       return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
1066 
1067     case Stmt::BinaryConditionalOperatorClass:
1068       return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1069 
1070     case Stmt::BinaryOperatorClass:
1071       return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
1072 
1073     case Stmt::BlockExprClass:
1074       return VisitNoRecurse(cast<Expr>(S), asc);
1075 
1076     case Stmt::BreakStmtClass:
1077       return VisitBreakStmt(cast<BreakStmt>(S));
1078 
1079     case Stmt::CallExprClass:
1080     case Stmt::CXXOperatorCallExprClass:
1081     case Stmt::CXXMemberCallExprClass:
1082     case Stmt::UserDefinedLiteralClass:
1083       return VisitCallExpr(cast<CallExpr>(S), asc);
1084 
1085     case Stmt::CaseStmtClass:
1086       return VisitCaseStmt(cast<CaseStmt>(S));
1087 
1088     case Stmt::ChooseExprClass:
1089       return VisitChooseExpr(cast<ChooseExpr>(S), asc);
1090 
1091     case Stmt::CompoundStmtClass:
1092       return VisitCompoundStmt(cast<CompoundStmt>(S));
1093 
1094     case Stmt::ConditionalOperatorClass:
1095       return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
1096 
1097     case Stmt::ContinueStmtClass:
1098       return VisitContinueStmt(cast<ContinueStmt>(S));
1099 
1100     case Stmt::CXXCatchStmtClass:
1101       return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1102 
1103     case Stmt::ExprWithCleanupsClass:
1104       return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
1105 
1106     case Stmt::CXXDefaultArgExprClass:
1107     case Stmt::CXXDefaultInitExprClass:
1108       // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1109       // called function's declaration, not by the caller. If we simply add
1110       // this expression to the CFG, we could end up with the same Expr
1111       // appearing multiple times.
1112       // PR13385 / <rdar://problem/12156507>
1113       //
1114       // It's likewise possible for multiple CXXDefaultInitExprs for the same
1115       // expression to be used in the same function (through aggregate
1116       // initialization).
1117       return VisitStmt(S, asc);
1118 
1119     case Stmt::CXXBindTemporaryExprClass:
1120       return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1121 
1122     case Stmt::CXXConstructExprClass:
1123       return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1124 
1125     case Stmt::CXXDeleteExprClass:
1126       return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1127 
1128     case Stmt::CXXFunctionalCastExprClass:
1129       return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1130 
1131     case Stmt::CXXTemporaryObjectExprClass:
1132       return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1133 
1134     case Stmt::CXXThrowExprClass:
1135       return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
1136 
1137     case Stmt::CXXTryStmtClass:
1138       return VisitCXXTryStmt(cast<CXXTryStmt>(S));
1139 
1140     case Stmt::CXXForRangeStmtClass:
1141       return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1142 
1143     case Stmt::DeclStmtClass:
1144       return VisitDeclStmt(cast<DeclStmt>(S));
1145 
1146     case Stmt::DefaultStmtClass:
1147       return VisitDefaultStmt(cast<DefaultStmt>(S));
1148 
1149     case Stmt::DoStmtClass:
1150       return VisitDoStmt(cast<DoStmt>(S));
1151 
1152     case Stmt::ForStmtClass:
1153       return VisitForStmt(cast<ForStmt>(S));
1154 
1155     case Stmt::GotoStmtClass:
1156       return VisitGotoStmt(cast<GotoStmt>(S));
1157 
1158     case Stmt::IfStmtClass:
1159       return VisitIfStmt(cast<IfStmt>(S));
1160 
1161     case Stmt::ImplicitCastExprClass:
1162       return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
1163 
1164     case Stmt::IndirectGotoStmtClass:
1165       return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
1166 
1167     case Stmt::LabelStmtClass:
1168       return VisitLabelStmt(cast<LabelStmt>(S));
1169 
1170     case Stmt::LambdaExprClass:
1171       return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1172 
1173     case Stmt::MemberExprClass:
1174       return VisitMemberExpr(cast<MemberExpr>(S), asc);
1175 
1176     case Stmt::NullStmtClass:
1177       return Block;
1178 
1179     case Stmt::ObjCAtCatchStmtClass:
1180       return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1181 
1182     case Stmt::ObjCAutoreleasePoolStmtClass:
1183     return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1184 
1185     case Stmt::ObjCAtSynchronizedStmtClass:
1186       return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
1187 
1188     case Stmt::ObjCAtThrowStmtClass:
1189       return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
1190 
1191     case Stmt::ObjCAtTryStmtClass:
1192       return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
1193 
1194     case Stmt::ObjCForCollectionStmtClass:
1195       return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
1196 
1197     case Stmt::OpaqueValueExprClass:
1198       return Block;
1199 
1200     case Stmt::PseudoObjectExprClass:
1201       return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1202 
1203     case Stmt::ReturnStmtClass:
1204       return VisitReturnStmt(cast<ReturnStmt>(S));
1205 
1206     case Stmt::UnaryExprOrTypeTraitExprClass:
1207       return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1208                                            asc);
1209 
1210     case Stmt::StmtExprClass:
1211       return VisitStmtExpr(cast<StmtExpr>(S), asc);
1212 
1213     case Stmt::SwitchStmtClass:
1214       return VisitSwitchStmt(cast<SwitchStmt>(S));
1215 
1216     case Stmt::UnaryOperatorClass:
1217       return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1218 
1219     case Stmt::WhileStmtClass:
1220       return VisitWhileStmt(cast<WhileStmt>(S));
1221   }
1222 }
1223 
1224 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
1225   if (asc.alwaysAdd(*this, S)) {
1226     autoCreateBlock();
1227     appendStmt(Block, S);
1228   }
1229 
1230   return VisitChildren(S);
1231 }
1232 
1233 /// VisitChildren - Visit the children of a Stmt.
1234 CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1235   CFGBlock *B = Block;
1236 
1237   // Visit the children in their reverse order so that they appear in
1238   // left-to-right (natural) order in the CFG.
1239   reverse_children RChildren(S);
1240   for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1241        I != E; ++I) {
1242     if (Stmt *Child = *I)
1243       if (CFGBlock *R = Visit(Child))
1244         B = R;
1245   }
1246   return B;
1247 }
1248 
1249 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1250                                          AddStmtChoice asc) {
1251   AddressTakenLabels.insert(A->getLabel());
1252 
1253   if (asc.alwaysAdd(*this, A)) {
1254     autoCreateBlock();
1255     appendStmt(Block, A);
1256   }
1257 
1258   return Block;
1259 }
1260 
1261 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
1262            AddStmtChoice asc) {
1263   if (asc.alwaysAdd(*this, U)) {
1264     autoCreateBlock();
1265     appendStmt(Block, U);
1266   }
1267 
1268   return Visit(U->getSubExpr(), AddStmtChoice());
1269 }
1270 
1271 CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1272   CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1273   appendStmt(ConfluenceBlock, B);
1274 
1275   if (badCFG)
1276     return 0;
1277 
1278   return VisitLogicalOperator(B, 0, ConfluenceBlock, ConfluenceBlock).first;
1279 }
1280 
1281 std::pair<CFGBlock*, CFGBlock*>
1282 CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1283                                  Stmt *Term,
1284                                  CFGBlock *TrueBlock,
1285                                  CFGBlock *FalseBlock) {
1286 
1287   // Introspect the RHS.  If it is a nested logical operation, we recursively
1288   // build the CFG using this function.  Otherwise, resort to default
1289   // CFG construction behavior.
1290   Expr *RHS = B->getRHS()->IgnoreParens();
1291   CFGBlock *RHSBlock, *ExitBlock;
1292 
1293   do {
1294     if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1295       if (B_RHS->isLogicalOp()) {
1296         llvm::tie(RHSBlock, ExitBlock) =
1297           VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1298         break;
1299       }
1300 
1301     // The RHS is not a nested logical operation.  Don't push the terminator
1302     // down further, but instead visit RHS and construct the respective
1303     // pieces of the CFG, and link up the RHSBlock with the terminator
1304     // we have been provided.
1305     ExitBlock = RHSBlock = createBlock(false);
1306 
1307     if (!Term) {
1308       assert(TrueBlock == FalseBlock);
1309       addSuccessor(RHSBlock, TrueBlock);
1310     }
1311     else {
1312       RHSBlock->setTerminator(Term);
1313       TryResult KnownVal = tryEvaluateBool(RHS);
1314       addSuccessor(RHSBlock, KnownVal.isFalse() ? NULL : TrueBlock);
1315       addSuccessor(RHSBlock, KnownVal.isTrue() ? NULL : FalseBlock);
1316     }
1317 
1318     Block = RHSBlock;
1319     RHSBlock = addStmt(RHS);
1320   }
1321   while (false);
1322 
1323   if (badCFG)
1324     return std::make_pair((CFGBlock*)0, (CFGBlock*)0);
1325 
1326   // Generate the blocks for evaluating the LHS.
1327   Expr *LHS = B->getLHS()->IgnoreParens();
1328 
1329   if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
1330     if (B_LHS->isLogicalOp()) {
1331       if (B->getOpcode() == BO_LOr)
1332         FalseBlock = RHSBlock;
1333       else
1334         TrueBlock = RHSBlock;
1335 
1336       // For the LHS, treat 'B' as the terminator that we want to sink
1337       // into the nested branch.  The RHS always gets the top-most
1338       // terminator.
1339       return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
1340     }
1341 
1342   // Create the block evaluating the LHS.
1343   // This contains the '&&' or '||' as the terminator.
1344   CFGBlock *LHSBlock = createBlock(false);
1345   LHSBlock->setTerminator(B);
1346 
1347   Block = LHSBlock;
1348   CFGBlock *EntryLHSBlock = addStmt(LHS);
1349 
1350   if (badCFG)
1351     return std::make_pair((CFGBlock*)0, (CFGBlock*)0);
1352 
1353   // See if this is a known constant.
1354   TryResult KnownVal = tryEvaluateBool(LHS);
1355 
1356   // Now link the LHSBlock with RHSBlock.
1357   if (B->getOpcode() == BO_LOr) {
1358     addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : TrueBlock);
1359     addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : RHSBlock);
1360   } else {
1361     assert(B->getOpcode() == BO_LAnd);
1362     addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
1363     addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : FalseBlock);
1364   }
1365 
1366   return std::make_pair(EntryLHSBlock, ExitBlock);
1367 }
1368 
1369 
1370 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
1371                                           AddStmtChoice asc) {
1372    // && or ||
1373   if (B->isLogicalOp())
1374     return VisitLogicalOperator(B);
1375 
1376   if (B->getOpcode() == BO_Comma) { // ,
1377     autoCreateBlock();
1378     appendStmt(Block, B);
1379     addStmt(B->getRHS());
1380     return addStmt(B->getLHS());
1381   }
1382 
1383   if (B->isAssignmentOp()) {
1384     if (asc.alwaysAdd(*this, B)) {
1385       autoCreateBlock();
1386       appendStmt(Block, B);
1387     }
1388     Visit(B->getLHS());
1389     return Visit(B->getRHS());
1390   }
1391 
1392   if (asc.alwaysAdd(*this, B)) {
1393     autoCreateBlock();
1394     appendStmt(Block, B);
1395   }
1396 
1397   CFGBlock *RBlock = Visit(B->getRHS());
1398   CFGBlock *LBlock = Visit(B->getLHS());
1399   // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
1400   // containing a DoStmt, and the LHS doesn't create a new block, then we should
1401   // return RBlock.  Otherwise we'll incorrectly return NULL.
1402   return (LBlock ? LBlock : RBlock);
1403 }
1404 
1405 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
1406   if (asc.alwaysAdd(*this, E)) {
1407     autoCreateBlock();
1408     appendStmt(Block, E);
1409   }
1410   return Block;
1411 }
1412 
1413 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
1414   // "break" is a control-flow statement.  Thus we stop processing the current
1415   // block.
1416   if (badCFG)
1417     return 0;
1418 
1419   // Now create a new block that ends with the break statement.
1420   Block = createBlock(false);
1421   Block->setTerminator(B);
1422 
1423   // If there is no target for the break, then we are looking at an incomplete
1424   // AST.  This means that the CFG cannot be constructed.
1425   if (BreakJumpTarget.block) {
1426     addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B);
1427     addSuccessor(Block, BreakJumpTarget.block);
1428   } else
1429     badCFG = true;
1430 
1431 
1432   return Block;
1433 }
1434 
1435 static bool CanThrow(Expr *E, ASTContext &Ctx) {
1436   QualType Ty = E->getType();
1437   if (Ty->isFunctionPointerType())
1438     Ty = Ty->getAs<PointerType>()->getPointeeType();
1439   else if (Ty->isBlockPointerType())
1440     Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
1441 
1442   const FunctionType *FT = Ty->getAs<FunctionType>();
1443   if (FT) {
1444     if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
1445       if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
1446           Proto->isNothrow(Ctx))
1447         return false;
1448   }
1449   return true;
1450 }
1451 
1452 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
1453   // Compute the callee type.
1454   QualType calleeType = C->getCallee()->getType();
1455   if (calleeType == Context->BoundMemberTy) {
1456     QualType boundType = Expr::findBoundMemberType(C->getCallee());
1457 
1458     // We should only get a null bound type if processing a dependent
1459     // CFG.  Recover by assuming nothing.
1460     if (!boundType.isNull()) calleeType = boundType;
1461   }
1462 
1463   // If this is a call to a no-return function, this stops the block here.
1464   bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
1465 
1466   bool AddEHEdge = false;
1467 
1468   // Languages without exceptions are assumed to not throw.
1469   if (Context->getLangOpts().Exceptions) {
1470     if (BuildOpts.AddEHEdges)
1471       AddEHEdge = true;
1472   }
1473 
1474   // If this is a call to a builtin function, it might not actually evaluate
1475   // its arguments. Don't add them to the CFG if this is the case.
1476   bool OmitArguments = false;
1477 
1478   if (FunctionDecl *FD = C->getDirectCallee()) {
1479     if (FD->isNoReturn())
1480       NoReturn = true;
1481     if (FD->hasAttr<NoThrowAttr>())
1482       AddEHEdge = false;
1483     if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
1484       OmitArguments = true;
1485   }
1486 
1487   if (!CanThrow(C->getCallee(), *Context))
1488     AddEHEdge = false;
1489 
1490   if (OmitArguments) {
1491     assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
1492     assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
1493     autoCreateBlock();
1494     appendStmt(Block, C);
1495     return Visit(C->getCallee());
1496   }
1497 
1498   if (!NoReturn && !AddEHEdge) {
1499     return VisitStmt(C, asc.withAlwaysAdd(true));
1500   }
1501 
1502   if (Block) {
1503     Succ = Block;
1504     if (badCFG)
1505       return 0;
1506   }
1507 
1508   if (NoReturn)
1509     Block = createNoReturnBlock();
1510   else
1511     Block = createBlock();
1512 
1513   appendStmt(Block, C);
1514 
1515   if (AddEHEdge) {
1516     // Add exceptional edges.
1517     if (TryTerminatedBlock)
1518       addSuccessor(Block, TryTerminatedBlock);
1519     else
1520       addSuccessor(Block, &cfg->getExit());
1521   }
1522 
1523   return VisitChildren(C);
1524 }
1525 
1526 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
1527                                       AddStmtChoice asc) {
1528   CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1529   appendStmt(ConfluenceBlock, C);
1530   if (badCFG)
1531     return 0;
1532 
1533   AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
1534   Succ = ConfluenceBlock;
1535   Block = NULL;
1536   CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
1537   if (badCFG)
1538     return 0;
1539 
1540   Succ = ConfluenceBlock;
1541   Block = NULL;
1542   CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
1543   if (badCFG)
1544     return 0;
1545 
1546   Block = createBlock(false);
1547   // See if this is a known constant.
1548   const TryResult& KnownVal = tryEvaluateBool(C->getCond());
1549   addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
1550   addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
1551   Block->setTerminator(C);
1552   return addStmt(C->getCond());
1553 }
1554 
1555 
1556 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
1557   addLocalScopeAndDtors(C);
1558   CFGBlock *LastBlock = Block;
1559 
1560   for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
1561        I != E; ++I ) {
1562     // If we hit a segment of code just containing ';' (NullStmts), we can
1563     // get a null block back.  In such cases, just use the LastBlock
1564     if (CFGBlock *newBlock = addStmt(*I))
1565       LastBlock = newBlock;
1566 
1567     if (badCFG)
1568       return NULL;
1569   }
1570 
1571   return LastBlock;
1572 }
1573 
1574 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
1575                                                AddStmtChoice asc) {
1576   const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
1577   const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : NULL);
1578 
1579   // Create the confluence block that will "merge" the results of the ternary
1580   // expression.
1581   CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1582   appendStmt(ConfluenceBlock, C);
1583   if (badCFG)
1584     return 0;
1585 
1586   AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
1587 
1588   // Create a block for the LHS expression if there is an LHS expression.  A
1589   // GCC extension allows LHS to be NULL, causing the condition to be the
1590   // value that is returned instead.
1591   //  e.g: x ?: y is shorthand for: x ? x : y;
1592   Succ = ConfluenceBlock;
1593   Block = NULL;
1594   CFGBlock *LHSBlock = 0;
1595   const Expr *trueExpr = C->getTrueExpr();
1596   if (trueExpr != opaqueValue) {
1597     LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
1598     if (badCFG)
1599       return 0;
1600     Block = NULL;
1601   }
1602   else
1603     LHSBlock = ConfluenceBlock;
1604 
1605   // Create the block for the RHS expression.
1606   Succ = ConfluenceBlock;
1607   CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
1608   if (badCFG)
1609     return 0;
1610 
1611   // If the condition is a logical '&&' or '||', build a more accurate CFG.
1612   if (BinaryOperator *Cond =
1613         dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
1614     if (Cond->isLogicalOp())
1615       return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
1616 
1617   // Create the block that will contain the condition.
1618   Block = createBlock(false);
1619 
1620   // See if this is a known constant.
1621   const TryResult& KnownVal = tryEvaluateBool(C->getCond());
1622   addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
1623   addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
1624   Block->setTerminator(C);
1625   Expr *condExpr = C->getCond();
1626 
1627   if (opaqueValue) {
1628     // Run the condition expression if it's not trivially expressed in
1629     // terms of the opaque value (or if there is no opaque value).
1630     if (condExpr != opaqueValue)
1631       addStmt(condExpr);
1632 
1633     // Before that, run the common subexpression if there was one.
1634     // At least one of this or the above will be run.
1635     return addStmt(BCO->getCommon());
1636   }
1637 
1638   return addStmt(condExpr);
1639 }
1640 
1641 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
1642   // Check if the Decl is for an __label__.  If so, elide it from the
1643   // CFG entirely.
1644   if (isa<LabelDecl>(*DS->decl_begin()))
1645     return Block;
1646 
1647   // This case also handles static_asserts.
1648   if (DS->isSingleDecl())
1649     return VisitDeclSubExpr(DS);
1650 
1651   CFGBlock *B = 0;
1652 
1653   // Build an individual DeclStmt for each decl.
1654   for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
1655                                        E = DS->decl_rend();
1656        I != E; ++I) {
1657     // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
1658     unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
1659                ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
1660 
1661     // Allocate the DeclStmt using the BumpPtrAllocator.  It will get
1662     // automatically freed with the CFG.
1663     DeclGroupRef DG(*I);
1664     Decl *D = *I;
1665     void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
1666     DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
1667     cfg->addSyntheticDeclStmt(DSNew, DS);
1668 
1669     // Append the fake DeclStmt to block.
1670     B = VisitDeclSubExpr(DSNew);
1671   }
1672 
1673   return B;
1674 }
1675 
1676 /// VisitDeclSubExpr - Utility method to add block-level expressions for
1677 /// DeclStmts and initializers in them.
1678 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
1679   assert(DS->isSingleDecl() && "Can handle single declarations only.");
1680   VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1681 
1682   if (!VD) {
1683     // Of everything that can be declared in a DeclStmt, only VarDecls impact
1684     // runtime semantics.
1685     return Block;
1686   }
1687 
1688   bool IsReference = false;
1689   bool HasTemporaries = false;
1690 
1691   // Guard static initializers under a branch.
1692   CFGBlock *blockAfterStaticInit = 0;
1693 
1694   if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
1695     // For static variables, we need to create a branch to track
1696     // whether or not they are initialized.
1697     if (Block) {
1698       Succ = Block;
1699       Block = 0;
1700       if (badCFG)
1701         return 0;
1702     }
1703     blockAfterStaticInit = Succ;
1704   }
1705 
1706   // Destructors of temporaries in initialization expression should be called
1707   // after initialization finishes.
1708   Expr *Init = VD->getInit();
1709   if (Init) {
1710     IsReference = VD->getType()->isReferenceType();
1711     HasTemporaries = isa<ExprWithCleanups>(Init);
1712 
1713     if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
1714       // Generate destructors for temporaries in initialization expression.
1715       VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1716           IsReference);
1717     }
1718   }
1719 
1720   autoCreateBlock();
1721   appendStmt(Block, DS);
1722 
1723   // Keep track of the last non-null block, as 'Block' can be nulled out
1724   // if the initializer expression is something like a 'while' in a
1725   // statement-expression.
1726   CFGBlock *LastBlock = Block;
1727 
1728   if (Init) {
1729     if (HasTemporaries) {
1730       // For expression with temporaries go directly to subexpression to omit
1731       // generating destructors for the second time.
1732       ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
1733       if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
1734         LastBlock = newBlock;
1735     }
1736     else {
1737       if (CFGBlock *newBlock = Visit(Init))
1738         LastBlock = newBlock;
1739     }
1740   }
1741 
1742   // If the type of VD is a VLA, then we must process its size expressions.
1743   for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
1744        VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) {
1745     if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
1746       LastBlock = newBlock;
1747   }
1748 
1749   // Remove variable from local scope.
1750   if (ScopePos && VD == *ScopePos)
1751     ++ScopePos;
1752 
1753   CFGBlock *B = LastBlock;
1754   if (blockAfterStaticInit) {
1755     Succ = B;
1756     Block = createBlock(false);
1757     Block->setTerminator(DS);
1758     addSuccessor(Block, blockAfterStaticInit);
1759     addSuccessor(Block, B);
1760     B = Block;
1761   }
1762 
1763   return B;
1764 }
1765 
1766 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
1767   // We may see an if statement in the middle of a basic block, or it may be the
1768   // first statement we are processing.  In either case, we create a new basic
1769   // block.  First, we create the blocks for the then...else statements, and
1770   // then we create the block containing the if statement.  If we were in the
1771   // middle of a block, we stop processing that block.  That block is then the
1772   // implicit successor for the "then" and "else" clauses.
1773 
1774   // Save local scope position because in case of condition variable ScopePos
1775   // won't be restored when traversing AST.
1776   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1777 
1778   // Create local scope for possible condition variable.
1779   // Store scope position. Add implicit destructor.
1780   if (VarDecl *VD = I->getConditionVariable()) {
1781     LocalScope::const_iterator BeginScopePos = ScopePos;
1782     addLocalScopeForVarDecl(VD);
1783     addAutomaticObjDtors(ScopePos, BeginScopePos, I);
1784   }
1785 
1786   // The block we were processing is now finished.  Make it the successor
1787   // block.
1788   if (Block) {
1789     Succ = Block;
1790     if (badCFG)
1791       return 0;
1792   }
1793 
1794   // Process the false branch.
1795   CFGBlock *ElseBlock = Succ;
1796 
1797   if (Stmt *Else = I->getElse()) {
1798     SaveAndRestore<CFGBlock*> sv(Succ);
1799 
1800     // NULL out Block so that the recursive call to Visit will
1801     // create a new basic block.
1802     Block = NULL;
1803 
1804     // If branch is not a compound statement create implicit scope
1805     // and add destructors.
1806     if (!isa<CompoundStmt>(Else))
1807       addLocalScopeAndDtors(Else);
1808 
1809     ElseBlock = addStmt(Else);
1810 
1811     if (!ElseBlock) // Can occur when the Else body has all NullStmts.
1812       ElseBlock = sv.get();
1813     else if (Block) {
1814       if (badCFG)
1815         return 0;
1816     }
1817   }
1818 
1819   // Process the true branch.
1820   CFGBlock *ThenBlock;
1821   {
1822     Stmt *Then = I->getThen();
1823     assert(Then);
1824     SaveAndRestore<CFGBlock*> sv(Succ);
1825     Block = NULL;
1826 
1827     // If branch is not a compound statement create implicit scope
1828     // and add destructors.
1829     if (!isa<CompoundStmt>(Then))
1830       addLocalScopeAndDtors(Then);
1831 
1832     ThenBlock = addStmt(Then);
1833 
1834     if (!ThenBlock) {
1835       // We can reach here if the "then" body has all NullStmts.
1836       // Create an empty block so we can distinguish between true and false
1837       // branches in path-sensitive analyses.
1838       ThenBlock = createBlock(false);
1839       addSuccessor(ThenBlock, sv.get());
1840     } else if (Block) {
1841       if (badCFG)
1842         return 0;
1843     }
1844   }
1845 
1846   // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
1847   // having these handle the actual control-flow jump.  Note that
1848   // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
1849   // we resort to the old control-flow behavior.  This special handling
1850   // removes infeasible paths from the control-flow graph by having the
1851   // control-flow transfer of '&&' or '||' go directly into the then/else
1852   // blocks directly.
1853   if (!I->getConditionVariable())
1854     if (BinaryOperator *Cond =
1855             dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens()))
1856       if (Cond->isLogicalOp())
1857         return VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
1858 
1859   // Now create a new block containing the if statement.
1860   Block = createBlock(false);
1861 
1862   // Set the terminator of the new block to the If statement.
1863   Block->setTerminator(I);
1864 
1865   // See if this is a known constant.
1866   const TryResult &KnownVal = tryEvaluateBool(I->getCond());
1867 
1868   // Now add the successors.
1869   addSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock);
1870   addSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock);
1871 
1872   // Add the condition as the last statement in the new block.  This may create
1873   // new blocks as the condition may contain control-flow.  Any newly created
1874   // blocks will be pointed to be "Block".
1875   CFGBlock *LastBlock = addStmt(I->getCond());
1876 
1877   // Finally, if the IfStmt contains a condition variable, add both the IfStmt
1878   // and the condition variable initialization to the CFG.
1879   if (VarDecl *VD = I->getConditionVariable()) {
1880     if (Expr *Init = VD->getInit()) {
1881       autoCreateBlock();
1882       appendStmt(Block, I->getConditionVariableDeclStmt());
1883       LastBlock = addStmt(Init);
1884     }
1885   }
1886 
1887   return LastBlock;
1888 }
1889 
1890 
1891 CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
1892   // If we were in the middle of a block we stop processing that block.
1893   //
1894   // NOTE: If a "return" appears in the middle of a block, this means that the
1895   //       code afterwards is DEAD (unreachable).  We still keep a basic block
1896   //       for that code; a simple "mark-and-sweep" from the entry block will be
1897   //       able to report such dead blocks.
1898 
1899   // Create the new block.
1900   Block = createBlock(false);
1901 
1902   addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
1903 
1904   // If the one of the destructors does not return, we already have the Exit
1905   // block as a successor.
1906   if (!Block->hasNoReturnElement())
1907     addSuccessor(Block, &cfg->getExit());
1908 
1909   // Add the return statement to the block.  This may create new blocks if R
1910   // contains control-flow (short-circuit operations).
1911   return VisitStmt(R, AddStmtChoice::AlwaysAdd);
1912 }
1913 
1914 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
1915   // Get the block of the labeled statement.  Add it to our map.
1916   addStmt(L->getSubStmt());
1917   CFGBlock *LabelBlock = Block;
1918 
1919   if (!LabelBlock)              // This can happen when the body is empty, i.e.
1920     LabelBlock = createBlock(); // scopes that only contains NullStmts.
1921 
1922   assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
1923          "label already in map");
1924   LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
1925 
1926   // Labels partition blocks, so this is the end of the basic block we were
1927   // processing (L is the block's label).  Because this is label (and we have
1928   // already processed the substatement) there is no extra control-flow to worry
1929   // about.
1930   LabelBlock->setLabel(L);
1931   if (badCFG)
1932     return 0;
1933 
1934   // We set Block to NULL to allow lazy creation of a new block (if necessary);
1935   Block = NULL;
1936 
1937   // This block is now the implicit successor of other blocks.
1938   Succ = LabelBlock;
1939 
1940   return LabelBlock;
1941 }
1942 
1943 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
1944   CFGBlock *LastBlock = VisitNoRecurse(E, asc);
1945   for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
1946        et = E->capture_init_end(); it != et; ++it) {
1947     if (Expr *Init = *it) {
1948       CFGBlock *Tmp = Visit(Init);
1949       if (Tmp != 0)
1950         LastBlock = Tmp;
1951     }
1952   }
1953   return LastBlock;
1954 }
1955 
1956 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
1957   // Goto is a control-flow statement.  Thus we stop processing the current
1958   // block and create a new one.
1959 
1960   Block = createBlock(false);
1961   Block->setTerminator(G);
1962 
1963   // If we already know the mapping to the label block add the successor now.
1964   LabelMapTy::iterator I = LabelMap.find(G->getLabel());
1965 
1966   if (I == LabelMap.end())
1967     // We will need to backpatch this block later.
1968     BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
1969   else {
1970     JumpTarget JT = I->second;
1971     addAutomaticObjDtors(ScopePos, JT.scopePosition, G);
1972     addSuccessor(Block, JT.block);
1973   }
1974 
1975   return Block;
1976 }
1977 
1978 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
1979   CFGBlock *LoopSuccessor = NULL;
1980 
1981   // Save local scope position because in case of condition variable ScopePos
1982   // won't be restored when traversing AST.
1983   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1984 
1985   // Create local scope for init statement and possible condition variable.
1986   // Add destructor for init statement and condition variable.
1987   // Store scope position for continue statement.
1988   if (Stmt *Init = F->getInit())
1989     addLocalScopeForStmt(Init);
1990   LocalScope::const_iterator LoopBeginScopePos = ScopePos;
1991 
1992   if (VarDecl *VD = F->getConditionVariable())
1993     addLocalScopeForVarDecl(VD);
1994   LocalScope::const_iterator ContinueScopePos = ScopePos;
1995 
1996   addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
1997 
1998   // "for" is a control-flow statement.  Thus we stop processing the current
1999   // block.
2000   if (Block) {
2001     if (badCFG)
2002       return 0;
2003     LoopSuccessor = Block;
2004   } else
2005     LoopSuccessor = Succ;
2006 
2007   // Save the current value for the break targets.
2008   // All breaks should go to the code following the loop.
2009   SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
2010   BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2011 
2012   CFGBlock *BodyBlock = 0, *TransitionBlock = 0;
2013 
2014   // Now create the loop body.
2015   {
2016     assert(F->getBody());
2017 
2018     // Save the current values for Block, Succ, continue and break targets.
2019     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2020     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
2021 
2022     // Create an empty block to represent the transition block for looping back
2023     // to the head of the loop.  If we have increment code, it will
2024     // go in this block as well.
2025     Block = Succ = TransitionBlock = createBlock(false);
2026     TransitionBlock->setLoopTarget(F);
2027 
2028     if (Stmt *I = F->getInc()) {
2029       // Generate increment code in its own basic block.  This is the target of
2030       // continue statements.
2031       Succ = addStmt(I);
2032     }
2033 
2034     // Finish up the increment (or empty) block if it hasn't been already.
2035     if (Block) {
2036       assert(Block == Succ);
2037       if (badCFG)
2038         return 0;
2039       Block = 0;
2040     }
2041 
2042    // The starting block for the loop increment is the block that should
2043    // represent the 'loop target' for looping back to the start of the loop.
2044    ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2045    ContinueJumpTarget.block->setLoopTarget(F);
2046 
2047     // Loop body should end with destructor of Condition variable (if any).
2048     addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
2049 
2050     // If body is not a compound statement create implicit scope
2051     // and add destructors.
2052     if (!isa<CompoundStmt>(F->getBody()))
2053       addLocalScopeAndDtors(F->getBody());
2054 
2055     // Now populate the body block, and in the process create new blocks as we
2056     // walk the body of the loop.
2057     BodyBlock = addStmt(F->getBody());
2058 
2059     if (!BodyBlock) {
2060       // In the case of "for (...;...;...);" we can have a null BodyBlock.
2061       // Use the continue jump target as the proxy for the body.
2062       BodyBlock = ContinueJumpTarget.block;
2063     }
2064     else if (badCFG)
2065       return 0;
2066   }
2067 
2068   // Because of short-circuit evaluation, the condition of the loop can span
2069   // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
2070   // evaluate the condition.
2071   CFGBlock *EntryConditionBlock = 0, *ExitConditionBlock = 0;
2072 
2073   do {
2074     Expr *C = F->getCond();
2075 
2076     // Specially handle logical operators, which have a slightly
2077     // more optimal CFG representation.
2078     if (BinaryOperator *Cond =
2079             dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : 0))
2080       if (Cond->isLogicalOp()) {
2081         llvm::tie(EntryConditionBlock, ExitConditionBlock) =
2082           VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2083         break;
2084       }
2085 
2086     // The default case when not handling logical operators.
2087     EntryConditionBlock = ExitConditionBlock = createBlock(false);
2088     ExitConditionBlock->setTerminator(F);
2089 
2090     // See if this is a known constant.
2091     TryResult KnownVal(true);
2092 
2093     if (C) {
2094       // Now add the actual condition to the condition block.
2095       // Because the condition itself may contain control-flow, new blocks may
2096       // be created.  Thus we update "Succ" after adding the condition.
2097       Block = ExitConditionBlock;
2098       EntryConditionBlock = addStmt(C);
2099 
2100       // If this block contains a condition variable, add both the condition
2101       // variable and initializer to the CFG.
2102       if (VarDecl *VD = F->getConditionVariable()) {
2103         if (Expr *Init = VD->getInit()) {
2104           autoCreateBlock();
2105           appendStmt(Block, F->getConditionVariableDeclStmt());
2106           EntryConditionBlock = addStmt(Init);
2107           assert(Block == EntryConditionBlock);
2108         }
2109       }
2110 
2111       if (Block && badCFG)
2112         return 0;
2113 
2114       KnownVal = tryEvaluateBool(C);
2115     }
2116 
2117     // Add the loop body entry as a successor to the condition.
2118     addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
2119     // Link up the condition block with the code that follows the loop.  (the
2120     // false branch).
2121     addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
2122 
2123   } while (false);
2124 
2125   // Link up the loop-back block to the entry condition block.
2126   addSuccessor(TransitionBlock, EntryConditionBlock);
2127 
2128   // The condition block is the implicit successor for any code above the loop.
2129   Succ = EntryConditionBlock;
2130 
2131   // If the loop contains initialization, create a new block for those
2132   // statements.  This block can also contain statements that precede the loop.
2133   if (Stmt *I = F->getInit()) {
2134     Block = createBlock();
2135     return addStmt(I);
2136   }
2137 
2138   // There is no loop initialization.  We are thus basically a while loop.
2139   // NULL out Block to force lazy block construction.
2140   Block = NULL;
2141   Succ = EntryConditionBlock;
2142   return EntryConditionBlock;
2143 }
2144 
2145 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
2146   if (asc.alwaysAdd(*this, M)) {
2147     autoCreateBlock();
2148     appendStmt(Block, M);
2149   }
2150   return Visit(M->getBase());
2151 }
2152 
2153 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
2154   // Objective-C fast enumeration 'for' statements:
2155   //  http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2156   //
2157   //  for ( Type newVariable in collection_expression ) { statements }
2158   //
2159   //  becomes:
2160   //
2161   //   prologue:
2162   //     1. collection_expression
2163   //     T. jump to loop_entry
2164   //   loop_entry:
2165   //     1. side-effects of element expression
2166   //     1. ObjCForCollectionStmt [performs binding to newVariable]
2167   //     T. ObjCForCollectionStmt  TB, FB  [jumps to TB if newVariable != nil]
2168   //   TB:
2169   //     statements
2170   //     T. jump to loop_entry
2171   //   FB:
2172   //     what comes after
2173   //
2174   //  and
2175   //
2176   //  Type existingItem;
2177   //  for ( existingItem in expression ) { statements }
2178   //
2179   //  becomes:
2180   //
2181   //   the same with newVariable replaced with existingItem; the binding works
2182   //   the same except that for one ObjCForCollectionStmt::getElement() returns
2183   //   a DeclStmt and the other returns a DeclRefExpr.
2184   //
2185 
2186   CFGBlock *LoopSuccessor = 0;
2187 
2188   if (Block) {
2189     if (badCFG)
2190       return 0;
2191     LoopSuccessor = Block;
2192     Block = 0;
2193   } else
2194     LoopSuccessor = Succ;
2195 
2196   // Build the condition blocks.
2197   CFGBlock *ExitConditionBlock = createBlock(false);
2198 
2199   // Set the terminator for the "exit" condition block.
2200   ExitConditionBlock->setTerminator(S);
2201 
2202   // The last statement in the block should be the ObjCForCollectionStmt, which
2203   // performs the actual binding to 'element' and determines if there are any
2204   // more items in the collection.
2205   appendStmt(ExitConditionBlock, S);
2206   Block = ExitConditionBlock;
2207 
2208   // Walk the 'element' expression to see if there are any side-effects.  We
2209   // generate new blocks as necessary.  We DON'T add the statement by default to
2210   // the CFG unless it contains control-flow.
2211   CFGBlock *EntryConditionBlock = Visit(S->getElement(),
2212                                         AddStmtChoice::NotAlwaysAdd);
2213   if (Block) {
2214     if (badCFG)
2215       return 0;
2216     Block = 0;
2217   }
2218 
2219   // The condition block is the implicit successor for the loop body as well as
2220   // any code above the loop.
2221   Succ = EntryConditionBlock;
2222 
2223   // Now create the true branch.
2224   {
2225     // Save the current values for Succ, continue and break targets.
2226     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2227     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2228                                save_break(BreakJumpTarget);
2229 
2230     // Add an intermediate block between the BodyBlock and the
2231     // EntryConditionBlock to represent the "loop back" transition, for looping
2232     // back to the head of the loop.
2233     CFGBlock *LoopBackBlock = 0;
2234     Succ = LoopBackBlock = createBlock();
2235     LoopBackBlock->setLoopTarget(S);
2236 
2237     BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2238     ContinueJumpTarget = JumpTarget(Succ, ScopePos);
2239 
2240     CFGBlock *BodyBlock = addStmt(S->getBody());
2241 
2242     if (!BodyBlock)
2243       BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
2244     else if (Block) {
2245       if (badCFG)
2246         return 0;
2247     }
2248 
2249     // This new body block is a successor to our "exit" condition block.
2250     addSuccessor(ExitConditionBlock, BodyBlock);
2251   }
2252 
2253   // Link up the condition block with the code that follows the loop.
2254   // (the false branch).
2255   addSuccessor(ExitConditionBlock, LoopSuccessor);
2256 
2257   // Now create a prologue block to contain the collection expression.
2258   Block = createBlock();
2259   return addStmt(S->getCollection());
2260 }
2261 
2262 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
2263   // Inline the body.
2264   return addStmt(S->getSubStmt());
2265   // TODO: consider adding cleanups for the end of @autoreleasepool scope.
2266 }
2267 
2268 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
2269   // FIXME: Add locking 'primitives' to CFG for @synchronized.
2270 
2271   // Inline the body.
2272   CFGBlock *SyncBlock = addStmt(S->getSynchBody());
2273 
2274   // The sync body starts its own basic block.  This makes it a little easier
2275   // for diagnostic clients.
2276   if (SyncBlock) {
2277     if (badCFG)
2278       return 0;
2279 
2280     Block = 0;
2281     Succ = SyncBlock;
2282   }
2283 
2284   // Add the @synchronized to the CFG.
2285   autoCreateBlock();
2286   appendStmt(Block, S);
2287 
2288   // Inline the sync expression.
2289   return addStmt(S->getSynchExpr());
2290 }
2291 
2292 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
2293   // FIXME
2294   return NYS();
2295 }
2296 
2297 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2298   autoCreateBlock();
2299 
2300   // Add the PseudoObject as the last thing.
2301   appendStmt(Block, E);
2302 
2303   CFGBlock *lastBlock = Block;
2304 
2305   // Before that, evaluate all of the semantics in order.  In
2306   // CFG-land, that means appending them in reverse order.
2307   for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
2308     Expr *Semantic = E->getSemanticExpr(--i);
2309 
2310     // If the semantic is an opaque value, we're being asked to bind
2311     // it to its source expression.
2312     if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
2313       Semantic = OVE->getSourceExpr();
2314 
2315     if (CFGBlock *B = Visit(Semantic))
2316       lastBlock = B;
2317   }
2318 
2319   return lastBlock;
2320 }
2321 
2322 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
2323   CFGBlock *LoopSuccessor = NULL;
2324 
2325   // Save local scope position because in case of condition variable ScopePos
2326   // won't be restored when traversing AST.
2327   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2328 
2329   // Create local scope for possible condition variable.
2330   // Store scope position for continue statement.
2331   LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2332   if (VarDecl *VD = W->getConditionVariable()) {
2333     addLocalScopeForVarDecl(VD);
2334     addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2335   }
2336 
2337   // "while" is a control-flow statement.  Thus we stop processing the current
2338   // block.
2339   if (Block) {
2340     if (badCFG)
2341       return 0;
2342     LoopSuccessor = Block;
2343     Block = 0;
2344   } else {
2345     LoopSuccessor = Succ;
2346   }
2347 
2348   CFGBlock *BodyBlock = 0, *TransitionBlock = 0;
2349 
2350   // Process the loop body.
2351   {
2352     assert(W->getBody());
2353 
2354     // Save the current values for Block, Succ, continue and break targets.
2355     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2356     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2357                                save_break(BreakJumpTarget);
2358 
2359     // Create an empty block to represent the transition block for looping back
2360     // to the head of the loop.
2361     Succ = TransitionBlock = createBlock(false);
2362     TransitionBlock->setLoopTarget(W);
2363     ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
2364 
2365     // All breaks should go to the code following the loop.
2366     BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2367 
2368     // Loop body should end with destructor of Condition variable (if any).
2369     addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2370 
2371     // If body is not a compound statement create implicit scope
2372     // and add destructors.
2373     if (!isa<CompoundStmt>(W->getBody()))
2374       addLocalScopeAndDtors(W->getBody());
2375 
2376     // Create the body.  The returned block is the entry to the loop body.
2377     BodyBlock = addStmt(W->getBody());
2378 
2379     if (!BodyBlock)
2380       BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
2381     else if (Block && badCFG)
2382       return 0;
2383   }
2384 
2385   // Because of short-circuit evaluation, the condition of the loop can span
2386   // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
2387   // evaluate the condition.
2388   CFGBlock *EntryConditionBlock = 0, *ExitConditionBlock = 0;
2389 
2390   do {
2391     Expr *C = W->getCond();
2392 
2393     // Specially handle logical operators, which have a slightly
2394     // more optimal CFG representation.
2395     if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
2396       if (Cond->isLogicalOp()) {
2397         llvm::tie(EntryConditionBlock, ExitConditionBlock) =
2398           VisitLogicalOperator(Cond, W, BodyBlock,
2399                                LoopSuccessor);
2400         break;
2401       }
2402 
2403     // The default case when not handling logical operators.
2404     ExitConditionBlock = createBlock(false);
2405     ExitConditionBlock->setTerminator(W);
2406 
2407     // Now add the actual condition to the condition block.
2408     // Because the condition itself may contain control-flow, new blocks may
2409     // be created.  Thus we update "Succ" after adding the condition.
2410     Block = ExitConditionBlock;
2411     Block = EntryConditionBlock = addStmt(C);
2412 
2413     // If this block contains a condition variable, add both the condition
2414     // variable and initializer to the CFG.
2415     if (VarDecl *VD = W->getConditionVariable()) {
2416       if (Expr *Init = VD->getInit()) {
2417         autoCreateBlock();
2418         appendStmt(Block, W->getConditionVariableDeclStmt());
2419         EntryConditionBlock = addStmt(Init);
2420         assert(Block == EntryConditionBlock);
2421       }
2422     }
2423 
2424     if (Block && badCFG)
2425       return 0;
2426 
2427     // See if this is a known constant.
2428     const TryResult& KnownVal = tryEvaluateBool(C);
2429 
2430     // Add the loop body entry as a successor to the condition.
2431     addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
2432     // Link up the condition block with the code that follows the loop.  (the
2433     // false branch).
2434     addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
2435 
2436   } while(false);
2437 
2438   // Link up the loop-back block to the entry condition block.
2439   addSuccessor(TransitionBlock, EntryConditionBlock);
2440 
2441   // There can be no more statements in the condition block since we loop back
2442   // to this block.  NULL out Block to force lazy creation of another block.
2443   Block = NULL;
2444 
2445   // Return the condition block, which is the dominating block for the loop.
2446   Succ = EntryConditionBlock;
2447   return EntryConditionBlock;
2448 }
2449 
2450 
2451 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
2452   // FIXME: For now we pretend that @catch and the code it contains does not
2453   //  exit.
2454   return Block;
2455 }
2456 
2457 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
2458   // FIXME: This isn't complete.  We basically treat @throw like a return
2459   //  statement.
2460 
2461   // If we were in the middle of a block we stop processing that block.
2462   if (badCFG)
2463     return 0;
2464 
2465   // Create the new block.
2466   Block = createBlock(false);
2467 
2468   // The Exit block is the only successor.
2469   addSuccessor(Block, &cfg->getExit());
2470 
2471   // Add the statement to the block.  This may create new blocks if S contains
2472   // control-flow (short-circuit operations).
2473   return VisitStmt(S, AddStmtChoice::AlwaysAdd);
2474 }
2475 
2476 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
2477   // If we were in the middle of a block we stop processing that block.
2478   if (badCFG)
2479     return 0;
2480 
2481   // Create the new block.
2482   Block = createBlock(false);
2483 
2484   if (TryTerminatedBlock)
2485     // The current try statement is the only successor.
2486     addSuccessor(Block, TryTerminatedBlock);
2487   else
2488     // otherwise the Exit block is the only successor.
2489     addSuccessor(Block, &cfg->getExit());
2490 
2491   // Add the statement to the block.  This may create new blocks if S contains
2492   // control-flow (short-circuit operations).
2493   return VisitStmt(T, AddStmtChoice::AlwaysAdd);
2494 }
2495 
2496 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
2497   CFGBlock *LoopSuccessor = NULL;
2498 
2499   // "do...while" is a control-flow statement.  Thus we stop processing the
2500   // current block.
2501   if (Block) {
2502     if (badCFG)
2503       return 0;
2504     LoopSuccessor = Block;
2505   } else
2506     LoopSuccessor = Succ;
2507 
2508   // Because of short-circuit evaluation, the condition of the loop can span
2509   // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
2510   // evaluate the condition.
2511   CFGBlock *ExitConditionBlock = createBlock(false);
2512   CFGBlock *EntryConditionBlock = ExitConditionBlock;
2513 
2514   // Set the terminator for the "exit" condition block.
2515   ExitConditionBlock->setTerminator(D);
2516 
2517   // Now add the actual condition to the condition block.  Because the condition
2518   // itself may contain control-flow, new blocks may be created.
2519   if (Stmt *C = D->getCond()) {
2520     Block = ExitConditionBlock;
2521     EntryConditionBlock = addStmt(C);
2522     if (Block) {
2523       if (badCFG)
2524         return 0;
2525     }
2526   }
2527 
2528   // The condition block is the implicit successor for the loop body.
2529   Succ = EntryConditionBlock;
2530 
2531   // See if this is a known constant.
2532   const TryResult &KnownVal = tryEvaluateBool(D->getCond());
2533 
2534   // Process the loop body.
2535   CFGBlock *BodyBlock = NULL;
2536   {
2537     assert(D->getBody());
2538 
2539     // Save the current values for Block, Succ, and continue and break targets
2540     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2541     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2542         save_break(BreakJumpTarget);
2543 
2544     // All continues within this loop should go to the condition block
2545     ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
2546 
2547     // All breaks should go to the code following the loop.
2548     BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2549 
2550     // NULL out Block to force lazy instantiation of blocks for the body.
2551     Block = NULL;
2552 
2553     // If body is not a compound statement create implicit scope
2554     // and add destructors.
2555     if (!isa<CompoundStmt>(D->getBody()))
2556       addLocalScopeAndDtors(D->getBody());
2557 
2558     // Create the body.  The returned block is the entry to the loop body.
2559     BodyBlock = addStmt(D->getBody());
2560 
2561     if (!BodyBlock)
2562       BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
2563     else if (Block) {
2564       if (badCFG)
2565         return 0;
2566     }
2567 
2568     if (!KnownVal.isFalse()) {
2569       // Add an intermediate block between the BodyBlock and the
2570       // ExitConditionBlock to represent the "loop back" transition.  Create an
2571       // empty block to represent the transition block for looping back to the
2572       // head of the loop.
2573       // FIXME: Can we do this more efficiently without adding another block?
2574       Block = NULL;
2575       Succ = BodyBlock;
2576       CFGBlock *LoopBackBlock = createBlock();
2577       LoopBackBlock->setLoopTarget(D);
2578 
2579       // Add the loop body entry as a successor to the condition.
2580       addSuccessor(ExitConditionBlock, LoopBackBlock);
2581     }
2582     else
2583       addSuccessor(ExitConditionBlock, NULL);
2584   }
2585 
2586   // Link up the condition block with the code that follows the loop.
2587   // (the false branch).
2588   addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
2589 
2590   // There can be no more statements in the body block(s) since we loop back to
2591   // the body.  NULL out Block to force lazy creation of another block.
2592   Block = NULL;
2593 
2594   // Return the loop body, which is the dominating block for the loop.
2595   Succ = BodyBlock;
2596   return BodyBlock;
2597 }
2598 
2599 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
2600   // "continue" is a control-flow statement.  Thus we stop processing the
2601   // current block.
2602   if (badCFG)
2603     return 0;
2604 
2605   // Now create a new block that ends with the continue statement.
2606   Block = createBlock(false);
2607   Block->setTerminator(C);
2608 
2609   // If there is no target for the continue, then we are looking at an
2610   // incomplete AST.  This means the CFG cannot be constructed.
2611   if (ContinueJumpTarget.block) {
2612     addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C);
2613     addSuccessor(Block, ContinueJumpTarget.block);
2614   } else
2615     badCFG = true;
2616 
2617   return Block;
2618 }
2619 
2620 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
2621                                                     AddStmtChoice asc) {
2622 
2623   if (asc.alwaysAdd(*this, E)) {
2624     autoCreateBlock();
2625     appendStmt(Block, E);
2626   }
2627 
2628   // VLA types have expressions that must be evaluated.
2629   CFGBlock *lastBlock = Block;
2630 
2631   if (E->isArgumentType()) {
2632     for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
2633          VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
2634       lastBlock = addStmt(VA->getSizeExpr());
2635   }
2636   return lastBlock;
2637 }
2638 
2639 /// VisitStmtExpr - Utility method to handle (nested) statement
2640 ///  expressions (a GCC extension).
2641 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
2642   if (asc.alwaysAdd(*this, SE)) {
2643     autoCreateBlock();
2644     appendStmt(Block, SE);
2645   }
2646   return VisitCompoundStmt(SE->getSubStmt());
2647 }
2648 
2649 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
2650   // "switch" is a control-flow statement.  Thus we stop processing the current
2651   // block.
2652   CFGBlock *SwitchSuccessor = NULL;
2653 
2654   // Save local scope position because in case of condition variable ScopePos
2655   // won't be restored when traversing AST.
2656   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2657 
2658   // Create local scope for possible condition variable.
2659   // Store scope position. Add implicit destructor.
2660   if (VarDecl *VD = Terminator->getConditionVariable()) {
2661     LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
2662     addLocalScopeForVarDecl(VD);
2663     addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
2664   }
2665 
2666   if (Block) {
2667     if (badCFG)
2668       return 0;
2669     SwitchSuccessor = Block;
2670   } else SwitchSuccessor = Succ;
2671 
2672   // Save the current "switch" context.
2673   SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
2674                             save_default(DefaultCaseBlock);
2675   SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
2676 
2677   // Set the "default" case to be the block after the switch statement.  If the
2678   // switch statement contains a "default:", this value will be overwritten with
2679   // the block for that code.
2680   DefaultCaseBlock = SwitchSuccessor;
2681 
2682   // Create a new block that will contain the switch statement.
2683   SwitchTerminatedBlock = createBlock(false);
2684 
2685   // Now process the switch body.  The code after the switch is the implicit
2686   // successor.
2687   Succ = SwitchSuccessor;
2688   BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
2689 
2690   // When visiting the body, the case statements should automatically get linked
2691   // up to the switch.  We also don't keep a pointer to the body, since all
2692   // control-flow from the switch goes to case/default statements.
2693   assert(Terminator->getBody() && "switch must contain a non-NULL body");
2694   Block = NULL;
2695 
2696   // For pruning unreachable case statements, save the current state
2697   // for tracking the condition value.
2698   SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
2699                                                      false);
2700 
2701   // Determine if the switch condition can be explicitly evaluated.
2702   assert(Terminator->getCond() && "switch condition must be non-NULL");
2703   Expr::EvalResult result;
2704   bool b = tryEvaluate(Terminator->getCond(), result);
2705   SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
2706                                                     b ? &result : 0);
2707 
2708   // If body is not a compound statement create implicit scope
2709   // and add destructors.
2710   if (!isa<CompoundStmt>(Terminator->getBody()))
2711     addLocalScopeAndDtors(Terminator->getBody());
2712 
2713   addStmt(Terminator->getBody());
2714   if (Block) {
2715     if (badCFG)
2716       return 0;
2717   }
2718 
2719   // If we have no "default:" case, the default transition is to the code
2720   // following the switch body.  Moreover, take into account if all the
2721   // cases of a switch are covered (e.g., switching on an enum value).
2722   //
2723   // Note: We add a successor to a switch that is considered covered yet has no
2724   //       case statements if the enumeration has no enumerators.
2725   bool SwitchAlwaysHasSuccessor = false;
2726   SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
2727   SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
2728                               Terminator->getSwitchCaseList();
2729   addSuccessor(SwitchTerminatedBlock,
2730                SwitchAlwaysHasSuccessor ? 0 : DefaultCaseBlock);
2731 
2732   // Add the terminator and condition in the switch block.
2733   SwitchTerminatedBlock->setTerminator(Terminator);
2734   Block = SwitchTerminatedBlock;
2735   CFGBlock *LastBlock = addStmt(Terminator->getCond());
2736 
2737   // Finally, if the SwitchStmt contains a condition variable, add both the
2738   // SwitchStmt and the condition variable initialization to the CFG.
2739   if (VarDecl *VD = Terminator->getConditionVariable()) {
2740     if (Expr *Init = VD->getInit()) {
2741       autoCreateBlock();
2742       appendStmt(Block, Terminator->getConditionVariableDeclStmt());
2743       LastBlock = addStmt(Init);
2744     }
2745   }
2746 
2747   return LastBlock;
2748 }
2749 
2750 static bool shouldAddCase(bool &switchExclusivelyCovered,
2751                           const Expr::EvalResult *switchCond,
2752                           const CaseStmt *CS,
2753                           ASTContext &Ctx) {
2754   if (!switchCond)
2755     return true;
2756 
2757   bool addCase = false;
2758 
2759   if (!switchExclusivelyCovered) {
2760     if (switchCond->Val.isInt()) {
2761       // Evaluate the LHS of the case value.
2762       const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
2763       const llvm::APSInt &condInt = switchCond->Val.getInt();
2764 
2765       if (condInt == lhsInt) {
2766         addCase = true;
2767         switchExclusivelyCovered = true;
2768       }
2769       else if (condInt < lhsInt) {
2770         if (const Expr *RHS = CS->getRHS()) {
2771           // Evaluate the RHS of the case value.
2772           const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
2773           if (V2 <= condInt) {
2774             addCase = true;
2775             switchExclusivelyCovered = true;
2776           }
2777         }
2778       }
2779     }
2780     else
2781       addCase = true;
2782   }
2783   return addCase;
2784 }
2785 
2786 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
2787   // CaseStmts are essentially labels, so they are the first statement in a
2788   // block.
2789   CFGBlock *TopBlock = 0, *LastBlock = 0;
2790 
2791   if (Stmt *Sub = CS->getSubStmt()) {
2792     // For deeply nested chains of CaseStmts, instead of doing a recursion
2793     // (which can blow out the stack), manually unroll and create blocks
2794     // along the way.
2795     while (isa<CaseStmt>(Sub)) {
2796       CFGBlock *currentBlock = createBlock(false);
2797       currentBlock->setLabel(CS);
2798 
2799       if (TopBlock)
2800         addSuccessor(LastBlock, currentBlock);
2801       else
2802         TopBlock = currentBlock;
2803 
2804       addSuccessor(SwitchTerminatedBlock,
2805                    shouldAddCase(switchExclusivelyCovered, switchCond,
2806                                  CS, *Context)
2807                    ? currentBlock : 0);
2808 
2809       LastBlock = currentBlock;
2810       CS = cast<CaseStmt>(Sub);
2811       Sub = CS->getSubStmt();
2812     }
2813 
2814     addStmt(Sub);
2815   }
2816 
2817   CFGBlock *CaseBlock = Block;
2818   if (!CaseBlock)
2819     CaseBlock = createBlock();
2820 
2821   // Cases statements partition blocks, so this is the top of the basic block we
2822   // were processing (the "case XXX:" is the label).
2823   CaseBlock->setLabel(CS);
2824 
2825   if (badCFG)
2826     return 0;
2827 
2828   // Add this block to the list of successors for the block with the switch
2829   // statement.
2830   assert(SwitchTerminatedBlock);
2831   addSuccessor(SwitchTerminatedBlock,
2832                shouldAddCase(switchExclusivelyCovered, switchCond,
2833                              CS, *Context)
2834                ? CaseBlock : 0);
2835 
2836   // We set Block to NULL to allow lazy creation of a new block (if necessary)
2837   Block = NULL;
2838 
2839   if (TopBlock) {
2840     addSuccessor(LastBlock, CaseBlock);
2841     Succ = TopBlock;
2842   } else {
2843     // This block is now the implicit successor of other blocks.
2844     Succ = CaseBlock;
2845   }
2846 
2847   return Succ;
2848 }
2849 
2850 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
2851   if (Terminator->getSubStmt())
2852     addStmt(Terminator->getSubStmt());
2853 
2854   DefaultCaseBlock = Block;
2855 
2856   if (!DefaultCaseBlock)
2857     DefaultCaseBlock = createBlock();
2858 
2859   // Default statements partition blocks, so this is the top of the basic block
2860   // we were processing (the "default:" is the label).
2861   DefaultCaseBlock->setLabel(Terminator);
2862 
2863   if (badCFG)
2864     return 0;
2865 
2866   // Unlike case statements, we don't add the default block to the successors
2867   // for the switch statement immediately.  This is done when we finish
2868   // processing the switch statement.  This allows for the default case
2869   // (including a fall-through to the code after the switch statement) to always
2870   // be the last successor of a switch-terminated block.
2871 
2872   // We set Block to NULL to allow lazy creation of a new block (if necessary)
2873   Block = NULL;
2874 
2875   // This block is now the implicit successor of other blocks.
2876   Succ = DefaultCaseBlock;
2877 
2878   return DefaultCaseBlock;
2879 }
2880 
2881 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
2882   // "try"/"catch" is a control-flow statement.  Thus we stop processing the
2883   // current block.
2884   CFGBlock *TrySuccessor = NULL;
2885 
2886   if (Block) {
2887     if (badCFG)
2888       return 0;
2889     TrySuccessor = Block;
2890   } else TrySuccessor = Succ;
2891 
2892   CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
2893 
2894   // Create a new block that will contain the try statement.
2895   CFGBlock *NewTryTerminatedBlock = createBlock(false);
2896   // Add the terminator in the try block.
2897   NewTryTerminatedBlock->setTerminator(Terminator);
2898 
2899   bool HasCatchAll = false;
2900   for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
2901     // The code after the try is the implicit successor.
2902     Succ = TrySuccessor;
2903     CXXCatchStmt *CS = Terminator->getHandler(h);
2904     if (CS->getExceptionDecl() == 0) {
2905       HasCatchAll = true;
2906     }
2907     Block = NULL;
2908     CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
2909     if (CatchBlock == 0)
2910       return 0;
2911     // Add this block to the list of successors for the block with the try
2912     // statement.
2913     addSuccessor(NewTryTerminatedBlock, CatchBlock);
2914   }
2915   if (!HasCatchAll) {
2916     if (PrevTryTerminatedBlock)
2917       addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
2918     else
2919       addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
2920   }
2921 
2922   // The code after the try is the implicit successor.
2923   Succ = TrySuccessor;
2924 
2925   // Save the current "try" context.
2926   SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
2927   cfg->addTryDispatchBlock(TryTerminatedBlock);
2928 
2929   assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
2930   Block = NULL;
2931   return addStmt(Terminator->getTryBlock());
2932 }
2933 
2934 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
2935   // CXXCatchStmt are treated like labels, so they are the first statement in a
2936   // block.
2937 
2938   // Save local scope position because in case of exception variable ScopePos
2939   // won't be restored when traversing AST.
2940   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2941 
2942   // Create local scope for possible exception variable.
2943   // Store scope position. Add implicit destructor.
2944   if (VarDecl *VD = CS->getExceptionDecl()) {
2945     LocalScope::const_iterator BeginScopePos = ScopePos;
2946     addLocalScopeForVarDecl(VD);
2947     addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
2948   }
2949 
2950   if (CS->getHandlerBlock())
2951     addStmt(CS->getHandlerBlock());
2952 
2953   CFGBlock *CatchBlock = Block;
2954   if (!CatchBlock)
2955     CatchBlock = createBlock();
2956 
2957   // CXXCatchStmt is more than just a label.  They have semantic meaning
2958   // as well, as they implicitly "initialize" the catch variable.  Add
2959   // it to the CFG as a CFGElement so that the control-flow of these
2960   // semantics gets captured.
2961   appendStmt(CatchBlock, CS);
2962 
2963   // Also add the CXXCatchStmt as a label, to mirror handling of regular
2964   // labels.
2965   CatchBlock->setLabel(CS);
2966 
2967   // Bail out if the CFG is bad.
2968   if (badCFG)
2969     return 0;
2970 
2971   // We set Block to NULL to allow lazy creation of a new block (if necessary)
2972   Block = NULL;
2973 
2974   return CatchBlock;
2975 }
2976 
2977 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
2978   // C++0x for-range statements are specified as [stmt.ranged]:
2979   //
2980   // {
2981   //   auto && __range = range-init;
2982   //   for ( auto __begin = begin-expr,
2983   //         __end = end-expr;
2984   //         __begin != __end;
2985   //         ++__begin ) {
2986   //     for-range-declaration = *__begin;
2987   //     statement
2988   //   }
2989   // }
2990 
2991   // Save local scope position before the addition of the implicit variables.
2992   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2993 
2994   // Create local scopes and destructors for range, begin and end variables.
2995   if (Stmt *Range = S->getRangeStmt())
2996     addLocalScopeForStmt(Range);
2997   if (Stmt *BeginEnd = S->getBeginEndStmt())
2998     addLocalScopeForStmt(BeginEnd);
2999   addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S);
3000 
3001   LocalScope::const_iterator ContinueScopePos = ScopePos;
3002 
3003   // "for" is a control-flow statement.  Thus we stop processing the current
3004   // block.
3005   CFGBlock *LoopSuccessor = NULL;
3006   if (Block) {
3007     if (badCFG)
3008       return 0;
3009     LoopSuccessor = Block;
3010   } else
3011     LoopSuccessor = Succ;
3012 
3013   // Save the current value for the break targets.
3014   // All breaks should go to the code following the loop.
3015   SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3016   BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3017 
3018   // The block for the __begin != __end expression.
3019   CFGBlock *ConditionBlock = createBlock(false);
3020   ConditionBlock->setTerminator(S);
3021 
3022   // Now add the actual condition to the condition block.
3023   if (Expr *C = S->getCond()) {
3024     Block = ConditionBlock;
3025     CFGBlock *BeginConditionBlock = addStmt(C);
3026     if (badCFG)
3027       return 0;
3028     assert(BeginConditionBlock == ConditionBlock &&
3029            "condition block in for-range was unexpectedly complex");
3030     (void)BeginConditionBlock;
3031   }
3032 
3033   // The condition block is the implicit successor for the loop body as well as
3034   // any code above the loop.
3035   Succ = ConditionBlock;
3036 
3037   // See if this is a known constant.
3038   TryResult KnownVal(true);
3039 
3040   if (S->getCond())
3041     KnownVal = tryEvaluateBool(S->getCond());
3042 
3043   // Now create the loop body.
3044   {
3045     assert(S->getBody());
3046 
3047     // Save the current values for Block, Succ, and continue targets.
3048     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3049     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3050 
3051     // Generate increment code in its own basic block.  This is the target of
3052     // continue statements.
3053     Block = 0;
3054     Succ = addStmt(S->getInc());
3055     ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3056 
3057     // The starting block for the loop increment is the block that should
3058     // represent the 'loop target' for looping back to the start of the loop.
3059     ContinueJumpTarget.block->setLoopTarget(S);
3060 
3061     // Finish up the increment block and prepare to start the loop body.
3062     assert(Block);
3063     if (badCFG)
3064       return 0;
3065     Block = 0;
3066 
3067 
3068     // Add implicit scope and dtors for loop variable.
3069     addLocalScopeAndDtors(S->getLoopVarStmt());
3070 
3071     // Populate a new block to contain the loop body and loop variable.
3072     addStmt(S->getBody());
3073     if (badCFG)
3074       return 0;
3075     CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
3076     if (badCFG)
3077       return 0;
3078 
3079     // This new body block is a successor to our condition block.
3080     addSuccessor(ConditionBlock, KnownVal.isFalse() ? 0 : LoopVarStmtBlock);
3081   }
3082 
3083   // Link up the condition block with the code that follows the loop (the
3084   // false branch).
3085   addSuccessor(ConditionBlock, KnownVal.isTrue() ? 0 : LoopSuccessor);
3086 
3087   // Add the initialization statements.
3088   Block = createBlock();
3089   addStmt(S->getBeginEndStmt());
3090   return addStmt(S->getRangeStmt());
3091 }
3092 
3093 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
3094     AddStmtChoice asc) {
3095   if (BuildOpts.AddTemporaryDtors) {
3096     // If adding implicit destructors visit the full expression for adding
3097     // destructors of temporaries.
3098     VisitForTemporaryDtors(E->getSubExpr());
3099 
3100     // Full expression has to be added as CFGStmt so it will be sequenced
3101     // before destructors of it's temporaries.
3102     asc = asc.withAlwaysAdd(true);
3103   }
3104   return Visit(E->getSubExpr(), asc);
3105 }
3106 
3107 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3108                                                 AddStmtChoice asc) {
3109   if (asc.alwaysAdd(*this, E)) {
3110     autoCreateBlock();
3111     appendStmt(Block, E);
3112 
3113     // We do not want to propagate the AlwaysAdd property.
3114     asc = asc.withAlwaysAdd(false);
3115   }
3116   return Visit(E->getSubExpr(), asc);
3117 }
3118 
3119 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3120                                             AddStmtChoice asc) {
3121   autoCreateBlock();
3122   appendStmt(Block, C);
3123 
3124   return VisitChildren(C);
3125 }
3126 
3127 
3128 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3129                                          AddStmtChoice asc) {
3130   autoCreateBlock();
3131   appendStmt(Block, DE);
3132   QualType DTy = DE->getDestroyedType();
3133   DTy = DTy.getNonReferenceType();
3134   CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
3135   if (RD) {
3136     if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
3137       appendDeleteDtor(Block, RD, DE);
3138   }
3139 
3140   return VisitChildren(DE);
3141 }
3142 
3143 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
3144                                                  AddStmtChoice asc) {
3145   if (asc.alwaysAdd(*this, E)) {
3146     autoCreateBlock();
3147     appendStmt(Block, E);
3148     // We do not want to propagate the AlwaysAdd property.
3149     asc = asc.withAlwaysAdd(false);
3150   }
3151   return Visit(E->getSubExpr(), asc);
3152 }
3153 
3154 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
3155                                                   AddStmtChoice asc) {
3156   autoCreateBlock();
3157   appendStmt(Block, C);
3158   return VisitChildren(C);
3159 }
3160 
3161 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
3162                                             AddStmtChoice asc) {
3163   if (asc.alwaysAdd(*this, E)) {
3164     autoCreateBlock();
3165     appendStmt(Block, E);
3166   }
3167   return Visit(E->getSubExpr(), AddStmtChoice());
3168 }
3169 
3170 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
3171   // Lazily create the indirect-goto dispatch block if there isn't one already.
3172   CFGBlock *IBlock = cfg->getIndirectGotoBlock();
3173 
3174   if (!IBlock) {
3175     IBlock = createBlock(false);
3176     cfg->setIndirectGotoBlock(IBlock);
3177   }
3178 
3179   // IndirectGoto is a control-flow statement.  Thus we stop processing the
3180   // current block and create a new one.
3181   if (badCFG)
3182     return 0;
3183 
3184   Block = createBlock(false);
3185   Block->setTerminator(I);
3186   addSuccessor(Block, IBlock);
3187   return addStmt(I->getTarget());
3188 }
3189 
3190 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary) {
3191   assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
3192 
3193 tryAgain:
3194   if (!E) {
3195     badCFG = true;
3196     return NULL;
3197   }
3198   switch (E->getStmtClass()) {
3199     default:
3200       return VisitChildrenForTemporaryDtors(E);
3201 
3202     case Stmt::BinaryOperatorClass:
3203       return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E));
3204 
3205     case Stmt::CXXBindTemporaryExprClass:
3206       return VisitCXXBindTemporaryExprForTemporaryDtors(
3207           cast<CXXBindTemporaryExpr>(E), BindToTemporary);
3208 
3209     case Stmt::BinaryConditionalOperatorClass:
3210     case Stmt::ConditionalOperatorClass:
3211       return VisitConditionalOperatorForTemporaryDtors(
3212           cast<AbstractConditionalOperator>(E), BindToTemporary);
3213 
3214     case Stmt::ImplicitCastExprClass:
3215       // For implicit cast we want BindToTemporary to be passed further.
3216       E = cast<CastExpr>(E)->getSubExpr();
3217       goto tryAgain;
3218 
3219     case Stmt::ParenExprClass:
3220       E = cast<ParenExpr>(E)->getSubExpr();
3221       goto tryAgain;
3222 
3223     case Stmt::MaterializeTemporaryExprClass:
3224       E = cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr();
3225       goto tryAgain;
3226   }
3227 }
3228 
3229 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E) {
3230   // When visiting children for destructors we want to visit them in reverse
3231   // order that they will appear in the CFG.  Because the CFG is built
3232   // bottom-up, this means we visit them in their natural order, which
3233   // reverses them in the CFG.
3234   CFGBlock *B = Block;
3235   for (Stmt::child_range I = E->children(); I; ++I) {
3236     if (Stmt *Child = *I)
3237       if (CFGBlock *R = VisitForTemporaryDtors(Child))
3238         B = R;
3239   }
3240   return B;
3241 }
3242 
3243 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E) {
3244   if (E->isLogicalOp()) {
3245     // Destructors for temporaries in LHS expression should be called after
3246     // those for RHS expression. Even if this will unnecessarily create a block,
3247     // this block will be used at least by the full expression.
3248     autoCreateBlock();
3249     CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getLHS());
3250     if (badCFG)
3251       return NULL;
3252 
3253     Succ = ConfluenceBlock;
3254     Block = NULL;
3255     CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
3256 
3257     if (RHSBlock) {
3258       if (badCFG)
3259         return NULL;
3260 
3261       // If RHS expression did produce destructors we need to connect created
3262       // blocks to CFG in same manner as for binary operator itself.
3263       CFGBlock *LHSBlock = createBlock(false);
3264       LHSBlock->setTerminator(CFGTerminator(E, true));
3265 
3266       // For binary operator LHS block is before RHS in list of predecessors
3267       // of ConfluenceBlock.
3268       std::reverse(ConfluenceBlock->pred_begin(),
3269           ConfluenceBlock->pred_end());
3270 
3271       // See if this is a known constant.
3272       TryResult KnownVal = tryEvaluateBool(E->getLHS());
3273       if (KnownVal.isKnown() && (E->getOpcode() == BO_LOr))
3274         KnownVal.negate();
3275 
3276       // Link LHSBlock with RHSBlock exactly the same way as for binary operator
3277       // itself.
3278       if (E->getOpcode() == BO_LOr) {
3279         addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
3280         addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
3281       } else {
3282         assert (E->getOpcode() == BO_LAnd);
3283         addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
3284         addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
3285       }
3286 
3287       Block = LHSBlock;
3288       return LHSBlock;
3289     }
3290 
3291     Block = ConfluenceBlock;
3292     return ConfluenceBlock;
3293   }
3294 
3295   if (E->isAssignmentOp()) {
3296     // For assignment operator (=) LHS expression is visited
3297     // before RHS expression. For destructors visit them in reverse order.
3298     CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
3299     CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS());
3300     return LHSBlock ? LHSBlock : RHSBlock;
3301   }
3302 
3303   // For any other binary operator RHS expression is visited before
3304   // LHS expression (order of children). For destructors visit them in reverse
3305   // order.
3306   CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS());
3307   CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
3308   return RHSBlock ? RHSBlock : LHSBlock;
3309 }
3310 
3311 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
3312     CXXBindTemporaryExpr *E, bool BindToTemporary) {
3313   // First add destructors for temporaries in subexpression.
3314   CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr());
3315   if (!BindToTemporary) {
3316     // If lifetime of temporary is not prolonged (by assigning to constant
3317     // reference) add destructor for it.
3318 
3319     // If the destructor is marked as a no-return destructor, we need to create
3320     // a new block for the destructor which does not have as a successor
3321     // anything built thus far. Control won't flow out of this block.
3322     const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
3323     if (Dtor->isNoReturn())
3324       Block = createNoReturnBlock();
3325     else
3326       autoCreateBlock();
3327 
3328     appendTemporaryDtor(Block, E);
3329     B = Block;
3330   }
3331   return B;
3332 }
3333 
3334 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
3335     AbstractConditionalOperator *E, bool BindToTemporary) {
3336   // First add destructors for condition expression.  Even if this will
3337   // unnecessarily create a block, this block will be used at least by the full
3338   // expression.
3339   autoCreateBlock();
3340   CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getCond());
3341   if (badCFG)
3342     return NULL;
3343   if (BinaryConditionalOperator *BCO
3344         = dyn_cast<BinaryConditionalOperator>(E)) {
3345     ConfluenceBlock = VisitForTemporaryDtors(BCO->getCommon());
3346     if (badCFG)
3347       return NULL;
3348   }
3349 
3350   // Try to add block with destructors for LHS expression.
3351   CFGBlock *LHSBlock = NULL;
3352   Succ = ConfluenceBlock;
3353   Block = NULL;
3354   LHSBlock = VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary);
3355   if (badCFG)
3356     return NULL;
3357 
3358   // Try to add block with destructors for RHS expression;
3359   Succ = ConfluenceBlock;
3360   Block = NULL;
3361   CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getFalseExpr(),
3362                                               BindToTemporary);
3363   if (badCFG)
3364     return NULL;
3365 
3366   if (!RHSBlock && !LHSBlock) {
3367     // If neither LHS nor RHS expression had temporaries to destroy don't create
3368     // more blocks.
3369     Block = ConfluenceBlock;
3370     return Block;
3371   }
3372 
3373   Block = createBlock(false);
3374   Block->setTerminator(CFGTerminator(E, true));
3375 
3376   // See if this is a known constant.
3377   const TryResult &KnownVal = tryEvaluateBool(E->getCond());
3378 
3379   if (LHSBlock) {
3380     addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
3381   } else if (KnownVal.isFalse()) {
3382     addSuccessor(Block, NULL);
3383   } else {
3384     addSuccessor(Block, ConfluenceBlock);
3385     std::reverse(ConfluenceBlock->pred_begin(), ConfluenceBlock->pred_end());
3386   }
3387 
3388   if (!RHSBlock)
3389     RHSBlock = ConfluenceBlock;
3390   addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
3391 
3392   return Block;
3393 }
3394 
3395 } // end anonymous namespace
3396 
3397 /// createBlock - Constructs and adds a new CFGBlock to the CFG.  The block has
3398 ///  no successors or predecessors.  If this is the first block created in the
3399 ///  CFG, it is automatically set to be the Entry and Exit of the CFG.
3400 CFGBlock *CFG::createBlock() {
3401   bool first_block = begin() == end();
3402 
3403   // Create the block.
3404   CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
3405   new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
3406   Blocks.push_back(Mem, BlkBVC);
3407 
3408   // If this is the first block, set it as the Entry and Exit.
3409   if (first_block)
3410     Entry = Exit = &back();
3411 
3412   // Return the block.
3413   return &back();
3414 }
3415 
3416 /// buildCFG - Constructs a CFG from an AST.  Ownership of the returned
3417 ///  CFG is returned to the caller.
3418 CFG* CFG::buildCFG(const Decl *D, Stmt *Statement, ASTContext *C,
3419     const BuildOptions &BO) {
3420   CFGBuilder Builder(C, BO);
3421   return Builder.buildCFG(D, Statement);
3422 }
3423 
3424 const CXXDestructorDecl *
3425 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
3426   switch (getKind()) {
3427     case CFGElement::Statement:
3428     case CFGElement::Initializer:
3429       llvm_unreachable("getDestructorDecl should only be used with "
3430                        "ImplicitDtors");
3431     case CFGElement::AutomaticObjectDtor: {
3432       const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
3433       QualType ty = var->getType();
3434       ty = ty.getNonReferenceType();
3435       while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
3436         ty = arrayType->getElementType();
3437       }
3438       const RecordType *recordType = ty->getAs<RecordType>();
3439       const CXXRecordDecl *classDecl =
3440       cast<CXXRecordDecl>(recordType->getDecl());
3441       return classDecl->getDestructor();
3442     }
3443     case CFGElement::DeleteDtor: {
3444       const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
3445       QualType DTy = DE->getDestroyedType();
3446       DTy = DTy.getNonReferenceType();
3447       const CXXRecordDecl *classDecl =
3448           astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
3449       return classDecl->getDestructor();
3450     }
3451     case CFGElement::TemporaryDtor: {
3452       const CXXBindTemporaryExpr *bindExpr =
3453         castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
3454       const CXXTemporary *temp = bindExpr->getTemporary();
3455       return temp->getDestructor();
3456     }
3457     case CFGElement::BaseDtor:
3458     case CFGElement::MemberDtor:
3459 
3460       // Not yet supported.
3461       return 0;
3462   }
3463   llvm_unreachable("getKind() returned bogus value");
3464 }
3465 
3466 bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
3467   if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
3468     return DD->isNoReturn();
3469   return false;
3470 }
3471 
3472 //===----------------------------------------------------------------------===//
3473 // Filtered walking of the CFG.
3474 //===----------------------------------------------------------------------===//
3475 
3476 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
3477         const CFGBlock *From, const CFGBlock *To) {
3478 
3479   if (To && F.IgnoreDefaultsWithCoveredEnums) {
3480     // If the 'To' has no label or is labeled but the label isn't a
3481     // CaseStmt then filter this edge.
3482     if (const SwitchStmt *S =
3483         dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
3484       if (S->isAllEnumCasesCovered()) {
3485         const Stmt *L = To->getLabel();
3486         if (!L || !isa<CaseStmt>(L))
3487           return true;
3488       }
3489     }
3490   }
3491 
3492   return false;
3493 }
3494 
3495 //===----------------------------------------------------------------------===//
3496 // CFG pretty printing
3497 //===----------------------------------------------------------------------===//
3498 
3499 namespace {
3500 
3501 class StmtPrinterHelper : public PrinterHelper  {
3502   typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
3503   typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
3504   StmtMapTy StmtMap;
3505   DeclMapTy DeclMap;
3506   signed currentBlock;
3507   unsigned currStmt;
3508   const LangOptions &LangOpts;
3509 public:
3510 
3511   StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
3512     : currentBlock(0), currStmt(0), LangOpts(LO)
3513   {
3514     for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
3515       unsigned j = 1;
3516       for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
3517            BI != BEnd; ++BI, ++j ) {
3518         if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
3519           const Stmt *stmt= SE->getStmt();
3520           std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
3521           StmtMap[stmt] = P;
3522 
3523           switch (stmt->getStmtClass()) {
3524             case Stmt::DeclStmtClass:
3525                 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
3526                 break;
3527             case Stmt::IfStmtClass: {
3528               const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
3529               if (var)
3530                 DeclMap[var] = P;
3531               break;
3532             }
3533             case Stmt::ForStmtClass: {
3534               const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
3535               if (var)
3536                 DeclMap[var] = P;
3537               break;
3538             }
3539             case Stmt::WhileStmtClass: {
3540               const VarDecl *var =
3541                 cast<WhileStmt>(stmt)->getConditionVariable();
3542               if (var)
3543                 DeclMap[var] = P;
3544               break;
3545             }
3546             case Stmt::SwitchStmtClass: {
3547               const VarDecl *var =
3548                 cast<SwitchStmt>(stmt)->getConditionVariable();
3549               if (var)
3550                 DeclMap[var] = P;
3551               break;
3552             }
3553             case Stmt::CXXCatchStmtClass: {
3554               const VarDecl *var =
3555                 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
3556               if (var)
3557                 DeclMap[var] = P;
3558               break;
3559             }
3560             default:
3561               break;
3562           }
3563         }
3564       }
3565     }
3566   }
3567 
3568 
3569   virtual ~StmtPrinterHelper() {}
3570 
3571   const LangOptions &getLangOpts() const { return LangOpts; }
3572   void setBlockID(signed i) { currentBlock = i; }
3573   void setStmtID(unsigned i) { currStmt = i; }
3574 
3575   virtual bool handledStmt(Stmt *S, raw_ostream &OS) {
3576     StmtMapTy::iterator I = StmtMap.find(S);
3577 
3578     if (I == StmtMap.end())
3579       return false;
3580 
3581     if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
3582                           && I->second.second == currStmt) {
3583       return false;
3584     }
3585 
3586     OS << "[B" << I->second.first << "." << I->second.second << "]";
3587     return true;
3588   }
3589 
3590   bool handleDecl(const Decl *D, raw_ostream &OS) {
3591     DeclMapTy::iterator I = DeclMap.find(D);
3592 
3593     if (I == DeclMap.end())
3594       return false;
3595 
3596     if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
3597                           && I->second.second == currStmt) {
3598       return false;
3599     }
3600 
3601     OS << "[B" << I->second.first << "." << I->second.second << "]";
3602     return true;
3603   }
3604 };
3605 } // end anonymous namespace
3606 
3607 
3608 namespace {
3609 class CFGBlockTerminatorPrint
3610   : public StmtVisitor<CFGBlockTerminatorPrint,void> {
3611 
3612   raw_ostream &OS;
3613   StmtPrinterHelper* Helper;
3614   PrintingPolicy Policy;
3615 public:
3616   CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
3617                           const PrintingPolicy &Policy)
3618     : OS(os), Helper(helper), Policy(Policy) {}
3619 
3620   void VisitIfStmt(IfStmt *I) {
3621     OS << "if ";
3622     I->getCond()->printPretty(OS,Helper,Policy);
3623   }
3624 
3625   // Default case.
3626   void VisitStmt(Stmt *Terminator) {
3627     Terminator->printPretty(OS, Helper, Policy);
3628   }
3629 
3630   void VisitDeclStmt(DeclStmt *DS) {
3631     VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
3632     OS << "static init " << VD->getName();
3633   }
3634 
3635   void VisitForStmt(ForStmt *F) {
3636     OS << "for (" ;
3637     if (F->getInit())
3638       OS << "...";
3639     OS << "; ";
3640     if (Stmt *C = F->getCond())
3641       C->printPretty(OS, Helper, Policy);
3642     OS << "; ";
3643     if (F->getInc())
3644       OS << "...";
3645     OS << ")";
3646   }
3647 
3648   void VisitWhileStmt(WhileStmt *W) {
3649     OS << "while " ;
3650     if (Stmt *C = W->getCond())
3651       C->printPretty(OS, Helper, Policy);
3652   }
3653 
3654   void VisitDoStmt(DoStmt *D) {
3655     OS << "do ... while ";
3656     if (Stmt *C = D->getCond())
3657       C->printPretty(OS, Helper, Policy);
3658   }
3659 
3660   void VisitSwitchStmt(SwitchStmt *Terminator) {
3661     OS << "switch ";
3662     Terminator->getCond()->printPretty(OS, Helper, Policy);
3663   }
3664 
3665   void VisitCXXTryStmt(CXXTryStmt *CS) {
3666     OS << "try ...";
3667   }
3668 
3669   void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
3670     C->getCond()->printPretty(OS, Helper, Policy);
3671     OS << " ? ... : ...";
3672   }
3673 
3674   void VisitChooseExpr(ChooseExpr *C) {
3675     OS << "__builtin_choose_expr( ";
3676     C->getCond()->printPretty(OS, Helper, Policy);
3677     OS << " )";
3678   }
3679 
3680   void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
3681     OS << "goto *";
3682     I->getTarget()->printPretty(OS, Helper, Policy);
3683   }
3684 
3685   void VisitBinaryOperator(BinaryOperator* B) {
3686     if (!B->isLogicalOp()) {
3687       VisitExpr(B);
3688       return;
3689     }
3690 
3691     B->getLHS()->printPretty(OS, Helper, Policy);
3692 
3693     switch (B->getOpcode()) {
3694       case BO_LOr:
3695         OS << " || ...";
3696         return;
3697       case BO_LAnd:
3698         OS << " && ...";
3699         return;
3700       default:
3701         llvm_unreachable("Invalid logical operator.");
3702     }
3703   }
3704 
3705   void VisitExpr(Expr *E) {
3706     E->printPretty(OS, Helper, Policy);
3707   }
3708 };
3709 } // end anonymous namespace
3710 
3711 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
3712                        const CFGElement &E) {
3713   if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
3714     const Stmt *S = CS->getStmt();
3715 
3716     // special printing for statement-expressions.
3717     if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
3718       const CompoundStmt *Sub = SE->getSubStmt();
3719 
3720       if (Sub->children()) {
3721         OS << "({ ... ; ";
3722         Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
3723         OS << " })\n";
3724         return;
3725       }
3726     }
3727     // special printing for comma expressions.
3728     if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
3729       if (B->getOpcode() == BO_Comma) {
3730         OS << "... , ";
3731         Helper.handledStmt(B->getRHS(),OS);
3732         OS << '\n';
3733         return;
3734       }
3735     }
3736     S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
3737 
3738     if (isa<CXXOperatorCallExpr>(S)) {
3739       OS << " (OperatorCall)";
3740     }
3741     else if (isa<CXXBindTemporaryExpr>(S)) {
3742       OS << " (BindTemporary)";
3743     }
3744     else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
3745       OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
3746     }
3747     else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
3748       OS << " (" << CE->getStmtClassName() << ", "
3749          << CE->getCastKindName()
3750          << ", " << CE->getType().getAsString()
3751          << ")";
3752     }
3753 
3754     // Expressions need a newline.
3755     if (isa<Expr>(S))
3756       OS << '\n';
3757 
3758   } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
3759     const CXXCtorInitializer *I = IE->getInitializer();
3760     if (I->isBaseInitializer())
3761       OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
3762     else if (I->isDelegatingInitializer())
3763       OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
3764     else OS << I->getAnyMember()->getName();
3765 
3766     OS << "(";
3767     if (Expr *IE = I->getInit())
3768       IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
3769     OS << ")";
3770 
3771     if (I->isBaseInitializer())
3772       OS << " (Base initializer)\n";
3773     else if (I->isDelegatingInitializer())
3774       OS << " (Delegating initializer)\n";
3775     else OS << " (Member initializer)\n";
3776 
3777   } else if (Optional<CFGAutomaticObjDtor> DE =
3778                  E.getAs<CFGAutomaticObjDtor>()) {
3779     const VarDecl *VD = DE->getVarDecl();
3780     Helper.handleDecl(VD, OS);
3781 
3782     const Type* T = VD->getType().getTypePtr();
3783     if (const ReferenceType* RT = T->getAs<ReferenceType>())
3784       T = RT->getPointeeType().getTypePtr();
3785     T = T->getBaseElementTypeUnsafe();
3786 
3787     OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
3788     OS << " (Implicit destructor)\n";
3789 
3790   } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
3791     const CXXRecordDecl *RD = DE->getCXXRecordDecl();
3792     if (!RD)
3793       return;
3794     CXXDeleteExpr *DelExpr =
3795         const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
3796     Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
3797     OS << "->~" << RD->getName().str() << "()";
3798     OS << " (Implicit destructor)\n";
3799   } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
3800     const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
3801     OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
3802     OS << " (Base object destructor)\n";
3803 
3804   } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
3805     const FieldDecl *FD = ME->getFieldDecl();
3806     const Type *T = FD->getType()->getBaseElementTypeUnsafe();
3807     OS << "this->" << FD->getName();
3808     OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
3809     OS << " (Member object destructor)\n";
3810 
3811   } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
3812     const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
3813     OS << "~";
3814     BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
3815     OS << "() (Temporary object destructor)\n";
3816   }
3817 }
3818 
3819 static void print_block(raw_ostream &OS, const CFG* cfg,
3820                         const CFGBlock &B,
3821                         StmtPrinterHelper &Helper, bool print_edges,
3822                         bool ShowColors) {
3823 
3824   Helper.setBlockID(B.getBlockID());
3825 
3826   // Print the header.
3827   if (ShowColors)
3828     OS.changeColor(raw_ostream::YELLOW, true);
3829 
3830   OS << "\n [B" << B.getBlockID();
3831 
3832   if (&B == &cfg->getEntry())
3833     OS << " (ENTRY)]\n";
3834   else if (&B == &cfg->getExit())
3835     OS << " (EXIT)]\n";
3836   else if (&B == cfg->getIndirectGotoBlock())
3837     OS << " (INDIRECT GOTO DISPATCH)]\n";
3838   else
3839     OS << "]\n";
3840 
3841   if (ShowColors)
3842     OS.resetColor();
3843 
3844   // Print the label of this block.
3845   if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
3846 
3847     if (print_edges)
3848       OS << "  ";
3849 
3850     if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
3851       OS << L->getName();
3852     else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
3853       OS << "case ";
3854       C->getLHS()->printPretty(OS, &Helper,
3855                                PrintingPolicy(Helper.getLangOpts()));
3856       if (C->getRHS()) {
3857         OS << " ... ";
3858         C->getRHS()->printPretty(OS, &Helper,
3859                                  PrintingPolicy(Helper.getLangOpts()));
3860       }
3861     } else if (isa<DefaultStmt>(Label))
3862       OS << "default";
3863     else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
3864       OS << "catch (";
3865       if (CS->getExceptionDecl())
3866         CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
3867                                       0);
3868       else
3869         OS << "...";
3870       OS << ")";
3871 
3872     } else
3873       llvm_unreachable("Invalid label statement in CFGBlock.");
3874 
3875     OS << ":\n";
3876   }
3877 
3878   // Iterate through the statements in the block and print them.
3879   unsigned j = 1;
3880 
3881   for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
3882        I != E ; ++I, ++j ) {
3883 
3884     // Print the statement # in the basic block and the statement itself.
3885     if (print_edges)
3886       OS << " ";
3887 
3888     OS << llvm::format("%3d", j) << ": ";
3889 
3890     Helper.setStmtID(j);
3891 
3892     print_elem(OS, Helper, *I);
3893   }
3894 
3895   // Print the terminator of this block.
3896   if (B.getTerminator()) {
3897     if (ShowColors)
3898       OS.changeColor(raw_ostream::GREEN);
3899 
3900     OS << "   T: ";
3901 
3902     Helper.setBlockID(-1);
3903 
3904     PrintingPolicy PP(Helper.getLangOpts());
3905     CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
3906     TPrinter.Visit(const_cast<Stmt*>(B.getTerminator().getStmt()));
3907     OS << '\n';
3908 
3909     if (ShowColors)
3910       OS.resetColor();
3911   }
3912 
3913   if (print_edges) {
3914     // Print the predecessors of this block.
3915     if (!B.pred_empty()) {
3916       const raw_ostream::Colors Color = raw_ostream::BLUE;
3917       if (ShowColors)
3918         OS.changeColor(Color);
3919       OS << "   Preds " ;
3920       if (ShowColors)
3921         OS.resetColor();
3922       OS << '(' << B.pred_size() << "):";
3923       unsigned i = 0;
3924 
3925       if (ShowColors)
3926         OS.changeColor(Color);
3927 
3928       for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
3929            I != E; ++I, ++i) {
3930 
3931         if (i % 10 == 8)
3932           OS << "\n     ";
3933 
3934         OS << " B" << (*I)->getBlockID();
3935       }
3936 
3937       if (ShowColors)
3938         OS.resetColor();
3939 
3940       OS << '\n';
3941     }
3942 
3943     // Print the successors of this block.
3944     if (!B.succ_empty()) {
3945       const raw_ostream::Colors Color = raw_ostream::MAGENTA;
3946       if (ShowColors)
3947         OS.changeColor(Color);
3948       OS << "   Succs ";
3949       if (ShowColors)
3950         OS.resetColor();
3951       OS << '(' << B.succ_size() << "):";
3952       unsigned i = 0;
3953 
3954       if (ShowColors)
3955         OS.changeColor(Color);
3956 
3957       for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
3958            I != E; ++I, ++i) {
3959 
3960         if (i % 10 == 8)
3961           OS << "\n    ";
3962 
3963         if (*I)
3964           OS << " B" << (*I)->getBlockID();
3965         else
3966           OS  << " NULL";
3967       }
3968 
3969       if (ShowColors)
3970         OS.resetColor();
3971       OS << '\n';
3972     }
3973   }
3974 }
3975 
3976 
3977 /// dump - A simple pretty printer of a CFG that outputs to stderr.
3978 void CFG::dump(const LangOptions &LO, bool ShowColors) const {
3979   print(llvm::errs(), LO, ShowColors);
3980 }
3981 
3982 /// print - A simple pretty printer of a CFG that outputs to an ostream.
3983 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
3984   StmtPrinterHelper Helper(this, LO);
3985 
3986   // Print the entry block.
3987   print_block(OS, this, getEntry(), Helper, true, ShowColors);
3988 
3989   // Iterate through the CFGBlocks and print them one by one.
3990   for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
3991     // Skip the entry block, because we already printed it.
3992     if (&(**I) == &getEntry() || &(**I) == &getExit())
3993       continue;
3994 
3995     print_block(OS, this, **I, Helper, true, ShowColors);
3996   }
3997 
3998   // Print the exit block.
3999   print_block(OS, this, getExit(), Helper, true, ShowColors);
4000   OS << '\n';
4001   OS.flush();
4002 }
4003 
4004 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
4005 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4006                     bool ShowColors) const {
4007   print(llvm::errs(), cfg, LO, ShowColors);
4008 }
4009 
4010 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4011 ///   Generally this will only be called from CFG::print.
4012 void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
4013                      const LangOptions &LO, bool ShowColors) const {
4014   StmtPrinterHelper Helper(cfg, LO);
4015   print_block(OS, cfg, *this, Helper, true, ShowColors);
4016   OS << '\n';
4017 }
4018 
4019 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
4020 void CFGBlock::printTerminator(raw_ostream &OS,
4021                                const LangOptions &LO) const {
4022   CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
4023   TPrinter.Visit(const_cast<Stmt*>(getTerminator().getStmt()));
4024 }
4025 
4026 Stmt *CFGBlock::getTerminatorCondition() {
4027   Stmt *Terminator = this->Terminator;
4028   if (!Terminator)
4029     return NULL;
4030 
4031   Expr *E = NULL;
4032 
4033   switch (Terminator->getStmtClass()) {
4034     default:
4035       break;
4036 
4037     case Stmt::CXXForRangeStmtClass:
4038       E = cast<CXXForRangeStmt>(Terminator)->getCond();
4039       break;
4040 
4041     case Stmt::ForStmtClass:
4042       E = cast<ForStmt>(Terminator)->getCond();
4043       break;
4044 
4045     case Stmt::WhileStmtClass:
4046       E = cast<WhileStmt>(Terminator)->getCond();
4047       break;
4048 
4049     case Stmt::DoStmtClass:
4050       E = cast<DoStmt>(Terminator)->getCond();
4051       break;
4052 
4053     case Stmt::IfStmtClass:
4054       E = cast<IfStmt>(Terminator)->getCond();
4055       break;
4056 
4057     case Stmt::ChooseExprClass:
4058       E = cast<ChooseExpr>(Terminator)->getCond();
4059       break;
4060 
4061     case Stmt::IndirectGotoStmtClass:
4062       E = cast<IndirectGotoStmt>(Terminator)->getTarget();
4063       break;
4064 
4065     case Stmt::SwitchStmtClass:
4066       E = cast<SwitchStmt>(Terminator)->getCond();
4067       break;
4068 
4069     case Stmt::BinaryConditionalOperatorClass:
4070       E = cast<BinaryConditionalOperator>(Terminator)->getCond();
4071       break;
4072 
4073     case Stmt::ConditionalOperatorClass:
4074       E = cast<ConditionalOperator>(Terminator)->getCond();
4075       break;
4076 
4077     case Stmt::BinaryOperatorClass: // '&&' and '||'
4078       E = cast<BinaryOperator>(Terminator)->getLHS();
4079       break;
4080 
4081     case Stmt::ObjCForCollectionStmtClass:
4082       return Terminator;
4083   }
4084 
4085   return E ? E->IgnoreParens() : NULL;
4086 }
4087 
4088 //===----------------------------------------------------------------------===//
4089 // CFG Graphviz Visualization
4090 //===----------------------------------------------------------------------===//
4091 
4092 
4093 #ifndef NDEBUG
4094 static StmtPrinterHelper* GraphHelper;
4095 #endif
4096 
4097 void CFG::viewCFG(const LangOptions &LO) const {
4098 #ifndef NDEBUG
4099   StmtPrinterHelper H(this, LO);
4100   GraphHelper = &H;
4101   llvm::ViewGraph(this,"CFG");
4102   GraphHelper = NULL;
4103 #endif
4104 }
4105 
4106 namespace llvm {
4107 template<>
4108 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
4109 
4110   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
4111 
4112   static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
4113 
4114 #ifndef NDEBUG
4115     std::string OutSStr;
4116     llvm::raw_string_ostream Out(OutSStr);
4117     print_block(Out,Graph, *Node, *GraphHelper, false, false);
4118     std::string& OutStr = Out.str();
4119 
4120     if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
4121 
4122     // Process string output to make it nicer...
4123     for (unsigned i = 0; i != OutStr.length(); ++i)
4124       if (OutStr[i] == '\n') {                            // Left justify
4125         OutStr[i] = '\\';
4126         OutStr.insert(OutStr.begin()+i+1, 'l');
4127       }
4128 
4129     return OutStr;
4130 #else
4131     return "";
4132 #endif
4133   }
4134 };
4135 } // end namespace llvm
4136