Coverage Report

Created: 2024-01-17 10:31

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