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