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