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