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