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