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