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