Coverage Report

Created: 2021-06-15 06:44

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