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