Coverage Report

Created: 2019-02-23 12:57

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/include/clang/Analysis/CFG.h
Line
Count
Source (jump to first uncovered line)
1
//===- CFG.h - Classes for representing and building CFGs -------*- C++ -*-===//
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
#ifndef LLVM_CLANG_ANALYSIS_CFG_H
15
#define LLVM_CLANG_ANALYSIS_CFG_H
16
17
#include "clang/Analysis/Support/BumpVector.h"
18
#include "clang/Analysis/ConstructionContext.h"
19
#include "clang/AST/ExprCXX.h"
20
#include "clang/AST/ExprObjC.h"
21
#include "clang/Basic/LLVM.h"
22
#include "llvm/ADT/DenseMap.h"
23
#include "llvm/ADT/GraphTraits.h"
24
#include "llvm/ADT/None.h"
25
#include "llvm/ADT/Optional.h"
26
#include "llvm/ADT/PointerIntPair.h"
27
#include "llvm/ADT/iterator_range.h"
28
#include "llvm/Support/Allocator.h"
29
#include "llvm/Support/raw_ostream.h"
30
#include <bitset>
31
#include <cassert>
32
#include <cstddef>
33
#include <iterator>
34
#include <memory>
35
#include <vector>
36
37
namespace clang {
38
39
class ASTContext;
40
class BinaryOperator;
41
class CFG;
42
class CXXBaseSpecifier;
43
class CXXBindTemporaryExpr;
44
class CXXCtorInitializer;
45
class CXXDeleteExpr;
46
class CXXDestructorDecl;
47
class CXXNewExpr;
48
class CXXRecordDecl;
49
class Decl;
50
class FieldDecl;
51
class LangOptions;
52
class VarDecl;
53
54
/// Represents a top-level expression in a basic block.
55
0
class CFGElement {
56
public:
57
  enum Kind {
58
    // main kind
59
    Initializer,
60
    ScopeBegin,
61
    ScopeEnd,
62
    NewAllocator,
63
    LifetimeEnds,
64
    LoopExit,
65
    // stmt kind
66
    Statement,
67
    Constructor,
68
    CXXRecordTypedCall,
69
    STMT_BEGIN = Statement,
70
    STMT_END = CXXRecordTypedCall,
71
    // dtor kind
72
    AutomaticObjectDtor,
73
    DeleteDtor,
74
    BaseDtor,
75
    MemberDtor,
76
    TemporaryDtor,
77
    DTOR_BEGIN = AutomaticObjectDtor,
78
    DTOR_END = TemporaryDtor
79
  };
80
81
protected:
82
  // The int bits are used to mark the kind.
83
  llvm::PointerIntPair<void *, 2> Data1;
84
  llvm::PointerIntPair<void *, 2> Data2;
85
86
  CFGElement(Kind kind, const void *Ptr1, const void *Ptr2 = nullptr)
87
      : Data1(const_cast<void*>(Ptr1), ((unsigned) kind) & 0x3),
88
9.08M
        Data2(const_cast<void*>(Ptr2), (((unsigned) kind) >> 2) & 0x3) {
89
9.08M
    assert(getKind() == kind);
90
9.08M
  }
91
92
20.5M
  CFGElement() = default;
93
94
public:
95
  /// Convert to the specified CFGElement type, asserting that this
96
  /// CFGElement is of the desired type.
97
  template<typename T>
98
2.30M
  T castAs() const {
99
2.30M
    assert(T::isKind(*this));
100
2.30M
    T t;
101
2.30M
    CFGElement& e = t;
102
2.30M
    e = *this;
103
2.30M
    return t;
104
2.30M
  }
clang::CFGStmt clang::CFGElement::castAs<clang::CFGStmt>() const
Line
Count
Source
98
2.29M
  T castAs() const {
99
2.29M
    assert(T::isKind(*this));
100
2.29M
    T t;
101
2.29M
    CFGElement& e = t;
102
2.29M
    e = *this;
103
2.29M
    return t;
104
2.29M
  }
clang::CFGInitializer clang::CFGElement::castAs<clang::CFGInitializer>() const
Line
Count
Source
98
8.12k
  T castAs() const {
99
8.12k
    assert(T::isKind(*this));
100
8.12k
    T t;
101
8.12k
    CFGElement& e = t;
102
8.12k
    e = *this;
103
8.12k
    return t;
104
8.12k
  }
clang::CFGNewAllocator clang::CFGElement::castAs<clang::CFGNewAllocator>() const
Line
Count
Source
98
1.02k
  T castAs() const {
99
1.02k
    assert(T::isKind(*this));
100
1.02k
    T t;
101
1.02k
    CFGElement& e = t;
102
1.02k
    e = *this;
103
1.02k
    return t;
104
1.02k
  }
clang::CFGImplicitDtor clang::CFGElement::castAs<clang::CFGImplicitDtor>() const
Line
Count
Source
98
1.46k
  T castAs() const {
99
1.46k
    assert(T::isKind(*this));
100
1.46k
    T t;
101
1.46k
    CFGElement& e = t;
102
1.46k
    e = *this;
103
1.46k
    return t;
104
1.46k
  }
clang::CFGLoopExit clang::CFGElement::castAs<clang::CFGLoopExit>() const
Line
Count
Source
98
141
  T castAs() const {
99
141
    assert(T::isKind(*this));
100
141
    T t;
101
141
    CFGElement& e = t;
102
141
    e = *this;
103
141
    return t;
104
141
  }
clang::CFGAutomaticObjDtor clang::CFGElement::castAs<clang::CFGAutomaticObjDtor>() const
Line
Count
Source
98
1.18k
  T castAs() const {
99
1.18k
    assert(T::isKind(*this));
100
1.18k
    T t;
101
1.18k
    CFGElement& e = t;
102
1.18k
    e = *this;
103
1.18k
    return t;
104
1.18k
  }
clang::CFGBaseDtor clang::CFGElement::castAs<clang::CFGBaseDtor>() const
Line
Count
Source
98
104
  T castAs() const {
99
104
    assert(T::isKind(*this));
100
104
    T t;
101
104
    CFGElement& e = t;
102
104
    e = *this;
103
104
    return t;
104
104
  }
clang::CFGMemberDtor clang::CFGElement::castAs<clang::CFGMemberDtor>() const
Line
Count
Source
98
45
  T castAs() const {
99
45
    assert(T::isKind(*this));
100
45
    T t;
101
45
    CFGElement& e = t;
102
45
    e = *this;
103
45
    return t;
104
45
  }
clang::CFGTemporaryDtor clang::CFGElement::castAs<clang::CFGTemporaryDtor>() const
Line
Count
Source
98
838
  T castAs() const {
99
838
    assert(T::isKind(*this));
100
838
    T t;
101
838
    CFGElement& e = t;
102
838
    e = *this;
103
838
    return t;
104
838
  }
clang::CFGDeleteDtor clang::CFGElement::castAs<clang::CFGDeleteDtor>() const
Line
Count
Source
98
129
  T castAs() const {
99
129
    assert(T::isKind(*this));
100
129
    T t;
101
129
    CFGElement& e = t;
102
129
    e = *this;
103
129
    return t;
104
129
  }
105
106
  /// Convert to the specified CFGElement type, returning None if this
107
  /// CFGElement is not of the desired type.
108
  template<typename T>
109
18.6M
  Optional<T> getAs() const {
110
18.6M
    if (!T::isKind(*this))
111
411k
      return None;
112
18.2M
    T t;
113
18.2M
    CFGElement& e = t;
114
18.2M
    e = *this;
115
18.2M
    return t;
116
18.2M
  }
llvm::Optional<clang::CFGStmt> clang::CFGElement::getAs<clang::CFGStmt>() const
Line
Count
Source
109
18.2M
  Optional<T> getAs() const {
110
18.2M
    if (!T::isKind(*this))
111
64.5k
      return None;
112
18.1M
    T t;
113
18.1M
    CFGElement& e = t;
114
18.1M
    e = *this;
115
18.1M
    return t;
116
18.1M
  }
llvm::Optional<clang::CFGAutomaticObjDtor> clang::CFGElement::getAs<clang::CFGAutomaticObjDtor>() const
Line
Count
Source
109
310k
  Optional<T> getAs() const {
110
310k
    if (!T::isKind(*this))
111
308k
      return None;
112
2.19k
    T t;
113
2.19k
    CFGElement& e = t;
114
2.19k
    e = *this;
115
2.19k
    return t;
116
2.19k
  }
llvm::Optional<clang::CFGDeleteDtor> clang::CFGElement::getAs<clang::CFGDeleteDtor>() const
Line
Count
Source
109
957
  Optional<T> getAs() const {
110
957
    if (!T::isKind(*this))
111
855
      return None;
112
102
    T t;
113
102
    CFGElement& e = t;
114
102
    e = *this;
115
102
    return t;
116
102
  }
llvm::Optional<clang::CFGBaseDtor> clang::CFGElement::getAs<clang::CFGBaseDtor>() const
Line
Count
Source
109
1.75k
  Optional<T> getAs() const {
110
1.75k
    if (!T::isKind(*this))
111
1.57k
      return None;
112
179
    T t;
113
179
    CFGElement& e = t;
114
179
    e = *this;
115
179
    return t;
116
179
  }
llvm::Optional<clang::CFGCXXRecordTypedCall> clang::CFGElement::getAs<clang::CFGCXXRecordTypedCall>() const
Line
Count
Source
109
31.9k
  Optional<T> getAs() const {
110
31.9k
    if (!T::isKind(*this))
111
30.7k
      return None;
112
1.16k
    T t;
113
1.16k
    CFGElement& e = t;
114
1.16k
    e = *this;
115
1.16k
    return t;
116
1.16k
  }
llvm::Optional<clang::CFGConstructor> clang::CFGElement::getAs<clang::CFGConstructor>() const
Line
Count
Source
109
25.9k
  Optional<T> getAs() const {
110
25.9k
    if (!T::isKind(*this))
111
978
      return None;
112
25.0k
    T t;
113
25.0k
    CFGElement& e = t;
114
25.0k
    e = *this;
115
25.0k
    return t;
116
25.0k
  }
llvm::Optional<clang::CFGNewAllocator> clang::CFGElement::getAs<clang::CFGNewAllocator>() const
Line
Count
Source
109
420
  Optional<T> getAs() const {
110
420
    if (!T::isKind(*this))
111
369
      return None;
112
51
    T t;
113
51
    CFGElement& e = t;
114
51
    e = *this;
115
51
    return t;
116
51
  }
llvm::Optional<clang::CFGInitializer> clang::CFGElement::getAs<clang::CFGInitializer>() const
Line
Count
Source
109
1.28k
  Optional<T> getAs() const {
110
1.28k
    if (!T::isKind(*this))
111
1.20k
      return None;
112
72
    T t;
113
72
    CFGElement& e = t;
114
72
    e = *this;
115
72
    return t;
116
72
  }
llvm::Optional<clang::CFGLifetimeEnds> clang::CFGElement::getAs<clang::CFGLifetimeEnds>() const
Line
Count
Source
109
638
  Optional<T> getAs() const {
110
638
    if (!T::isKind(*this))
111
556
      return None;
112
82
    T t;
113
82
    CFGElement& e = t;
114
82
    e = *this;
115
82
    return t;
116
82
  }
llvm::Optional<clang::CFGLoopExit> clang::CFGElement::getAs<clang::CFGLoopExit>() const
Line
Count
Source
109
556
  Optional<T> getAs() const {
110
556
    if (!T::isKind(*this))
111
543
      return None;
112
13
    T t;
113
13
    CFGElement& e = t;
114
13
    e = *this;
115
13
    return t;
116
13
  }
llvm::Optional<clang::CFGScopeBegin> clang::CFGElement::getAs<clang::CFGScopeBegin>() const
Line
Count
Source
109
543
  Optional<T> getAs() const {
110
543
    if (!T::isKind(*this))
111
497
      return None;
112
46
    T t;
113
46
    CFGElement& e = t;
114
46
    e = *this;
115
46
    return t;
116
46
  }
llvm::Optional<clang::CFGScopeEnd> clang::CFGElement::getAs<clang::CFGScopeEnd>() const
Line
Count
Source
109
497
  Optional<T> getAs() const {
110
497
    if (!T::isKind(*this))
111
419
      return None;
112
78
    T t;
113
78
    CFGElement& e = t;
114
78
    e = *this;
115
78
    return t;
116
78
  }
llvm::Optional<clang::CFGMemberDtor> clang::CFGElement::getAs<clang::CFGMemberDtor>() const
Line
Count
Source
109
360
  Optional<T> getAs() const {
110
360
    if (!T::isKind(*this))
111
356
      return None;
112
4
    T t;
113
4
    CFGElement& e = t;
114
4
    e = *this;
115
4
    return t;
116
4
  }
llvm::Optional<clang::CFGTemporaryDtor> clang::CFGElement::getAs<clang::CFGTemporaryDtor>() const
Line
Count
Source
109
356
  Optional<T> getAs() const {
110
356
    if (!T::isKind(*this))
111
0
      return None;
112
356
    T t;
113
356
    CFGElement& e = t;
114
356
    e = *this;
115
356
    return t;
116
356
  }
117
118
44.2M
  Kind getKind() const {
119
44.2M
    unsigned x = Data2.getInt();
120
44.2M
    x <<= 2;
121
44.2M
    x |= Data1.getInt();
122
44.2M
    return (Kind) x;
123
44.2M
  }
124
};
125
126
class CFGStmt : public CFGElement {
127
public:
128
8.98M
  explicit CFGStmt(Stmt *S, Kind K = Statement) : CFGElement(K, S) {
129
8.98M
    assert(isKind(*this));
130
8.98M
  }
131
132
19.9M
  const Stmt *getStmt() const {
133
19.9M
    return static_cast<const Stmt *>(Data1.getPointer());
134
19.9M
  }
135
136
private:
137
  friend class CFGElement;
138
139
18.2M
  static bool isKind(const CFGElement &E) {
140
18.2M
    return E.getKind() >= STMT_BEGIN && 
E.getKind() <= STMT_END18.2M
;
141
18.2M
  }
142
143
protected:
144
20.5M
  CFGStmt() = default;
145
};
146
147
/// Represents C++ constructor call. Maintains information necessary to figure
148
/// out what memory is being initialized by the constructor expression. For now
149
/// this is only used by the analyzer's CFG.
150
class CFGConstructor : public CFGStmt {
151
public:
152
  explicit CFGConstructor(CXXConstructExpr *CE, const ConstructionContext *C)
153
12.7k
      : CFGStmt(CE, Constructor) {
154
12.7k
    assert(C);
155
12.7k
    Data2.setPointer(const_cast<ConstructionContext *>(C));
156
12.7k
  }
157
158
25.0k
  const ConstructionContext *getConstructionContext() const {
159
25.0k
    return static_cast<ConstructionContext *>(Data2.getPointer());
160
25.0k
  }
161
162
private:
163
  friend class CFGElement;
164
165
25.0k
  CFGConstructor() = default;
166
167
25.9k
  static bool isKind(const CFGElement &E) {
168
25.9k
    return E.getKind() == Constructor;
169
25.9k
  }
170
};
171
172
/// Represents a function call that returns a C++ object by value. This, like
173
/// constructor, requires a construction context in order to understand the
174
/// storage of the returned object . In C such tracking is not necessary because
175
/// no additional effort is required for destroying the object or modeling copy
176
/// elision. Like CFGConstructor, this element is for now only used by the
177
/// analyzer's CFG.
178
class CFGCXXRecordTypedCall : public CFGStmt {
179
public:
180
  /// Returns true when call expression \p CE needs to be represented
181
  /// by CFGCXXRecordTypedCall, as opposed to a regular CFGStmt.
182
8.14k
  static bool isCXXRecordTypedCall(Expr *E) {
183
8.14k
    assert(isa<CallExpr>(E) || isa<ObjCMessageExpr>(E));
184
8.14k
    // There is no such thing as reference-type expression. If the function
185
8.14k
    // returns a reference, it'll return the respective lvalue or xvalue
186
8.14k
    // instead, and we're only interested in objects.
187
8.14k
    return !E->isGLValue() &&
188
8.14k
           
E->getType().getCanonicalType()->getAsCXXRecordDecl()8.09k
;
189
8.14k
  }
190
191
  explicit CFGCXXRecordTypedCall(Expr *E, const ConstructionContext *C)
192
2.00k
      : CFGStmt(E, CXXRecordTypedCall) {
193
2.00k
    assert(isCXXRecordTypedCall(E));
194
2.00k
    assert(C && (isa<TemporaryObjectConstructionContext>(C) ||
195
2.00k
                 // These are possible in C++17 due to mandatory copy elision.
196
2.00k
                 isa<ReturnedValueConstructionContext>(C) ||
197
2.00k
                 isa<VariableConstructionContext>(C) ||
198
2.00k
                 isa<ConstructorInitializerConstructionContext>(C) ||
199
2.00k
                 isa<ArgumentConstructionContext>(C)));
200
2.00k
    Data2.setPointer(const_cast<ConstructionContext *>(C));
201
2.00k
  }
202
203
1.16k
  const ConstructionContext *getConstructionContext() const {
204
1.16k
    return static_cast<ConstructionContext *>(Data2.getPointer());
205
1.16k
  }
206
207
private:
208
  friend class CFGElement;
209
210
1.16k
  CFGCXXRecordTypedCall() = default;
211
212
31.9k
  static bool isKind(const CFGElement &E) {
213
31.9k
    return E.getKind() == CXXRecordTypedCall;
214
31.9k
  }
215
};
216
217
/// Represents C++ base or member initializer from constructor's initialization
218
/// list.
219
class CFGInitializer : public CFGElement {
220
public:
221
  explicit CFGInitializer(CXXCtorInitializer *initializer)
222
68.8k
      : CFGElement(Initializer, initializer) {}
223
224
8.19k
  CXXCtorInitializer* getInitializer() const {
225
8.19k
    return static_cast<CXXCtorInitializer*>(Data1.getPointer());
226
8.19k
  }
227
228
private:
229
  friend class CFGElement;
230
231
8.19k
  CFGInitializer() = default;
232
233
1.28k
  static bool isKind(const CFGElement &E) {
234
1.28k
    return E.getKind() == Initializer;
235
1.28k
  }
236
};
237
238
/// Represents C++ allocator call.
239
class CFGNewAllocator : public CFGElement {
240
public:
241
  explicit CFGNewAllocator(const CXXNewExpr *S)
242
1.62k
    : CFGElement(NewAllocator, S) {}
243
244
  // Get the new expression.
245
1.07k
  const CXXNewExpr *getAllocatorExpr() const {
246
1.07k
    return static_cast<CXXNewExpr *>(Data1.getPointer());
247
1.07k
  }
248
249
private:
250
  friend class CFGElement;
251
252
1.07k
  CFGNewAllocator() = default;
253
254
420
  static bool isKind(const CFGElement &elem) {
255
420
    return elem.getKind() == NewAllocator;
256
420
  }
257
};
258
259
/// Represents the point where a loop ends.
260
/// This element is is only produced when building the CFG for the static
261
/// analyzer and hidden behind the 'cfg-loopexit' analyzer config flag.
262
///
263
/// Note: a loop exit element can be reached even when the loop body was never
264
/// entered.
265
class CFGLoopExit : public CFGElement {
266
public:
267
238
  explicit CFGLoopExit(const Stmt *stmt) : CFGElement(LoopExit, stmt) {}
268
269
154
  const Stmt *getLoopStmt() const {
270
154
    return static_cast<Stmt *>(Data1.getPointer());
271
154
  }
272
273
private:
274
  friend class CFGElement;
275
276
154
  CFGLoopExit() = default;
277
278
556
  static bool isKind(const CFGElement &elem) {
279
556
    return elem.getKind() == LoopExit;
280
556
  }
281
};
282
283
/// Represents the point where the lifetime of an automatic object ends
284
class CFGLifetimeEnds : public CFGElement {
285
public:
286
  explicit CFGLifetimeEnds(const VarDecl *var, const Stmt *stmt)
287
166
      : CFGElement(LifetimeEnds, var, stmt) {}
288
289
82
  const VarDecl *getVarDecl() const {
290
82
    return static_cast<VarDecl *>(Data1.getPointer());
291
82
  }
292
293
0
  const Stmt *getTriggerStmt() const {
294
0
    return static_cast<Stmt *>(Data2.getPointer());
295
0
  }
296
297
private:
298
  friend class CFGElement;
299
300
82
  CFGLifetimeEnds() = default;
301
302
638
  static bool isKind(const CFGElement &elem) {
303
638
    return elem.getKind() == LifetimeEnds;
304
638
  }
305
};
306
307
/// Represents beginning of a scope implicitly generated
308
/// by the compiler on encountering a CompoundStmt
309
class CFGScopeBegin : public CFGElement {
310
public:
311
46
  CFGScopeBegin() {}
312
  CFGScopeBegin(const VarDecl *VD, const Stmt *S)
313
92
      : CFGElement(ScopeBegin, VD, S) {}
314
315
  // Get statement that triggered a new scope.
316
0
  const Stmt *getTriggerStmt() const {
317
0
    return static_cast<Stmt*>(Data2.getPointer());
318
0
  }
319
320
  // Get VD that triggered a new scope.
321
46
  const VarDecl *getVarDecl() const {
322
46
    return static_cast<VarDecl *>(Data1.getPointer());
323
46
  }
324
325
private:
326
  friend class CFGElement;
327
543
  static bool isKind(const CFGElement &E) {
328
543
    Kind kind = E.getKind();
329
543
    return kind == ScopeBegin;
330
543
  }
331
};
332
333
/// Represents end of a scope implicitly generated by
334
/// the compiler after the last Stmt in a CompoundStmt's body
335
class CFGScopeEnd : public CFGElement {
336
public:
337
78
  CFGScopeEnd() {}
338
158
  CFGScopeEnd(const VarDecl *VD, const Stmt *S) : CFGElement(ScopeEnd, VD, S) {}
339
340
78
  const VarDecl *getVarDecl() const {
341
78
    return static_cast<VarDecl *>(Data1.getPointer());
342
78
  }
343
344
0
  const Stmt *getTriggerStmt() const {
345
0
    return static_cast<Stmt *>(Data2.getPointer());
346
0
  }
347
348
private:
349
  friend class CFGElement;
350
497
  static bool isKind(const CFGElement &E) {
351
497
    Kind kind = E.getKind();
352
497
    return kind == ScopeEnd;
353
497
  }
354
};
355
356
/// Represents C++ object destructor implicitly generated by compiler on various
357
/// occasions.
358
class CFGImplicitDtor : public CFGElement {
359
protected:
360
6.60k
  CFGImplicitDtor() = default;
361
362
  CFGImplicitDtor(Kind kind, const void *data1, const void *data2 = nullptr)
363
29.0k
    : CFGElement(kind, data1, data2) {
364
29.0k
    assert(kind >= DTOR_BEGIN && kind <= DTOR_END);
365
29.0k
  }
366
367
public:
368
  const CXXDestructorDecl *getDestructorDecl(ASTContext &astContext) const;
369
  bool isNoReturn(ASTContext &astContext) const;
370
371
private:
372
  friend class CFGElement;
373
374
0
  static bool isKind(const CFGElement &E) {
375
0
    Kind kind = E.getKind();
376
0
    return kind >= DTOR_BEGIN && kind <= DTOR_END;
377
0
  }
378
};
379
380
/// Represents C++ object destructor implicitly generated for automatic object
381
/// or temporary bound to const reference at the point of leaving its local
382
/// scope.
383
class CFGAutomaticObjDtor: public CFGImplicitDtor {
384
public:
385
  CFGAutomaticObjDtor(const VarDecl *var, const Stmt *stmt)
386
21.8k
      : CFGImplicitDtor(AutomaticObjectDtor, var, stmt) {}
387
388
2.29k
  const VarDecl *getVarDecl() const {
389
2.29k
    return static_cast<VarDecl*>(Data1.getPointer());
390
2.29k
  }
391
392
  // Get statement end of which triggered the destructor call.
393
1.89k
  const Stmt *getTriggerStmt() const {
394
1.89k
    return static_cast<Stmt*>(Data2.getPointer());
395
1.89k
  }
396
397
private:
398
  friend class CFGElement;
399
400
3.38k
  CFGAutomaticObjDtor() = default;
401
402
310k
  static bool isKind(const CFGElement &elem) {
403
310k
    return elem.getKind() == AutomaticObjectDtor;
404
310k
  }
405
};
406
407
/// Represents C++ object destructor generated from a call to delete.
408
class CFGDeleteDtor : public CFGImplicitDtor {
409
public:
410
  CFGDeleteDtor(const CXXRecordDecl *RD, const CXXDeleteExpr *DE)
411
254
      : CFGImplicitDtor(DeleteDtor, RD, DE) {}
412
413
4
  const CXXRecordDecl *getCXXRecordDecl() const {
414
4
    return static_cast<CXXRecordDecl*>(Data1.getPointer());
415
4
  }
416
417
  // Get Delete expression which triggered the destructor call.
418
231
  const CXXDeleteExpr *getDeleteExpr() const {
419
231
    return static_cast<CXXDeleteExpr *>(Data2.getPointer());
420
231
  }
421
422
private:
423
  friend class CFGElement;
424
425
231
  CFGDeleteDtor() = default;
426
427
957
  static bool isKind(const CFGElement &elem) {
428
957
    return elem.getKind() == DeleteDtor;
429
957
  }
430
};
431
432
/// Represents C++ object destructor implicitly generated for base object in
433
/// destructor.
434
class CFGBaseDtor : public CFGImplicitDtor {
435
public:
436
  CFGBaseDtor(const CXXBaseSpecifier *base)
437
355
      : CFGImplicitDtor(BaseDtor, base) {}
438
439
109
  const CXXBaseSpecifier *getBaseSpecifier() const {
440
109
    return static_cast<const CXXBaseSpecifier*>(Data1.getPointer());
441
109
  }
442
443
private:
444
  friend class CFGElement;
445
446
283
  CFGBaseDtor() = default;
447
448
1.75k
  static bool isKind(const CFGElement &E) {
449
1.75k
    return E.getKind() == BaseDtor;
450
1.75k
  }
451
};
452
453
/// Represents C++ object destructor implicitly generated for member object in
454
/// destructor.
455
class CFGMemberDtor : public CFGImplicitDtor {
456
public:
457
  CFGMemberDtor(const FieldDecl *field)
458
521
      : CFGImplicitDtor(MemberDtor, field, nullptr) {}
459
460
49
  const FieldDecl *getFieldDecl() const {
461
49
    return static_cast<const FieldDecl*>(Data1.getPointer());
462
49
  }
463
464
private:
465
  friend class CFGElement;
466
467
49
  CFGMemberDtor() = default;
468
469
360
  static bool isKind(const CFGElement &E) {
470
360
    return E.getKind() == MemberDtor;
471
360
  }
472
};
473
474
/// Represents C++ object destructor implicitly generated at the end of full
475
/// expression for temporary object.
476
class CFGTemporaryDtor : public CFGImplicitDtor {
477
public:
478
  CFGTemporaryDtor(CXXBindTemporaryExpr *expr)
479
6.13k
      : CFGImplicitDtor(TemporaryDtor, expr, nullptr) {}
480
481
3.94k
  const CXXBindTemporaryExpr *getBindTemporaryExpr() const {
482
3.94k
    return static_cast<const CXXBindTemporaryExpr *>(Data1.getPointer());
483
3.94k
  }
484
485
private:
486
  friend class CFGElement;
487
488
1.19k
  CFGTemporaryDtor() = default;
489
490
356
  static bool isKind(const CFGElement &E) {
491
356
    return E.getKind() == TemporaryDtor;
492
356
  }
493
};
494
495
/// Represents CFGBlock terminator statement.
496
///
497
/// TemporaryDtorsBranch bit is set to true if the terminator marks a branch
498
/// in control flow of destructors of temporaries. In this case terminator
499
/// statement is the same statement that branches control flow in evaluation
500
/// of matching full expression.
501
0
class CFGTerminator {
502
  llvm::PointerIntPair<Stmt *, 1> Data;
503
504
public:
505
  CFGTerminator() = default;
506
  CFGTerminator(Stmt *S, bool TemporaryDtorsBranch = false)
507
2.43M
      : Data(S, TemporaryDtorsBranch) {}
508
509
18.5k
  Stmt *getStmt() { return Data.getPointer(); }
510
701k
  const Stmt *getStmt() const { return Data.getPointer(); }
511
512
674
  bool isTemporaryDtorsBranch() const { return Data.getInt(); }
513
514
15.3k
  operator Stmt *() { return getStmt(); }
515
315k
  operator const Stmt *() const { return getStmt(); }
516
517
0
  Stmt *operator->() { return getStmt(); }
518
0
  const Stmt *operator->() const { return getStmt(); }
519
520
0
  Stmt &operator*() { return *getStmt(); }
521
0
  const Stmt &operator*() const { return *getStmt(); }
522
523
36.3k
  explicit operator bool() const { return getStmt(); }
524
};
525
526
/// Represents a single basic block in a source-level CFG.
527
///  It consists of:
528
///
529
///  (1) A set of statements/expressions (which may contain subexpressions).
530
///  (2) A "terminator" statement (not in the set of statements).
531
///  (3) A list of successors and predecessors.
532
///
533
/// Terminator: The terminator represents the type of control-flow that occurs
534
/// at the end of the basic block.  The terminator is a Stmt* referring to an
535
/// AST node that has control-flow: if-statements, breaks, loops, etc.
536
/// If the control-flow is conditional, the condition expression will appear
537
/// within the set of statements in the block (usually the last statement).
538
///
539
/// Predecessors: the order in the set of predecessors is arbitrary.
540
///
541
/// Successors: the order in the set of successors is NOT arbitrary.  We
542
///  currently have the following orderings based on the terminator:
543
///
544
///     Terminator       Successor Ordering
545
///  -----------------------------------------------------
546
///       if            Then Block;  Else Block
547
///     ? operator      LHS expression;  RHS expression
548
///     &&, ||          expression that uses result of && or ||, RHS
549
///
550
/// But note that any of that may be NULL in case of optimized-out edges.
551
class CFGBlock {
552
  class ElementList {
553
    using ImplTy = BumpVector<CFGElement>;
554
555
    ImplTy Impl;
556
557
  public:
558
2.02M
    ElementList(BumpVectorContext &C) : Impl(C, 4) {}
559
560
    using iterator = std::reverse_iterator<ImplTy::iterator>;
561
    using const_iterator = std::reverse_iterator<ImplTy::const_iterator>;
562
    using reverse_iterator = ImplTy::iterator;
563
    using const_reverse_iterator = ImplTy::const_iterator;
564
    using const_reference = ImplTy::const_reference;
565
566
9.08M
    void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e, C); }
567
568
    reverse_iterator insert(reverse_iterator I, size_t Cnt, CFGElement E,
569
116
        BumpVectorContext &C) {
570
116
      return Impl.insert(I, Cnt, E, C);
571
116
    }
572
573
96.4k
    const_reference front() const { return Impl.back(); }
574
54.3k
    const_reference back() const { return Impl.front(); }
575
576
1.60M
    iterator begin() { return Impl.rbegin(); }
577
1.60M
    iterator end() { return Impl.rend(); }
578
776k
    const_iterator begin() const { return Impl.rbegin(); }
579
776k
    const_iterator end() const { return Impl.rend(); }
580
0
    reverse_iterator rbegin() { return Impl.begin(); }
581
0
    reverse_iterator rend() { return Impl.end(); }
582
355k
    const_reverse_iterator rbegin() const { return Impl.begin(); }
583
354k
    const_reverse_iterator rend() const { return Impl.end(); }
584
585
2.46M
    CFGElement operator[](size_t i) const  {
586
2.46M
      assert(i < Impl.size());
587
2.46M
      return Impl[Impl.size() - 1 - i];
588
2.46M
    }
589
590
857k
    size_t size() const { return Impl.size(); }
591
168k
    bool empty() const { return Impl.empty(); }
592
  };
593
594
  /// The set of statements in the basic block.
595
  ElementList Elements;
596
597
  /// An (optional) label that prefixes the executable statements in the block.
598
  /// When this variable is non-NULL, it is either an instance of LabelStmt,
599
  /// SwitchCase or CXXCatchStmt.
600
  Stmt *Label = nullptr;
601
602
  /// The terminator for a basic block that indicates the type of control-flow
603
  /// that occurs between a block and its successors.
604
  CFGTerminator Terminator;
605
606
  /// Some blocks are used to represent the "loop edge" to the start of a loop
607
  /// from within the loop body. This Stmt* will be refer to the loop statement
608
  /// for such blocks (and be null otherwise).
609
  const Stmt *LoopTarget = nullptr;
610
611
  /// A numerical ID assigned to a CFGBlock during construction of the CFG.
612
  unsigned BlockID;
613
614
public:
615
  /// This class represents a potential adjacent block in the CFG.  It encodes
616
  /// whether or not the block is actually reachable, or can be proved to be
617
  /// trivially unreachable.  For some cases it allows one to encode scenarios
618
  /// where a block was substituted because the original (now alternate) block
619
  /// is unreachable.
620
  class AdjacentBlock {
621
    enum Kind {
622
      AB_Normal,
623
      AB_Unreachable,
624
      AB_Alternate
625
    };
626
627
    CFGBlock *ReachableBlock;
628
    llvm::PointerIntPair<CFGBlock *, 2> UnreachableBlock;
629
630
  public:
631
    /// Construct an AdjacentBlock with a possibly unreachable block.
632
    AdjacentBlock(CFGBlock *B, bool IsReachable);
633
634
    /// Construct an AdjacentBlock with a reachable block and an alternate
635
    /// unreachable block.
636
    AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock);
637
638
    /// Get the reachable block, if one exists.
639
8.78M
    CFGBlock *getReachableBlock() const {
640
8.78M
      return ReachableBlock;
641
8.78M
    }
642
643
    /// Get the potentially unreachable block.
644
2.19M
    CFGBlock *getPossiblyUnreachableBlock() const {
645
2.19M
      return UnreachableBlock.getPointer();
646
2.19M
    }
647
648
    /// Provide an implicit conversion to CFGBlock* so that
649
    /// AdjacentBlock can be substituted for CFGBlock*.
650
6.67M
    operator CFGBlock*() const {
651
6.67M
      return getReachableBlock();
652
6.67M
    }
653
654
0
    CFGBlock& operator *() const {
655
0
      return *getReachableBlock();
656
0
    }
657
658
19.2k
    CFGBlock* operator ->() const {
659
19.2k
      return getReachableBlock();
660
19.2k
    }
661
662
1.92M
    bool isReachable() const {
663
1.92M
      Kind K = (Kind) UnreachableBlock.getInt();
664
1.92M
      return K == AB_Normal || 
K == AB_Alternate2.43k
;
665
1.92M
    }
666
  };
667
668
private:
669
  /// Keep track of the predecessor / successor CFG blocks.
670
  using AdjacentBlocks = BumpVector<AdjacentBlock>;
671
  AdjacentBlocks Preds;
672
  AdjacentBlocks Succs;
673
674
  /// This bit is set when the basic block contains a function call
675
  /// or implicit destructor that is attributed as 'noreturn'. In that case,
676
  /// control cannot technically ever proceed past this block. All such blocks
677
  /// will have a single immediate successor: the exit block. This allows them
678
  /// to be easily reached from the exit block and using this bit quickly
679
  /// recognized without scanning the contents of the block.
680
  ///
681
  /// Optimization Note: This bit could be profitably folded with Terminator's
682
  /// storage if the memory usage of CFGBlock becomes an issue.
683
  unsigned HasNoReturnElement : 1;
684
685
  /// The parent CFG that owns this CFGBlock.
686
  CFG *Parent;
687
688
public:
689
  explicit CFGBlock(unsigned blockid, BumpVectorContext &C, CFG *parent)
690
      : Elements(C), Terminator(nullptr), BlockID(blockid), Preds(C, 1),
691
2.02M
        Succs(C, 1), HasNoReturnElement(false), Parent(parent) {}
692
693
  // Statement iterators
694
  using iterator = ElementList::iterator;
695
  using const_iterator = ElementList::const_iterator;
696
  using reverse_iterator = ElementList::reverse_iterator;
697
  using const_reverse_iterator = ElementList::const_reverse_iterator;
698
699
96.4k
  CFGElement                 front()       const { return Elements.front();   }
700
54.3k
  CFGElement                 back()        const { return Elements.back();    }
701
702
1.60M
  iterator                   begin()             { return Elements.begin();   }
703
1.60M
  iterator                   end()               { return Elements.end();     }
704
776k
  const_iterator             begin()       const { return Elements.begin();   }
705
776k
  const_iterator             end()         const { return Elements.end();     }
706
707
0
  reverse_iterator           rbegin()            { return Elements.rbegin();  }
708
0
  reverse_iterator           rend()              { return Elements.rend();    }
709
355k
  const_reverse_iterator     rbegin()      const { return Elements.rbegin();  }
710
354k
  const_reverse_iterator     rend()        const { return Elements.rend();    }
711
712
857k
  unsigned                   size()        const { return Elements.size();    }
713
168k
  bool                       empty()       const { return Elements.empty();   }
714
715
2.46M
  CFGElement operator[](size_t i) const  { return Elements[i]; }
716
717
  // CFG iterators
718
  using pred_iterator = AdjacentBlocks::iterator;
719
  using const_pred_iterator = AdjacentBlocks::const_iterator;
720
  using pred_reverse_iterator = AdjacentBlocks::reverse_iterator;
721
  using const_pred_reverse_iterator = AdjacentBlocks::const_reverse_iterator;
722
  using pred_range = llvm::iterator_range<pred_iterator>;
723
  using pred_const_range = llvm::iterator_range<const_pred_iterator>;
724
725
  using succ_iterator = AdjacentBlocks::iterator;
726
  using const_succ_iterator = AdjacentBlocks::const_iterator;
727
  using succ_reverse_iterator = AdjacentBlocks::reverse_iterator;
728
  using const_succ_reverse_iterator = AdjacentBlocks::const_reverse_iterator;
729
  using succ_range = llvm::iterator_range<succ_iterator>;
730
  using succ_const_range = llvm::iterator_range<const_succ_iterator>;
731
732
0
  pred_iterator                pred_begin()        { return Preds.begin();   }
733
0
  pred_iterator                pred_end()          { return Preds.end();     }
734
1.23M
  const_pred_iterator          pred_begin()  const { return Preds.begin();   }
735
1.23M
  const_pred_iterator          pred_end()    const { return Preds.end();     }
736
737
  pred_reverse_iterator        pred_rbegin()       { return Preds.rbegin();  }
738
  pred_reverse_iterator        pred_rend()         { return Preds.rend();    }
739
  const_pred_reverse_iterator  pred_rbegin() const { return Preds.rbegin();  }
740
  const_pred_reverse_iterator  pred_rend()   const { return Preds.rend();    }
741
742
  pred_range preds() {
743
    return pred_range(pred_begin(), pred_end());
744
  }
745
746
  pred_const_range preds() const {
747
    return pred_const_range(pred_begin(), pred_end());
748
  }
749
750
824k
  succ_iterator                succ_begin()        { return Succs.begin();   }
751
824k
  succ_iterator                succ_end()          { return Succs.end();     }
752
3.02M
  const_succ_iterator          succ_begin()  const { return Succs.begin();   }
753
3.85M
  const_succ_iterator          succ_end()    const { return Succs.end();     }
754
755
0
  succ_reverse_iterator        succ_rbegin()       { return Succs.rbegin();  }
756
0
  succ_reverse_iterator        succ_rend()         { return Succs.rend();    }
757
348
  const_succ_reverse_iterator  succ_rbegin() const { return Succs.rbegin();  }
758
216
  const_succ_reverse_iterator  succ_rend()   const { return Succs.rend();    }
759
760
138
  succ_range succs() {
761
138
    return succ_range(succ_begin(), succ_end());
762
138
  }
763
764
693
  succ_const_range succs() const {
765
693
    return succ_const_range(succ_begin(), succ_end());
766
693
  }
767
768
7.64k
  unsigned                     succ_size()   const { return Succs.size();    }
769
2.96k
  bool                         succ_empty()  const { return Succs.empty();   }
770
771
6.94k
  unsigned                     pred_size()   const { return Preds.size();    }
772
308k
  bool                         pred_empty()  const { return Preds.empty();   }
773
774
775
  class FilterOptions {
776
  public:
777
    unsigned IgnoreNullPredecessors : 1;
778
    unsigned IgnoreDefaultsWithCoveredEnums : 1;
779
780
    FilterOptions()
781
219k
        : IgnoreNullPredecessors(1), IgnoreDefaultsWithCoveredEnums(0) {}
782
  };
783
784
  static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src,
785
       const CFGBlock *Dst);
786
787
  template <typename IMPL, bool IsPred>
788
  class FilteredCFGBlockIterator {
789
  private:
790
    IMPL I, E;
791
    const FilterOptions F;
792
    const CFGBlock *From;
793
794
  public:
795
    explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
796
                                      const CFGBlock *from,
797
                                      const FilterOptions &f)
798
219k
        : I(i), E(e), F(f), From(from) {
799
219k
      while (hasMore() && 
Filter(*I)218k
)
800
1
        ++I;
801
219k
    }
802
803
1.13M
    bool hasMore() const { return I != E; }
804
805
348k
    FilteredCFGBlockIterator &operator++() {
806
352k
      do { ++I; } while (hasMore() && 
Filter(*I)133k
);
807
348k
      return *this;
808
348k
    }
809
810
348k
    const CFGBlock *operator*() const { return *I; }
811
812
  private:
813
352k
    bool Filter(const CFGBlock *To) {
814
352k
      return IsPred ? FilterEdge(F, To, From) : 
FilterEdge(F, From, To)0
;
815
352k
    }
816
  };
817
818
  using filtered_pred_iterator =
819
      FilteredCFGBlockIterator<const_pred_iterator, true>;
820
821
  using filtered_succ_iterator =
822
      FilteredCFGBlockIterator<const_succ_iterator, false>;
823
824
219k
  filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const {
825
219k
    return filtered_pred_iterator(pred_begin(), pred_end(), this, f);
826
219k
  }
827
828
  filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const {
829
    return filtered_succ_iterator(succ_begin(), succ_end(), this, f);
830
  }
831
832
  // Manipulation of block contents
833
834
413k
  void setTerminator(CFGTerminator Term) { Terminator = Term; }
835
72.4k
  void setLabel(Stmt *Statement) { Label = Statement; }
836
92.4k
  void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
837
51.9k
  void setHasNoReturnElement() { HasNoReturnElement = true; }
838
839
9.09k
  CFGTerminator getTerminator() { return Terminator; }
840
705k
  const CFGTerminator getTerminator() const { return Terminator; }
841
842
  Stmt *getTerminatorCondition(bool StripParens = true);
843
844
6.33k
  const Stmt *getTerminatorCondition(bool StripParens = true) const {
845
6.33k
    return const_cast<CFGBlock*>(this)->getTerminatorCondition(StripParens);
846
6.33k
  }
847
848
1.84k
  const Stmt *getLoopTarget() const { return LoopTarget; }
849
850
3.69k
  Stmt *getLabel() { return Label; }
851
5.13k
  const Stmt *getLabel() const { return Label; }
852
853
649k
  bool hasNoReturnElement() const { return HasNoReturnElement; }
854
855
14.0M
  unsigned getBlockID() const { return BlockID; }
856
857
726
  CFG *getParent() const { return Parent; }
858
859
  void dump() const;
860
861
  void dump(const CFG *cfg, const LangOptions &LO, bool ShowColors = false) const;
862
  void print(raw_ostream &OS, const CFG* cfg, const LangOptions &LO,
863
             bool ShowColors) const;
864
  void printTerminator(raw_ostream &OS, const LangOptions &LO) const;
865
0
  void printAsOperand(raw_ostream &OS, bool /*PrintType*/) {
866
0
    OS << "BB#" << getBlockID();
867
0
  }
868
869
  /// Adds a (potentially unreachable) successor block to the current block.
870
  void addSuccessor(AdjacentBlock Succ, BumpVectorContext &C);
871
872
8.96M
  void appendStmt(Stmt *statement, BumpVectorContext &C) {
873
8.96M
    Elements.push_back(CFGStmt(statement), C);
874
8.96M
  }
875
876
  void appendConstructor(CXXConstructExpr *CE, const ConstructionContext *CC,
877
12.7k
                         BumpVectorContext &C) {
878
12.7k
    Elements.push_back(CFGConstructor(CE, CC), C);
879
12.7k
  }
880
881
  void appendCXXRecordTypedCall(Expr *E,
882
                                const ConstructionContext *CC,
883
2.00k
                                BumpVectorContext &C) {
884
2.00k
    Elements.push_back(CFGCXXRecordTypedCall(E, CC), C);
885
2.00k
  }
886
887
  void appendInitializer(CXXCtorInitializer *initializer,
888
68.8k
                        BumpVectorContext &C) {
889
68.8k
    Elements.push_back(CFGInitializer(initializer), C);
890
68.8k
  }
891
892
  void appendNewAllocator(CXXNewExpr *NE,
893
1.62k
                          BumpVectorContext &C) {
894
1.62k
    Elements.push_back(CFGNewAllocator(NE), C);
895
1.62k
  }
896
897
  void appendScopeBegin(const VarDecl *VD, const Stmt *S,
898
92
                        BumpVectorContext &C) {
899
92
    Elements.push_back(CFGScopeBegin(VD, S), C);
900
92
  }
901
902
  void prependScopeBegin(const VarDecl *VD, const Stmt *S,
903
0
                         BumpVectorContext &C) {
904
0
    Elements.insert(Elements.rbegin(), 1, CFGScopeBegin(VD, S), C);
905
0
  }
906
907
154
  void appendScopeEnd(const VarDecl *VD, const Stmt *S, BumpVectorContext &C) {
908
154
    Elements.push_back(CFGScopeEnd(VD, S), C);
909
154
  }
910
911
0
  void prependScopeEnd(const VarDecl *VD, const Stmt *S, BumpVectorContext &C) {
912
0
    Elements.insert(Elements.rbegin(), 1, CFGScopeEnd(VD, S), C);
913
0
  }
914
915
355
  void appendBaseDtor(const CXXBaseSpecifier *BS, BumpVectorContext &C) {
916
355
    Elements.push_back(CFGBaseDtor(BS), C);
917
355
  }
918
919
521
  void appendMemberDtor(FieldDecl *FD, BumpVectorContext &C) {
920
521
    Elements.push_back(CFGMemberDtor(FD), C);
921
521
  }
922
923
6.13k
  void appendTemporaryDtor(CXXBindTemporaryExpr *E, BumpVectorContext &C) {
924
6.13k
    Elements.push_back(CFGTemporaryDtor(E), C);
925
6.13k
  }
926
927
21.6k
  void appendAutomaticObjDtor(VarDecl *VD, Stmt *S, BumpVectorContext &C) {
928
21.6k
    Elements.push_back(CFGAutomaticObjDtor(VD, S), C);
929
21.6k
  }
930
931
162
  void appendLifetimeEnds(VarDecl *VD, Stmt *S, BumpVectorContext &C) {
932
162
    Elements.push_back(CFGLifetimeEnds(VD, S), C);
933
162
  }
934
935
238
  void appendLoopExit(const Stmt *LoopStmt, BumpVectorContext &C) {
936
238
    Elements.push_back(CFGLoopExit(LoopStmt), C);
937
238
  }
938
939
254
  void appendDeleteDtor(CXXRecordDecl *RD, CXXDeleteExpr *DE, BumpVectorContext &C) {
940
254
    Elements.push_back(CFGDeleteDtor(RD, DE), C);
941
254
  }
942
943
  // Destructors must be inserted in reversed order. So insertion is in two
944
  // steps. First we prepare space for some number of elements, then we insert
945
  // the elements beginning at the last position in prepared space.
946
  iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
947
112
      BumpVectorContext &C) {
948
112
    return iterator(Elements.insert(I.base(), Cnt,
949
112
                                    CFGAutomaticObjDtor(nullptr, nullptr), C));
950
112
  }
951
23
  iterator insertAutomaticObjDtor(iterator I, VarDecl *VD, Stmt *S) {
952
23
    *I = CFGAutomaticObjDtor(VD, S);
953
23
    return ++I;
954
23
  }
955
956
  // Scope leaving must be performed in reversed order. So insertion is in two
957
  // steps. First we prepare space for some number of elements, then we insert
958
  // the elements beginning at the last position in prepared space.
959
  iterator beginLifetimeEndsInsert(iterator I, size_t Cnt,
960
2
                                   BumpVectorContext &C) {
961
2
    return iterator(
962
2
        Elements.insert(I.base(), Cnt, CFGLifetimeEnds(nullptr, nullptr), C));
963
2
  }
964
2
  iterator insertLifetimeEnds(iterator I, VarDecl *VD, Stmt *S) {
965
2
    *I = CFGLifetimeEnds(VD, S);
966
2
    return ++I;
967
2
  }
968
969
  // Scope leaving must be performed in reversed order. So insertion is in two
970
  // steps. First we prepare space for some number of elements, then we insert
971
  // the elements beginning at the last position in prepared space.
972
2
  iterator beginScopeEndInsert(iterator I, size_t Cnt, BumpVectorContext &C) {
973
2
    return iterator(
974
2
        Elements.insert(I.base(), Cnt, CFGScopeEnd(nullptr, nullptr), C));
975
2
  }
976
2
  iterator insertScopeEnd(iterator I, VarDecl *VD, Stmt *S) {
977
2
    *I = CFGScopeEnd(VD, S);
978
2
    return ++I;
979
2
  }
980
981
};
982
983
/// CFGCallback defines methods that should be called when a logical
984
/// operator error is found when building the CFG.
985
class CFGCallback {
986
public:
987
42
  CFGCallback() = default;
988
42
  virtual ~CFGCallback() = default;
989
990
0
  virtual void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) {}
991
  virtual void compareBitwiseEquality(const BinaryOperator *B,
992
0
                                      bool isAlwaysTrue) {}
993
};
994
995
/// Represents a source-level, intra-procedural CFG that represents the
996
///  control-flow of a Stmt.  The Stmt can represent an entire function body,
997
///  or a single expression.  A CFG will always contain one empty block that
998
///  represents the Exit point of the CFG.  A CFG will also contain a designated
999
///  Entry block.  The CFG solely represents control-flow; it consists of
1000
///  CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
1001
///  was constructed from.
1002
class CFG {
1003
public:
1004
  //===--------------------------------------------------------------------===//
1005
  // CFG Construction & Manipulation.
1006
  //===--------------------------------------------------------------------===//
1007
1008
  class BuildOptions {
1009
    std::bitset<Stmt::lastStmtConstant> alwaysAddMask;
1010
1011
  public:
1012
    using ForcedBlkExprs = llvm::DenseMap<const Stmt *, const CFGBlock *>;
1013
1014
    ForcedBlkExprs **forcedBlkExprs = nullptr;
1015
    CFGCallback *Observer = nullptr;
1016
    bool PruneTriviallyFalseEdges = true;
1017
    bool AddEHEdges = false;
1018
    bool AddInitializers = false;
1019
    bool AddImplicitDtors = false;
1020
    bool AddLifetime = false;
1021
    bool AddLoopExit = false;
1022
    bool AddTemporaryDtors = false;
1023
    bool AddScopes = false;
1024
    bool AddStaticInitBranches = false;
1025
    bool AddCXXNewAllocator = false;
1026
    bool AddCXXDefaultInitExprInCtors = false;
1027
    bool AddRichCXXConstructors = false;
1028
    bool MarkElidedCXXConstructors = false;
1029
1030
430k
    BuildOptions() = default;
1031
1032
18.5M
    bool alwaysAdd(const Stmt *stmt) const {
1033
18.5M
      return alwaysAddMask[stmt->getStmtClass()];
1034
18.5M
    }
1035
1036
3.42M
    BuildOptions &setAlwaysAdd(Stmt::StmtClass stmtClass, bool val = true) {
1037
3.42M
      alwaysAddMask[stmtClass] = val;
1038
3.42M
      return *this;
1039
3.42M
    }
1040
1041
3.18k
    BuildOptions &setAllAlwaysAdd() {
1042
3.18k
      alwaysAddMask.set();
1043
3.18k
      return *this;
1044
3.18k
    }
1045
  };
1046
1047
  /// Builds a CFG from an AST.
1048
  static std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *AST, ASTContext *C,
1049
                                       const BuildOptions &BO);
1050
1051
  /// Create a new block in the CFG. The CFG owns the block; the caller should
1052
  /// not directly free it.
1053
  CFGBlock *createBlock();
1054
1055
  /// Set the entry block of the CFG. This is typically used only during CFG
1056
  /// construction. Most CFG clients expect that the entry block has no
1057
  /// predecessors and contains no statements.
1058
403k
  void setEntry(CFGBlock *B) { Entry = B; }
1059
1060
  /// Set the block used for indirect goto jumps. This is typically used only
1061
  /// during CFG construction.
1062
15
  void setIndirectGotoBlock(CFGBlock *B) { IndirectGotoBlock = B; }
1063
1064
  //===--------------------------------------------------------------------===//
1065
  // Block Iterators
1066
  //===--------------------------------------------------------------------===//
1067
1068
  using CFGBlockListTy = BumpVector<CFGBlock *>;
1069
  using iterator = CFGBlockListTy::iterator;
1070
  using const_iterator = CFGBlockListTy::const_iterator;
1071
  using reverse_iterator = std::reverse_iterator<iterator>;
1072
  using const_reverse_iterator = std::reverse_iterator<const_iterator>;
1073
1074
  CFGBlock &                front()                { return *Blocks.front(); }
1075
2.42M
  CFGBlock &                back()                 { return *Blocks.back(); }
1076
1077
2.09M
  iterator                  begin()                { return Blocks.begin(); }
1078
2.09M
  iterator                  end()                  { return Blocks.end(); }
1079
88.3k
  const_iterator            begin()       const    { return Blocks.begin(); }
1080
88.3k
  const_iterator            end()         const    { return Blocks.end(); }
1081
1082
  iterator nodes_begin() { return iterator(Blocks.begin()); }
1083
  iterator nodes_end() { return iterator(Blocks.end()); }
1084
  const_iterator nodes_begin() const { return const_iterator(Blocks.begin()); }
1085
  const_iterator nodes_end() const { return const_iterator(Blocks.end()); }
1086
1087
67
  reverse_iterator          rbegin()               { return Blocks.rbegin(); }
1088
67
  reverse_iterator          rend()                 { return Blocks.rend(); }
1089
0
  const_reverse_iterator    rbegin()      const    { return Blocks.rbegin(); }
1090
0
  const_reverse_iterator    rend()        const    { return Blocks.rend(); }
1091
1092
545k
  CFGBlock &                getEntry()             { return *Entry; }
1093
426k
  const CFGBlock &          getEntry()    const    { return *Entry; }
1094
1.40M
  CFGBlock &                getExit()              { return *Exit; }
1095
6.57k
  const CFGBlock &          getExit()     const    { return *Exit; }
1096
1097
403k
  CFGBlock *       getIndirectGotoBlock() { return IndirectGotoBlock; }
1098
1.65k
  const CFGBlock * getIndirectGotoBlock() const { return IndirectGotoBlock; }
1099
1100
  using try_block_iterator = std::vector<const CFGBlock *>::const_iterator;
1101
1102
105
  try_block_iterator try_blocks_begin() const {
1103
105
    return TryDispatchBlocks.begin();
1104
105
  }
1105
1106
105
  try_block_iterator try_blocks_end() const {
1107
105
    return TryDispatchBlocks.end();
1108
105
  }
1109
1110
238
  void addTryDispatchBlock(const CFGBlock *block) {
1111
238
    TryDispatchBlocks.push_back(block);
1112
238
  }
1113
1114
  /// Records a synthetic DeclStmt and the DeclStmt it was constructed from.
1115
  ///
1116
  /// The CFG uses synthetic DeclStmts when a single AST DeclStmt contains
1117
  /// multiple decls.
1118
  void addSyntheticDeclStmt(const DeclStmt *Synthetic,
1119
11.3k
                            const DeclStmt *Source) {
1120
11.3k
    assert(Synthetic->isSingleDecl() && "Can handle single declarations only");
1121
11.3k
    assert(Synthetic != Source && "Don't include original DeclStmts in map");
1122
11.3k
    assert(!SyntheticDeclStmts.count(Synthetic) && "Already in map");
1123
11.3k
    SyntheticDeclStmts[Synthetic] = Source;
1124
11.3k
  }
1125
1126
  using synthetic_stmt_iterator =
1127
      llvm::DenseMap<const DeclStmt *, const DeclStmt *>::const_iterator;
1128
  using synthetic_stmt_range = llvm::iterator_range<synthetic_stmt_iterator>;
1129
1130
  /// Iterates over synthetic DeclStmts in the CFG.
1131
  ///
1132
  /// Each element is a (synthetic statement, source statement) pair.
1133
  ///
1134
  /// \sa addSyntheticDeclStmt
1135
17.3k
  synthetic_stmt_iterator synthetic_stmt_begin() const {
1136
17.3k
    return SyntheticDeclStmts.begin();
1137
17.3k
  }
1138
1139
  /// \sa synthetic_stmt_begin
1140
17.3k
  synthetic_stmt_iterator synthetic_stmt_end() const {
1141
17.3k
    return SyntheticDeclStmts.end();
1142
17.3k
  }
1143
1144
  /// \sa synthetic_stmt_begin
1145
  synthetic_stmt_range synthetic_stmts() const {
1146
    return synthetic_stmt_range(synthetic_stmt_begin(), synthetic_stmt_end());
1147
  }
1148
1149
  //===--------------------------------------------------------------------===//
1150
  // Member templates useful for various batch operations over CFGs.
1151
  //===--------------------------------------------------------------------===//
1152
1153
  template <typename CALLBACK>
1154
86.5k
  void VisitBlockStmts(CALLBACK& O) const {
1155
955k
    for (const_iterator I = begin(), E = end(); I != E; 
++I868k
)
1156
868k
      for (CFGBlock::const_iterator BI = (*I)->begin(), BE = (*I)->end();
1157
6.71M
           BI != BE; 
++BI5.84M
) {
1158
5.84M
        if (Optional<CFGStmt> stmt = BI->getAs<CFGStmt>())
1159
5.82M
          O(const_cast<Stmt*>(stmt->getStmt()));
1160
5.84M
      }
1161
86.5k
  }
DeadStoresChecker.cpp:void clang::CFG::VisitBlockStmts<(anonymous namespace)::FindEscaped>((anonymous namespace)::FindEscaped&) const
Line
Count
Source
1154
446
  void VisitBlockStmts(CALLBACK& O) const {
1155
2.66k
    for (const_iterator I = begin(), E = end(); I != E; 
++I2.21k
)
1156
2.21k
      for (CFGBlock::const_iterator BI = (*I)->begin(), BE = (*I)->end();
1157
10.1k
           BI != BE; 
++BI7.89k
) {
1158
7.89k
        if (Optional<CFGStmt> stmt = BI->getAs<CFGStmt>())
1159
7.87k
          O(const_cast<Stmt*>(stmt->getStmt()));
1160
7.89k
      }
1161
446
  }
UninitializedValues.cpp:void clang::CFG::VisitBlockStmts<(anonymous namespace)::ClassifyRefs>((anonymous namespace)::ClassifyRefs&) const
Line
Count
Source
1154
86.1k
  void VisitBlockStmts(CALLBACK& O) const {
1155
952k
    for (const_iterator I = begin(), E = end(); I != E; 
++I866k
)
1156
866k
      for (CFGBlock::const_iterator BI = (*I)->begin(), BE = (*I)->end();
1157
6.70M
           BI != BE; 
++BI5.83M
) {
1158
5.83M
        if (Optional<CFGStmt> stmt = BI->getAs<CFGStmt>())
1159
5.81M
          O(const_cast<Stmt*>(stmt->getStmt()));
1160
5.83M
      }
1161
86.1k
  }
1162
1163
  //===--------------------------------------------------------------------===//
1164
  // CFG Introspection.
1165
  //===--------------------------------------------------------------------===//
1166
1167
  /// Returns the total number of BlockIDs allocated (which start at 0).
1168
1.65M
  unsigned getNumBlockIDs() const { return NumBlockIDs; }
1169
1170
  /// Return the total number of CFGBlocks within the CFG This is simply a
1171
  /// renaming of the getNumBlockIDs(). This is necessary because the dominator
1172
  /// implementation needs such an interface.
1173
25.9k
  unsigned size() const { return NumBlockIDs; }
1174
1175
  //===--------------------------------------------------------------------===//
1176
  // CFG Debugging: Pretty-Printing and Visualization.
1177
  //===--------------------------------------------------------------------===//
1178
1179
  void viewCFG(const LangOptions &LO) const;
1180
  void print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const;
1181
  void dump(const LangOptions &LO, bool ShowColors) const;
1182
1183
  //===--------------------------------------------------------------------===//
1184
  // Internal: constructors and data.
1185
  //===--------------------------------------------------------------------===//
1186
1187
403k
  CFG() : Blocks(BlkBVC, 10) {}
1188
1189
2.03M
  llvm::BumpPtrAllocator& getAllocator() {
1190
2.03M
    return BlkBVC.getAllocator();
1191
2.03M
  }
1192
1193
11.9M
  BumpVectorContext &getBumpVectorContext() {
1194
11.9M
    return BlkBVC;
1195
11.9M
  }
1196
1197
private:
1198
  CFGBlock *Entry = nullptr;
1199
  CFGBlock *Exit = nullptr;
1200
1201
  // Special block to contain collective dispatch for indirect gotos
1202
  CFGBlock* IndirectGotoBlock = nullptr;
1203
1204
  unsigned  NumBlockIDs = 0;
1205
1206
  BumpVectorContext BlkBVC;
1207
1208
  CFGBlockListTy Blocks;
1209
1210
  /// C++ 'try' statements are modeled with an indirect dispatch block.
1211
  /// This is the collection of such blocks present in the CFG.
1212
  std::vector<const CFGBlock *> TryDispatchBlocks;
1213
1214
  /// Collects DeclStmts synthesized for this CFG and maps each one back to its
1215
  /// source DeclStmt.
1216
  llvm::DenseMap<const DeclStmt *, const DeclStmt *> SyntheticDeclStmts;
1217
};
1218
1219
} // namespace clang
1220
1221
//===----------------------------------------------------------------------===//
1222
// GraphTraits specializations for CFG basic block graphs (source-level CFGs)
1223
//===----------------------------------------------------------------------===//
1224
1225
namespace llvm {
1226
1227
/// Implement simplify_type for CFGTerminator, so that we can dyn_cast from
1228
/// CFGTerminator to a specific Stmt class.
1229
template <> struct simplify_type< ::clang::CFGTerminator> {
1230
  using SimpleType = ::clang::Stmt *;
1231
1232
1.85k
  static SimpleType getSimplifiedValue(::clang::CFGTerminator Val) {
1233
1.85k
    return Val.getStmt();
1234
1.85k
  }
1235
};
1236
1237
// Traits for: CFGBlock
1238
1239
template <> struct GraphTraits< ::clang::CFGBlock *> {
1240
  using NodeRef = ::clang::CFGBlock *;
1241
  using ChildIteratorType = ::clang::CFGBlock::succ_iterator;
1242
1243
  static NodeRef getEntryNode(::clang::CFGBlock *BB) { return BB; }
1244
52
  static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
1245
52
  static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
1246
};
1247
1248
template <> struct GraphTraits< const ::clang::CFGBlock *> {
1249
  using NodeRef = const ::clang::CFGBlock *;
1250
  using ChildIteratorType = ::clang::CFGBlock::const_succ_iterator;
1251
1252
  static NodeRef getEntryNode(const clang::CFGBlock *BB) { return BB; }
1253
832k
  static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
1254
1.85M
  static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
1255
};
1256
1257
template <> struct GraphTraits<Inverse< ::clang::CFGBlock *>> {
1258
  using NodeRef = ::clang::CFGBlock *;
1259
  using ChildIteratorType = ::clang::CFGBlock::const_pred_iterator;
1260
1261
  static NodeRef getEntryNode(Inverse<::clang::CFGBlock *> G) {
1262
    return G.Graph;
1263
  }
1264
1265
  static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
1266
  static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
1267
};
1268
1269
template <> struct GraphTraits<Inverse<const ::clang::CFGBlock *>> {
1270
  using NodeRef = const ::clang::CFGBlock *;
1271
  using ChildIteratorType = ::clang::CFGBlock::const_pred_iterator;
1272
1273
  static NodeRef getEntryNode(Inverse<const ::clang::CFGBlock *> G) {
1274
    return G.Graph;
1275
  }
1276
1277
  static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
1278
  static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
1279
};
1280
1281
// Traits for: CFG
1282
1283
template <> struct GraphTraits< ::clang::CFG* >
1284
    : public GraphTraits< ::clang::CFGBlock *>  {
1285
  using nodes_iterator = ::clang::CFG::iterator;
1286
1287
5
  static NodeRef getEntryNode(::clang::CFG *F) { return &F->getEntry(); }
1288
  static nodes_iterator nodes_begin(::clang::CFG* F) { return F->nodes_begin();}
1289
  static nodes_iterator   nodes_end(::clang::CFG* F) { return F->nodes_end(); }
1290
  static unsigned              size(::clang::CFG* F) { return F->size(); }
1291
};
1292
1293
template <> struct GraphTraits<const ::clang::CFG* >
1294
    : public GraphTraits<const ::clang::CFGBlock *>  {
1295
  using nodes_iterator = ::clang::CFG::const_iterator;
1296
1297
106k
  static NodeRef getEntryNode(const ::clang::CFG *F) { return &F->getEntry(); }
1298
1299
  static nodes_iterator nodes_begin( const ::clang::CFG* F) {
1300
    return F->nodes_begin();
1301
  }
1302
1303
  static nodes_iterator nodes_end( const ::clang::CFG* F) {
1304
    return F->nodes_end();
1305
  }
1306
1307
  static unsigned size(const ::clang::CFG* F) {
1308
    return F->size();
1309
  }
1310
};
1311
1312
template <> struct GraphTraits<Inverse< ::clang::CFG *>>
1313
  : public GraphTraits<Inverse< ::clang::CFGBlock *>> {
1314
  using nodes_iterator = ::clang::CFG::iterator;
1315
1316
  static NodeRef getEntryNode(::clang::CFG *F) { return &F->getExit(); }
1317
  static nodes_iterator nodes_begin( ::clang::CFG* F) {return F->nodes_begin();}
1318
  static nodes_iterator nodes_end( ::clang::CFG* F) { return F->nodes_end(); }
1319
};
1320
1321
template <> struct GraphTraits<Inverse<const ::clang::CFG *>>
1322
  : public GraphTraits<Inverse<const ::clang::CFGBlock *>> {
1323
  using nodes_iterator = ::clang::CFG::const_iterator;
1324
1325
  static NodeRef getEntryNode(const ::clang::CFG *F) { return &F->getExit(); }
1326
1327
  static nodes_iterator nodes_begin(const ::clang::CFG* F) {
1328
    return F->nodes_begin();
1329
  }
1330
1331
  static nodes_iterator nodes_end(const ::clang::CFG* F) {
1332
    return F->nodes_end();
1333
  }
1334
};
1335
1336
} // namespace llvm
1337
1338
#endif // LLVM_CLANG_ANALYSIS_CFG_H