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/Ownership.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
35 class ObjCPropertyDecl;
37 class ImplicitParamDecl;
42 class TemplateTypeParmDecl;
43 class TemplateParameterList;
45 class ObjCIvarRefExpr;
46 class ObjCPropertyRefExpr;
47 class ObjCMessageExpr;
51 /// \brief Contains information about the compound statement currently being
53 class CompoundScopeInfo {
56 : HasEmptyLoopBodies(false) { }
58 /// \brief Whether this compound stamement contains `for' or `while' loops
59 /// with empty bodies.
60 bool HasEmptyLoopBodies;
62 void setHasEmptyLoopBodies() {
63 HasEmptyLoopBodies = true;
67 class PossiblyUnreachableDiag {
73 PossiblyUnreachableDiag(const PartialDiagnostic &PD, SourceLocation Loc,
75 : PD(PD), Loc(Loc), stmt(stmt) {}
78 /// \brief Retains information about a function, method, or block that is
79 /// currently being parsed.
80 class FunctionScopeInfo {
90 /// \brief What kind of scope we are describing.
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;
98 /// \brief Whether this function contains any switches or direct gotos.
99 bool HasBranchIntoScope;
101 /// \brief Whether this function contains any indirect gotos.
102 bool HasIndirectGoto;
104 /// \brief Whether a statement was dropped because it was invalid.
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;
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
117 bool ObjCWarnForNoDesignatedInitChain;
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;
127 /// First C++ 'try' statement in the current function.
128 SourceLocation FirstCXXTryLoc;
130 /// First SEH '__try' statement in the current function.
131 SourceLocation FirstSEHTryLoc;
133 /// \brief Used to determine if errors occurred in this function or block.
134 DiagnosticErrorTrap ErrorTrap;
136 /// SwitchStack - This is the current set of active switch statements in the
138 SmallVector<SwitchStmt*, 8> SwitchStack;
140 /// \brief The list of return statements that occur within the function or
141 /// block, if there is any chance of applying the named return value
142 /// optimization, or if we need to infer a return type.
143 SmallVector<ReturnStmt*, 4> Returns;
145 /// \brief The stack of currently active compound stamement scopes in the
147 SmallVector<CompoundScopeInfo, 4> CompoundScopes;
149 /// \brief A list of PartialDiagnostics created but delayed within the
150 /// current function scope. These diagnostics are vetted for reachability
151 /// prior to being emitted.
152 SmallVector<PossiblyUnreachableDiag, 4> PossiblyUnreachableDiags;
154 /// \brief A list of parameters which have the nonnull attribute and are
155 /// modified in the function.
156 llvm::SmallPtrSet<const ParmVarDecl*, 8> ModifiedNonNullParams;
159 /// Represents a simple identification of a weak object.
161 /// Part of the implementation of -Wrepeated-use-of-weak.
163 /// This is used to determine if two weak accesses refer to the same object.
164 /// Here are some examples of how various accesses are "profiled":
166 /// Access Expression | "Base" Decl | "Property" Decl
167 /// :---------------: | :-----------------: | :------------------------------:
168 /// self.property | self (VarDecl) | property (ObjCPropertyDecl)
169 /// self.implicitProp | self (VarDecl) | -implicitProp (ObjCMethodDecl)
170 /// self->ivar.prop | ivar (ObjCIvarDecl) | prop (ObjCPropertyDecl)
171 /// cxxObj.obj.prop | obj (FieldDecl) | prop (ObjCPropertyDecl)
172 /// [self foo].prop | 0 (unknown) | prop (ObjCPropertyDecl)
173 /// self.prop1.prop2 | prop1 (ObjCPropertyDecl) | prop2 (ObjCPropertyDecl)
174 /// MyClass.prop | MyClass (ObjCInterfaceDecl) | -prop (ObjCMethodDecl)
175 /// weakVar | 0 (known) | weakVar (VarDecl)
176 /// self->weakIvar | self (VarDecl) | weakIvar (ObjCIvarDecl)
178 /// Objects are identified with only two Decls to make it reasonably fast to
180 class WeakObjectProfileTy {
181 /// The base object decl, as described in the class documentation.
183 /// The extra flag is "true" if the Base and Property are enough to uniquely
184 /// identify the object in memory.
186 /// \sa isExactProfile()
187 typedef llvm::PointerIntPair<const NamedDecl *, 1, bool> BaseInfoTy;
190 /// The "property" decl, as described in the class documentation.
192 /// Note that this may not actually be an ObjCPropertyDecl, e.g. in the
193 /// case of "implicit" properties (regular methods accessed via dot syntax).
194 const NamedDecl *Property;
196 /// Used to find the proper base profile for a given base expression.
197 static BaseInfoTy getBaseInfo(const Expr *BaseE);
199 inline WeakObjectProfileTy();
200 static inline WeakObjectProfileTy getSentinel();
203 WeakObjectProfileTy(const ObjCPropertyRefExpr *RE);
204 WeakObjectProfileTy(const Expr *Base, const ObjCPropertyDecl *Property);
205 WeakObjectProfileTy(const DeclRefExpr *RE);
206 WeakObjectProfileTy(const ObjCIvarRefExpr *RE);
208 const NamedDecl *getBase() const { return Base.getPointer(); }
209 const NamedDecl *getProperty() const { return Property; }
211 /// Returns true if the object base specifies a known object in memory,
212 /// rather than, say, an instance variable or property of another object.
214 /// Note that this ignores the effects of aliasing; that is, \c foo.bar is
215 /// considered an exact profile if \c foo is a local variable, even if
216 /// another variable \c foo2 refers to the same object as \c foo.
218 /// For increased precision, accesses with base variables that are
219 /// properties or ivars of 'self' (e.g. self.prop1.prop2) are considered to
220 /// be exact, though this is not true for arbitrary variables
221 /// (foo.prop1.prop2).
222 bool isExactProfile() const {
223 return Base.getInt();
226 bool operator==(const WeakObjectProfileTy &Other) const {
227 return Base == Other.Base && Property == Other.Property;
230 // For use in DenseMap.
231 // We can't specialize the usual llvm::DenseMapInfo at the end of the file
232 // because by that point the DenseMap in FunctionScopeInfo has already been
236 static inline WeakObjectProfileTy getEmptyKey() {
237 return WeakObjectProfileTy();
239 static inline WeakObjectProfileTy getTombstoneKey() {
240 return WeakObjectProfileTy::getSentinel();
243 static unsigned getHashValue(const WeakObjectProfileTy &Val) {
244 typedef std::pair<BaseInfoTy, const NamedDecl *> Pair;
245 return llvm::DenseMapInfo<Pair>::getHashValue(Pair(Val.Base,
249 static bool isEqual(const WeakObjectProfileTy &LHS,
250 const WeakObjectProfileTy &RHS) {
256 /// Represents a single use of a weak object.
258 /// Stores both the expression and whether the access is potentially unsafe
259 /// (i.e. it could potentially be warned about).
261 /// Part of the implementation of -Wrepeated-use-of-weak.
263 llvm::PointerIntPair<const Expr *, 1, bool> Rep;
265 WeakUseTy(const Expr *Use, bool IsRead) : Rep(Use, IsRead) {}
267 const Expr *getUseExpr() const { return Rep.getPointer(); }
268 bool isUnsafe() const { return Rep.getInt(); }
269 void markSafe() { Rep.setInt(false); }
271 bool operator==(const WeakUseTy &Other) const {
272 return Rep == Other.Rep;
276 /// Used to collect uses of a particular weak object in a function body.
278 /// Part of the implementation of -Wrepeated-use-of-weak.
279 typedef SmallVector<WeakUseTy, 4> WeakUseVector;
281 /// Used to collect all uses of weak objects in a function body.
283 /// Part of the implementation of -Wrepeated-use-of-weak.
284 typedef llvm::SmallDenseMap<WeakObjectProfileTy, WeakUseVector, 8,
285 WeakObjectProfileTy::DenseMapInfo>
289 /// Used to collect all uses of weak objects in this function body.
291 /// Part of the implementation of -Wrepeated-use-of-weak.
292 WeakObjectUseMap WeakObjectUses;
295 /// Record that a weak object was accessed.
297 /// Part of the implementation of -Wrepeated-use-of-weak.
298 template <typename ExprT>
299 inline void recordUseOfWeak(const ExprT *E, bool IsRead = true);
301 void recordUseOfWeak(const ObjCMessageExpr *Msg,
302 const ObjCPropertyDecl *Prop);
304 /// Record that a given expression is a "safe" access of a weak object (e.g.
305 /// assigning it to a strong variable.)
307 /// Part of the implementation of -Wrepeated-use-of-weak.
308 void markSafeWeakUse(const Expr *E);
310 const WeakObjectUseMap &getWeakObjectUses() const {
311 return WeakObjectUses;
314 void setHasBranchIntoScope() {
315 HasBranchIntoScope = true;
318 void setHasBranchProtectedScope() {
319 HasBranchProtectedScope = true;
322 void setHasIndirectGoto() {
323 HasIndirectGoto = true;
326 void setHasDroppedStmt() {
327 HasDroppedStmt = true;
330 void setHasCXXTry(SourceLocation TryLoc) {
331 setHasBranchProtectedScope();
332 FirstCXXTryLoc = TryLoc;
335 void setHasSEHTry(SourceLocation TryLoc) {
336 setHasBranchProtectedScope();
337 FirstSEHTryLoc = TryLoc;
340 bool NeedsScopeChecking() const {
341 return !HasDroppedStmt &&
343 (HasBranchProtectedScope && HasBranchIntoScope));
346 FunctionScopeInfo(DiagnosticsEngine &Diag)
348 HasBranchProtectedScope(false),
349 HasBranchIntoScope(false),
350 HasIndirectGoto(false),
351 HasDroppedStmt(false),
352 ObjCShouldCallSuper(false),
353 ObjCIsDesignatedInit(false),
354 ObjCWarnForNoDesignatedInitChain(false),
355 ObjCIsSecondaryInit(false),
356 ObjCWarnForNoInitDelegation(false),
359 virtual ~FunctionScopeInfo();
361 /// \brief Clear out the information in this function scope, making it
362 /// suitable for reuse.
366 class CapturingScopeInfo : public FunctionScopeInfo {
368 enum ImplicitCaptureStyle {
369 ImpCap_None, ImpCap_LambdaByval, ImpCap_LambdaByref, ImpCap_Block,
370 ImpCap_CapturedRegion
373 ImplicitCaptureStyle ImpCaptureStyle;
376 // There are three categories of capture: capturing 'this', capturing
377 // local variables, and C++1y initialized captures (which can have an
378 // arbitrary initializer, and don't really capture in the traditional
381 // There are three ways to capture a local variable:
382 // - capture by copy in the C++11 sense,
383 // - capture by reference in the C++11 sense, and
384 // - __block capture.
385 // Lambdas explicitly specify capture by copy or capture by reference.
386 // For blocks, __block capture applies to variables with that annotation,
387 // variables of reference type are captured by reference, and other
388 // variables are captured by copy.
390 Cap_ByCopy, Cap_ByRef, Cap_Block, Cap_This
393 /// The variable being captured (if we are not capturing 'this') and whether
394 /// this is a nested capture.
395 llvm::PointerIntPair<VarDecl*, 1, bool> VarAndNested;
397 /// Expression to initialize a field of the given type, and the kind of
398 /// capture (if this is a capture and not an init-capture). The expression
399 /// is only required if we are capturing ByVal and the variable's type has
400 /// a non-trivial copy constructor.
401 llvm::PointerIntPair<void *, 2, CaptureKind> InitExprAndCaptureKind;
403 /// \brief The source location at which the first capture occurred.
406 /// \brief The location of the ellipsis that expands a parameter pack.
407 SourceLocation EllipsisLoc;
409 /// \brief The type as it was captured, which is in effect the type of the
410 /// non-static data member that would hold the capture.
411 QualType CaptureType;
414 Capture(VarDecl *Var, bool Block, bool ByRef, bool IsNested,
415 SourceLocation Loc, SourceLocation EllipsisLoc,
416 QualType CaptureType, Expr *Cpy)
417 : VarAndNested(Var, IsNested),
418 InitExprAndCaptureKind(Cpy, Block ? Cap_Block :
419 ByRef ? Cap_ByRef : Cap_ByCopy),
420 Loc(Loc), EllipsisLoc(EllipsisLoc), CaptureType(CaptureType) {}
422 enum IsThisCapture { ThisCapture };
423 Capture(IsThisCapture, bool IsNested, SourceLocation Loc,
424 QualType CaptureType, Expr *Cpy)
425 : VarAndNested(nullptr, IsNested),
426 InitExprAndCaptureKind(Cpy, Cap_This),
427 Loc(Loc), EllipsisLoc(), CaptureType(CaptureType) {}
429 bool isThisCapture() const {
430 return InitExprAndCaptureKind.getInt() == Cap_This;
432 bool isVariableCapture() const {
433 return InitExprAndCaptureKind.getInt() != Cap_This && !isVLATypeCapture();
435 bool isCopyCapture() const {
436 return InitExprAndCaptureKind.getInt() == Cap_ByCopy &&
439 bool isReferenceCapture() const {
440 return InitExprAndCaptureKind.getInt() == Cap_ByRef;
442 bool isBlockCapture() const {
443 return InitExprAndCaptureKind.getInt() == Cap_Block;
445 bool isVLATypeCapture() const {
446 return InitExprAndCaptureKind.getInt() == Cap_ByCopy &&
447 getVariable() == nullptr;
449 bool isNested() const { return VarAndNested.getInt(); }
451 VarDecl *getVariable() const {
452 return VarAndNested.getPointer();
455 /// \brief Retrieve the location at which this variable was captured.
456 SourceLocation getLocation() const { return Loc; }
458 /// \brief Retrieve the source location of the ellipsis, whose presence
459 /// indicates that the capture is a pack expansion.
460 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
462 /// \brief Retrieve the capture type for this capture, which is effectively
463 /// the type of the non-static data member in the lambda/block structure
464 /// that would store this capture.
465 QualType getCaptureType() const { return CaptureType; }
467 Expr *getInitExpr() const {
468 assert(!isVLATypeCapture() && "no init expression for type capture");
469 return static_cast<Expr *>(InitExprAndCaptureKind.getPointer());
473 CapturingScopeInfo(DiagnosticsEngine &Diag, ImplicitCaptureStyle Style)
474 : FunctionScopeInfo(Diag), ImpCaptureStyle(Style), CXXThisCaptureIndex(0),
475 HasImplicitReturnType(false)
478 /// CaptureMap - A map of captured variables to (index+1) into Captures.
479 llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
481 /// CXXThisCaptureIndex - The (index+1) of the capture of 'this';
482 /// zero if 'this' is not captured.
483 unsigned CXXThisCaptureIndex;
485 /// Captures - The captures.
486 SmallVector<Capture, 4> Captures;
488 /// \brief - Whether the target type of return statements in this context
489 /// is deduced (e.g. a lambda or block with omitted return type).
490 bool HasImplicitReturnType;
492 /// ReturnType - The target type of return statements in this context,
493 /// or null if unknown.
496 void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested,
497 SourceLocation Loc, SourceLocation EllipsisLoc,
498 QualType CaptureType, Expr *Cpy) {
499 Captures.push_back(Capture(Var, isBlock, isByref, isNested, Loc,
500 EllipsisLoc, CaptureType, Cpy));
501 CaptureMap[Var] = Captures.size();
504 void addVLATypeCapture(SourceLocation Loc, QualType CaptureType) {
505 Captures.push_back(Capture(/*Var*/ nullptr, /*isBlock*/ false,
506 /*isByref*/ false, /*isNested*/ false, Loc,
507 /*EllipsisLoc*/ SourceLocation(), CaptureType,
511 void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType,
514 /// \brief Determine whether the C++ 'this' is captured.
515 bool isCXXThisCaptured() const { return CXXThisCaptureIndex != 0; }
517 /// \brief Retrieve the capture of C++ 'this', if it has been captured.
518 Capture &getCXXThisCapture() {
519 assert(isCXXThisCaptured() && "this has not been captured");
520 return Captures[CXXThisCaptureIndex - 1];
523 /// \brief Determine whether the given variable has been captured.
524 bool isCaptured(VarDecl *Var) const {
525 return CaptureMap.count(Var);
528 /// \brief Determine whether the given variable-array type has been captured.
529 bool isVLATypeCaptured(const VariableArrayType *VAT) const;
531 /// \brief Retrieve the capture of the given variable, if it has been
532 /// captured already.
533 Capture &getCapture(VarDecl *Var) {
534 assert(isCaptured(Var) && "Variable has not been captured");
535 return Captures[CaptureMap[Var] - 1];
538 const Capture &getCapture(VarDecl *Var) const {
539 llvm::DenseMap<VarDecl*, unsigned>::const_iterator Known
540 = CaptureMap.find(Var);
541 assert(Known != CaptureMap.end() && "Variable has not been captured");
542 return Captures[Known->second - 1];
545 static bool classof(const FunctionScopeInfo *FSI) {
546 return FSI->Kind == SK_Block || FSI->Kind == SK_Lambda
547 || FSI->Kind == SK_CapturedRegion;
551 /// \brief Retains information about a block that is currently being parsed.
552 class BlockScopeInfo : public CapturingScopeInfo {
556 /// TheScope - This is the scope for the block itself, which contains
560 /// BlockType - The function type of the block, if one was given.
561 /// Its return type may be BuiltinType::Dependent.
562 QualType FunctionType;
564 BlockScopeInfo(DiagnosticsEngine &Diag, Scope *BlockScope, BlockDecl *Block)
565 : CapturingScopeInfo(Diag, ImpCap_Block), TheDecl(Block),
571 ~BlockScopeInfo() override;
573 static bool classof(const FunctionScopeInfo *FSI) {
574 return FSI->Kind == SK_Block;
578 /// \brief Retains information about a captured region.
579 class CapturedRegionScopeInfo: public CapturingScopeInfo {
581 /// \brief The CapturedDecl for this statement.
582 CapturedDecl *TheCapturedDecl;
583 /// \brief The captured record type.
584 RecordDecl *TheRecordDecl;
585 /// \brief This is the enclosing scope of the captured region.
587 /// \brief The implicit parameter for the captured variables.
588 ImplicitParamDecl *ContextParam;
589 /// \brief The kind of captured region.
590 CapturedRegionKind CapRegionKind;
592 CapturedRegionScopeInfo(DiagnosticsEngine &Diag, Scope *S, CapturedDecl *CD,
593 RecordDecl *RD, ImplicitParamDecl *Context,
594 CapturedRegionKind K)
595 : CapturingScopeInfo(Diag, ImpCap_CapturedRegion),
596 TheCapturedDecl(CD), TheRecordDecl(RD), TheScope(S),
597 ContextParam(Context), CapRegionKind(K)
599 Kind = SK_CapturedRegion;
602 ~CapturedRegionScopeInfo() override;
604 /// \brief A descriptive name for the kind of captured region this is.
605 StringRef getRegionName() const {
606 switch (CapRegionKind) {
608 return "default captured statement";
610 return "OpenMP region";
612 llvm_unreachable("Invalid captured region kind!");
615 static bool classof(const FunctionScopeInfo *FSI) {
616 return FSI->Kind == SK_CapturedRegion;
620 class LambdaScopeInfo : public CapturingScopeInfo {
622 /// \brief The class that describes the lambda.
623 CXXRecordDecl *Lambda;
625 /// \brief The lambda's compiler-generated \c operator().
626 CXXMethodDecl *CallOperator;
628 /// \brief Source range covering the lambda introducer [...].
629 SourceRange IntroducerRange;
631 /// \brief Source location of the '&' or '=' specifying the default capture
633 SourceLocation CaptureDefaultLoc;
635 /// \brief The number of captures in the \c Captures list that are
636 /// explicit captures.
637 unsigned NumExplicitCaptures;
639 /// \brief Whether this is a mutable lambda.
642 /// \brief Whether the (empty) parameter list is explicit.
645 /// \brief Whether any of the capture expressions requires cleanups.
646 bool ExprNeedsCleanups;
648 /// \brief Whether the lambda contains an unexpanded parameter pack.
649 bool ContainsUnexpandedParameterPack;
651 /// \brief If this is a generic lambda, use this as the depth of
652 /// each 'auto' parameter, during initial AST construction.
653 unsigned AutoTemplateParameterDepth;
655 /// \brief Store the list of the auto parameters for a generic lambda.
656 /// If this is a generic lambda, store the list of the auto
657 /// parameters converted into TemplateTypeParmDecls into a vector
658 /// that can be used to construct the generic lambda's template
659 /// parameter list, during initial AST construction.
660 SmallVector<TemplateTypeParmDecl*, 4> AutoTemplateParams;
662 /// If this is a generic lambda, and the template parameter
663 /// list has been created (from the AutoTemplateParams) then
664 /// store a reference to it (cache it to avoid reconstructing it).
665 TemplateParameterList *GLTemplateParameterList;
667 /// \brief Contains all variable-referring-expressions (i.e. DeclRefExprs
668 /// or MemberExprs) that refer to local variables in a generic lambda
669 /// or a lambda in a potentially-evaluated-if-used context.
671 /// Potentially capturable variables of a nested lambda that might need
672 /// to be captured by the lambda are housed here.
673 /// This is specifically useful for generic lambdas or
674 /// lambdas within a a potentially evaluated-if-used context.
675 /// If an enclosing variable is named in an expression of a lambda nested
676 /// within a generic lambda, we don't always know know whether the variable
677 /// will truly be odr-used (i.e. need to be captured) by that nested lambda,
678 /// until its instantiation. But we still need to capture it in the
679 /// enclosing lambda if all intervening lambdas can capture the variable.
681 llvm::SmallVector<Expr*, 4> PotentiallyCapturingExprs;
683 /// \brief Contains all variable-referring-expressions that refer
684 /// to local variables that are usable as constant expressions and
685 /// do not involve an odr-use (they may still need to be captured
686 /// if the enclosing full-expression is instantiation dependent).
687 llvm::SmallSet<Expr*, 8> NonODRUsedCapturingExprs;
689 SourceLocation PotentialThisCaptureLocation;
691 LambdaScopeInfo(DiagnosticsEngine &Diag)
692 : CapturingScopeInfo(Diag, ImpCap_None), Lambda(nullptr),
693 CallOperator(nullptr), NumExplicitCaptures(0), Mutable(false),
694 ExplicitParams(false), ExprNeedsCleanups(false),
695 ContainsUnexpandedParameterPack(false), AutoTemplateParameterDepth(0),
696 GLTemplateParameterList(nullptr) {
700 ~LambdaScopeInfo() override;
702 /// \brief Note when all explicit captures have been added.
703 void finishedExplicitCaptures() {
704 NumExplicitCaptures = Captures.size();
707 static bool classof(const FunctionScopeInfo *FSI) {
708 return FSI->Kind == SK_Lambda;
712 /// \brief Add a variable that might potentially be captured by the
713 /// lambda and therefore the enclosing lambdas.
715 /// This is also used by enclosing lambda's to speculatively capture
716 /// variables that nested lambda's - depending on their enclosing
717 /// specialization - might need to capture.
719 /// void f(int, int); <-- don't capture
720 /// void f(const int&, double); <-- capture
722 /// const int x = 10;
723 /// auto L = [=](auto a) { // capture 'x'
724 /// return [=](auto b) {
725 /// f(x, a); // we may or may not need to capture 'x'
729 void addPotentialCapture(Expr *VarExpr) {
730 assert(isa<DeclRefExpr>(VarExpr) || isa<MemberExpr>(VarExpr));
731 PotentiallyCapturingExprs.push_back(VarExpr);
734 void addPotentialThisCapture(SourceLocation Loc) {
735 PotentialThisCaptureLocation = Loc;
737 bool hasPotentialThisCapture() const {
738 return PotentialThisCaptureLocation.isValid();
741 /// \brief Mark a variable's reference in a lambda as non-odr using.
743 /// For generic lambdas, if a variable is named in a potentially evaluated
744 /// expression, where the enclosing full expression is dependent then we
745 /// must capture the variable (given a default capture).
746 /// This is accomplished by recording all references to variables
747 /// (DeclRefExprs or MemberExprs) within said nested lambda in its array of
748 /// PotentialCaptures. All such variables have to be captured by that lambda,
749 /// except for as described below.
750 /// If that variable is usable as a constant expression and is named in a
751 /// manner that does not involve its odr-use (e.g. undergoes
752 /// lvalue-to-rvalue conversion, or discarded) record that it is so. Upon the
753 /// act of analyzing the enclosing full expression (ActOnFinishFullExpr)
754 /// if we can determine that the full expression is not instantiation-
755 /// dependent, then we can entirely avoid its capture.
761 /// Interestingly, this strategy would involve a capture of n, even though
762 /// it's obviously not odr-used here, because the full-expression is
763 /// instantiation-dependent. It could be useful to avoid capturing such
764 /// variables, even when they are referred to in an instantiation-dependent
765 /// expression, if we can unambiguously determine that they shall never be
766 /// odr-used. This would involve removal of the variable-referring-expression
767 /// from the array of PotentialCaptures during the lvalue-to-rvalue
768 /// conversions. But per the working draft N3797, (post-chicago 2013) we must
769 /// capture such variables.
770 /// Before anyone is tempted to implement a strategy for not-capturing 'n',
771 /// consider the insightful warning in:
772 /// /cfe-commits/Week-of-Mon-20131104/092596.html
773 /// "The problem is that the set of captures for a lambda is part of the ABI
774 /// (since lambda layout can be made visible through inline functions and the
775 /// like), and there are no guarantees as to which cases we'll manage to build
776 /// an lvalue-to-rvalue conversion in, when parsing a template -- some
777 /// seemingly harmless change elsewhere in Sema could cause us to start or stop
778 /// building such a node. So we need a rule that anyone can implement and get
779 /// exactly the same result".
781 void markVariableExprAsNonODRUsed(Expr *CapturingVarExpr) {
782 assert(isa<DeclRefExpr>(CapturingVarExpr)
783 || isa<MemberExpr>(CapturingVarExpr));
784 NonODRUsedCapturingExprs.insert(CapturingVarExpr);
786 bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const {
787 assert(isa<DeclRefExpr>(CapturingVarExpr)
788 || isa<MemberExpr>(CapturingVarExpr));
789 return NonODRUsedCapturingExprs.count(CapturingVarExpr);
791 void removePotentialCapture(Expr *E) {
792 PotentiallyCapturingExprs.erase(
793 std::remove(PotentiallyCapturingExprs.begin(),
794 PotentiallyCapturingExprs.end(), E),
795 PotentiallyCapturingExprs.end());
797 void clearPotentialCaptures() {
798 PotentiallyCapturingExprs.clear();
799 PotentialThisCaptureLocation = SourceLocation();
801 unsigned getNumPotentialVariableCaptures() const {
802 return PotentiallyCapturingExprs.size();
805 bool hasPotentialCaptures() const {
806 return getNumPotentialVariableCaptures() ||
807 PotentialThisCaptureLocation.isValid();
810 // When passed the index, returns the VarDecl and Expr associated
812 void getPotentialVariableCapture(unsigned Idx, VarDecl *&VD, Expr *&E) const;
815 FunctionScopeInfo::WeakObjectProfileTy::WeakObjectProfileTy()
816 : Base(nullptr, false), Property(nullptr) {}
818 FunctionScopeInfo::WeakObjectProfileTy
819 FunctionScopeInfo::WeakObjectProfileTy::getSentinel() {
820 FunctionScopeInfo::WeakObjectProfileTy Result;
821 Result.Base.setInt(true);
825 template <typename ExprT>
826 void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
828 WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
829 Uses.push_back(WeakUseTy(E, IsRead));
833 CapturingScopeInfo::addThisCapture(bool isNested, SourceLocation Loc,
834 QualType CaptureType, Expr *Cpy) {
835 Captures.push_back(Capture(Capture::ThisCapture, isNested, Loc, CaptureType,
837 CXXThisCaptureIndex = Captures.size();
840 } // end namespace sema
841 } // end namespace clang