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