Coverage Report

Created: 2020-09-15 12:33

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/include/clang/Sema/ScopeInfo.h
Line
Count
Source (jump to first uncovered line)
1
//===- ScopeInfo.h - Information about a semantic context -------*- 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 FunctionScopeInfo and its subclasses, which contain
10
// information about a single function, block, lambda, or method body.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#ifndef LLVM_CLANG_SEMA_SCOPEINFO_H
15
#define LLVM_CLANG_SEMA_SCOPEINFO_H
16
17
#include "clang/AST/Expr.h"
18
#include "clang/AST/ExprCXX.h"
19
#include "clang/AST/Type.h"
20
#include "clang/Basic/CapturedStmt.h"
21
#include "clang/Basic/LLVM.h"
22
#include "clang/Basic/PartialDiagnostic.h"
23
#include "clang/Basic/SourceLocation.h"
24
#include "clang/Sema/CleanupInfo.h"
25
#include "clang/Sema/DeclSpec.h"
26
#include "llvm/ADT/DenseMap.h"
27
#include "llvm/ADT/DenseMapInfo.h"
28
#include "llvm/ADT/MapVector.h"
29
#include "llvm/ADT/PointerIntPair.h"
30
#include "llvm/ADT/SmallPtrSet.h"
31
#include "llvm/ADT/SmallSet.h"
32
#include "llvm/ADT/SmallVector.h"
33
#include "llvm/ADT/StringRef.h"
34
#include "llvm/ADT/StringSwitch.h"
35
#include "llvm/ADT/TinyPtrVector.h"
36
#include "llvm/Support/Casting.h"
37
#include "llvm/Support/ErrorHandling.h"
38
#include <algorithm>
39
#include <cassert>
40
#include <utility>
41
42
namespace clang {
43
44
class BlockDecl;
45
class CapturedDecl;
46
class CXXMethodDecl;
47
class CXXRecordDecl;
48
class ImplicitParamDecl;
49
class NamedDecl;
50
class ObjCIvarRefExpr;
51
class ObjCMessageExpr;
52
class ObjCPropertyDecl;
53
class ObjCPropertyRefExpr;
54
class ParmVarDecl;
55
class RecordDecl;
56
class ReturnStmt;
57
class Scope;
58
class Stmt;
59
class SwitchStmt;
60
class TemplateParameterList;
61
class TemplateTypeParmDecl;
62
class VarDecl;
63
64
namespace sema {
65
66
/// Contains information about the compound statement currently being
67
/// parsed.
68
class CompoundScopeInfo {
69
public:
70
  /// Whether this compound stamement contains `for' or `while' loops
71
  /// with empty bodies.
72
  bool HasEmptyLoopBodies = false;
73
74
  /// Whether this compound statement corresponds to a GNU statement
75
  /// expression.
76
  bool IsStmtExpr;
77
78
4.09M
  CompoundScopeInfo(bool IsStmtExpr) : IsStmtExpr(IsStmtExpr) {}
79
80
24.8k
  void setHasEmptyLoopBodies() {
81
24.8k
    HasEmptyLoopBodies = true;
82
24.8k
  }
83
};
84
85
class PossiblyUnreachableDiag {
86
public:
87
  PartialDiagnostic PD;
88
  SourceLocation Loc;
89
  llvm::TinyPtrVector<const Stmt*> Stmts;
90
91
  PossiblyUnreachableDiag(const PartialDiagnostic &PD, SourceLocation Loc,
92
                          ArrayRef<const Stmt *> Stmts)
93
75.8k
      : PD(PD), Loc(Loc), Stmts(Stmts) {}
94
};
95
96
/// Retains information about a function, method, or block that is
97
/// currently being parsed.
98
class FunctionScopeInfo {
99
protected:
100
  enum ScopeKind {
101
    SK_Function,
102
    SK_Block,
103
    SK_Lambda,
104
    SK_CapturedRegion
105
  };
106
107
public:
108
  /// What kind of scope we are describing.
109
  ScopeKind Kind : 3;
110
111
  /// Whether this function contains a VLA, \@try, try, C++
112
  /// initializer, or anything else that can't be jumped past.
113
  bool HasBranchProtectedScope : 1;
114
115
  /// Whether this function contains any switches or direct gotos.
116
  bool HasBranchIntoScope : 1;
117
118
  /// Whether this function contains any indirect gotos.
119
  bool HasIndirectGoto : 1;
120
121
  /// Whether a statement was dropped because it was invalid.
122
  bool HasDroppedStmt : 1;
123
124
  /// True if current scope is for OpenMP declare reduction combiner.
125
  bool HasOMPDeclareReductionCombiner : 1;
126
127
  /// Whether there is a fallthrough statement in this function.
128
  bool HasFallthroughStmt : 1;
129
130
  /// Whether we make reference to a declaration that could be
131
  /// unavailable.
132
  bool HasPotentialAvailabilityViolations : 1;
133
134
  /// A flag that is set when parsing a method that must call super's
135
  /// implementation, such as \c -dealloc, \c -finalize, or any method marked
136
  /// with \c __attribute__((objc_requires_super)).
137
  bool ObjCShouldCallSuper : 1;
138
139
  /// True when this is a method marked as a designated initializer.
140
  bool ObjCIsDesignatedInit : 1;
141
142
  /// This starts true for a method marked as designated initializer and will
143
  /// be set to false if there is an invocation to a designated initializer of
144
  /// the super class.
145
  bool ObjCWarnForNoDesignatedInitChain : 1;
146
147
  /// True when this is an initializer method not marked as a designated
148
  /// initializer within a class that has at least one initializer marked as a
149
  /// designated initializer.
150
  bool ObjCIsSecondaryInit : 1;
151
152
  /// This starts true for a secondary initializer method and will be set to
153
  /// false if there is an invocation of an initializer on 'self'.
154
  bool ObjCWarnForNoInitDelegation : 1;
155
156
  /// True only when this function has not already built, or attempted
157
  /// to build, the initial and final coroutine suspend points
158
  bool NeedsCoroutineSuspends : 1;
159
160
  /// An enumeration represeting the kind of the first coroutine statement
161
  /// in the function. One of co_return, co_await, or co_yield.
162
  unsigned char FirstCoroutineStmtKind : 2;
163
164
  /// First coroutine statement in the current function.
165
  /// (ex co_return, co_await, co_yield)
166
  SourceLocation FirstCoroutineStmtLoc;
167
168
  /// First 'return' statement in the current function.
169
  SourceLocation FirstReturnLoc;
170
171
  /// First C++ 'try' statement in the current function.
172
  SourceLocation FirstCXXTryLoc;
173
174
  /// First SEH '__try' statement in the current function.
175
  SourceLocation FirstSEHTryLoc;
176
177
private:
178
  /// Used to determine if errors occurred in this function or block.
179
  DiagnosticErrorTrap ErrorTrap;
180
181
public:
182
  /// A SwitchStmt, along with a flag indicating if its list of case statements
183
  /// is incomplete (because we dropped an invalid one while parsing).
184
  using SwitchInfo = llvm::PointerIntPair<SwitchStmt*, 1, bool>;
185
186
  /// SwitchStack - This is the current set of active switch statements in the
187
  /// block.
188
  SmallVector<SwitchInfo, 8> SwitchStack;
189
190
  /// The list of return statements that occur within the function or
191
  /// block, if there is any chance of applying the named return value
192
  /// optimization, or if we need to infer a return type.
193
  SmallVector<ReturnStmt*, 4> Returns;
194
195
  /// The promise object for this coroutine, if any.
196
  VarDecl *CoroutinePromise = nullptr;
197
198
  /// A mapping between the coroutine function parameters that were moved
199
  /// to the coroutine frame, and their move statements.
200
  llvm::SmallMapVector<ParmVarDecl *, Stmt *, 4> CoroutineParameterMoves;
201
202
  /// The initial and final coroutine suspend points.
203
  std::pair<Stmt *, Stmt *> CoroutineSuspends;
204
205
  /// The stack of currently active compound stamement scopes in the
206
  /// function.
207
  SmallVector<CompoundScopeInfo, 4> CompoundScopes;
208
209
  /// The set of blocks that are introduced in this function.
210
  llvm::SmallPtrSet<const BlockDecl *, 1> Blocks;
211
212
  /// The set of __block variables that are introduced in this function.
213
  llvm::TinyPtrVector<VarDecl *> ByrefBlockVars;
214
215
  /// A list of PartialDiagnostics created but delayed within the
216
  /// current function scope.  These diagnostics are vetted for reachability
217
  /// prior to being emitted.
218
  SmallVector<PossiblyUnreachableDiag, 4> PossiblyUnreachableDiags;
219
220
  /// A list of parameters which have the nonnull attribute and are
221
  /// modified in the function.
222
  llvm::SmallPtrSet<const ParmVarDecl *, 8> ModifiedNonNullParams;
223
224
public:
225
  /// Represents a simple identification of a weak object.
226
  ///
227
  /// Part of the implementation of -Wrepeated-use-of-weak.
228
  ///
229
  /// This is used to determine if two weak accesses refer to the same object.
230
  /// Here are some examples of how various accesses are "profiled":
231
  ///
232
  /// Access Expression |     "Base" Decl     |          "Property" Decl
233
  /// :---------------: | :-----------------: | :------------------------------:
234
  /// self.property     | self (VarDecl)      | property (ObjCPropertyDecl)
235
  /// self.implicitProp | self (VarDecl)      | -implicitProp (ObjCMethodDecl)
236
  /// self->ivar.prop   | ivar (ObjCIvarDecl) | prop (ObjCPropertyDecl)
237
  /// cxxObj.obj.prop   | obj (FieldDecl)     | prop (ObjCPropertyDecl)
238
  /// [self foo].prop   | 0 (unknown)         | prop (ObjCPropertyDecl)
239
  /// self.prop1.prop2  | prop1 (ObjCPropertyDecl)    | prop2 (ObjCPropertyDecl)
240
  /// MyClass.prop      | MyClass (ObjCInterfaceDecl) | -prop (ObjCMethodDecl)
241
  /// MyClass.foo.prop  | +foo (ObjCMethodDecl)       | -prop (ObjCPropertyDecl)
242
  /// weakVar           | 0 (known)           | weakVar (VarDecl)
243
  /// self->weakIvar    | self (VarDecl)      | weakIvar (ObjCIvarDecl)
244
  ///
245
  /// Objects are identified with only two Decls to make it reasonably fast to
246
  /// compare them.
247
  class WeakObjectProfileTy {
248
    /// The base object decl, as described in the class documentation.
249
    ///
250
    /// The extra flag is "true" if the Base and Property are enough to uniquely
251
    /// identify the object in memory.
252
    ///
253
    /// \sa isExactProfile()
254
    using BaseInfoTy = llvm::PointerIntPair<const NamedDecl *, 1, bool>;
255
    BaseInfoTy Base;
256
257
    /// The "property" decl, as described in the class documentation.
258
    ///
259
    /// Note that this may not actually be an ObjCPropertyDecl, e.g. in the
260
    /// case of "implicit" properties (regular methods accessed via dot syntax).
261
    const NamedDecl *Property = nullptr;
262
263
    /// Used to find the proper base profile for a given base expression.
264
    static BaseInfoTy getBaseInfo(const Expr *BaseE);
265
266
    inline WeakObjectProfileTy();
267
    static inline WeakObjectProfileTy getSentinel();
268
269
  public:
270
    WeakObjectProfileTy(const ObjCPropertyRefExpr *RE);
271
    WeakObjectProfileTy(const Expr *Base, const ObjCPropertyDecl *Property);
272
    WeakObjectProfileTy(const DeclRefExpr *RE);
273
    WeakObjectProfileTy(const ObjCIvarRefExpr *RE);
274
275
18
    const NamedDecl *getBase() const { return Base.getPointer(); }
276
84
    const NamedDecl *getProperty() const { return Property; }
277
278
    /// Returns true if the object base specifies a known object in memory,
279
    /// rather than, say, an instance variable or property of another object.
280
    ///
281
    /// Note that this ignores the effects of aliasing; that is, \c foo.bar is
282
    /// considered an exact profile if \c foo is a local variable, even if
283
    /// another variable \c foo2 refers to the same object as \c foo.
284
    ///
285
    /// For increased precision, accesses with base variables that are
286
    /// properties or ivars of 'self' (e.g. self.prop1.prop2) are considered to
287
    /// be exact, though this is not true for arbitrary variables
288
    /// (foo.prop1.prop2).
289
102
    bool isExactProfile() const {
290
102
      return Base.getInt();
291
102
    }
292
293
5.98M
    bool operator==(const WeakObjectProfileTy &Other) const {
294
5.98M
      return Base == Other.Base && 
Property == Other.Property5.98M
;
295
5.98M
    }
296
297
    // For use in DenseMap.
298
    // We can't specialize the usual llvm::DenseMapInfo at the end of the file
299
    // because by that point the DenseMap in FunctionScopeInfo has already been
300
    // instantiated.
301
    class DenseMapInfo {
302
    public:
303
1.53M
      static inline WeakObjectProfileTy getEmptyKey() {
304
1.53M
        return WeakObjectProfileTy();
305
1.53M
      }
306
307
741k
      static inline WeakObjectProfileTy getTombstoneKey() {
308
741k
        return WeakObjectProfileTy::getSentinel();
309
741k
      }
310
311
346
      static unsigned getHashValue(const WeakObjectProfileTy &Val) {
312
346
        using Pair = std::pair<BaseInfoTy, const NamedDecl *>;
313
346
314
346
        return llvm::DenseMapInfo<Pair>::getHashValue(Pair(Val.Base,
315
346
                                                           Val.Property));
316
346
      }
317
318
      static bool isEqual(const WeakObjectProfileTy &LHS,
319
5.98M
                          const WeakObjectProfileTy &RHS) {
320
5.98M
        return LHS == RHS;
321
5.98M
      }
322
    };
323
  };
324
325
  /// Represents a single use of a weak object.
326
  ///
327
  /// Stores both the expression and whether the access is potentially unsafe
328
  /// (i.e. it could potentially be warned about).
329
  ///
330
  /// Part of the implementation of -Wrepeated-use-of-weak.
331
  class WeakUseTy {
332
    llvm::PointerIntPair<const Expr *, 1, bool> Rep;
333
334
  public:
335
326
    WeakUseTy(const Expr *Use, bool IsRead) : Rep(Use, IsRead) {}
336
337
487
    const Expr *getUseExpr() const { return Rep.getPointer(); }
338
271
    bool isUnsafe() const { return Rep.getInt(); }
339
44
    void markSafe() { Rep.setInt(false); }
340
341
50
    bool operator==(const WeakUseTy &Other) const {
342
50
      return Rep == Other.Rep;
343
50
    }
344
  };
345
346
  /// Used to collect uses of a particular weak object in a function body.
347
  ///
348
  /// Part of the implementation of -Wrepeated-use-of-weak.
349
  using WeakUseVector = SmallVector<WeakUseTy, 4>;
350
351
  /// Used to collect all uses of weak objects in a function body.
352
  ///
353
  /// Part of the implementation of -Wrepeated-use-of-weak.
354
  using WeakObjectUseMap =
355
      llvm::SmallDenseMap<WeakObjectProfileTy, WeakUseVector, 8,
356
                          WeakObjectProfileTy::DenseMapInfo>;
357
358
private:
359
  /// Used to collect all uses of weak objects in this function body.
360
  ///
361
  /// Part of the implementation of -Wrepeated-use-of-weak.
362
  WeakObjectUseMap WeakObjectUses;
363
364
protected:
365
7.32k
  FunctionScopeInfo(const FunctionScopeInfo&) = default;
366
367
public:
368
  FunctionScopeInfo(DiagnosticsEngine &Diag)
369
      : Kind(SK_Function), HasBranchProtectedScope(false),
370
        HasBranchIntoScope(false), HasIndirectGoto(false),
371
        HasDroppedStmt(false), HasOMPDeclareReductionCombiner(false),
372
        HasFallthroughStmt(false), HasPotentialAvailabilityViolations(false),
373
        ObjCShouldCallSuper(false), ObjCIsDesignatedInit(false),
374
        ObjCWarnForNoDesignatedInitChain(false), ObjCIsSecondaryInit(false),
375
        ObjCWarnForNoInitDelegation(false), NeedsCoroutineSuspends(true),
376
729k
        ErrorTrap(Diag) {}
377
378
  virtual ~FunctionScopeInfo();
379
380
  /// Determine whether an unrecoverable error has occurred within this
381
  /// function. Note that this may return false even if the function body is
382
  /// invalid, because the errors may be suppressed if they're caused by prior
383
  /// invalid declarations.
384
  ///
385
  /// FIXME: Migrate the caller of this to use containsErrors() instead once
386
  /// it's ready.
387
17.0k
  bool hasUnrecoverableErrorOccurred() const {
388
17.0k
    return ErrorTrap.hasUnrecoverableErrorOccurred();
389
17.0k
  }
390
391
  /// Record that a weak object was accessed.
392
  ///
393
  /// Part of the implementation of -Wrepeated-use-of-weak.
394
  template <typename ExprT>
395
  inline void recordUseOfWeak(const ExprT *E, bool IsRead = true);
396
397
  void recordUseOfWeak(const ObjCMessageExpr *Msg,
398
                       const ObjCPropertyDecl *Prop);
399
400
  /// Record that a given expression is a "safe" access of a weak object (e.g.
401
  /// assigning it to a strong variable.)
402
  ///
403
  /// Part of the implementation of -Wrepeated-use-of-weak.
404
  void markSafeWeakUse(const Expr *E);
405
406
112
  const WeakObjectUseMap &getWeakObjectUses() const {
407
112
    return WeakObjectUses;
408
112
  }
409
410
13.4k
  void setHasBranchIntoScope() {
411
13.4k
    HasBranchIntoScope = true;
412
13.4k
  }
413
414
1.50M
  void setHasBranchProtectedScope() {
415
1.50M
    HasBranchProtectedScope = true;
416
1.50M
  }
417
418
127
  void setHasIndirectGoto() {
419
127
    HasIndirectGoto = true;
420
127
  }
421
422
0
  void setHasDroppedStmt() {
423
0
    HasDroppedStmt = true;
424
0
  }
425
426
752
  void setHasOMPDeclareReductionCombiner() {
427
752
    HasOMPDeclareReductionCombiner = true;
428
752
  }
429
430
957
  void setHasFallthroughStmt() {
431
957
    HasFallthroughStmt = true;
432
957
  }
433
434
10.8k
  void setHasCXXTry(SourceLocation TryLoc) {
435
10.8k
    setHasBranchProtectedScope();
436
10.8k
    FirstCXXTryLoc = TryLoc;
437
10.8k
  }
438
439
267
  void setHasSEHTry(SourceLocation TryLoc) {
440
267
    setHasBranchProtectedScope();
441
267
    FirstSEHTryLoc = TryLoc;
442
267
  }
443
444
3.30M
  bool NeedsScopeChecking() const {
445
3.30M
    return !HasDroppedStmt &&
446
3.30M
        (HasIndirectGoto ||
447
3.30M
          (HasBranchProtectedScope && 
HasBranchIntoScope220k
));
448
3.30M
  }
449
450
  // Add a block introduced in this function.
451
2.62k
  void addBlock(const BlockDecl *BD) {
452
2.62k
    Blocks.insert(BD);
453
2.62k
  }
454
455
  // Add a __block variable introduced in this function.
456
135
  void addByrefBlockVar(VarDecl *VD) {
457
135
    ByrefBlockVars.push_back(VD);
458
135
  }
459
460
399k
  bool isCoroutine() const { return !FirstCoroutineStmtLoc.isInvalid(); }
461
462
281
  void setFirstCoroutineStmt(SourceLocation Loc, StringRef Keyword) {
463
281
    assert(FirstCoroutineStmtLoc.isInvalid() &&
464
281
                   "first coroutine statement location already set");
465
281
    FirstCoroutineStmtLoc = Loc;
466
281
    FirstCoroutineStmtKind = llvm::StringSwitch<unsigned char>(Keyword)
467
281
            .Case("co_return", 0)
468
281
            .Case("co_await", 1)
469
281
            .Case("co_yield", 2);
470
281
  }
471
472
19
  StringRef getFirstCoroutineStmtKeyword() const {
473
19
    assert(FirstCoroutineStmtLoc.isValid()
474
19
                   && "no coroutine statement available");
475
19
    switch (FirstCoroutineStmtKind) {
476
10
    case 0: return "co_return";
477
4
    case 1: return "co_await";
478
5
    case 2: return "co_yield";
479
0
    default:
480
0
      llvm_unreachable("FirstCoroutineStmtKind has an invalid value");
481
0
    };
482
0
  }
483
484
269
  void setNeedsCoroutineSuspends(bool value = true) {
485
269
    assert((!value || CoroutineSuspends.first == nullptr) &&
486
269
            "we already have valid suspend points");
487
269
    NeedsCoroutineSuspends = value;
488
269
  }
489
490
260
  bool hasInvalidCoroutineSuspends() const {
491
260
    return !NeedsCoroutineSuspends && CoroutineSuspends.first == nullptr;
492
260
  }
493
494
258
  void setCoroutineSuspends(Stmt *Initial, Stmt *Final) {
495
258
    assert(Initial && Final && "suspend points cannot be null");
496
258
    assert(CoroutineSuspends.first == nullptr && "suspend points already set");
497
258
    NeedsCoroutineSuspends = false;
498
258
    CoroutineSuspends.first = Initial;
499
258
    CoroutineSuspends.second = Final;
500
258
  }
501
502
  /// Clear out the information in this function scope, making it
503
  /// suitable for reuse.
504
  void Clear();
505
506
3.93M
  bool isPlainFunction() const { return Kind == SK_Function; }
507
};
508
509
class Capture {
510
  // There are three categories of capture: capturing 'this', capturing
511
  // local variables, and C++1y initialized captures (which can have an
512
  // arbitrary initializer, and don't really capture in the traditional
513
  // sense at all).
514
  //
515
  // There are three ways to capture a local variable:
516
  //  - capture by copy in the C++11 sense,
517
  //  - capture by reference in the C++11 sense, and
518
  //  - __block capture.
519
  // Lambdas explicitly specify capture by copy or capture by reference.
520
  // For blocks, __block capture applies to variables with that annotation,
521
  // variables of reference type are captured by reference, and other
522
  // variables are captured by copy.
523
  enum CaptureKind {
524
    Cap_ByCopy, Cap_ByRef, Cap_Block, Cap_VLA
525
  };
526
527
  union {
528
    /// If Kind == Cap_VLA, the captured type.
529
    const VariableArrayType *CapturedVLA;
530
531
    /// Otherwise, the captured variable (if any).
532
    VarDecl *CapturedVar;
533
  };
534
535
  /// The source location at which the first capture occurred.
536
  SourceLocation Loc;
537
538
  /// The location of the ellipsis that expands a parameter pack.
539
  SourceLocation EllipsisLoc;
540
541
  /// The type as it was captured, which is the type of the non-static data
542
  /// member that would hold the capture.
543
  QualType CaptureType;
544
545
  /// The CaptureKind of this capture.
546
  unsigned Kind : 2;
547
548
  /// Whether this is a nested capture (a capture of an enclosing capturing
549
  /// scope's capture).
550
  unsigned Nested : 1;
551
552
  /// Whether this is a capture of '*this'.
553
  unsigned CapturesThis : 1;
554
555
  /// Whether an explicit capture has been odr-used in the body of the
556
  /// lambda.
557
  unsigned ODRUsed : 1;
558
559
  /// Whether an explicit capture has been non-odr-used in the body of
560
  /// the lambda.
561
  unsigned NonODRUsed : 1;
562
563
  /// Whether the capture is invalid (a capture was required but the entity is
564
  /// non-capturable).
565
  unsigned Invalid : 1;
566
567
public:
568
  Capture(VarDecl *Var, bool Block, bool ByRef, bool IsNested,
569
          SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType,
570
          bool Invalid)
571
      : CapturedVar(Var), Loc(Loc), EllipsisLoc(EllipsisLoc),
572
        CaptureType(CaptureType),
573
        Kind(Block ? Cap_Block : ByRef ? Cap_ByRef : Cap_ByCopy),
574
        Nested(IsNested), CapturesThis(false), ODRUsed(false),
575
398k
        NonODRUsed(false), Invalid(Invalid) {}
576
577
  enum IsThisCapture { ThisCapture };
578
  Capture(IsThisCapture, bool IsNested, SourceLocation Loc,
579
          QualType CaptureType, const bool ByCopy, bool Invalid)
580
      : Loc(Loc), CaptureType(CaptureType),
581
        Kind(ByCopy ? Cap_ByCopy : Cap_ByRef), Nested(IsNested),
582
        CapturesThis(true), ODRUsed(false), NonODRUsed(false),
583
11.3k
        Invalid(Invalid) {}
584
585
  enum IsVLACapture { VLACapture };
586
  Capture(IsVLACapture, const VariableArrayType *VLA, bool IsNested,
587
          SourceLocation Loc, QualType CaptureType)
588
      : CapturedVLA(VLA), Loc(Loc), CaptureType(CaptureType), Kind(Cap_VLA),
589
        Nested(IsNested), CapturesThis(false), ODRUsed(false),
590
8.81k
        NonODRUsed(false), Invalid(false) {}
591
592
3.64M
  bool isThisCapture() const { return CapturesThis; }
593
2.87M
  bool isVariableCapture() const {
594
2.87M
    return !isThisCapture() && 
!isVLATypeCapture()2.85M
;
595
2.87M
  }
596
597
968k
  bool isCopyCapture() const { return Kind == Cap_ByCopy; }
598
363k
  bool isReferenceCapture() const { return Kind == Cap_ByRef; }
599
8.15k
  bool isBlockCapture() const { return Kind == Cap_Block; }
600
4.12M
  bool isVLATypeCapture() const { return Kind == Cap_VLA; }
601
602
382k
  bool isNested() const { return Nested; }
603
604
390k
  bool isInvalid() const { return Invalid; }
605
606
  /// Determine whether this capture is an init-capture.
607
  bool isInitCapture() const;
608
609
1.33k
  bool isODRUsed() const { return ODRUsed; }
610
558
  bool isNonODRUsed() const { return NonODRUsed; }
611
959k
  void markUsed(bool IsODRUse) {
612
959k
    if (IsODRUse)
613
345k
      ODRUsed = true;
614
613k
    else
615
613k
      NonODRUsed = true;
616
959k
  }
617
618
1.60M
  VarDecl *getVariable() const {
619
1.60M
    assert(isVariableCapture());
620
1.60M
    return CapturedVar;
621
1.60M
  }
622
623
39.7k
  const VariableArrayType *getCapturedVLAType() const {
624
39.7k
    assert(isVLATypeCapture());
625
39.7k
    return CapturedVLA;
626
39.7k
  }
627
628
  /// Retrieve the location at which this variable was captured.
629
1.16M
  SourceLocation getLocation() const { return Loc; }
630
631
  /// Retrieve the source location of the ellipsis, whose presence
632
  /// indicates that the capture is a pack expansion.
633
4.37k
  SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
634
635
  /// Retrieve the capture type for this capture, which is effectively
636
  /// the type of the non-static data member in the lambda/block structure
637
  /// that would store this capture.
638
1.34M
  QualType getCaptureType() const { return CaptureType; }
639
};
640
641
class CapturingScopeInfo : public FunctionScopeInfo {
642
protected:
643
7.32k
  CapturingScopeInfo(const CapturingScopeInfo&) = default;
644
645
public:
646
  enum ImplicitCaptureStyle {
647
    ImpCap_None, ImpCap_LambdaByval, ImpCap_LambdaByref, ImpCap_Block,
648
    ImpCap_CapturedRegion
649
  };
650
651
  ImplicitCaptureStyle ImpCaptureStyle;
652
653
  CapturingScopeInfo(DiagnosticsEngine &Diag, ImplicitCaptureStyle Style)
654
562k
      : FunctionScopeInfo(Diag), ImpCaptureStyle(Style) {}
655
656
  /// CaptureMap - A map of captured variables to (index+1) into Captures.
657
  llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
658
659
  /// CXXThisCaptureIndex - The (index+1) of the capture of 'this';
660
  /// zero if 'this' is not captured.
661
  unsigned CXXThisCaptureIndex = 0;
662
663
  /// Captures - The captures.
664
  SmallVector<Capture, 4> Captures;
665
666
  /// - Whether the target type of return statements in this context
667
  /// is deduced (e.g. a lambda or block with omitted return type).
668
  bool HasImplicitReturnType = false;
669
670
  /// ReturnType - The target type of return statements in this context,
671
  /// or null if unknown.
672
  QualType ReturnType;
673
674
  void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested,
675
                  SourceLocation Loc, SourceLocation EllipsisLoc,
676
398k
                  QualType CaptureType, bool Invalid) {
677
398k
    Captures.push_back(Capture(Var, isBlock, isByref, isNested, Loc,
678
398k
                               EllipsisLoc, CaptureType, Invalid));
679
398k
    CaptureMap[Var] = Captures.size();
680
398k
  }
681
682
  void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType,
683
8.81k
                         QualType CaptureType) {
684
8.81k
    Captures.push_back(Capture(Capture::VLACapture, VLAType,
685
8.81k
                               /*FIXME: IsNested*/ false, Loc, CaptureType));
686
8.81k
  }
687
688
  void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType,
689
                      bool ByCopy);
690
691
  /// Determine whether the C++ 'this' is captured.
692
6.74k
  bool isCXXThisCaptured() const { return CXXThisCaptureIndex != 0; }
693
694
  /// Retrieve the capture of C++ 'this', if it has been captured.
695
2.37k
  Capture &getCXXThisCapture() {
696
2.37k
    assert(isCXXThisCaptured() && "this has not been captured");
697
2.37k
    return Captures[CXXThisCaptureIndex - 1];
698
2.37k
  }
699
700
  /// Determine whether the given variable has been captured.
701
2.84M
  bool isCaptured(VarDecl *Var) const {
702
2.84M
    return CaptureMap.count(Var);
703
2.84M
  }
704
705
  /// Determine whether the given variable-array type has been captured.
706
  bool isVLATypeCaptured(const VariableArrayType *VAT) const;
707
708
  /// Retrieve the capture of the given variable, if it has been
709
  /// captured already.
710
2.84M
  Capture &getCapture(VarDecl *Var) {
711
2.84M
    assert(isCaptured(Var) && "Variable has not been captured");
712
2.84M
    return Captures[CaptureMap[Var] - 1];
713
2.84M
  }
714
715
0
  const Capture &getCapture(VarDecl *Var) const {
716
0
    llvm::DenseMap<VarDecl*, unsigned>::const_iterator Known
717
0
      = CaptureMap.find(Var);
718
0
    assert(Known != CaptureMap.end() && "Variable has not been captured");
719
0
    return Captures[Known->second - 1];
720
0
  }
721
722
22.3M
  static bool classof(const FunctionScopeInfo *FSI) {
723
22.3M
    return FSI->Kind == SK_Block || 
FSI->Kind == SK_Lambda22.3M
724
22.2M
                                 || FSI->Kind == SK_CapturedRegion;
725
22.3M
  }
726
};
727
728
/// Retains information about a block that is currently being parsed.
729
class BlockScopeInfo final : public CapturingScopeInfo {
730
public:
731
  BlockDecl *TheDecl;
732
733
  /// TheScope - This is the scope for the block itself, which contains
734
  /// arguments etc.
735
  Scope *TheScope;
736
737
  /// BlockType - The function type of the block, if one was given.
738
  /// Its return type may be BuiltinType::Dependent.
739
  QualType FunctionType;
740
741
  BlockScopeInfo(DiagnosticsEngine &Diag, Scope *BlockScope, BlockDecl *Block)
742
      : CapturingScopeInfo(Diag, ImpCap_Block), TheDecl(Block),
743
2.88k
        TheScope(BlockScope) {
744
2.88k
    Kind = SK_Block;
745
2.88k
  }
746
747
  ~BlockScopeInfo() override;
748
749
2.91M
  static bool classof(const FunctionScopeInfo *FSI) {
750
2.91M
    return FSI->Kind == SK_Block;
751
2.91M
  }
752
};
753
754
/// Retains information about a captured region.
755
class CapturedRegionScopeInfo final : public CapturingScopeInfo {
756
public:
757
  /// The CapturedDecl for this statement.
758
  CapturedDecl *TheCapturedDecl;
759
760
  /// The captured record type.
761
  RecordDecl *TheRecordDecl;
762
763
  /// This is the enclosing scope of the captured region.
764
  Scope *TheScope;
765
766
  /// The implicit parameter for the captured variables.
767
  ImplicitParamDecl *ContextParam;
768
769
  /// The kind of captured region.
770
  unsigned short CapRegionKind;
771
772
  unsigned short OpenMPLevel;
773
  unsigned short OpenMPCaptureLevel;
774
775
  CapturedRegionScopeInfo(DiagnosticsEngine &Diag, Scope *S, CapturedDecl *CD,
776
                          RecordDecl *RD, ImplicitParamDecl *Context,
777
                          CapturedRegionKind K, unsigned OpenMPLevel,
778
                          unsigned OpenMPCaptureLevel)
779
      : CapturingScopeInfo(Diag, ImpCap_CapturedRegion),
780
        TheCapturedDecl(CD), TheRecordDecl(RD), TheScope(S),
781
        ContextParam(Context), CapRegionKind(K), OpenMPLevel(OpenMPLevel),
782
550k
        OpenMPCaptureLevel(OpenMPCaptureLevel) {
783
550k
    Kind = SK_CapturedRegion;
784
550k
  }
785
786
  ~CapturedRegionScopeInfo() override;
787
788
  /// A descriptive name for the kind of captured region this is.
789
239
  StringRef getRegionName() const {
790
239
    switch (CapRegionKind) {
791
1
    case CR_Default:
792
1
      return "default captured statement";
793
0
    case CR_ObjCAtFinally:
794
0
      return "Objective-C @finally statement";
795
238
    case CR_OpenMP:
796
238
      return "OpenMP region";
797
0
    }
798
0
    llvm_unreachable("Invalid captured region kind!");
799
0
  }
800
801
8.58M
  static bool classof(const FunctionScopeInfo *FSI) {
802
8.58M
    return FSI->Kind == SK_CapturedRegion;
803
8.58M
  }
804
};
805
806
class LambdaScopeInfo final :
807
    public CapturingScopeInfo, public InventedTemplateParameterInfo {
808
public:
809
  /// The class that describes the lambda.
810
  CXXRecordDecl *Lambda = nullptr;
811
812
  /// The lambda's compiler-generated \c operator().
813
  CXXMethodDecl *CallOperator = nullptr;
814
815
  /// Source range covering the lambda introducer [...].
816
  SourceRange IntroducerRange;
817
818
  /// Source location of the '&' or '=' specifying the default capture
819
  /// type, if any.
820
  SourceLocation CaptureDefaultLoc;
821
822
  /// The number of captures in the \c Captures list that are
823
  /// explicit captures.
824
  unsigned NumExplicitCaptures = 0;
825
826
  /// Whether this is a mutable lambda.
827
  bool Mutable = false;
828
829
  /// Whether the (empty) parameter list is explicit.
830
  bool ExplicitParams = false;
831
832
  /// Whether any of the capture expressions requires cleanups.
833
  CleanupInfo Cleanup;
834
835
  /// Whether the lambda contains an unexpanded parameter pack.
836
  bool ContainsUnexpandedParameterPack = false;
837
838
  /// Packs introduced by this lambda, if any.
839
  SmallVector<NamedDecl*, 4> LocalPacks;
840
841
  /// Source range covering the explicit template parameter list (if it exists).
842
  SourceRange ExplicitTemplateParamsRange;
843
844
  /// If this is a generic lambda, and the template parameter
845
  /// list has been created (from the TemplateParams) then store
846
  /// a reference to it (cache it to avoid reconstructing it).
847
  TemplateParameterList *GLTemplateParameterList = nullptr;
848
849
  /// Contains all variable-referring-expressions (i.e. DeclRefExprs
850
  ///  or MemberExprs) that refer to local variables in a generic lambda
851
  ///  or a lambda in a potentially-evaluated-if-used context.
852
  ///
853
  ///  Potentially capturable variables of a nested lambda that might need
854
  ///   to be captured by the lambda are housed here.
855
  ///  This is specifically useful for generic lambdas or
856
  ///  lambdas within a potentially evaluated-if-used context.
857
  ///  If an enclosing variable is named in an expression of a lambda nested
858
  ///  within a generic lambda, we don't always know know whether the variable
859
  ///  will truly be odr-used (i.e. need to be captured) by that nested lambda,
860
  ///  until its instantiation. But we still need to capture it in the
861
  ///  enclosing lambda if all intervening lambdas can capture the variable.
862
  llvm::SmallVector<Expr*, 4> PotentiallyCapturingExprs;
863
864
  /// Contains all variable-referring-expressions that refer
865
  ///  to local variables that are usable as constant expressions and
866
  ///  do not involve an odr-use (they may still need to be captured
867
  ///  if the enclosing full-expression is instantiation dependent).
868
  llvm::SmallSet<Expr *, 8> NonODRUsedCapturingExprs;
869
870
  /// A map of explicit capture indices to their introducer source ranges.
871
  llvm::DenseMap<unsigned, SourceRange> ExplicitCaptureRanges;
872
873
  /// Contains all of the variables defined in this lambda that shadow variables
874
  /// that were defined in parent contexts. Used to avoid warnings when the
875
  /// shadowed variables are uncaptured by this lambda.
876
  struct ShadowedOuterDecl {
877
    const VarDecl *VD;
878
    const VarDecl *ShadowedDecl;
879
  };
880
  llvm::SmallVector<ShadowedOuterDecl, 4> ShadowingDecls;
881
882
  SourceLocation PotentialThisCaptureLocation;
883
884
  LambdaScopeInfo(DiagnosticsEngine &Diag)
885
8.85k
      : CapturingScopeInfo(Diag, ImpCap_None) {
886
8.85k
    Kind = SK_Lambda;
887
8.85k
  }
888
889
  /// Note when all explicit captures have been added.
890
7.52k
  void finishedExplicitCaptures() {
891
7.52k
    NumExplicitCaptures = Captures.size();
892
7.52k
  }
893
894
16.1M
  static bool classof(const FunctionScopeInfo *FSI) {
895
16.1M
    return FSI->Kind == SK_Lambda;
896
16.1M
  }
897
898
  /// Is this scope known to be for a generic lambda? (This will be false until
899
  /// we parse a template parameter list or the first 'auto'-typed parameter).
900
0
  bool isGenericLambda() const {
901
0
    return !TemplateParams.empty() || GLTemplateParameterList;
902
0
  }
903
904
  /// Add a variable that might potentially be captured by the
905
  /// lambda and therefore the enclosing lambdas.
906
  ///
907
  /// This is also used by enclosing lambda's to speculatively capture
908
  /// variables that nested lambda's - depending on their enclosing
909
  /// specialization - might need to capture.
910
  /// Consider:
911
  /// void f(int, int); <-- don't capture
912
  /// void f(const int&, double); <-- capture
913
  /// void foo() {
914
  ///   const int x = 10;
915
  ///   auto L = [=](auto a) { // capture 'x'
916
  ///      return [=](auto b) {
917
  ///        f(x, a);  // we may or may not need to capture 'x'
918
  ///      };
919
  ///   };
920
  /// }
921
571
  void addPotentialCapture(Expr *VarExpr) {
922
571
    assert(isa<DeclRefExpr>(VarExpr) || isa<MemberExpr>(VarExpr) ||
923
571
           isa<FunctionParmPackExpr>(VarExpr));
924
571
    PotentiallyCapturingExprs.push_back(VarExpr);
925
571
  }
926
927
38
  void addPotentialThisCapture(SourceLocation Loc) {
928
38
    PotentialThisCaptureLocation = Loc;
929
38
  }
930
931
508
  bool hasPotentialThisCapture() const {
932
508
    return PotentialThisCaptureLocation.isValid();
933
508
  }
934
935
  /// Mark a variable's reference in a lambda as non-odr using.
936
  ///
937
  /// For generic lambdas, if a variable is named in a potentially evaluated
938
  /// expression, where the enclosing full expression is dependent then we
939
  /// must capture the variable (given a default capture).
940
  /// This is accomplished by recording all references to variables
941
  /// (DeclRefExprs or MemberExprs) within said nested lambda in its array of
942
  /// PotentialCaptures. All such variables have to be captured by that lambda,
943
  /// except for as described below.
944
  /// If that variable is usable as a constant expression and is named in a
945
  /// manner that does not involve its odr-use (e.g. undergoes
946
  /// lvalue-to-rvalue conversion, or discarded) record that it is so. Upon the
947
  /// act of analyzing the enclosing full expression (ActOnFinishFullExpr)
948
  /// if we can determine that the full expression is not instantiation-
949
  /// dependent, then we can entirely avoid its capture.
950
  ///
951
  ///   const int n = 0;
952
  ///   [&] (auto x) {
953
  ///     (void)+n + x;
954
  ///   };
955
  /// Interestingly, this strategy would involve a capture of n, even though
956
  /// it's obviously not odr-used here, because the full-expression is
957
  /// instantiation-dependent.  It could be useful to avoid capturing such
958
  /// variables, even when they are referred to in an instantiation-dependent
959
  /// expression, if we can unambiguously determine that they shall never be
960
  /// odr-used.  This would involve removal of the variable-referring-expression
961
  /// from the array of PotentialCaptures during the lvalue-to-rvalue
962
  /// conversions.  But per the working draft N3797, (post-chicago 2013) we must
963
  /// capture such variables.
964
  /// Before anyone is tempted to implement a strategy for not-capturing 'n',
965
  /// consider the insightful warning in:
966
  ///    /cfe-commits/Week-of-Mon-20131104/092596.html
967
  /// "The problem is that the set of captures for a lambda is part of the ABI
968
  ///  (since lambda layout can be made visible through inline functions and the
969
  ///  like), and there are no guarantees as to which cases we'll manage to build
970
  ///  an lvalue-to-rvalue conversion in, when parsing a template -- some
971
  ///  seemingly harmless change elsewhere in Sema could cause us to start or stop
972
  ///  building such a node. So we need a rule that anyone can implement and get
973
  ///  exactly the same result".
974
359
  void markVariableExprAsNonODRUsed(Expr *CapturingVarExpr) {
975
359
    assert(isa<DeclRefExpr>(CapturingVarExpr) ||
976
359
           isa<MemberExpr>(CapturingVarExpr) ||
977
359
           isa<FunctionParmPackExpr>(CapturingVarExpr));
978
359
    NonODRUsedCapturingExprs.insert(CapturingVarExpr);
979
359
  }
980
583
  bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const {
981
583
    assert(isa<DeclRefExpr>(CapturingVarExpr) ||
982
583
           isa<MemberExpr>(CapturingVarExpr) ||
983
583
           isa<FunctionParmPackExpr>(CapturingVarExpr));
984
583
    return NonODRUsedCapturingExprs.count(CapturingVarExpr);
985
583
  }
986
0
  void removePotentialCapture(Expr *E) {
987
0
    PotentiallyCapturingExprs.erase(
988
0
        std::remove(PotentiallyCapturingExprs.begin(),
989
0
            PotentiallyCapturingExprs.end(), E),
990
0
        PotentiallyCapturingExprs.end());
991
0
  }
992
508
  void clearPotentialCaptures() {
993
508
    PotentiallyCapturingExprs.clear();
994
508
    PotentialThisCaptureLocation = SourceLocation();
995
508
  }
996
26.0k
  unsigned getNumPotentialVariableCaptures() const {
997
26.0k
    return PotentiallyCapturingExprs.size();
998
26.0k
  }
999
1000
26.0k
  bool hasPotentialCaptures() const {
1001
26.0k
    return getNumPotentialVariableCaptures() ||
1002
25.6k
                                  PotentialThisCaptureLocation.isValid();
1003
26.0k
  }
1004
1005
  void visitPotentialCaptures(
1006
      llvm::function_ref<void(VarDecl *, Expr *)> Callback) const;
1007
};
1008
1009
FunctionScopeInfo::WeakObjectProfileTy::WeakObjectProfileTy()
1010
2.27M
    : Base(nullptr, false) {}
1011
1012
FunctionScopeInfo::WeakObjectProfileTy
1013
741k
FunctionScopeInfo::WeakObjectProfileTy::getSentinel() {
1014
741k
  FunctionScopeInfo::WeakObjectProfileTy Result;
1015
741k
  Result.Base.setInt(true);
1016
741k
  return Result;
1017
741k
}
1018
1019
template <typename ExprT>
1020
256
void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
1021
256
  assert(E);
1022
256
  WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
1023
256
  Uses.push_back(WeakUseTy(E, IsRead));
1024
256
}
void clang::sema::FunctionScopeInfo::recordUseOfWeak<clang::DeclRefExpr>(clang::DeclRefExpr const*, bool)
Line
Count
Source
1020
26
void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
1021
26
  assert(E);
1022
26
  WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
1023
26
  Uses.push_back(WeakUseTy(E, IsRead));
1024
26
}
void clang::sema::FunctionScopeInfo::recordUseOfWeak<clang::ObjCIvarRefExpr>(clang::ObjCIvarRefExpr const*, bool)
Line
Count
Source
1020
24
void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
1021
24
  assert(E);
1022
24
  WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
1023
24
  Uses.push_back(WeakUseTy(E, IsRead));
1024
24
}
void clang::sema::FunctionScopeInfo::recordUseOfWeak<clang::ObjCPropertyRefExpr>(clang::ObjCPropertyRefExpr const*, bool)
Line
Count
Source
1020
206
void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
1021
206
  assert(E);
1022
206
  WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
1023
206
  Uses.push_back(WeakUseTy(E, IsRead));
1024
206
}
1025
1026
inline void CapturingScopeInfo::addThisCapture(bool isNested,
1027
                                               SourceLocation Loc,
1028
                                               QualType CaptureType,
1029
11.3k
                                               bool ByCopy) {
1030
11.3k
  Captures.push_back(Capture(Capture::ThisCapture, isNested, Loc, CaptureType,
1031
11.3k
                             ByCopy, /*Invalid*/ false));
1032
11.3k
  CXXThisCaptureIndex = Captures.size();
1033
11.3k
}
1034
1035
} // namespace sema
1036
1037
} // namespace clang
1038
1039
#endif // LLVM_CLANG_SEMA_SCOPEINFO_H