1 //===--- ScopeInfo.h - Information about a semantic context -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines FunctionScopeInfo and its subclasses, which contain
11 // information about a single function, block, lambda, or method body.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_SEMA_SCOPEINFO_H
16 #define LLVM_CLANG_SEMA_SCOPEINFO_H
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/Type.h"
20 #include "clang/Basic/CapturedStmt.h"
21 #include "clang/Basic/PartialDiagnostic.h"
22 #include "clang/Sema/CleanupInfo.h"
23 #include "clang/Sema/Ownership.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
36 class ObjCPropertyDecl;
38 class ImplicitParamDecl;
43 class TemplateTypeParmDecl;
44 class TemplateParameterList;
46 class ObjCIvarRefExpr;
47 class ObjCPropertyRefExpr;
48 class ObjCMessageExpr;
52 /// \brief Contains information about the compound statement currently being
54 class CompoundScopeInfo {
57 : HasEmptyLoopBodies(false) { }
59 /// \brief Whether this compound stamement contains `for' or `while' loops
60 /// with empty bodies.
61 bool HasEmptyLoopBodies;
63 void setHasEmptyLoopBodies() {
64 HasEmptyLoopBodies = true;
68 class PossiblyUnreachableDiag {
74 PossiblyUnreachableDiag(const PartialDiagnostic &PD, SourceLocation Loc,
76 : PD(PD), Loc(Loc), stmt(stmt) {}
79 /// \brief Retains information about a function, method, or block that is
80 /// currently being parsed.
81 class FunctionScopeInfo {
91 /// \brief What kind of scope we are describing.
95 /// \brief Whether this function contains a VLA, \@try, try, C++
96 /// initializer, or anything else that can't be jumped past.
97 bool HasBranchProtectedScope : 1;
99 /// \brief Whether this function contains any switches or direct gotos.
100 bool HasBranchIntoScope : 1;
102 /// \brief Whether this function contains any indirect gotos.
103 bool HasIndirectGoto : 1;
105 /// \brief Whether a statement was dropped because it was invalid.
106 bool HasDroppedStmt : 1;
108 /// \brief True if current scope is for OpenMP declare reduction combiner.
109 bool HasOMPDeclareReductionCombiner : 1;
111 /// \brief Whether there is a fallthrough statement in this function.
112 bool HasFallthroughStmt : 1;
114 /// \brief Whether we make reference to a declaration that could be
116 bool HasPotentialAvailabilityViolations : 1;
118 /// A flag that is set when parsing a method that must call super's
119 /// implementation, such as \c -dealloc, \c -finalize, or any method marked
120 /// with \c __attribute__((objc_requires_super)).
121 bool ObjCShouldCallSuper : 1;
123 /// True when this is a method marked as a designated initializer.
124 bool ObjCIsDesignatedInit : 1;
125 /// This starts true for a method marked as designated initializer and will
126 /// be set to false if there is an invocation to a designated initializer of
128 bool ObjCWarnForNoDesignatedInitChain : 1;
130 /// True when this is an initializer method not marked as a designated
131 /// initializer within a class that has at least one initializer marked as a
132 /// designated initializer.
133 bool ObjCIsSecondaryInit : 1;
134 /// This starts true for a secondary initializer method and will be set to
135 /// false if there is an invocation of an initializer on 'self'.
136 bool ObjCWarnForNoInitDelegation : 1;
138 /// First 'return' statement in the current function.
139 SourceLocation FirstReturnLoc;
141 /// First C++ 'try' statement in the current function.
142 SourceLocation FirstCXXTryLoc;
144 /// First SEH '__try' statement in the current function.
145 SourceLocation FirstSEHTryLoc;
147 /// \brief Used to determine if errors occurred in this function or block.
148 DiagnosticErrorTrap ErrorTrap;
150 /// SwitchStack - This is the current set of active switch statements in the
152 SmallVector<SwitchStmt*, 8> SwitchStack;
154 /// \brief The list of return statements that occur within the function or
155 /// block, if there is any chance of applying the named return value
156 /// optimization, or if we need to infer a return type.
157 SmallVector<ReturnStmt*, 4> Returns;
159 /// \brief The promise object for this coroutine, if any.
160 VarDecl *CoroutinePromise;
162 /// \brief The list of coroutine control flow constructs (co_await, co_yield,
163 /// co_return) that occur within the function or block. Empty if and only if
164 /// this function or block is not (yet known to be) a coroutine.
165 SmallVector<Stmt*, 4> CoroutineStmts;
167 /// \brief The stack of currently active compound stamement scopes in the
169 SmallVector<CompoundScopeInfo, 4> CompoundScopes;
171 /// \brief A list of PartialDiagnostics created but delayed within the
172 /// current function scope. These diagnostics are vetted for reachability
173 /// prior to being emitted.
174 SmallVector<PossiblyUnreachableDiag, 4> PossiblyUnreachableDiags;
176 /// \brief A list of parameters which have the nonnull attribute and are
177 /// modified in the function.
178 llvm::SmallPtrSet<const ParmVarDecl*, 8> ModifiedNonNullParams;
181 /// Represents a simple identification of a weak object.
183 /// Part of the implementation of -Wrepeated-use-of-weak.
185 /// This is used to determine if two weak accesses refer to the same object.
186 /// Here are some examples of how various accesses are "profiled":
188 /// Access Expression | "Base" Decl | "Property" Decl
189 /// :---------------: | :-----------------: | :------------------------------:
190 /// self.property | self (VarDecl) | property (ObjCPropertyDecl)
191 /// self.implicitProp | self (VarDecl) | -implicitProp (ObjCMethodDecl)
192 /// self->ivar.prop | ivar (ObjCIvarDecl) | prop (ObjCPropertyDecl)
193 /// cxxObj.obj.prop | obj (FieldDecl) | prop (ObjCPropertyDecl)
194 /// [self foo].prop | 0 (unknown) | prop (ObjCPropertyDecl)
195 /// self.prop1.prop2 | prop1 (ObjCPropertyDecl) | prop2 (ObjCPropertyDecl)
196 /// MyClass.prop | MyClass (ObjCInterfaceDecl) | -prop (ObjCMethodDecl)
197 /// MyClass.foo.prop | +foo (ObjCMethodDecl) | -prop (ObjCPropertyDecl)
198 /// weakVar | 0 (known) | weakVar (VarDecl)
199 /// self->weakIvar | self (VarDecl) | weakIvar (ObjCIvarDecl)
201 /// Objects are identified with only two Decls to make it reasonably fast to
203 class WeakObjectProfileTy {
204 /// The base object decl, as described in the class documentation.
206 /// The extra flag is "true" if the Base and Property are enough to uniquely
207 /// identify the object in memory.
209 /// \sa isExactProfile()
210 typedef llvm::PointerIntPair<const NamedDecl *, 1, bool> BaseInfoTy;
213 /// The "property" decl, as described in the class documentation.
215 /// Note that this may not actually be an ObjCPropertyDecl, e.g. in the
216 /// case of "implicit" properties (regular methods accessed via dot syntax).
217 const NamedDecl *Property;
219 /// Used to find the proper base profile for a given base expression.
220 static BaseInfoTy getBaseInfo(const Expr *BaseE);
222 inline WeakObjectProfileTy();
223 static inline WeakObjectProfileTy getSentinel();
226 WeakObjectProfileTy(const ObjCPropertyRefExpr *RE);
227 WeakObjectProfileTy(const Expr *Base, const ObjCPropertyDecl *Property);
228 WeakObjectProfileTy(const DeclRefExpr *RE);
229 WeakObjectProfileTy(const ObjCIvarRefExpr *RE);
231 const NamedDecl *getBase() const { return Base.getPointer(); }
232 const NamedDecl *getProperty() const { return Property; }
234 /// Returns true if the object base specifies a known object in memory,
235 /// rather than, say, an instance variable or property of another object.
237 /// Note that this ignores the effects of aliasing; that is, \c foo.bar is
238 /// considered an exact profile if \c foo is a local variable, even if
239 /// another variable \c foo2 refers to the same object as \c foo.
241 /// For increased precision, accesses with base variables that are
242 /// properties or ivars of 'self' (e.g. self.prop1.prop2) are considered to
243 /// be exact, though this is not true for arbitrary variables
244 /// (foo.prop1.prop2).
245 bool isExactProfile() const {
246 return Base.getInt();
249 bool operator==(const WeakObjectProfileTy &Other) const {
250 return Base == Other.Base && Property == Other.Property;
253 // For use in DenseMap.
254 // We can't specialize the usual llvm::DenseMapInfo at the end of the file
255 // because by that point the DenseMap in FunctionScopeInfo has already been
259 static inline WeakObjectProfileTy getEmptyKey() {
260 return WeakObjectProfileTy();
262 static inline WeakObjectProfileTy getTombstoneKey() {
263 return WeakObjectProfileTy::getSentinel();
266 static unsigned getHashValue(const WeakObjectProfileTy &Val) {
267 typedef std::pair<BaseInfoTy, const NamedDecl *> Pair;
268 return llvm::DenseMapInfo<Pair>::getHashValue(Pair(Val.Base,
272 static bool isEqual(const WeakObjectProfileTy &LHS,
273 const WeakObjectProfileTy &RHS) {
279 /// Represents a single use of a weak object.
281 /// Stores both the expression and whether the access is potentially unsafe
282 /// (i.e. it could potentially be warned about).
284 /// Part of the implementation of -Wrepeated-use-of-weak.
286 llvm::PointerIntPair<const Expr *, 1, bool> Rep;
288 WeakUseTy(const Expr *Use, bool IsRead) : Rep(Use, IsRead) {}
290 const Expr *getUseExpr() const { return Rep.getPointer(); }
291 bool isUnsafe() const { return Rep.getInt(); }
292 void markSafe() { Rep.setInt(false); }
294 bool operator==(const WeakUseTy &Other) const {
295 return Rep == Other.Rep;
299 /// Used to collect uses of a particular weak object in a function body.
301 /// Part of the implementation of -Wrepeated-use-of-weak.
302 typedef SmallVector<WeakUseTy, 4> WeakUseVector;
304 /// Used to collect all uses of weak objects in a function body.
306 /// Part of the implementation of -Wrepeated-use-of-weak.
307 typedef llvm::SmallDenseMap<WeakObjectProfileTy, WeakUseVector, 8,
308 WeakObjectProfileTy::DenseMapInfo>
312 /// Used to collect all uses of weak objects in this function body.
314 /// Part of the implementation of -Wrepeated-use-of-weak.
315 WeakObjectUseMap WeakObjectUses;
318 FunctionScopeInfo(const FunctionScopeInfo&) = default;
321 /// Record that a weak object was accessed.
323 /// Part of the implementation of -Wrepeated-use-of-weak.
324 template <typename ExprT>
325 inline void recordUseOfWeak(const ExprT *E, bool IsRead = true);
327 void recordUseOfWeak(const ObjCMessageExpr *Msg,
328 const ObjCPropertyDecl *Prop);
330 /// Record that a given expression is a "safe" access of a weak object (e.g.
331 /// assigning it to a strong variable.)
333 /// Part of the implementation of -Wrepeated-use-of-weak.
334 void markSafeWeakUse(const Expr *E);
336 const WeakObjectUseMap &getWeakObjectUses() const {
337 return WeakObjectUses;
340 void setHasBranchIntoScope() {
341 HasBranchIntoScope = true;
344 void setHasBranchProtectedScope() {
345 HasBranchProtectedScope = true;
348 void setHasIndirectGoto() {
349 HasIndirectGoto = true;
352 void setHasDroppedStmt() {
353 HasDroppedStmt = true;
356 void setHasOMPDeclareReductionCombiner() {
357 HasOMPDeclareReductionCombiner = true;
360 void setHasFallthroughStmt() {
361 HasFallthroughStmt = true;
364 void setHasCXXTry(SourceLocation TryLoc) {
365 setHasBranchProtectedScope();
366 FirstCXXTryLoc = TryLoc;
369 void setHasSEHTry(SourceLocation TryLoc) {
370 setHasBranchProtectedScope();
371 FirstSEHTryLoc = TryLoc;
374 bool NeedsScopeChecking() const {
375 return !HasDroppedStmt &&
377 (HasBranchProtectedScope && HasBranchIntoScope));
380 FunctionScopeInfo(DiagnosticsEngine &Diag)
382 HasBranchProtectedScope(false),
383 HasBranchIntoScope(false),
384 HasIndirectGoto(false),
385 HasDroppedStmt(false),
386 HasOMPDeclareReductionCombiner(false),
387 HasFallthroughStmt(false),
388 HasPotentialAvailabilityViolations(false),
389 ObjCShouldCallSuper(false),
390 ObjCIsDesignatedInit(false),
391 ObjCWarnForNoDesignatedInitChain(false),
392 ObjCIsSecondaryInit(false),
393 ObjCWarnForNoInitDelegation(false),
396 virtual ~FunctionScopeInfo();
398 /// \brief Clear out the information in this function scope, making it
399 /// suitable for reuse.
403 class CapturingScopeInfo : public FunctionScopeInfo {
405 CapturingScopeInfo(const CapturingScopeInfo&) = default;
408 enum ImplicitCaptureStyle {
409 ImpCap_None, ImpCap_LambdaByval, ImpCap_LambdaByref, ImpCap_Block,
410 ImpCap_CapturedRegion
413 ImplicitCaptureStyle ImpCaptureStyle;
416 // There are three categories of capture: capturing 'this', capturing
417 // local variables, and C++1y initialized captures (which can have an
418 // arbitrary initializer, and don't really capture in the traditional
421 // There are three ways to capture a local variable:
422 // - capture by copy in the C++11 sense,
423 // - capture by reference in the C++11 sense, and
424 // - __block capture.
425 // Lambdas explicitly specify capture by copy or capture by reference.
426 // For blocks, __block capture applies to variables with that annotation,
427 // variables of reference type are captured by reference, and other
428 // variables are captured by copy.
430 Cap_ByCopy, Cap_ByRef, Cap_Block, Cap_VLA
433 IsNestedCapture = 0x1,
436 /// The variable being captured (if we are not capturing 'this') and whether
437 /// this is a nested capture, and whether we are capturing 'this'
438 llvm::PointerIntPair<VarDecl*, 2> VarAndNestedAndThis;
439 /// Expression to initialize a field of the given type, and the kind of
440 /// capture (if this is a capture and not an init-capture). The expression
441 /// is only required if we are capturing ByVal and the variable's type has
442 /// a non-trivial copy constructor.
443 llvm::PointerIntPair<void *, 2, CaptureKind> InitExprAndCaptureKind;
445 /// \brief The source location at which the first capture occurred.
448 /// \brief The location of the ellipsis that expands a parameter pack.
449 SourceLocation EllipsisLoc;
451 /// \brief The type as it was captured, which is in effect the type of the
452 /// non-static data member that would hold the capture.
453 QualType CaptureType;
456 Capture(VarDecl *Var, bool Block, bool ByRef, bool IsNested,
457 SourceLocation Loc, SourceLocation EllipsisLoc,
458 QualType CaptureType, Expr *Cpy)
459 : VarAndNestedAndThis(Var, IsNested ? IsNestedCapture : 0),
460 InitExprAndCaptureKind(
461 Cpy, !Var ? Cap_VLA : Block ? Cap_Block : ByRef ? Cap_ByRef
463 Loc(Loc), EllipsisLoc(EllipsisLoc), CaptureType(CaptureType) {}
465 enum IsThisCapture { ThisCapture };
466 Capture(IsThisCapture, bool IsNested, SourceLocation Loc,
467 QualType CaptureType, Expr *Cpy, const bool ByCopy)
468 : VarAndNestedAndThis(
469 nullptr, (IsThisCaptured | (IsNested ? IsNestedCapture : 0))),
470 InitExprAndCaptureKind(Cpy, ByCopy ? Cap_ByCopy : Cap_ByRef),
471 Loc(Loc), EllipsisLoc(), CaptureType(CaptureType) {}
473 bool isThisCapture() const {
474 return VarAndNestedAndThis.getInt() & IsThisCaptured;
476 bool isVariableCapture() const {
477 return !isThisCapture() && !isVLATypeCapture();
479 bool isCopyCapture() const {
480 return InitExprAndCaptureKind.getInt() == Cap_ByCopy;
482 bool isReferenceCapture() const {
483 return InitExprAndCaptureKind.getInt() == Cap_ByRef;
485 bool isBlockCapture() const {
486 return InitExprAndCaptureKind.getInt() == Cap_Block;
488 bool isVLATypeCapture() const {
489 return InitExprAndCaptureKind.getInt() == Cap_VLA;
491 bool isNested() const {
492 return VarAndNestedAndThis.getInt() & IsNestedCapture;
495 VarDecl *getVariable() const {
496 return VarAndNestedAndThis.getPointer();
499 /// \brief Retrieve the location at which this variable was captured.
500 SourceLocation getLocation() const { return Loc; }
502 /// \brief Retrieve the source location of the ellipsis, whose presence
503 /// indicates that the capture is a pack expansion.
504 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
506 /// \brief Retrieve the capture type for this capture, which is effectively
507 /// the type of the non-static data member in the lambda/block structure
508 /// that would store this capture.
509 QualType getCaptureType() const {
510 assert(!isThisCapture());
514 Expr *getInitExpr() const {
515 assert(!isVLATypeCapture() && "no init expression for type capture");
516 return static_cast<Expr *>(InitExprAndCaptureKind.getPointer());
520 CapturingScopeInfo(DiagnosticsEngine &Diag, ImplicitCaptureStyle Style)
521 : FunctionScopeInfo(Diag), ImpCaptureStyle(Style), CXXThisCaptureIndex(0),
522 HasImplicitReturnType(false)
525 /// CaptureMap - A map of captured variables to (index+1) into Captures.
526 llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
528 /// CXXThisCaptureIndex - The (index+1) of the capture of 'this';
529 /// zero if 'this' is not captured.
530 unsigned CXXThisCaptureIndex;
532 /// Captures - The captures.
533 SmallVector<Capture, 4> Captures;
535 /// \brief - Whether the target type of return statements in this context
536 /// is deduced (e.g. a lambda or block with omitted return type).
537 bool HasImplicitReturnType;
539 /// ReturnType - The target type of return statements in this context,
540 /// or null if unknown.
543 void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested,
544 SourceLocation Loc, SourceLocation EllipsisLoc,
545 QualType CaptureType, Expr *Cpy) {
546 Captures.push_back(Capture(Var, isBlock, isByref, isNested, Loc,
547 EllipsisLoc, CaptureType, Cpy));
548 CaptureMap[Var] = Captures.size();
551 void addVLATypeCapture(SourceLocation Loc, QualType CaptureType) {
552 Captures.push_back(Capture(/*Var*/ nullptr, /*isBlock*/ false,
553 /*isByref*/ false, /*isNested*/ false, Loc,
554 /*EllipsisLoc*/ SourceLocation(), CaptureType,
558 // Note, we do not need to add the type of 'this' since that is always
559 // retrievable from Sema::getCurrentThisType - and is also encoded within the
560 // type of the corresponding FieldDecl.
561 void addThisCapture(bool isNested, SourceLocation Loc,
562 Expr *Cpy, bool ByCopy);
564 /// \brief Determine whether the C++ 'this' is captured.
565 bool isCXXThisCaptured() const { return CXXThisCaptureIndex != 0; }
567 /// \brief Retrieve the capture of C++ 'this', if it has been captured.
568 Capture &getCXXThisCapture() {
569 assert(isCXXThisCaptured() && "this has not been captured");
570 return Captures[CXXThisCaptureIndex - 1];
573 /// \brief Determine whether the given variable has been captured.
574 bool isCaptured(VarDecl *Var) const {
575 return CaptureMap.count(Var);
578 /// \brief Determine whether the given variable-array type has been captured.
579 bool isVLATypeCaptured(const VariableArrayType *VAT) const;
581 /// \brief Retrieve the capture of the given variable, if it has been
582 /// captured already.
583 Capture &getCapture(VarDecl *Var) {
584 assert(isCaptured(Var) && "Variable has not been captured");
585 return Captures[CaptureMap[Var] - 1];
588 const Capture &getCapture(VarDecl *Var) const {
589 llvm::DenseMap<VarDecl*, unsigned>::const_iterator Known
590 = CaptureMap.find(Var);
591 assert(Known != CaptureMap.end() && "Variable has not been captured");
592 return Captures[Known->second - 1];
595 static bool classof(const FunctionScopeInfo *FSI) {
596 return FSI->Kind == SK_Block || FSI->Kind == SK_Lambda
597 || FSI->Kind == SK_CapturedRegion;
601 /// \brief Retains information about a block that is currently being parsed.
602 class BlockScopeInfo final : public CapturingScopeInfo {
606 /// TheScope - This is the scope for the block itself, which contains
610 /// BlockType - The function type of the block, if one was given.
611 /// Its return type may be BuiltinType::Dependent.
612 QualType FunctionType;
614 BlockScopeInfo(DiagnosticsEngine &Diag, Scope *BlockScope, BlockDecl *Block)
615 : CapturingScopeInfo(Diag, ImpCap_Block), TheDecl(Block),
621 ~BlockScopeInfo() override;
623 static bool classof(const FunctionScopeInfo *FSI) {
624 return FSI->Kind == SK_Block;
628 /// \brief Retains information about a captured region.
629 class CapturedRegionScopeInfo final : public CapturingScopeInfo {
631 /// \brief The CapturedDecl for this statement.
632 CapturedDecl *TheCapturedDecl;
633 /// \brief The captured record type.
634 RecordDecl *TheRecordDecl;
635 /// \brief This is the enclosing scope of the captured region.
637 /// \brief The implicit parameter for the captured variables.
638 ImplicitParamDecl *ContextParam;
639 /// \brief The kind of captured region.
640 unsigned short CapRegionKind;
641 unsigned short OpenMPLevel;
643 CapturedRegionScopeInfo(DiagnosticsEngine &Diag, Scope *S, CapturedDecl *CD,
644 RecordDecl *RD, ImplicitParamDecl *Context,
645 CapturedRegionKind K, unsigned OpenMPLevel)
646 : CapturingScopeInfo(Diag, ImpCap_CapturedRegion),
647 TheCapturedDecl(CD), TheRecordDecl(RD), TheScope(S),
648 ContextParam(Context), CapRegionKind(K), OpenMPLevel(OpenMPLevel)
650 Kind = SK_CapturedRegion;
653 ~CapturedRegionScopeInfo() override;
655 /// \brief A descriptive name for the kind of captured region this is.
656 StringRef getRegionName() const {
657 switch (CapRegionKind) {
659 return "default captured statement";
661 return "OpenMP region";
663 llvm_unreachable("Invalid captured region kind!");
666 static bool classof(const FunctionScopeInfo *FSI) {
667 return FSI->Kind == SK_CapturedRegion;
671 class LambdaScopeInfo final : public CapturingScopeInfo {
673 /// \brief The class that describes the lambda.
674 CXXRecordDecl *Lambda;
676 /// \brief The lambda's compiler-generated \c operator().
677 CXXMethodDecl *CallOperator;
679 /// \brief Source range covering the lambda introducer [...].
680 SourceRange IntroducerRange;
682 /// \brief Source location of the '&' or '=' specifying the default capture
684 SourceLocation CaptureDefaultLoc;
686 /// \brief The number of captures in the \c Captures list that are
687 /// explicit captures.
688 unsigned NumExplicitCaptures;
690 /// \brief Whether this is a mutable lambda.
693 /// \brief Whether the (empty) parameter list is explicit.
696 /// \brief Whether any of the capture expressions requires cleanups.
699 /// \brief Whether the lambda contains an unexpanded parameter pack.
700 bool ContainsUnexpandedParameterPack;
702 /// \brief If this is a generic lambda, use this as the depth of
703 /// each 'auto' parameter, during initial AST construction.
704 unsigned AutoTemplateParameterDepth;
706 /// \brief Store the list of the auto parameters for a generic lambda.
707 /// If this is a generic lambda, store the list of the auto
708 /// parameters converted into TemplateTypeParmDecls into a vector
709 /// that can be used to construct the generic lambda's template
710 /// parameter list, during initial AST construction.
711 SmallVector<TemplateTypeParmDecl*, 4> AutoTemplateParams;
713 /// If this is a generic lambda, and the template parameter
714 /// list has been created (from the AutoTemplateParams) then
715 /// store a reference to it (cache it to avoid reconstructing it).
716 TemplateParameterList *GLTemplateParameterList;
718 /// \brief Contains all variable-referring-expressions (i.e. DeclRefExprs
719 /// or MemberExprs) that refer to local variables in a generic lambda
720 /// or a lambda in a potentially-evaluated-if-used context.
722 /// Potentially capturable variables of a nested lambda that might need
723 /// to be captured by the lambda are housed here.
724 /// This is specifically useful for generic lambdas or
725 /// lambdas within a a potentially evaluated-if-used context.
726 /// If an enclosing variable is named in an expression of a lambda nested
727 /// within a generic lambda, we don't always know know whether the variable
728 /// will truly be odr-used (i.e. need to be captured) by that nested lambda,
729 /// until its instantiation. But we still need to capture it in the
730 /// enclosing lambda if all intervening lambdas can capture the variable.
732 llvm::SmallVector<Expr*, 4> PotentiallyCapturingExprs;
734 /// \brief Contains all variable-referring-expressions that refer
735 /// to local variables that are usable as constant expressions and
736 /// do not involve an odr-use (they may still need to be captured
737 /// if the enclosing full-expression is instantiation dependent).
738 llvm::SmallSet<Expr *, 8> NonODRUsedCapturingExprs;
740 /// Contains all of the variables defined in this lambda that shadow variables
741 /// that were defined in parent contexts. Used to avoid warnings when the
742 /// shadowed variables are uncaptured by this lambda.
743 struct ShadowedOuterDecl {
745 const VarDecl *ShadowedDecl;
747 llvm::SmallVector<ShadowedOuterDecl, 4> ShadowingDecls;
749 SourceLocation PotentialThisCaptureLocation;
751 LambdaScopeInfo(DiagnosticsEngine &Diag)
752 : CapturingScopeInfo(Diag, ImpCap_None), Lambda(nullptr),
753 CallOperator(nullptr), NumExplicitCaptures(0), Mutable(false),
754 ExplicitParams(false), Cleanup{},
755 ContainsUnexpandedParameterPack(false), AutoTemplateParameterDepth(0),
756 GLTemplateParameterList(nullptr) {
760 /// \brief Note when all explicit captures have been added.
761 void finishedExplicitCaptures() {
762 NumExplicitCaptures = Captures.size();
765 static bool classof(const FunctionScopeInfo *FSI) {
766 return FSI->Kind == SK_Lambda;
770 /// \brief Add a variable that might potentially be captured by the
771 /// lambda and therefore the enclosing lambdas.
773 /// This is also used by enclosing lambda's to speculatively capture
774 /// variables that nested lambda's - depending on their enclosing
775 /// specialization - might need to capture.
777 /// void f(int, int); <-- don't capture
778 /// void f(const int&, double); <-- capture
780 /// const int x = 10;
781 /// auto L = [=](auto a) { // capture 'x'
782 /// return [=](auto b) {
783 /// f(x, a); // we may or may not need to capture 'x'
787 void addPotentialCapture(Expr *VarExpr) {
788 assert(isa<DeclRefExpr>(VarExpr) || isa<MemberExpr>(VarExpr));
789 PotentiallyCapturingExprs.push_back(VarExpr);
792 void addPotentialThisCapture(SourceLocation Loc) {
793 PotentialThisCaptureLocation = Loc;
795 bool hasPotentialThisCapture() const {
796 return PotentialThisCaptureLocation.isValid();
799 /// \brief Mark a variable's reference in a lambda as non-odr using.
801 /// For generic lambdas, if a variable is named in a potentially evaluated
802 /// expression, where the enclosing full expression is dependent then we
803 /// must capture the variable (given a default capture).
804 /// This is accomplished by recording all references to variables
805 /// (DeclRefExprs or MemberExprs) within said nested lambda in its array of
806 /// PotentialCaptures. All such variables have to be captured by that lambda,
807 /// except for as described below.
808 /// If that variable is usable as a constant expression and is named in a
809 /// manner that does not involve its odr-use (e.g. undergoes
810 /// lvalue-to-rvalue conversion, or discarded) record that it is so. Upon the
811 /// act of analyzing the enclosing full expression (ActOnFinishFullExpr)
812 /// if we can determine that the full expression is not instantiation-
813 /// dependent, then we can entirely avoid its capture.
819 /// Interestingly, this strategy would involve a capture of n, even though
820 /// it's obviously not odr-used here, because the full-expression is
821 /// instantiation-dependent. It could be useful to avoid capturing such
822 /// variables, even when they are referred to in an instantiation-dependent
823 /// expression, if we can unambiguously determine that they shall never be
824 /// odr-used. This would involve removal of the variable-referring-expression
825 /// from the array of PotentialCaptures during the lvalue-to-rvalue
826 /// conversions. But per the working draft N3797, (post-chicago 2013) we must
827 /// capture such variables.
828 /// Before anyone is tempted to implement a strategy for not-capturing 'n',
829 /// consider the insightful warning in:
830 /// /cfe-commits/Week-of-Mon-20131104/092596.html
831 /// "The problem is that the set of captures for a lambda is part of the ABI
832 /// (since lambda layout can be made visible through inline functions and the
833 /// like), and there are no guarantees as to which cases we'll manage to build
834 /// an lvalue-to-rvalue conversion in, when parsing a template -- some
835 /// seemingly harmless change elsewhere in Sema could cause us to start or stop
836 /// building such a node. So we need a rule that anyone can implement and get
837 /// exactly the same result".
839 void markVariableExprAsNonODRUsed(Expr *CapturingVarExpr) {
840 assert(isa<DeclRefExpr>(CapturingVarExpr)
841 || isa<MemberExpr>(CapturingVarExpr));
842 NonODRUsedCapturingExprs.insert(CapturingVarExpr);
844 bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const {
845 assert(isa<DeclRefExpr>(CapturingVarExpr)
846 || isa<MemberExpr>(CapturingVarExpr));
847 return NonODRUsedCapturingExprs.count(CapturingVarExpr);
849 void removePotentialCapture(Expr *E) {
850 PotentiallyCapturingExprs.erase(
851 std::remove(PotentiallyCapturingExprs.begin(),
852 PotentiallyCapturingExprs.end(), E),
853 PotentiallyCapturingExprs.end());
855 void clearPotentialCaptures() {
856 PotentiallyCapturingExprs.clear();
857 PotentialThisCaptureLocation = SourceLocation();
859 unsigned getNumPotentialVariableCaptures() const {
860 return PotentiallyCapturingExprs.size();
863 bool hasPotentialCaptures() const {
864 return getNumPotentialVariableCaptures() ||
865 PotentialThisCaptureLocation.isValid();
868 // When passed the index, returns the VarDecl and Expr associated
870 void getPotentialVariableCapture(unsigned Idx, VarDecl *&VD, Expr *&E) const;
873 FunctionScopeInfo::WeakObjectProfileTy::WeakObjectProfileTy()
874 : Base(nullptr, false), Property(nullptr) {}
876 FunctionScopeInfo::WeakObjectProfileTy
877 FunctionScopeInfo::WeakObjectProfileTy::getSentinel() {
878 FunctionScopeInfo::WeakObjectProfileTy Result;
879 Result.Base.setInt(true);
883 template <typename ExprT>
884 void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
886 WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
887 Uses.push_back(WeakUseTy(E, IsRead));
891 CapturingScopeInfo::addThisCapture(bool isNested, SourceLocation Loc,
894 Captures.push_back(Capture(Capture::ThisCapture, isNested, Loc, QualType(),
896 CXXThisCaptureIndex = Captures.size();
899 } // end namespace sema
900 } // end namespace clang