Coverage Report

Created: 2017-10-03 07:32

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