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