Coverage Report

Created: 2018-07-21 08:31

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