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