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