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