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