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