clang  14.0.0git
Sema.h
Go to the documentation of this file.
1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the Sema class, which performs semantic analysis and
10 // builds ASTs.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_SEMA_SEMA_H
15 #define LLVM_CLANG_SEMA_SEMA_H
16 
17 #include "clang/AST/ASTConcept.h"
18 #include "clang/AST/ASTFwd.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Availability.h"
22 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprConcepts.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
30 #include "clang/AST/LocInfoType.h"
32 #include "clang/AST/NSAPI.h"
34 #include "clang/AST/StmtCXX.h"
35 #include "clang/AST/StmtOpenMP.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/TypeOrdering.h"
39 #include "clang/Basic/Builtins.h"
42 #include "clang/Basic/Module.h"
46 #include "clang/Basic/Specifiers.h"
48 #include "clang/Basic/TypeTraits.h"
50 #include "clang/Sema/CleanupInfo.h"
51 #include "clang/Sema/DeclSpec.h"
55 #include "clang/Sema/Ownership.h"
56 #include "clang/Sema/Scope.h"
57 #include "clang/Sema/SemaConcept.h"
59 #include "clang/Sema/Weak.h"
60 #include "llvm/ADT/ArrayRef.h"
61 #include "llvm/ADT/Optional.h"
62 #include "llvm/ADT/SetVector.h"
63 #include "llvm/ADT/SmallBitVector.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/SmallSet.h"
66 #include "llvm/ADT/SmallVector.h"
67 #include "llvm/ADT/TinyPtrVector.h"
68 #include "llvm/Frontend/OpenMP/OMPConstants.h"
69 #include <deque>
70 #include <memory>
71 #include <string>
72 #include <tuple>
73 #include <vector>
74 
75 namespace llvm {
76  class APSInt;
77  template <typename ValueT> struct DenseMapInfo;
78  template <typename ValueT, typename ValueInfoT> class DenseSet;
79  class SmallBitVector;
80  struct InlineAsmIdentifierInfo;
81 }
82 
83 namespace clang {
84  class ADLResult;
85  class ASTConsumer;
86  class ASTContext;
87  class ASTMutationListener;
88  class ASTReader;
89  class ASTWriter;
90  class ArrayType;
91  class ParsedAttr;
92  class BindingDecl;
93  class BlockDecl;
94  class CapturedDecl;
95  class CXXBasePath;
96  class CXXBasePaths;
97  class CXXBindTemporaryExpr;
99  class CXXConstructorDecl;
100  class CXXConversionDecl;
101  class CXXDeleteExpr;
102  class CXXDestructorDecl;
103  class CXXFieldCollector;
104  class CXXMemberCallExpr;
105  class CXXMethodDecl;
106  class CXXScopeSpec;
107  class CXXTemporary;
108  class CXXTryStmt;
109  class CallExpr;
110  class ClassTemplateDecl;
111  class ClassTemplatePartialSpecializationDecl;
112  class ClassTemplateSpecializationDecl;
113  class VarTemplatePartialSpecializationDecl;
114  class CodeCompleteConsumer;
115  class CodeCompletionAllocator;
116  class CodeCompletionTUInfo;
117  class CodeCompletionResult;
118  class CoroutineBodyStmt;
119  class Decl;
120  class DeclAccessPair;
121  class DeclContext;
122  class DeclRefExpr;
123  class DeclaratorDecl;
124  class DeducedTemplateArgument;
125  class DependentDiagnostic;
126  class DesignatedInitExpr;
127  class Designation;
128  class EnableIfAttr;
129  class EnumConstantDecl;
130  class Expr;
131  class ExtVectorType;
132  class FormatAttr;
133  class FriendDecl;
134  class FunctionDecl;
135  class FunctionProtoType;
136  class FunctionTemplateDecl;
137  class ImplicitConversionSequence;
139  class InitListExpr;
140  class InitializationKind;
141  class InitializationSequence;
142  class InitializedEntity;
143  class IntegerLiteral;
144  class LabelStmt;
145  class LambdaExpr;
146  class LangOptions;
147  class LocalInstantiationScope;
148  class LookupResult;
149  class MacroInfo;
151  class ModuleLoader;
152  class MultiLevelTemplateArgumentList;
153  class NamedDecl;
154  class ObjCCategoryDecl;
155  class ObjCCategoryImplDecl;
156  class ObjCCompatibleAliasDecl;
157  class ObjCContainerDecl;
158  class ObjCImplDecl;
159  class ObjCImplementationDecl;
160  class ObjCInterfaceDecl;
161  class ObjCIvarDecl;
162  template <class T> class ObjCList;
163  class ObjCMessageExpr;
164  class ObjCMethodDecl;
165  class ObjCPropertyDecl;
166  class ObjCProtocolDecl;
167  class OMPThreadPrivateDecl;
168  class OMPRequiresDecl;
169  class OMPDeclareReductionDecl;
170  class OMPDeclareSimdDecl;
171  class OMPClause;
172  struct OMPVarListLocTy;
173  struct OverloadCandidate;
174  enum class OverloadCandidateParamOrder : char;
176  class OverloadCandidateSet;
177  class OverloadExpr;
178  class ParenListExpr;
179  class ParmVarDecl;
180  class Preprocessor;
181  class PseudoDestructorTypeStorage;
182  class PseudoObjectExpr;
183  class QualType;
184  class StandardConversionSequence;
185  class Stmt;
186  class StringLiteral;
187  class SwitchStmt;
188  class TemplateArgument;
189  class TemplateArgumentList;
190  class TemplateArgumentLoc;
191  class TemplateDecl;
192  class TemplateInstantiationCallback;
193  class TemplateParameterList;
194  class TemplatePartialOrderingContext;
195  class TemplateTemplateParmDecl;
196  class Token;
197  class TypeAliasDecl;
198  class TypedefDecl;
199  class TypedefNameDecl;
200  class TypeLoc;
201  class TypoCorrectionConsumer;
202  class UnqualifiedId;
203  class UnresolvedLookupExpr;
204  class UnresolvedMemberExpr;
205  class UnresolvedSetImpl;
206  class UnresolvedSetIterator;
207  class UsingDecl;
208  class UsingShadowDecl;
209  class ValueDecl;
210  class VarDecl;
211  class VarTemplateSpecializationDecl;
212  class VisibilityAttr;
213  class VisibleDeclConsumer;
214  class IndirectFieldDecl;
215  struct DeductionFailureInfo;
216  class TemplateSpecCandidateSet;
217 
218 namespace sema {
219  class AccessedEntity;
220  class BlockScopeInfo;
221  class Capture;
222  class CapturedRegionScopeInfo;
223  class CapturingScopeInfo;
224  class CompoundScopeInfo;
225  class DelayedDiagnostic;
226  class DelayedDiagnosticPool;
227  class FunctionScopeInfo;
228  class LambdaScopeInfo;
229  class PossiblyUnreachableDiag;
230  class SemaPPCallbacks;
231  class TemplateDeductionInfo;
232 }
233 
234 namespace threadSafety {
235  class BeforeSet;
236  void threadSafetyCleanup(BeforeSet* Cache);
237 }
238 
239 // FIXME: No way to easily map from TemplateTypeParmTypes to
240 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
241 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
243 
244 /// Describes whether we've seen any nullability information for the given
245 /// file.
247  /// The first pointer declarator (of any pointer kind) in the file that does
248  /// not have a corresponding nullability annotation.
250 
251  /// The end location for the first pointer declarator in the file. Used for
252  /// placing fix-its.
254 
255  /// Which kind of pointer declarator we saw.
256  uint8_t PointerKind;
257 
258  /// Whether we saw any type nullability annotations in the given file.
259  bool SawTypeNullability = false;
260 };
261 
262 /// A mapping from file IDs to a record of whether we've seen nullability
263 /// information in that file.
265  /// A mapping from file IDs to the nullability information for each file ID.
266  llvm::DenseMap<FileID, FileNullability> Map;
267 
268  /// A single-element cache based on the file ID.
269  struct {
272  } Cache;
273 
274 public:
276  // Check the single-element cache.
277  if (file == Cache.File)
278  return Cache.Nullability;
279 
280  // It's not in the single-element cache; flush the cache if we have one.
281  if (!Cache.File.isInvalid()) {
282  Map[Cache.File] = Cache.Nullability;
283  }
284 
285  // Pull this entry into the cache.
286  Cache.File = file;
287  Cache.Nullability = Map[file];
288  return Cache.Nullability;
289  }
290 };
291 
292 /// Tracks expected type during expression parsing, for use in code completion.
293 /// The type is tied to a particular token, all functions that update or consume
294 /// the type take a start location of the token they are looking at as a
295 /// parameter. This avoids updating the type on hot paths in the parser.
297 public:
298  PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
299 
300  void enterCondition(Sema &S, SourceLocation Tok);
301  void enterReturn(Sema &S, SourceLocation Tok);
302  void enterVariableInit(SourceLocation Tok, Decl *D);
303  /// Handles e.g. BaseType{ .D = Tok...
305  const Designation &D);
306  /// Computing a type for the function argument may require running
307  /// overloading, so we postpone its computation until it is actually needed.
308  ///
309  /// Clients should be very careful when using this funciton, as it stores a
310  /// function_ref, clients should make sure all calls to get() with the same
311  /// location happen while function_ref is alive.
312  ///
313  /// The callback should also emit signature help as a side-effect, but only
314  /// if the completion point has been reached.
316  llvm::function_ref<QualType()> ComputeType);
317 
318  void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
319  void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
320  SourceLocation OpLoc);
321  void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
322  void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
323  void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
324  /// Handles all type casts, including C-style cast, C++ casts, etc.
326 
327  /// Get the expected type associated with this location, if any.
328  ///
329  /// If the location is a function argument, determining the expected type
330  /// involves considering all function overloads and the arguments so far.
331  /// In this case, signature help for these function overloads will be reported
332  /// as a side-effect (only if the completion point has been reached).
334  if (!Enabled || Tok != ExpectedLoc)
335  return QualType();
336  if (!Type.isNull())
337  return Type;
338  if (ComputeType)
339  return ComputeType();
340  return QualType();
341  }
342 
343 private:
344  bool Enabled;
345  /// Start position of a token for which we store expected type.
346  SourceLocation ExpectedLoc;
347  /// Expected type for a token starting at ExpectedLoc.
348  QualType Type;
349  /// A function to compute expected type at ExpectedLoc. It is only considered
350  /// if Type is null.
351  llvm::function_ref<QualType()> ComputeType;
352 };
353 
354 /// Sema - This implements semantic analysis and AST building for C.
355 class Sema final {
356  Sema(const Sema &) = delete;
357  void operator=(const Sema &) = delete;
358 
359  ///Source of additional semantic information.
360  ExternalSemaSource *ExternalSource;
361 
362  ///Whether Sema has generated a multiplexer and has to delete it.
363  bool isMultiplexExternalSource;
364 
365  static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
366 
367  bool isVisibleSlow(const NamedDecl *D);
368 
369  /// Determine whether two declarations should be linked together, given that
370  /// the old declaration might not be visible and the new declaration might
371  /// not have external linkage.
372  bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
373  const NamedDecl *New) {
374  if (isVisible(Old))
375  return true;
376  // See comment in below overload for why it's safe to compute the linkage
377  // of the new declaration here.
378  if (New->isExternallyDeclarable()) {
379  assert(Old->isExternallyDeclarable() &&
380  "should not have found a non-externally-declarable previous decl");
381  return true;
382  }
383  return false;
384  }
385  bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
386 
387  void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
388  QualType ResultTy,
389  ArrayRef<QualType> Args);
390 
391 public:
392  /// The maximum alignment, same as in llvm::Value. We duplicate them here
393  /// because that allows us not to duplicate the constants in clang code,
394  /// which we must to since we can't directly use the llvm constants.
395  /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
396  ///
397  /// This is the greatest alignment value supported by load, store, and alloca
398  /// instructions, and global values.
399  static const unsigned MaxAlignmentExponent = 30;
400  static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
401 
405 
408 
415 
416  /// Flag indicating whether or not to collect detailed statistics.
418 
419  /// Code-completion consumer.
421 
422  /// CurContext - This is the current declaration context of parsing.
424 
425  /// Generally null except when we temporarily switch decl contexts,
426  /// like in \see ActOnObjCTemporaryExitContainerContext.
428 
429  /// VAListTagName - The declaration name corresponding to __va_list_tag.
430  /// This is used as part of a hack to omit that class from ADL results.
432 
433  bool MSStructPragmaOn; // True when \#pragma ms_struct on
434 
435  /// Controls member pointer representation format under the MS ABI.
438 
439  /// Stack of active SEH __finally scopes. Can be empty.
441 
442  /// Source location for newly created implicit MSInheritanceAttrs
444 
445  /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
446  /// `TransformTypos` in order to keep track of any TypoExprs that are created
447  /// recursively during typo correction and wipe them away if the correction
448  /// fails.
450 
451  /// pragma clang section kind
454  PCSK_BSS = 1,
459  };
460 
462  PCSA_Set = 0,
464  };
465 
468  bool Valid = false;
470  };
471 
477 
479  PSK_Reset = 0x0, // #pragma ()
480  PSK_Set = 0x1, // #pragma (value)
481  PSK_Push = 0x2, // #pragma (push[, id])
482  PSK_Pop = 0x4, // #pragma (pop[, id])
483  PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
484  PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
485  PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
486  };
487 
488  // #pragma pack and align.
490  public:
491  // `Native` represents default align mode, which may vary based on the
492  // platform.
493  enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
494 
495  // #pragma pack info constructor
496  AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
497  : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
498  assert(Num == PackNumber && "The pack number has been truncated.");
499  }
500 
501  // #pragma align info constructor
503  : PackAttr(false), AlignMode(M),
504  PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
505 
506  explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
507 
509 
510  // When a AlignPackInfo itself cannot be used, this returns an 32-bit
511  // integer encoding for it. This should only be passed to
512  // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
513  static uint32_t getRawEncoding(const AlignPackInfo &Info) {
514  std::uint32_t Encoding{};
515  if (Info.IsXLStack())
516  Encoding |= IsXLMask;
517 
518  Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
519 
520  if (Info.IsPackAttr())
521  Encoding |= PackAttrMask;
522 
523  Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
524 
525  return Encoding;
526  }
527 
529  bool IsXL = static_cast<bool>(Encoding & IsXLMask);
531  static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
532  int PackNumber = (Encoding & PackNumMask) >> 4;
533 
534  if (Encoding & PackAttrMask)
535  return AlignPackInfo(M, PackNumber, IsXL);
536 
537  return AlignPackInfo(M, IsXL);
538  }
539 
540  bool IsPackAttr() const { return PackAttr; }
541 
542  bool IsAlignAttr() const { return !PackAttr; }
543 
544  Mode getAlignMode() const { return AlignMode; }
545 
546  unsigned getPackNumber() const { return PackNumber; }
547 
548  bool IsPackSet() const {
549  // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
550  // attriute on a decl.
551  return PackNumber != UninitPackVal && PackNumber != 0;
552  }
553 
554  bool IsXLStack() const { return XLStack; }
555 
556  bool operator==(const AlignPackInfo &Info) const {
557  return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
558  std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
559  Info.XLStack);
560  }
561 
562  bool operator!=(const AlignPackInfo &Info) const {
563  return !(*this == Info);
564  }
565 
566  private:
567  /// \brief True if this is a pragma pack attribute,
568  /// not a pragma align attribute.
569  bool PackAttr;
570 
571  /// \brief The alignment mode that is in effect.
572  Mode AlignMode;
573 
574  /// \brief The pack number of the stack.
575  unsigned char PackNumber;
576 
577  /// \brief True if it is a XL #pragma align/pack stack.
578  bool XLStack;
579 
580  /// \brief Uninitialized pack value.
581  static constexpr unsigned char UninitPackVal = -1;
582 
583  // Masks to encode and decode an AlignPackInfo.
584  static constexpr uint32_t IsXLMask{0x0000'0001};
585  static constexpr uint32_t AlignModeMask{0x0000'0006};
586  static constexpr uint32_t PackAttrMask{0x00000'0008};
587  static constexpr uint32_t PackNumMask{0x0000'01F0};
588  };
589 
590  template<typename ValueType>
591  struct PragmaStack {
592  struct Slot {
593  llvm::StringRef StackSlotLabel;
594  ValueType Value;
597  Slot(llvm::StringRef StackSlotLabel, ValueType Value,
602  };
603 
604  void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
605  llvm::StringRef StackSlotLabel, ValueType Value) {
606  if (Action == PSK_Reset) {
608  CurrentPragmaLocation = PragmaLocation;
609  return;
610  }
611  if (Action & PSK_Push)
612  Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
613  PragmaLocation);
614  else if (Action & PSK_Pop) {
615  if (!StackSlotLabel.empty()) {
616  // If we've got a label, try to find it and jump there.
617  auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
618  return x.StackSlotLabel == StackSlotLabel;
619  });
620  // If we found the label so pop from there.
621  if (I != Stack.rend()) {
622  CurrentValue = I->Value;
623  CurrentPragmaLocation = I->PragmaLocation;
624  Stack.erase(std::prev(I.base()), Stack.end());
625  }
626  } else if (!Stack.empty()) {
627  // We do not have a label, just pop the last entry.
628  CurrentValue = Stack.back().Value;
629  CurrentPragmaLocation = Stack.back().PragmaLocation;
630  Stack.pop_back();
631  }
632  }
633  if (Action & PSK_Set) {
635  CurrentPragmaLocation = PragmaLocation;
636  }
637  }
638 
639  // MSVC seems to add artificial slots to #pragma stacks on entering a C++
640  // method body to restore the stacks on exit, so it works like this:
641  //
642  // struct S {
643  // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
644  // void Method {}
645  // #pragma <name>(pop, InternalPragmaSlot)
646  // };
647  //
648  // It works even with #pragma vtordisp, although MSVC doesn't support
649  // #pragma vtordisp(push [, id], n)
650  // syntax.
651  //
652  // Push / pop a named sentinel slot.
653  void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
654  assert((Action == PSK_Push || Action == PSK_Pop) &&
655  "Can only push / pop #pragma stack sentinels!");
657  }
658 
659  // Constructors.
660  explicit PragmaStack(const ValueType &Default)
662 
663  bool hasValue() const { return CurrentValue != DefaultValue; }
664 
666  ValueType DefaultValue; // Value used for PSK_Reset action.
667  ValueType CurrentValue;
669  };
670  // FIXME: We should serialize / deserialize these if they occur in a PCH (but
671  // we shouldn't do so if they're in a module).
672 
673  /// Whether to insert vtordisps prior to virtual bases in the Microsoft
674  /// C++ ABI. Possible values are 0, 1, and 2, which mean:
675  ///
676  /// 0: Suppress all vtordisps
677  /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
678  /// structors
679  /// 2: Always insert vtordisps to support RTTI on partially constructed
680  /// objects
683  // The current #pragma align/pack values and locations at each #include.
688  };
690  // Segment #pragmas.
695 
696  // This stack tracks the current state of Sema.CurFPFeatures.
699  FPOptionsOverride result;
700  if (!FpPragmaStack.hasValue()) {
701  result = FPOptionsOverride();
702  } else {
703  result = FpPragmaStack.CurrentValue;
704  }
705  return result;
706  }
707 
708  // RAII object to push / pop sentinel slots for all MS #pragma stacks.
709  // Actions should be performed only if we enter / exit a C++ method body.
711  public:
712  PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
714 
715  private:
716  Sema &S;
717  StringRef SlotLabel;
718  bool ShouldAct;
719  };
720 
721  /// A mapping that describes the nullability we've seen in each header file.
723 
724  /// Last section used with #pragma init_seg.
727 
728  /// VisContext - Manages the stack for \#pragma GCC visibility.
729  void *VisContext; // Really a "PragmaVisStack*"
730 
731  /// This an attribute introduced by \#pragma clang attribute.
736  bool IsUsed;
737  };
738 
739  /// A push'd group of PragmaAttributeEntries.
741  /// The location of the push attribute.
743  /// The namespace of this push group.
746  };
747 
749 
750  /// The declaration that is currently receiving an attribute from the
751  /// #pragma attribute stack.
753 
754  /// This represents the last location of a "#pragma clang optimize off"
755  /// directive if such a directive has not been closed by an "on" yet. If
756  /// optimizations are currently "on", this is set to an invalid location.
758 
759  /// Flag indicating if Sema is building a recovery call expression.
760  ///
761  /// This flag is used to avoid building recovery call expressions
762  /// if Sema is already doing so, which would cause infinite recursions.
764 
765  /// Used to control the generation of ExprWithCleanups.
767 
768  /// ExprCleanupObjects - This is the stack of objects requiring
769  /// cleanup that are created by the current full expression.
771 
772  /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
773  /// to a variable (constant) that may or may not be odr-used in this Expr, and
774  /// we won't know until all lvalue-to-rvalue and discarded value conversions
775  /// have been applied to all subexpressions of the enclosing full expression.
776  /// This is cleared at the end of each full expression.
777  using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
780 
781  std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
782 
783  /// Stack containing information about each of the nested
784  /// function, block, and method scopes that are currently active.
786 
787  /// The index of the first FunctionScope that corresponds to the current
788  /// context.
789  unsigned FunctionScopesStart = 0;
790 
792  return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
793  FunctionScopes.end());
794  }
795 
796  /// Stack containing information needed when in C++2a an 'auto' is encountered
797  /// in a function declaration parameter type specifier in order to invent a
798  /// corresponding template parameter in the enclosing abbreviated function
799  /// template. This information is also present in LambdaScopeInfo, stored in
800  /// the FunctionScopes stack.
802 
803  /// The index of the first InventedParameterInfo that refers to the current
804  /// context.
806 
808  return llvm::makeArrayRef(InventedParameterInfos.begin() +
810  InventedParameterInfos.end());
811  }
812 
816 
817  /// ExtVectorDecls - This is a list all the extended vector types. This allows
818  /// us to associate a raw vector type with one of the ext_vector type names.
819  /// This is only necessary for issuing pretty diagnostics.
821 
822  /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
823  std::unique_ptr<CXXFieldCollector> FieldCollector;
824 
826 
827  /// Set containing all declared private fields that are not used.
829 
830  /// Set containing all typedefs that are likely unused.
833 
834  /// Delete-expressions to be analyzed at the end of translation unit
835  ///
836  /// This list contains class members, and locations of delete-expressions
837  /// that could not be proven as to whether they mismatch with new-expression
838  /// used in initializer of the field.
839  typedef std::pair<SourceLocation, bool> DeleteExprLoc;
841  llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
842 
844 
845  /// PureVirtualClassDiagSet - a set of class declarations which we have
846  /// emitted a list of pure virtual functions. Used to prevent emitting the
847  /// same list more than once.
848  std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
849 
850  /// ParsingInitForAutoVars - a set of declarations with auto types for which
851  /// we are currently parsing the initializer.
853 
854  /// Look for a locally scoped extern "C" declaration by the given name.
856 
860 
861  /// All the tentative definitions encountered in the TU.
863 
864  /// All the external declarations encoutered and used in the TU.
866 
870 
871  /// The set of file scoped decls seen so far that have not been used
872  /// and must warn if not used. Only contains the first declaration.
874 
878 
879  /// All the delegating constructors seen so far in the file, used for
880  /// cycle detection at the end of the TU.
882 
883  /// All the overriding functions seen during a class definition
884  /// that had their exception spec checks delayed, plus the overridden
885  /// function.
888 
889  /// All the function redeclarations seen during a class definition that had
890  /// their exception spec checks delayed, plus the prior declaration they
891  /// should be checked against. Except during error recovery, the new decl
892  /// should always be a friend declaration, as that's the only valid way to
893  /// redeclare a special member before its class is complete.
896 
897  typedef llvm::MapVector<const FunctionDecl *,
898  std::unique_ptr<LateParsedTemplate>>
901 
902  /// Callback to the parser to parse templated functions when needed.
903  typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
904  typedef void LateTemplateParserCleanupCB(void *P);
908 
910  LateTemplateParserCleanupCB *LTPCleanup,
911  void *P) {
912  LateTemplateParser = LTP;
913  LateTemplateParserCleanup = LTPCleanup;
914  OpaqueParser = P;
915  }
916 
917  // Does the work necessary to deal with a SYCL kernel lambda. At the moment,
918  // this just marks the list of lambdas required to name the kernel.
919  void AddSYCLKernelLambda(const FunctionDecl *FD);
920 
921  class DelayedDiagnostics;
922 
924  sema::DelayedDiagnosticPool *SavedPool;
926  };
929 
930  /// A class which encapsulates the logic for delaying diagnostics
931  /// during parsing and other processing.
933  /// The current pool of diagnostics into which delayed
934  /// diagnostics should go.
936 
937  public:
938  DelayedDiagnostics() : CurPool(nullptr) {}
939 
940  /// Adds a delayed diagnostic.
941  void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
942 
943  /// Determines whether diagnostics should be delayed.
944  bool shouldDelayDiagnostics() { return CurPool != nullptr; }
945 
946  /// Returns the current delayed-diagnostics pool.
948  return CurPool;
949  }
950 
951  /// Enter a new scope. Access and deprecation diagnostics will be
952  /// collected in this pool.
955  state.SavedPool = CurPool;
956  CurPool = &pool;
957  return state;
958  }
959 
960  /// Leave a delayed-diagnostic state that was previously pushed.
961  /// Do not emit any of the diagnostics. This is performed as part
962  /// of the bookkeeping of popping a pool "properly".
964  CurPool = state.SavedPool;
965  }
966 
967  /// Enter a new scope where access and deprecation diagnostics are
968  /// not delayed.
971  state.SavedPool = CurPool;
972  CurPool = nullptr;
973  return state;
974  }
975 
976  /// Undo a previous pushUndelayed().
978  assert(CurPool == nullptr);
979  CurPool = state.SavedPool;
980  }
982 
983  /// A RAII object to temporarily push a declaration context.
984  class ContextRAII {
985  private:
986  Sema &S;
987  DeclContext *SavedContext;
988  ProcessingContextState SavedContextState;
989  QualType SavedCXXThisTypeOverride;
990  unsigned SavedFunctionScopesStart;
991  unsigned SavedInventedParameterInfosStart;
992 
993  public:
994  ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
995  : S(S), SavedContext(S.CurContext),
996  SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
997  SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
998  SavedFunctionScopesStart(S.FunctionScopesStart),
999  SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1000  {
1001  assert(ContextToPush && "pushing null context");
1002  S.CurContext = ContextToPush;
1003  if (NewThisContext)
1004  S.CXXThisTypeOverride = QualType();
1005  // Any saved FunctionScopes do not refer to this context.
1006  S.FunctionScopesStart = S.FunctionScopes.size();
1007  S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1008  }
1009 
1010  void pop() {
1011  if (!SavedContext) return;
1012  S.CurContext = SavedContext;
1013  S.DelayedDiagnostics.popUndelayed(SavedContextState);
1014  S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1015  S.FunctionScopesStart = SavedFunctionScopesStart;
1016  S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1017  SavedContext = nullptr;
1018  }
1019 
1021  pop();
1022  }
1023  };
1024 
1025  /// Whether the AST is currently being rebuilt to correct immediate
1026  /// invocations. Immediate invocation candidates and references to consteval
1027  /// functions aren't tracked when this is set.
1029 
1030  /// Used to change context to isConstantEvaluated without pushing a heavy
1031  /// ExpressionEvaluationContextRecord object.
1033 
1035  return ExprEvalContexts.back().isConstantEvaluated() ||
1037  }
1038 
1039  /// RAII object to handle the state changes required to synthesize
1040  /// a function body.
1042  Sema &S;
1043  Sema::ContextRAII SavedContext;
1044  bool PushedCodeSynthesisContext = false;
1045 
1046  public:
1048  : S(S), SavedContext(S, DC) {
1049  S.PushFunctionScope();
1050  S.PushExpressionEvaluationContext(
1052  if (auto *FD = dyn_cast<FunctionDecl>(DC))
1053  FD->setWillHaveBody(true);
1054  else
1055  assert(isa<ObjCMethodDecl>(DC));
1056  }
1057 
1059  assert(!PushedCodeSynthesisContext);
1060 
1063  Ctx.PointOfInstantiation = UseLoc;
1064  Ctx.Entity = cast<Decl>(S.CurContext);
1065  S.pushCodeSynthesisContext(Ctx);
1066 
1067  PushedCodeSynthesisContext = true;
1068  }
1069 
1071  if (PushedCodeSynthesisContext)
1072  S.popCodeSynthesisContext();
1073  if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1074  FD->setWillHaveBody(false);
1075  S.PopExpressionEvaluationContext();
1076  S.PopFunctionScopeInfo();
1077  }
1078  };
1079 
1080  /// WeakUndeclaredIdentifiers - Identifiers contained in
1081  /// \#pragma weak before declared. rare. may alias another
1082  /// identifier, declared or undeclared
1083  llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
1084 
1085  /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1086  /// \#pragma redefine_extname before declared. Used in Solaris system headers
1087  /// to define functions that occur in multiple standards to call the version
1088  /// in the currently selected standard.
1089  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1090 
1091 
1092  /// Load weak undeclared identifiers from the external source.
1094 
1095  /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1096  /// \#pragma weak during processing of other Decls.
1097  /// I couldn't figure out a clean way to generate these in-line, so
1098  /// we store them here and handle separately -- which is a hack.
1099  /// It would be best to refactor this.
1101 
1103 
1104  /// Translation Unit Scope - useful to Objective-C actions that need
1105  /// to lookup file scope declarations in the "ordinary" C decl namespace.
1106  /// For example, user-defined classes, built-in "id" type, etc.
1108 
1109  /// The C++ "std" namespace, where the standard library resides.
1111 
1112  /// The C++ "std::bad_alloc" class, which is defined by the C++
1113  /// standard library.
1115 
1116  /// The C++ "std::align_val_t" enum class, which is defined by the C++
1117  /// standard library.
1119 
1120  /// The C++ "std::experimental" namespace, where the experimental parts
1121  /// of the standard library resides.
1123 
1124  /// The C++ "std::initializer_list" template, which is defined in
1125  /// <initializer_list>.
1127 
1128  /// The C++ "std::coroutine_traits" template, which is defined in
1129  /// <coroutine_traits>
1131 
1132  /// The C++ "type_info" declaration, which is defined in <typeinfo>.
1134 
1135  /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1137 
1138  /// Caches identifiers/selectors for NSFoundation APIs.
1139  std::unique_ptr<NSAPI> NSAPIObj;
1140 
1141  /// The declaration of the Objective-C NSNumber class.
1143 
1144  /// The declaration of the Objective-C NSValue class.
1146 
1147  /// Pointer to NSNumber type (NSNumber *).
1149 
1150  /// Pointer to NSValue type (NSValue *).
1152 
1153  /// The Objective-C NSNumber methods used to create NSNumber literals.
1155 
1156  /// The declaration of the Objective-C NSString class.
1158 
1159  /// Pointer to NSString type (NSString *).
1161 
1162  /// The declaration of the stringWithUTF8String: method.
1164 
1165  /// The declaration of the valueWithBytes:objCType: method.
1167 
1168  /// The declaration of the Objective-C NSArray class.
1170 
1171  /// The declaration of the arrayWithObjects:count: method.
1173 
1174  /// The declaration of the Objective-C NSDictionary class.
1176 
1177  /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1179 
1180  /// id<NSCopying> type.
1182 
1183  /// will hold 'respondsToSelector:'
1185 
1186  /// A flag to remember whether the implicit forms of operator new and delete
1187  /// have been declared.
1189 
1190  /// Describes how the expressions currently being parsed are
1191  /// evaluated at run-time, if at all.
1193  /// The current expression and its subexpressions occur within an
1194  /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1195  /// \c sizeof, where the type of the expression may be significant but
1196  /// no code will be generated to evaluate the value of the expression at
1197  /// run time.
1198  Unevaluated,
1199 
1200  /// The current expression occurs within a braced-init-list within
1201  /// an unevaluated operand. This is mostly like a regular unevaluated
1202  /// context, except that we still instantiate constexpr functions that are
1203  /// referenced here so that we can perform narrowing checks correctly.
1205 
1206  /// The current expression occurs within a discarded statement.
1207  /// This behaves largely similarly to an unevaluated operand in preventing
1208  /// definitions from being required, but not in other ways.
1210 
1211  /// The current expression occurs within an unevaluated
1212  /// operand that unconditionally permits abstract references to
1213  /// fields, such as a SIZE operator in MS-style inline assembly.
1215 
1216  /// The current context is "potentially evaluated" in C++11 terms,
1217  /// but the expression is evaluated at compile-time (like the values of
1218  /// cases in a switch statement).
1220 
1221  /// The current expression is potentially evaluated at run time,
1222  /// which means that code may be generated to evaluate the value of the
1223  /// expression at run time.
1225 
1226  /// The current expression is potentially evaluated, but any
1227  /// declarations referenced inside that expression are only used if
1228  /// in fact the current expression is used.
1229  ///
1230  /// This value is used when parsing default function arguments, for which
1231  /// we would like to provide diagnostics (e.g., passing non-POD arguments
1232  /// through varargs) but do not want to mark declarations as "referenced"
1233  /// until the default argument is used.
1235  };
1236 
1237  using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1238 
1239  /// Data structure used to record current or nested
1240  /// expression evaluation contexts.
1242  /// The expression evaluation context.
1244 
1245  /// Whether the enclosing context needed a cleanup.
1247 
1248  /// The number of active cleanup objects when we entered
1249  /// this expression evaluation context.
1251 
1252  /// The number of typos encountered during this expression evaluation
1253  /// context (i.e. the number of TypoExprs created).
1254  unsigned NumTypos;
1255 
1257 
1258  /// The lambdas that are present within this context, if it
1259  /// is indeed an unevaluated context.
1261 
1262  /// The declaration that provides context for lambda expressions
1263  /// and block literals if the normal declaration context does not
1264  /// suffice, e.g., in a default function argument.
1266 
1267  /// If we are processing a decltype type, a set of call expressions
1268  /// for which we have deferred checking the completeness of the return type.
1270 
1271  /// If we are processing a decltype type, a set of temporary binding
1272  /// expressions for which we have deferred checking the destructor.
1274 
1276 
1277  /// Expressions appearing as the LHS of a volatile assignment in this
1278  /// context. We produce a warning for these when popping the context if
1279  /// they are not discarded-value expressions nor unevaluated operands.
1281 
1282  /// Set of candidates for starting an immediate invocation.
1284 
1285  /// Set of DeclRefExprs referencing a consteval function when used in a
1286  /// context not already known to be immediately invoked.
1288 
1289  /// \brief Describes whether we are in an expression constext which we have
1290  /// to handle differently.
1293  } ExprContext;
1294 
1296  unsigned NumCleanupObjects,
1303 
1304  bool isUnevaluated() const {
1308  }
1309  bool isConstantEvaluated() const {
1311  }
1312  };
1313 
1314  /// A stack of expression evaluation contexts.
1316 
1317  /// Emit a warning for all pending noderef expressions that we recorded.
1319 
1320  /// Compute the mangling number context for a lambda expression or
1321  /// block literal. Also return the extra mangling decl if any.
1322  ///
1323  /// \param DC - The DeclContext containing the lambda expression or
1324  /// block literal.
1325  std::tuple<MangleNumberingContext *, Decl *>
1327 
1328 
1329  /// SpecialMemberOverloadResult - The overloading result for a special member
1330  /// function.
1331  ///
1332  /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1333  /// integer are used to determine whether overload resolution succeeded.
1335  public:
1336  enum Kind {
1340  };
1341 
1342  private:
1343  llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1344 
1345  public:
1348  : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1349 
1350  CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1351  void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1352 
1353  Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1354  void setKind(Kind K) { Pair.setInt(K); }
1355  };
1356 
1358  : public llvm::FastFoldingSetNode,
1360  public:
1361  SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1362  : FastFoldingSetNode(ID)
1363  {}
1364  };
1365 
1366  /// A cache of special member function overload resolution results
1367  /// for C++ records.
1368  llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1369 
1370  /// A cache of the flags available in enumerations with the flag_bits
1371  /// attribute.
1372  mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1373 
1374  /// The kind of translation unit we are processing.
1375  ///
1376  /// When we're processing a complete translation unit, Sema will perform
1377  /// end-of-translation-unit semantic tasks (such as creating
1378  /// initializers for tentative definitions in C) once parsing has
1379  /// completed. Modules and precompiled headers perform different kinds of
1380  /// checks.
1382 
1383  llvm::BumpPtrAllocator BumpAlloc;
1384 
1385  /// The number of SFINAE diagnostics that have been trapped.
1387 
1388  typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1390 
1391  /// A mapping from parameters with unparsed default arguments to the
1392  /// set of instantiations of each parameter.
1393  ///
1394  /// This mapping is a temporary data structure used when parsing
1395  /// nested class templates or nested classes of class templates,
1396  /// where we might end up instantiating an inner class before the
1397  /// default arguments of its methods have been parsed.
1399 
1400  // Contains the locations of the beginning of unparsed default
1401  // argument locations.
1402  llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1403 
1404  /// UndefinedInternals - all the used, undefined objects which require a
1405  /// definition in this translation unit.
1406  llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1407 
1408  /// Determine if VD, which must be a variable or function, is an external
1409  /// symbol that nonetheless can't be referenced from outside this translation
1410  /// unit because its type has no linkage and it's not extern "C".
1412 
1413  /// Obtain a sorted list of functions that are undefined but ODR-used.
1414  void getUndefinedButUsed(
1415  SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1416 
1417  /// Retrieves list of suspicious delete-expressions that will be checked at
1418  /// the end of translation unit.
1419  const llvm::MapVector<FieldDecl *, DeleteLocs> &
1421 
1423  public:
1424  using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1425  using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1426  iterator begin() { return Methods.begin(); }
1427  iterator end() { return Methods.end(); }
1428  iterator find(Selector Sel) { return Methods.find(Sel); }
1429  std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1430  return Methods.insert(Val);
1431  }
1432  int count(Selector Sel) const { return Methods.count(Sel); }
1433  bool empty() const { return Methods.empty(); }
1434 
1435  private:
1436  llvm::DenseMap<Selector, Lists> Methods;
1437  };
1438 
1439  /// Method Pool - allows efficient lookup when typechecking messages to "id".
1440  /// We need to maintain a list, since selectors can have differing signatures
1441  /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1442  /// of selectors are "overloaded").
1443  /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1444  /// methods inside categories with a particular selector.
1446 
1447  /// Method selectors used in a \@selector expression. Used for implementation
1448  /// of -Wselector.
1449  llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1450 
1451  /// List of SourceLocations where 'self' is implicitly retained inside a
1452  /// block.
1455 
1456  /// Kinds of C++ special members.
1465  };
1466 
1467  typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1469 
1470  /// The C++ special members which we are currently in the process of
1471  /// declaring. If this process recursively triggers the declaration of the
1472  /// same special member, we should act as if it is not yet declared.
1474 
1475  /// Kinds of defaulted comparison operator functions.
1476  enum class DefaultedComparisonKind : unsigned char {
1477  /// This is not a defaultable comparison operator.
1478  None,
1479  /// This is an operator== that should be implemented as a series of
1480  /// subobject comparisons.
1481  Equal,
1482  /// This is an operator<=> that should be implemented as a series of
1483  /// subobject comparisons.
1484  ThreeWay,
1485  /// This is an operator!= that should be implemented as a rewrite in terms
1486  /// of a == comparison.
1487  NotEqual,
1488  /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1489  /// terms of a <=> comparison.
1490  Relational,
1491  };
1492 
1493  /// The function definitions which were renamed as part of typo-correction
1494  /// to match their respective declarations. We want to keep track of them
1495  /// to ensure that we don't emit a "redefinition" error if we encounter a
1496  /// correctly named definition after the renamed definition.
1498 
1499  /// Stack of types that correspond to the parameter entities that are
1500  /// currently being copy-initialized. Can be empty.
1502 
1503  void ReadMethodPool(Selector Sel);
1505 
1506  /// Private Helper predicate to check for 'self'.
1507  bool isSelfExpr(Expr *RExpr);
1508  bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1509 
1510  /// Cause the active diagnostic on the DiagosticsEngine to be
1511  /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1512  /// should not be used elsewhere.
1513  void EmitCurrentDiagnostic(unsigned DiagID);
1514 
1515  /// Records and restores the CurFPFeatures state on entry/exit of compound
1516  /// statements.
1518  public:
1519  FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) {
1520  OldOverrides = S.FpPragmaStack.CurrentValue;
1521  }
1523  S.CurFPFeatures = OldFPFeaturesState;
1524  S.FpPragmaStack.CurrentValue = OldOverrides;
1525  }
1526  FPOptionsOverride getOverrides() { return OldOverrides; }
1527 
1528  private:
1529  Sema& S;
1530  FPOptions OldFPFeaturesState;
1531  FPOptionsOverride OldOverrides;
1532  };
1533 
1534  void addImplicitTypedef(StringRef Name, QualType T);
1535 
1536  bool WarnedStackExhausted = false;
1537 
1538  /// Increment when we find a reference; decrement when we find an ignored
1539  /// assignment. Ultimately the value is 0 if every reference is an ignored
1540  /// assignment.
1541  llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1542 
1544 
1545 public:
1546  Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1548  CodeCompleteConsumer *CompletionConsumer = nullptr);
1549  ~Sema();
1550 
1551  /// Perform initialization that occurs after the parser has been
1552  /// initialized but before it parses anything.
1553  void Initialize();
1554 
1555  /// This virtual key function only exists to limit the emission of debug info
1556  /// describing the Sema class. GCC and Clang only emit debug info for a class
1557  /// with a vtable when the vtable is emitted. Sema is final and not
1558  /// polymorphic, but the debug info size savings are so significant that it is
1559  /// worth adding a vtable just to take advantage of this optimization.
1560  virtual void anchor();
1561 
1562  const LangOptions &getLangOpts() const { return LangOpts; }
1565 
1568  Preprocessor &getPreprocessor() const { return PP; }
1569  ASTContext &getASTContext() const { return Context; }
1570  ASTConsumer &getASTConsumer() const { return Consumer; }
1572  ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1574  StringRef Platform);
1575 
1576  ///Registers an external source. If an external source already exists,
1577  /// creates a multiplex external source and appends to it.
1578  ///
1579  ///\param[in] E - A non-null external sema source.
1580  ///
1582 
1583  void PrintStats() const;
1584 
1585  /// Warn that the stack is nearly exhausted.
1587 
1588  /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1589  /// guaranteed). Produces a warning if we're low on stack space and allocates
1590  /// more in that case. Use this in code that may recurse deeply (for example,
1591  /// in template instantiation) to avoid stack overflow.
1593  llvm::function_ref<void()> Fn);
1594 
1595  /// Helper class that creates diagnostics with optional
1596  /// template instantiation stacks.
1597  ///
1598  /// This class provides a wrapper around the basic DiagnosticBuilder
1599  /// class that emits diagnostics. ImmediateDiagBuilder is
1600  /// responsible for emitting the diagnostic (as DiagnosticBuilder
1601  /// does) and, if the diagnostic comes from inside a template
1602  /// instantiation, printing the template instantiation stack as
1603  /// well.
1605  Sema &SemaRef;
1606  unsigned DiagID;
1607 
1608  public:
1609  ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1610  : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1611  ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1612  : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1613 
1614  // This is a cunning lie. DiagnosticBuilder actually performs move
1615  // construction in its copy constructor (but due to varied uses, it's not
1616  // possible to conveniently express this as actual move construction). So
1617  // the default copy ctor here is fine, because the base class disables the
1618  // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1619  // in that case anwyay.
1620  ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1621 
1623  // If we aren't active, there is nothing to do.
1624  if (!isActive()) return;
1625 
1626  // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1627  // builder itself so it won't emit the diagnostic in its own destructor.
1628  //
1629  // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1630  // do its own needless checks to see if the diagnostic needs to be
1631  // emitted. However, because we take care to ensure that the builder
1632  // objects never escape, a sufficiently smart compiler will be able to
1633  // eliminate that code.
1634  Clear();
1635 
1636  // Dispatch to Sema to emit the diagnostic.
1637  SemaRef.EmitCurrentDiagnostic(DiagID);
1638  }
1639 
1640  /// Teach operator<< to produce an object of the correct type.
1641  template <typename T>
1642  friend const ImmediateDiagBuilder &
1644  const DiagnosticBuilder &BaseDiag = Diag;
1645  BaseDiag << Value;
1646  return Diag;
1647  }
1648 
1649  // It is necessary to limit this to rvalue reference to avoid calling this
1650  // function with a bitfield lvalue argument since non-const reference to
1651  // bitfield is not allowed.
1652  template <typename T, typename = typename std::enable_if<
1653  !std::is_lvalue_reference<T>::value>::type>
1654  const ImmediateDiagBuilder &operator<<(T &&V) const {
1655  const DiagnosticBuilder &BaseDiag = *this;
1656  BaseDiag << std::move(V);
1657  return *this;
1658  }
1659  };
1660 
1661  /// A generic diagnostic builder for errors which may or may not be deferred.
1662  ///
1663  /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1664  /// which are not allowed to appear inside __device__ functions and are
1665  /// allowed to appear in __host__ __device__ functions only if the host+device
1666  /// function is never codegen'ed.
1667  ///
1668  /// To handle this, we use the notion of "deferred diagnostics", where we
1669  /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1670  ///
1671  /// This class lets you emit either a regular diagnostic, a deferred
1672  /// diagnostic, or no diagnostic at all, according to an argument you pass to
1673  /// its constructor, thus simplifying the process of creating these "maybe
1674  /// deferred" diagnostics.
1676  public:
1677  enum Kind {
1678  /// Emit no diagnostics.
1680  /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1682  /// Emit the diagnostic immediately, and, if it's a warning or error, also
1683  /// emit a call stack showing how this function can be reached by an a
1684  /// priori known-emitted function.
1686  /// Create a deferred diagnostic, which is emitted only if the function
1687  /// it's attached to is codegen'ed. Also emit a call stack as with
1688  /// K_ImmediateWithCallStack.
1690  };
1691 
1692  SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1693  FunctionDecl *Fn, Sema &S);
1695  SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1697 
1698  bool isImmediate() const { return ImmediateDiag.hasValue(); }
1699 
1700  /// Convertible to bool: True if we immediately emitted an error, false if
1701  /// we didn't emit an error or we created a deferred error.
1702  ///
1703  /// Example usage:
1704  ///
1705  /// if (SemaDiagnosticBuilder(...) << foo << bar)
1706  /// return ExprError();
1707  ///
1708  /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1709  /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1710  operator bool() const { return isImmediate(); }
1711 
1712  template <typename T>
1713  friend const SemaDiagnosticBuilder &
1715  if (Diag.ImmediateDiag.hasValue())
1716  *Diag.ImmediateDiag << Value;
1717  else if (Diag.PartialDiagId.hasValue())
1718  Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1719  << Value;
1720  return Diag;
1721  }
1722 
1723  // It is necessary to limit this to rvalue reference to avoid calling this
1724  // function with a bitfield lvalue argument since non-const reference to
1725  // bitfield is not allowed.
1726  template <typename T, typename = typename std::enable_if<
1727  !std::is_lvalue_reference<T>::value>::type>
1728  const SemaDiagnosticBuilder &operator<<(T &&V) const {
1729  if (ImmediateDiag.hasValue())
1730  *ImmediateDiag << std::move(V);
1731  else if (PartialDiagId.hasValue())
1732  S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1733  return *this;
1734  }
1735 
1736  friend const SemaDiagnosticBuilder &
1738  if (Diag.ImmediateDiag.hasValue())
1739  PD.Emit(*Diag.ImmediateDiag);
1740  else if (Diag.PartialDiagId.hasValue())
1741  Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1742  return Diag;
1743  }
1744 
1745  void AddFixItHint(const FixItHint &Hint) const {
1746  if (ImmediateDiag.hasValue())
1747  ImmediateDiag->AddFixItHint(Hint);
1748  else if (PartialDiagId.hasValue())
1749  S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1750  }
1751 
1753  return ExprError();
1754  }
1756  return StmtError();
1757  }
1758  operator ExprResult() const { return ExprError(); }
1759  operator StmtResult() const { return StmtError(); }
1760  operator TypeResult() const { return TypeError(); }
1761  operator DeclResult() const { return DeclResult(true); }
1762  operator MemInitResult() const { return MemInitResult(true); }
1763 
1764  private:
1765  Sema &S;
1766  SourceLocation Loc;
1767  unsigned DiagID;
1768  FunctionDecl *Fn;
1769  bool ShowCallStack;
1770 
1771  // Invariant: At most one of these Optionals has a value.
1772  // FIXME: Switch these to a Variant once that exists.
1774  llvm::Optional<unsigned> PartialDiagId;
1775  };
1776 
1777  /// Is the last error level diagnostic immediate. This is used to determined
1778  /// whether the next info diagnostic should be immediate.
1780 
1781  /// Emit a diagnostic.
1782  SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1783  bool DeferHint = false);
1784 
1785  /// Emit a partial diagnostic.
1787  bool DeferHint = false);
1788 
1789  /// Build a partial diagnostic.
1790  PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1791 
1792  /// Whether deferrable diagnostics should be deferred.
1793  bool DeferDiags = false;
1794 
1795  /// RAII class to control scope of DeferDiags.
1797  Sema &S;
1798  bool SavedDeferDiags = false;
1799 
1800  public:
1802  : S(S), SavedDeferDiags(S.DeferDiags) {
1803  S.DeferDiags = DeferDiags;
1804  }
1805  ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1806  };
1807 
1808  /// Whether uncompilable error has occurred. This includes error happens
1809  /// in deferred diagnostics.
1810  bool hasUncompilableErrorOccurred() const;
1811 
1812  bool findMacroSpelling(SourceLocation &loc, StringRef name);
1813 
1814  /// Get a string to suggest for zero-initialization of a type.
1815  std::string
1818 
1819  /// Calls \c Lexer::getLocForEndOfToken()
1821 
1822  /// Retrieve the module loader associated with the preprocessor.
1823  ModuleLoader &getModuleLoader() const;
1824 
1825  /// Invent a new identifier for parameters of abbreviated templates.
1826  IdentifierInfo *
1828  unsigned Index);
1829 
1831 
1832  private:
1833  /// Function or variable declarations to be checked for whether the deferred
1834  /// diagnostics should be emitted.
1835  llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1836 
1837  public:
1838  // Emit all deferred diagnostics.
1839  void emitDeferredDiags();
1840 
1842  /// The global module fragment, between 'module;' and a module-declaration.
1844  /// A normal translation unit fragment. For a non-module unit, this is the
1845  /// entire translation unit. Otherwise, it runs from the module-declaration
1846  /// to the private-module-fragment (if any) or the end of the TU (if not).
1848  /// The private module fragment, between 'module :private;' and the end of
1849  /// the translation unit.
1851  };
1852 
1856 
1858 
1860 
1861  void PushFunctionScope();
1862  void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1864 
1865  /// This is used to inform Sema what the current TemplateParameterDepth
1866  /// is during Parsing. Currently it is used to pass on the depth
1867  /// when parsing generic lambda 'auto' parameters.
1869 
1870  void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1872  unsigned OpenMPCaptureLevel = 0);
1873 
1874  /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1875  /// time after they've been popped.
1877  Sema *Self;
1878 
1879  public:
1880  explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1882  };
1883 
1884  using PoppedFunctionScopePtr =
1885  std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1886 
1889  const Decl *D = nullptr,
1890  QualType BlockType = QualType());
1891 
1893  return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1894  }
1895 
1897 
1901  void setFunctionHasMustTail();
1902 
1903  void PushCompoundScope(bool IsStmtExpr);
1904  void PopCompoundScope();
1905 
1907 
1909 
1910  /// Retrieve the current block, if any.
1912 
1913  /// Get the innermost lambda enclosing the current location, if any. This
1914  /// looks through intervening non-lambda scopes such as local functions and
1915  /// blocks.
1917 
1918  /// Retrieve the current lambda scope info, if any.
1919  /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1920  /// lambda scope info ignoring all inner capturing scopes that are not
1921  /// lambda scopes.
1923  getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1924 
1925  /// Retrieve the current generic lambda info, if any.
1927 
1928  /// Retrieve the current captured region, if any.
1930 
1931  /// Retrieve the current function, if any, that should be analyzed for
1932  /// potential availability violations.
1934 
1935  /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1937 
1938  /// Called before parsing a function declarator belonging to a function
1939  /// declaration.
1941  unsigned TemplateParameterDepth);
1942 
1943  /// Called after parsing a function declarator belonging to a function
1944  /// declaration.
1946 
1947  void ActOnComment(SourceRange Comment);
1948 
1949  //===--------------------------------------------------------------------===//
1950  // Type Analysis / Processing: SemaType.cpp.
1951  //
1952 
1954  const DeclSpec *DS = nullptr);
1955  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1956  const DeclSpec *DS = nullptr);
1958  SourceLocation Loc, DeclarationName Entity);
1959  QualType BuildReferenceType(QualType T, bool LValueRef,
1960  SourceLocation Loc, DeclarationName Entity);
1962  Expr *ArraySize, unsigned Quals,
1963  SourceRange Brackets, DeclarationName Entity);
1964  QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1965  QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1966  SourceLocation AttrLoc);
1967  QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
1968  SourceLocation AttrLoc);
1969 
1970  QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1971  SourceLocation AttrLoc);
1972 
1973  /// Same as above, but constructs the AddressSpace index if not provided.
1975  SourceLocation AttrLoc);
1976 
1978 
1980 
1981  /// Build a function type.
1982  ///
1983  /// This routine checks the function type according to C++ rules and
1984  /// under the assumption that the result type and parameter types have
1985  /// just been instantiated from a template. It therefore duplicates
1986  /// some of the behavior of GetTypeForDeclarator, but in a much
1987  /// simpler form that is only suitable for this narrow use case.
1988  ///
1989  /// \param T The return type of the function.
1990  ///
1991  /// \param ParamTypes The parameter types of the function. This array
1992  /// will be modified to account for adjustments to the types of the
1993  /// function parameters.
1994  ///
1995  /// \param Loc The location of the entity whose type involves this
1996  /// function type or, if there is no such entity, the location of the
1997  /// type that will have function type.
1998  ///
1999  /// \param Entity The name of the entity that involves the function
2000  /// type, if known.
2001  ///
2002  /// \param EPI Extra information about the function type. Usually this will
2003  /// be taken from an existing function with the same prototype.
2004  ///
2005  /// \returns A suitable function type, if there are no errors. The
2006  /// unqualified type will always be a FunctionProtoType.
2007  /// Otherwise, returns a NULL type.
2009  MutableArrayRef<QualType> ParamTypes,
2010  SourceLocation Loc, DeclarationName Entity,
2011  const FunctionProtoType::ExtProtoInfo &EPI);
2012 
2014  SourceLocation Loc,
2015  DeclarationName Entity);
2017  SourceLocation Loc, DeclarationName Entity);
2021  SourceLocation Loc);
2023  SourceLocation Loc);
2024  QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2025 
2028 
2029  /// Package the given type and TSI into a ParsedType.
2034  TypeSourceInfo **TInfo = nullptr);
2035  CanThrowResult canThrow(const Stmt *E);
2036  /// Determine whether the callee of a particular function call can throw.
2037  /// E, D and Loc are all optional.
2038  static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2039  SourceLocation Loc = SourceLocation());
2041  const FunctionProtoType *FPT);
2048  const FunctionProtoType *Old, SourceLocation OldLoc,
2049  const FunctionProtoType *New, SourceLocation NewLoc);
2051  const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2052  const FunctionProtoType *Old, SourceLocation OldLoc,
2053  const FunctionProtoType *New, SourceLocation NewLoc);
2054  bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2055  bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2056  const PartialDiagnostic &NestedDiagID,
2057  const PartialDiagnostic &NoteID,
2058  const PartialDiagnostic &NoThrowDiagID,
2059  const FunctionProtoType *Superset,
2060  SourceLocation SuperLoc,
2061  const FunctionProtoType *Subset,
2062  SourceLocation SubLoc);
2063  bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2064  const PartialDiagnostic &NoteID,
2065  const FunctionProtoType *Target,
2066  SourceLocation TargetLoc,
2067  const FunctionProtoType *Source,
2068  SourceLocation SourceLoc);
2069 
2071 
2072  /// The parser has parsed the context-sensitive type 'instancetype'
2073  /// in an Objective-C message declaration. Return the appropriate type.
2075 
2076  /// Abstract class used to diagnose incomplete types.
2077  struct TypeDiagnoser {
2079 
2080  virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2081  virtual ~TypeDiagnoser() {}
2082  };
2083 
2084  static int getPrintable(int I) { return I; }
2085  static unsigned getPrintable(unsigned I) { return I; }
2086  static bool getPrintable(bool B) { return B; }
2087  static const char * getPrintable(const char *S) { return S; }
2088  static StringRef getPrintable(StringRef S) { return S; }
2089  static const std::string &getPrintable(const std::string &S) { return S; }
2090  static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2091  return II;
2092  }
2094  static QualType getPrintable(QualType T) { return T; }
2095  static SourceRange getPrintable(SourceRange R) { return R; }
2096  static SourceRange getPrintable(SourceLocation L) { return L; }
2097  static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2098  static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2099 
2100  template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2101  protected:
2102  unsigned DiagID;
2103  std::tuple<const Ts &...> Args;
2104 
2105  template <std::size_t... Is>
2106  void emit(const SemaDiagnosticBuilder &DB,
2107  std::index_sequence<Is...>) const {
2108  // Apply all tuple elements to the builder in order.
2109  bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2110  (void)Dummy;
2111  }
2112 
2113  public:
2114  BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2115  : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2116  assert(DiagID != 0 && "no diagnostic for type diagnoser");
2117  }
2118 
2119  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2120  const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2121  emit(DB, std::index_sequence_for<Ts...>());
2122  DB << T;
2123  }
2124  };
2125 
2126  /// Do a check to make sure \p Name looks like a legal argument for the
2127  /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2128  /// is invalid for the given declaration.
2129  ///
2130  /// \p AL is used to provide caret diagnostics in case of a malformed name.
2131  ///
2132  /// \returns true if the name is a valid swift name for \p D, false otherwise.
2133  bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2134  const ParsedAttr &AL, bool IsAsync);
2135 
2136  /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2137  /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2138  /// For example, a diagnostic with no other parameters would generally have
2139  /// the form "...%select{incomplete|sizeless}0 type %1...".
2140  template <typename... Ts>
2142  public:
2143  SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2144  : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2145 
2146  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2147  const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2148  this->emit(DB, std::index_sequence_for<Ts...>());
2149  DB << T->isSizelessType() << T;
2150  }
2151  };
2152 
2153  enum class CompleteTypeKind {
2154  /// Apply the normal rules for complete types. In particular,
2155  /// treat all sizeless types as incomplete.
2156  Normal,
2157 
2158  /// Relax the normal rules for complete types so that they include
2159  /// sizeless built-in types.
2161 
2162  // FIXME: Eventually we should flip the default to Normal and opt in
2163  // to AcceptSizeless rather than opt out of it.
2165  };
2166 
2167 private:
2168  /// Methods for marking which expressions involve dereferencing a pointer
2169  /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2170  /// they are parsed, meaning that a noderef pointer may not be accessed. For
2171  /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2172  /// `*p`, but need to check that `address of` is called on it. This requires
2173  /// keeping a container of all pending expressions and checking if the address
2174  /// of them are eventually taken.
2175  void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2176  void CheckAddressOfNoDeref(const Expr *E);
2177  void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2178 
2179  bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2180  CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2181 
2182  struct ModuleScope {
2183  SourceLocation BeginLoc;
2184  clang::Module *Module = nullptr;
2185  bool ModuleInterface = false;
2186  bool ImplicitGlobalModuleFragment = false;
2187  VisibleModuleSet OuterVisibleModules;
2188  };
2189  /// The modules we're currently parsing.
2191 
2192  /// Namespace definitions that we will export when they finish.
2193  llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2194 
2195  /// Get the module whose scope we are currently within.
2196  Module *getCurrentModule() const {
2197  return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2198  }
2199 
2200  VisibleModuleSet VisibleModules;
2201 
2202 public:
2203  /// Get the module owning an entity.
2204  Module *getOwningModule(const Decl *Entity) {
2205  return Entity->getOwningModule();
2206  }
2207 
2208  /// Make a merged definition of an existing hidden definition \p ND
2209  /// visible at the specified location.
2211 
2212  bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2213 
2214  // When loading a non-modular PCH files, this is used to restore module
2215  // visibility.
2216  void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2217  VisibleModules.setVisible(Mod, ImportLoc);
2218  }
2219 
2220  /// Determine whether a declaration is visible to name lookup.
2221  bool isVisible(const NamedDecl *D) {
2222  return D->isUnconditionallyVisible() || isVisibleSlow(D);
2223  }
2224 
2225  /// Determine whether any declaration of an entity is visible.
2226  bool
2228  llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2229  return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2230  }
2231  bool hasVisibleDeclarationSlow(const NamedDecl *D,
2233 
2236 
2237  /// Determine if \p D and \p Suggested have a structurally compatible
2238  /// layout as described in C11 6.2.7/1.
2239  bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2240 
2241  /// Determine if \p D has a visible definition. If not, suggest a declaration
2242  /// that should be made visible to expose the definition.
2243  bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2244  bool OnlyNeedComplete = false);
2246  NamedDecl *Hidden;
2247  return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2248  }
2249 
2250  /// Determine if the template parameter \p D has a visible default argument.
2251  bool
2253  llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2254 
2255  /// Determine if there is a visible declaration of \p D that is an explicit
2256  /// specialization declaration for a specialization of a template. (For a
2257  /// member specialization, use hasVisibleMemberSpecialization.)
2259  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2260 
2261  /// Determine if there is a visible declaration of \p D that is a member
2262  /// specialization declaration (as opposed to an instantiated declaration).
2264  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2265 
2266  /// Determine if \p A and \p B are equivalent internal linkage declarations
2267  /// from different modules, and thus an ambiguity error can be downgraded to
2268  /// an extension warning.
2270  const NamedDecl *B);
2272  SourceLocation Loc, const NamedDecl *D,
2274 
2276 
2279  return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2280  }
2282  CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2284  CompleteTypeKind Kind, unsigned DiagID);
2285 
2287  TypeDiagnoser &Diagnoser) {
2288  return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2289  }
2290  bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2291  return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2292  }
2293 
2294  template <typename... Ts>
2295  bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2296  const Ts &...Args) {
2297  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2298  return RequireCompleteType(Loc, T, Diagnoser);
2299  }
2300 
2301  template <typename... Ts>
2302  bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2303  const Ts &... Args) {
2304  SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2305  return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2306  }
2307 
2308  /// Get the type of expression E, triggering instantiation to complete the
2309  /// type if necessary -- that is, if the expression refers to a templated
2310  /// static data member of incomplete array type.
2311  ///
2312  /// May still return an incomplete type if instantiation was not possible or
2313  /// if the type is incomplete for a different reason. Use
2314  /// RequireCompleteExprType instead if a diagnostic is expected for an
2315  /// incomplete expression type.
2317 
2318  void completeExprArrayBound(Expr *E);
2320  TypeDiagnoser &Diagnoser);
2321  bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2322 
2323  template <typename... Ts>
2324  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2325  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2326  return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2327  }
2328 
2329  template <typename... Ts>
2330  bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2331  const Ts &... Args) {
2332  SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2333  return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2334  }
2335 
2337  TypeDiagnoser &Diagnoser);
2338  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2339 
2340  template <typename... Ts>
2341  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2342  const Ts &...Args) {
2343  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2344  return RequireLiteralType(Loc, T, Diagnoser);
2345  }
2346 
2348  const CXXScopeSpec &SS, QualType T,
2349  TagDecl *OwnedTagDecl = nullptr);
2350 
2352  /// If AsUnevaluated is false, E is treated as though it were an evaluated
2353  /// context, such as when building a type for decltype(auto).
2355  bool AsUnevaluated = true);
2358  SourceLocation Loc);
2359 
2360  //===--------------------------------------------------------------------===//
2361  // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2362  //
2363 
2364  struct SkipBodyInfo {
2367  New(nullptr) {}
2372  };
2373 
2374  DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2375 
2377 
2379 
2381  Scope *S, CXXScopeSpec *SS = nullptr,
2382  bool isClassName = false, bool HasTrailingDot = false,
2383  ParsedType ObjectType = nullptr,
2384  bool IsCtorOrDtorName = false,
2385  bool WantNontrivialTypeSourceInfo = false,
2386  bool IsClassTemplateDeductionContext = true,
2387  IdentifierInfo **CorrectedII = nullptr);
2389  bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2391  SourceLocation IILoc,
2392  Scope *S,
2393  CXXScopeSpec *SS,
2394  ParsedType &SuggestedType,
2395  bool IsTemplateName = false);
2396 
2397  /// Attempt to behave like MSVC in situations where lookup of an unqualified
2398  /// type name has failed in a dependent context. In these situations, we
2399  /// automatically form a DependentTypeName that will retry lookup in a related
2400  /// scope during instantiation.
2402  SourceLocation NameLoc,
2403  bool IsTemplateTypeArg);
2404 
2405  /// Describes the result of the name lookup and resolution performed
2406  /// by \c ClassifyName().
2408  /// This name is not a type or template in this context, but might be
2409  /// something else.
2411  /// Classification failed; an error has been produced.
2413  /// The name has been typo-corrected to a keyword.
2415  /// The name was classified as a type.
2417  /// The name was classified as a specific non-type, non-template
2418  /// declaration. ActOnNameClassifiedAsNonType should be called to
2419  /// convert the declaration to an expression.
2421  /// The name was classified as an ADL-only function name.
2422  /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2423  /// result to an expression.
2425  /// The name denotes a member of a dependent type that could not be
2426  /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2427  /// convert the result to an expression.
2429  /// The name was classified as an overload set, and an expression
2430  /// representing that overload set has been formed.
2431  /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2432  /// expression referencing the overload set.
2434  /// The name was classified as a template whose specializations are types.
2436  /// The name was classified as a variable template name.
2438  /// The name was classified as a function template name.
2440  /// The name was classified as an ADL-only function template name.
2442  /// The name was classified as a concept name.
2444  };
2445 
2448  union {
2453  };
2454 
2455  explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2456 
2457  public:
2459 
2460  NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2461 
2463  return NameClassification(NC_Error);
2464  }
2465 
2468  }
2469 
2472  Result.Expr = E;
2473  return Result;
2474  }
2475 
2478  Result.NonTypeDecl = D;
2479  return Result;
2480  }
2481 
2484  }
2485 
2488  }
2489 
2492  Result.Template = Name;
2493  return Result;
2494  }
2495 
2498  Result.Template = Name;
2499  return Result;
2500  }
2501 
2504  Result.Template = Name;
2505  return Result;
2506  }
2507 
2510  Result.Template = Name;
2511  return Result;
2512  }
2513 
2516  Result.Template = Name;
2517  return Result;
2518  }
2519 
2520  NameClassificationKind getKind() const { return Kind; }
2521 
2523  assert(Kind == NC_OverloadSet);
2524  return Expr;
2525  }
2526 
2528  assert(Kind == NC_Type);
2529  return Type;
2530  }
2531 
2533  assert(Kind == NC_NonType);
2534  return NonTypeDecl;
2535  }
2536 
2538  assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2539  Kind == NC_VarTemplate || Kind == NC_Concept ||
2540  Kind == NC_UndeclaredTemplate);
2541  return Template;
2542  }
2543 
2545  switch (Kind) {
2546  case NC_TypeTemplate:
2547  return TNK_Type_template;
2548  case NC_FunctionTemplate:
2549  return TNK_Function_template;
2550  case NC_VarTemplate:
2551  return TNK_Var_template;
2552  case NC_Concept:
2553  return TNK_Concept_template;
2554  case NC_UndeclaredTemplate:
2555  return TNK_Undeclared_template;
2556  default:
2557  llvm_unreachable("unsupported name classification.");
2558  }
2559  }
2560  };
2561 
2562  /// Perform name lookup on the given name, classifying it based on
2563  /// the results of name lookup and the following token.
2564  ///
2565  /// This routine is used by the parser to resolve identifiers and help direct
2566  /// parsing. When the identifier cannot be found, this routine will attempt
2567  /// to correct the typo and classify based on the resulting name.
2568  ///
2569  /// \param S The scope in which we're performing name lookup.
2570  ///
2571  /// \param SS The nested-name-specifier that precedes the name.
2572  ///
2573  /// \param Name The identifier. If typo correction finds an alternative name,
2574  /// this pointer parameter will be updated accordingly.
2575  ///
2576  /// \param NameLoc The location of the identifier.
2577  ///
2578  /// \param NextToken The token following the identifier. Used to help
2579  /// disambiguate the name.
2580  ///
2581  /// \param CCC The correction callback, if typo correction is desired.
2582  NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2583  IdentifierInfo *&Name, SourceLocation NameLoc,
2584  const Token &NextToken,
2585  CorrectionCandidateCallback *CCC = nullptr);
2586 
2587  /// Act on the result of classifying a name as an undeclared (ADL-only)
2588  /// non-type declaration.
2590  SourceLocation NameLoc);
2591  /// Act on the result of classifying a name as an undeclared member of a
2592  /// dependent base class.
2594  IdentifierInfo *Name,
2595  SourceLocation NameLoc,
2596  bool IsAddressOfOperand);
2597  /// Act on the result of classifying a name as a specific non-type
2598  /// declaration.
2600  NamedDecl *Found,
2601  SourceLocation NameLoc,
2602  const Token &NextToken);
2603  /// Act on the result of classifying a name as an overload set.
2605 
2606  /// Describes the detailed kind of a template name. Used in diagnostics.
2608  ClassTemplate,
2610  VarTemplate,
2611  AliasTemplate,
2613  Concept,
2615  };
2618 
2619  /// Determine whether it's plausible that E was intended to be a
2620  /// template-name.
2621  bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2622  if (!getLangOpts().CPlusPlus || E.isInvalid())
2623  return false;
2624  Dependent = false;
2625  if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2626  return !DRE->hasExplicitTemplateArgs();
2627  if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2628  return !ME->hasExplicitTemplateArgs();
2629  Dependent = true;
2630  if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2631  return !DSDRE->hasExplicitTemplateArgs();
2632  if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2633  return !DSME->hasExplicitTemplateArgs();
2634  // Any additional cases recognized here should also be handled by
2635  // diagnoseExprIntendedAsTemplateName.
2636  return false;
2637  }
2639  SourceLocation Less,
2640  SourceLocation Greater);
2641 
2642  void warnOnReservedIdentifier(const NamedDecl *D);
2643 
2645 
2647  MultiTemplateParamsArg TemplateParameterLists);
2649  QualType &T, SourceLocation Loc,
2650  unsigned FailedFoldDiagID);
2654  DeclarationName Name, SourceLocation Loc,
2655  bool IsTemplateId);
2656  void
2657  diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2658  SourceLocation FallbackLoc,
2659  SourceLocation ConstQualLoc = SourceLocation(),
2660  SourceLocation VolatileQualLoc = SourceLocation(),
2661  SourceLocation RestrictQualLoc = SourceLocation(),
2662  SourceLocation AtomicQualLoc = SourceLocation(),
2663  SourceLocation UnalignedQualLoc = SourceLocation());
2664 
2665  static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2666  void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2668  const LookupResult &R);
2671  const LookupResult &R);
2672  void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2673  const LookupResult &R);
2674  void CheckShadow(Scope *S, VarDecl *D);
2675 
2676  /// Warn if 'E', which is an expression that is about to be modified, refers
2677  /// to a shadowing declaration.
2679 
2681 
2682 private:
2683  /// Map of current shadowing declarations to shadowed declarations. Warn if
2684  /// it looks like the user is trying to modify the shadowing declaration.
2685  llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2686 
2687 public:
2688  void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2689  void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2690  void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2691  TypedefNameDecl *NewTD);
2694  TypeSourceInfo *TInfo,
2697  LookupResult &Previous, bool &Redeclaration);
2699  TypeSourceInfo *TInfo,
2701  MultiTemplateParamsArg TemplateParamLists,
2702  bool &AddToScope,
2704  NamedDecl *
2706  MultiTemplateParamsArg TemplateParamLists);
2707  // Returns true if the variable declaration is a redeclaration
2710  bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2711  Expr *Init);
2715 
2717  TypeSourceInfo *TInfo,
2719  MultiTemplateParamsArg TemplateParamLists,
2720  bool &AddToScope);
2722 
2723  enum class CheckConstexprKind {
2724  /// Diagnose issues that are non-constant or that are extensions.
2725  Diagnose,
2726  /// Identify whether this function satisfies the formal rules for constexpr
2727  /// functions in the current lanugage mode (with no extensions).
2728  CheckValid
2729  };
2730 
2733 
2736  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2738  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2739  // Returns true if the function declaration is a redeclaration
2742  bool IsMemberSpecialization);
2743  bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2745  QualType NewT, QualType OldT);
2746  void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2749  bool IsDefinition);
2753  SourceLocation Loc,
2754  QualType T);
2756  SourceLocation NameLoc, IdentifierInfo *Name,
2757  QualType T, TypeSourceInfo *TSInfo,
2758  StorageClass SC);
2759  void ActOnParamDefaultArgument(Decl *param,
2760  SourceLocation EqualLoc,
2761  Expr *defarg);
2763  SourceLocation ArgLoc);
2764  void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2766  SourceLocation EqualLoc);
2767  void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2768  SourceLocation EqualLoc);
2769 
2770  // Contexts where using non-trivial C union types can be disallowed. This is
2771  // passed to err_non_trivial_c_union_in_invalid_context.
2773  // Function parameter.
2775  // Function return.
2777  // Default-initialized object.
2779  // Variable with automatic storage duration.
2781  // Initializer expression that might copy from another object.
2783  // Assignment.
2785  // Compound literal.
2787  // Block capture.
2789  // lvalue-to-rvalue conversion of volatile type.
2791  };
2792 
2793  /// Emit diagnostics if the initializer or any of its explicit or
2794  /// implicitly-generated subexpressions require copying or
2795  /// default-initializing a type that is or contains a C union type that is
2796  /// non-trivial to copy or default-initialize.
2798 
2799  // These flags are passed to checkNonTrivialCUnion.
2801  NTCUK_Init = 0x1,
2803  NTCUK_Copy = 0x4,
2804  };
2805 
2806  /// Emit diagnostics if a non-trivial C union type or a struct that contains
2807  /// a non-trivial C union is used in an invalid context.
2809  NonTrivialCUnionContext UseContext,
2810  unsigned NonTrivialKind);
2811 
2812  void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2813  void ActOnUninitializedDecl(Decl *dcl);
2814  void ActOnInitializerError(Decl *Dcl);
2815 
2816  void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2817  void ActOnCXXForRangeDecl(Decl *D);
2819  IdentifierInfo *Ident,
2820  ParsedAttributes &Attrs,
2821  SourceLocation AttrEnd);
2822  void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2823  void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2825  void FinalizeDeclaration(Decl *D);
2827  ArrayRef<Decl *> Group);
2829 
2830  /// Should be called on all declarations that might have attached
2831  /// documentation comments.
2832  void ActOnDocumentableDecl(Decl *D);
2834 
2836  SourceLocation LocAfterDecls);
2838  FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2839  SkipBodyInfo *SkipBody = nullptr);
2841  MultiTemplateParamsArg TemplateParamLists,
2842  SkipBodyInfo *SkipBody = nullptr);
2844  SkipBodyInfo *SkipBody = nullptr);
2847  ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
2848  void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2850  return D && isa<ObjCMethodDecl>(D);
2851  }
2852 
2853  /// Determine whether we can delay parsing the body of a function or
2854  /// function template until it is used, assuming we don't care about emitting
2855  /// code for that function.
2856  ///
2857  /// This will be \c false if we may need the body of the function in the
2858  /// middle of parsing an expression (where it's impractical to switch to
2859  /// parsing a different function), for instance, if it's constexpr in C++11
2860  /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2861  bool canDelayFunctionBody(const Declarator &D);
2862 
2863  /// Determine whether we can skip parsing the body of a function
2864  /// definition, assuming we don't care about analyzing its body or emitting
2865  /// code for that function.
2866  ///
2867  /// This will be \c false only if we may need the body of the function in
2868  /// order to parse the rest of the program (for instance, if it is
2869  /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2870  bool canSkipFunctionBody(Decl *D);
2871 
2874  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2877 
2878  /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2879  /// attribute for which parsing is delayed.
2881 
2882  /// Diagnose any unused parameters in the given sequence of
2883  /// ParmVarDecl pointers.
2885 
2886  /// Diagnose whether the size of parameters or return value of a
2887  /// function or obj-c method definition is pass-by-value and larger than a
2888  /// specified threshold.
2889  void
2891  QualType ReturnTy, NamedDecl *D);
2892 
2893  void DiagnoseInvalidJumps(Stmt *Body);
2895  SourceLocation AsmLoc,
2896  SourceLocation RParenLoc);
2897 
2898  /// Handle a C++11 empty-declaration and attribute-declaration.
2900  SourceLocation SemiLoc);
2901 
2902  enum class ModuleDeclKind {
2903  Interface, ///< 'export module X;'
2904  Implementation, ///< 'module X;'
2905  };
2906 
2907  /// The parser has processed a module-declaration that begins the definition
2908  /// of a module interface or implementation.
2910  SourceLocation ModuleLoc, ModuleDeclKind MDK,
2911  ModuleIdPath Path, bool IsFirstDecl);
2912 
2913  /// The parser has processed a global-module-fragment declaration that begins
2914  /// the definition of the global module fragment of the current module unit.
2915  /// \param ModuleLoc The location of the 'module' keyword.
2917 
2918  /// The parser has processed a private-module-fragment declaration that begins
2919  /// the definition of the private module fragment of the current module unit.
2920  /// \param ModuleLoc The location of the 'module' keyword.
2921  /// \param PrivateLoc The location of the 'private' keyword.
2923  SourceLocation PrivateLoc);
2924 
2925  /// The parser has processed a module import declaration.
2926  ///
2927  /// \param StartLoc The location of the first token in the declaration. This
2928  /// could be the location of an '@', 'export', or 'import'.
2929  /// \param ExportLoc The location of the 'export' keyword, if any.
2930  /// \param ImportLoc The location of the 'import' keyword.
2931  /// \param Path The module access path.
2933  SourceLocation ExportLoc,
2934  SourceLocation ImportLoc, ModuleIdPath Path);
2936  SourceLocation ExportLoc,
2937  SourceLocation ImportLoc, Module *M,
2938  ModuleIdPath Path = {});
2939 
2940  /// The parser has processed a module import translated from a
2941  /// #include or similar preprocessing directive.
2942  void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2943  void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2944 
2945  /// The parsed has entered a submodule.
2946  void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2947  /// The parser has left a submodule.
2948  void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2949 
2950  /// Create an implicit import of the given module at the given
2951  /// source location, for error recovery, if possible.
2952  ///
2953  /// This routine is typically used when an entity found by name lookup
2954  /// is actually hidden within a module that we know about but the user
2955  /// has forgotten to import.
2956  void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2957  Module *Mod);
2958 
2959  /// Kinds of missing import. Note, the values of these enumerators correspond
2960  /// to %select values in diagnostics.
2961  enum class MissingImportKind {
2962  Declaration,
2963  Definition,
2967  };
2968 
2969  /// Diagnose that the specified declaration needs to be visible but
2970  /// isn't, and suggest a module import that would resolve the problem.
2972  MissingImportKind MIK, bool Recover = true);
2974  SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2975  MissingImportKind MIK, bool Recover);
2976 
2978  SourceLocation LBraceLoc);
2980  SourceLocation RBraceLoc);
2981 
2982  /// We've found a use of a templated declaration that would trigger an
2983  /// implicit instantiation. Check that any relevant explicit specializations
2984  /// and partial specializations are visible, and diagnose if not.
2986 
2987  /// Retrieve a suitable printing policy for diagnostics.
2989  return getPrintingPolicy(Context, PP);
2990  }
2991 
2992  /// Retrieve a suitable printing policy for diagnostics.
2993  static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2994  const Preprocessor &PP);
2995 
2996  /// Scope actions.
2997  void ActOnPopScope(SourceLocation Loc, Scope *S);
2999 
3001  RecordDecl *&AnonRecord);
3003  MultiTemplateParamsArg TemplateParams,
3004  bool IsExplicitInstantiation,
3005  RecordDecl *&AnonRecord);
3006 
3008  AccessSpecifier AS,
3009  RecordDecl *Record,
3010  const PrintingPolicy &Policy);
3011 
3013  RecordDecl *Record);
3014 
3015  /// Common ways to introduce type names without a tag for use in diagnostics.
3016  /// Keep in sync with err_tag_reference_non_tag.
3017  enum NonTagKind {
3027  };
3028 
3029  /// Given a non-tag type declaration, returns an enum useful for indicating
3030  /// what kind of non-tag type this is.
3032 
3034  TagTypeKind NewTag, bool isDefinition,
3035  SourceLocation NewTagLoc,
3036  const IdentifierInfo *Name);
3037 
3038  enum TagUseKind {
3039  TUK_Reference, // Reference to a tag: 'struct foo *X;'
3040  TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3041  TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3042  TUK_Friend // Friend declaration: 'friend struct foo;'
3043  };
3044 
3045  Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3046  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
3047  SourceLocation NameLoc, const ParsedAttributesView &Attr,
3048  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
3049  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
3050  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
3051  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3052  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3053  SkipBodyInfo *SkipBody = nullptr);
3054 
3056  unsigned TagSpec, SourceLocation TagLoc,
3057  CXXScopeSpec &SS, IdentifierInfo *Name,
3058  SourceLocation NameLoc,
3059  const ParsedAttributesView &Attr,
3060  MultiTemplateParamsArg TempParamLists);
3061 
3063  unsigned TagSpec,
3064  TagUseKind TUK,
3065  const CXXScopeSpec &SS,
3066  IdentifierInfo *Name,
3067  SourceLocation TagLoc,
3068  SourceLocation NameLoc);
3069 
3070  void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3071  IdentifierInfo *ClassName,
3072  SmallVectorImpl<Decl *> &Decls);
3073  Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3074  Declarator &D, Expr *BitfieldWidth);
3075 
3076  FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3077  Declarator &D, Expr *BitfieldWidth,
3078  InClassInitStyle InitStyle,
3079  AccessSpecifier AS);
3081  SourceLocation DeclStart, Declarator &D,
3082  Expr *BitfieldWidth,
3083  InClassInitStyle InitStyle,
3084  AccessSpecifier AS,
3085  const ParsedAttr &MSPropertyAttr);
3086 
3088  TypeSourceInfo *TInfo,
3089  RecordDecl *Record, SourceLocation Loc,
3090  bool Mutable, Expr *BitfieldWidth,
3091  InClassInitStyle InitStyle,
3092  SourceLocation TSSL,
3093  AccessSpecifier AS, NamedDecl *PrevDecl,
3094  Declarator *D = nullptr);
3095 
3096  bool CheckNontrivialField(FieldDecl *FD);
3097  void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3098 
3100  /// The triviality of a method unaffected by "trivial_abi".
3102 
3103  /// The triviality of a method affected by "trivial_abi".
3105  };
3106 
3109  bool Diagnose = false);
3110 
3111  /// For a defaulted function, the kind of defaulted function that it is.
3113  CXXSpecialMember SpecialMember : 8;
3114  DefaultedComparisonKind Comparison : 8;
3115 
3116  public:
3118  : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3119  }
3121  : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3123  : SpecialMember(CXXInvalid), Comparison(Comp) {}
3124 
3125  bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3126  bool isComparison() const {
3127  return Comparison != DefaultedComparisonKind::None;
3128  }
3129 
3130  explicit operator bool() const {
3131  return isSpecialMember() || isComparison();
3132  }
3133 
3134  CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3135  DefaultedComparisonKind asComparison() const { return Comparison; }
3136 
3137  /// Get the index of this function kind for use in diagnostics.
3138  unsigned getDiagnosticIndex() const {
3139  static_assert(CXXInvalid > CXXDestructor,
3140  "invalid should have highest index");
3141  static_assert((unsigned)DefaultedComparisonKind::None == 0,
3142  "none should be equal to zero");
3143  return SpecialMember + (unsigned)Comparison;
3144  }
3145  };
3146 
3147  DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3148 
3151  }
3154  }
3155 
3156  void ActOnLastBitfield(SourceLocation DeclStart,
3157  SmallVectorImpl<Decl *> &AllIvarDecls);
3158  Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3159  Declarator &D, Expr *BitfieldWidth,
3160  tok::ObjCKeywordKind visibility);
3161 
3162  // This is used for both record definitions and ObjC interface declarations.
3163  void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3164  ArrayRef<Decl *> Fields, SourceLocation LBrac,
3165  SourceLocation RBrac, const ParsedAttributesView &AttrList);
3166 
3167  /// ActOnTagStartDefinition - Invoked when we have entered the
3168  /// scope of a tag's definition (e.g., for an enumeration, class,
3169  /// struct, or union).
3171 
3172  /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3173  /// Differently from C++, actually parse the body and reject / error out
3174  /// in case of a structural mismatch.
3175  bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
3176  SkipBodyInfo &SkipBody);
3177 
3179 
3180  /// Invoked when we enter a tag definition that we're skipping.
3182 
3184 
3185  /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3186  /// C++ record definition's base-specifiers clause and are starting its
3187  /// member declarations.
3189  SourceLocation FinalLoc,
3190  bool IsFinalSpelledSealed,
3191  bool IsAbstract,
3192  SourceLocation LBraceLoc);
3193 
3194  /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3195  /// the definition of a tag (enumeration, class, struct, or union).
3197  SourceRange BraceRange);
3198 
3200 
3202 
3203  /// Invoked when we must temporarily exit the objective-c container
3204  /// scope for parsing/looking-up C constructs.
3205  ///
3206  /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3209 
3210  /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3211  /// error parsing the definition of a tag.
3213 
3215  EnumConstantDecl *LastEnumConst,
3216  SourceLocation IdLoc,
3217  IdentifierInfo *Id,
3218  Expr *val);
3220  bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3221  QualType EnumUnderlyingTy, bool IsFixed,
3222  const EnumDecl *Prev);
3223 
3224  /// Determine whether the body of an anonymous enumeration should be skipped.
3225  /// \param II The name of the first enumerator.
3227  SourceLocation IILoc);
3228 
3229  Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3231  const ParsedAttributesView &Attrs,
3232  SourceLocation EqualLoc, Expr *Val);
3233  void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3234  Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3235  const ParsedAttributesView &Attr);
3236 
3237  /// Set the current declaration context until it gets popped.
3238  void PushDeclContext(Scope *S, DeclContext *DC);
3239  void PopDeclContext();
3240 
3241  /// EnterDeclaratorContext - Used when we must lookup names in the context
3242  /// of a declarator's nested name specifier.
3244  void ExitDeclaratorContext(Scope *S);
3245 
3246  /// Enter a template parameter scope, after it's been associated with a particular
3247  /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3248  /// in the correct order.
3249  void EnterTemplatedContext(Scope *S, DeclContext *DC);
3250 
3251  /// Push the parameters of D, which must be a function, into scope.
3252  void ActOnReenterFunctionContext(Scope* S, Decl* D);
3253  void ActOnExitFunctionContext();
3254 
3256 
3257  /// getCurFunctionDecl - If inside of a function body, this returns a pointer
3258  /// to the function decl for the function being parsed. If we're currently
3259  /// in a 'block', this returns the containing context.
3261 
3262  /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3263  /// the method decl for the method being parsed. If we're currently
3264  /// in a 'block', this returns the containing context.
3266 
3267  /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3268  /// or C function we're in, otherwise return null. If we're currently
3269  /// in a 'block', this returns the containing context.
3271 
3272  /// Add this decl to the scope shadowed decl chains.
3273  void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3274 
3275  /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3276  /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3277  /// true if 'D' belongs to the given declaration context.
3278  ///
3279  /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3280  /// enclosing namespace set of the context, rather than contained
3281  /// directly within it.
3282  bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3283  bool AllowInlineNamespace = false);
3284 
3285  /// Finds the scope corresponding to the given decl context, if it
3286  /// happens to be an enclosing scope. Otherwise return NULL.
3287  static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3288 
3289  /// Subroutines of ActOnDeclarator().
3291  TypeSourceInfo *TInfo);
3293 
3294  /// Describes the kind of merge to perform for availability
3295  /// attributes (including "deprecated", "unavailable", and "availability").
3297  /// Don't merge availability attributes at all.
3299  /// Merge availability attributes for a redeclaration, which requires
3300  /// an exact match.
3302  /// Merge availability attributes for an override, which requires
3303  /// an exact match or a weakening of constraints.
3305  /// Merge availability attributes for an implementation of
3306  /// a protocol requirement.
3308  /// Merge availability attributes for an implementation of
3309  /// an optional protocol requirement.
3311  };
3312 
3313  /// Describes the kind of priority given to an availability attribute.
3314  ///
3315  /// The sum of priorities deteremines the final priority of the attribute.
3316  /// The final priority determines how the attribute will be merged.
3317  /// An attribute with a lower priority will always remove higher priority
3318  /// attributes for the specified platform when it is being applied. An
3319  /// attribute with a higher priority will not be applied if the declaration
3320  /// already has an availability attribute with a lower priority for the
3321  /// specified platform. The final prirority values are not expected to match
3322  /// the values in this enumeration, but instead should be treated as a plain
3323  /// integer value. This enumeration just names the priority weights that are
3324  /// used to calculate that final vaue.
3326  /// The availability attribute was specified explicitly next to the
3327  /// declaration.
3329 
3330  /// The availability attribute was applied using '#pragma clang attribute'.
3332 
3333  /// The availability attribute for a specific platform was inferred from
3334  /// an availability attribute for another platform.
3336  };
3337 
3338  /// Attribute merging methods. Return true if a new attribute was added.
3339  AvailabilityAttr *
3341  IdentifierInfo *Platform, bool Implicit,
3342  VersionTuple Introduced, VersionTuple Deprecated,
3343  VersionTuple Obsoleted, bool IsUnavailable,
3344  StringRef Message, bool IsStrict, StringRef Replacement,
3345  AvailabilityMergeKind AMK, int Priority);
3346  TypeVisibilityAttr *
3348  TypeVisibilityAttr::VisibilityType Vis);
3349  VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3350  VisibilityAttr::VisibilityType Vis);
3351  UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3352  StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3353  DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3354  DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3355  MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3356  const AttributeCommonInfo &CI,
3357  bool BestCase,
3358  MSInheritanceModel Model);
3359  ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3360  StringRef NewUserDiagnostic);
3361  FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3362  IdentifierInfo *Format, int FormatIdx,
3363  int FirstArg);
3364  SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3365  StringRef Name);
3366  CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3367  StringRef Name);
3368  AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3369  const AttributeCommonInfo &CI,
3370  const IdentifierInfo *Ident);
3371  MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3372  SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3373  StringRef Name);
3374  OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3375  const AttributeCommonInfo &CI);
3376  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3377  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3378  const InternalLinkageAttr &AL);
3379  WebAssemblyImportNameAttr *mergeImportNameAttr(
3380  Decl *D, const WebAssemblyImportNameAttr &AL);
3381  WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3382  Decl *D, const WebAssemblyImportModuleAttr &AL);
3383  EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3384  EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3385  const EnforceTCBLeafAttr &AL);
3386  BTFTagAttr *mergeBTFTagAttr(Decl *D, const BTFTagAttr &AL);
3387 
3388  void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3391  LookupResult &OldDecls);
3392  bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3393  bool MergeTypeWithOld);
3395  Scope *S, bool MergeTypeWithOld);
3398  void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3399  void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3400  bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3401  void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3402  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3403 
3404  // AssignmentAction - This is used by all the assignment diagnostic functions
3405  // to represent what is actually causing the operation
3415  };
3416 
3417  /// C++ Overloading.
3419  /// This is a legitimate overload: the existing declarations are
3420  /// functions or function templates with different signatures.
3422 
3423  /// This is not an overload because the signature exactly matches
3424  /// an existing declaration.
3426 
3427  /// This is not an overload because the lookup results contain a
3428  /// non-function.
3430  };
3432  FunctionDecl *New,
3433  const LookupResult &OldDecls,
3434  NamedDecl *&OldDecl,
3435  bool IsForUsingDecl);
3436  bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
3437  bool ConsiderCudaAttrs = true,
3438  bool ConsiderRequiresClauses = true);
3439 
3440  enum class AllowedExplicit {
3441  /// Allow no explicit functions to be used.
3442  None,
3443  /// Allow explicit conversion functions but not explicit constructors.
3444  Conversions,
3445  /// Allow both explicit conversion functions and explicit constructors.
3446  All
3447  };
3448 
3450  TryImplicitConversion(Expr *From, QualType ToType,
3451  bool SuppressUserConversions,
3452  AllowedExplicit AllowExplicit,
3453  bool InOverloadResolution,
3454  bool CStyle,
3455  bool AllowObjCWritebackConversion);
3456 
3457  bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3458  bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3459  bool IsComplexPromotion(QualType FromType, QualType ToType);
3460  bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3461  bool InOverloadResolution,
3462  QualType& ConvertedType, bool &IncompatibleObjC);
3463  bool isObjCPointerConversion(QualType FromType, QualType ToType,
3464  QualType& ConvertedType, bool &IncompatibleObjC);
3465  bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3466  QualType &ConvertedType);
3467  bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3468  QualType& ConvertedType);
3469  bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3470  const FunctionProtoType *NewType,
3471  unsigned *ArgPos = nullptr);
3473  QualType FromType, QualType ToType);
3474 
3477  bool CheckPointerConversion(Expr *From, QualType ToType,
3478  CastKind &Kind,
3479  CXXCastPath& BasePath,
3480  bool IgnoreBaseAccess,
3481  bool Diagnose = true);
3482  bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3483  bool InOverloadResolution,
3484  QualType &ConvertedType);
3485  bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3486  CastKind &Kind,
3487  CXXCastPath &BasePath,
3488  bool IgnoreBaseAccess);
3489  bool IsQualificationConversion(QualType FromType, QualType ToType,
3490  bool CStyle, bool &ObjCLifetimeConversion);
3491  bool IsFunctionConversion(QualType FromType, QualType ToType,
3492  QualType &ResultTy);
3495 
3497  const InitializedEntity &Entity, InitListExpr *From);
3498 
3499  bool IsStringInit(Expr *Init, const ArrayType *AT);
3500 
3502  ExprResult Init);
3504  SourceLocation EqualLoc,
3505  ExprResult Init,
3506  bool TopLevelOfInitList = false,
3507  bool AllowExplicit = false);
3509  NestedNameSpecifier *Qualifier,
3510  NamedDecl *FoundDecl,
3511  CXXMethodDecl *Method);
3512 
3513  /// Check that the lifetime of the initializer (and its subobjects) is
3514  /// sufficient for initializing the entity, and perform lifetime extension
3515  /// (when permitted) if not.
3516  void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3517 
3520 
3521  /// Contexts in which a converted constant expression is required.
3522  enum CCEKind {
3523  CCEK_CaseValue, ///< Expression in a case label.
3524  CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
3525  CCEK_TemplateArg, ///< Value of a non-type template parameter.
3526  CCEK_ArrayBound, ///< Array bound in array declarator or new-expression.
3527  CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3528  CCEK_Noexcept ///< Condition in a noexcept(bool) specifier.
3529  };
3531  llvm::APSInt &Value, CCEKind CCE);
3533  APValue &Value, CCEKind CCE,
3534  NamedDecl *Dest = nullptr);
3535 
3536  /// Abstract base class used to perform a contextual implicit
3537  /// conversion from an expression to any type passing a filter.
3539  public:
3540  bool Suppress;
3542 
3544  bool SuppressConversion = false)
3546 
3547  /// Determine whether the specified type is a valid destination type
3548  /// for this conversion.
3549  virtual bool match(QualType T) = 0;
3550 
3551  /// Emits a diagnostic complaining that the expression does not have
3552  /// integral or enumeration type.
3553  virtual SemaDiagnosticBuilder
3554  diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3555 
3556  /// Emits a diagnostic when the expression has incomplete class type.
3557  virtual SemaDiagnosticBuilder
3559 
3560  /// Emits a diagnostic when the only matching conversion function
3561  /// is explicit.
3563  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3564 
3565  /// Emits a note for the explicit conversion function.
3566  virtual SemaDiagnosticBuilder
3567  noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3568 
3569  /// Emits a diagnostic when there are multiple possible conversion
3570  /// functions.
3571  virtual SemaDiagnosticBuilder
3573 
3574  /// Emits a note for one of the candidate conversions.
3575  virtual SemaDiagnosticBuilder
3576  noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3577 
3578  /// Emits a diagnostic when we picked a conversion function
3579  /// (for cases when we are not allowed to pick a conversion function).
3581  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3582 
3584  };
3585 
3587  bool AllowScopedEnumerations;
3588 
3589  public:
3590  ICEConvertDiagnoser(bool AllowScopedEnumerations,
3591  bool Suppress, bool SuppressConversion)
3593  AllowScopedEnumerations(AllowScopedEnumerations) {}
3594 
3595  /// Match an integral or (possibly scoped) enumeration type.
3596  bool match(QualType T) override;
3597 
3600  return diagnoseNotInt(S, Loc, T);
3601  }
3602 
3603  /// Emits a diagnostic complaining that the expression does not have
3604  /// integral or enumeration type.
3605  virtual SemaDiagnosticBuilder
3606  diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3607  };
3608 
3609  /// Perform a contextual implicit conversion.
3611  SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3612 
3613 
3618  };
3620 
3621  // Note that LK_String is intentionally after the other literals, as
3622  // this is used for diagnostics logic.
3631  };
3633 
3635  NestedNameSpecifier *Qualifier,
3636  NamedDecl *FoundDecl,
3637  NamedDecl *Member);
3638 
3639  // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3640  // TODO: make this is a typesafe union.
3643 
3645 
3646  void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3647  ArrayRef<Expr *> Args,
3648  OverloadCandidateSet &CandidateSet,
3649  bool SuppressUserConversions = false,
3650  bool PartialOverloading = false,
3651  bool AllowExplicit = true,
3652  bool AllowExplicitConversion = false,
3653  ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3654  ConversionSequenceList EarlyConversions = None,
3655  OverloadCandidateParamOrder PO = {});
3656  void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3657  ArrayRef<Expr *> Args,
3658  OverloadCandidateSet &CandidateSet,
3659  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3660  bool SuppressUserConversions = false,
3661  bool PartialOverloading = false,
3662  bool FirstArgumentIsBase = false);
3663  void AddMethodCandidate(DeclAccessPair FoundDecl,
3664  QualType ObjectType,
3665  Expr::Classification ObjectClassification,
3666  ArrayRef<Expr *> Args,
3667  OverloadCandidateSet& CandidateSet,
3668  bool SuppressUserConversion = false,
3669  OverloadCandidateParamOrder PO = {});
3670  void AddMethodCandidate(CXXMethodDecl *Method,
3671  DeclAccessPair FoundDecl,
3672  CXXRecordDecl *ActingContext, QualType ObjectType,
3673  Expr::Classification ObjectClassification,
3674  ArrayRef<Expr *> Args,
3675  OverloadCandidateSet& CandidateSet,
3676  bool SuppressUserConversions = false,
3677  bool PartialOverloading = false,
3678  ConversionSequenceList EarlyConversions = None,
3679  OverloadCandidateParamOrder PO = {});
3680  void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3681  DeclAccessPair FoundDecl,
3682  CXXRecordDecl *ActingContext,
3683  TemplateArgumentListInfo *ExplicitTemplateArgs,
3684  QualType ObjectType,
3685  Expr::Classification ObjectClassification,
3686  ArrayRef<Expr *> Args,
3687  OverloadCandidateSet& CandidateSet,
3688  bool SuppressUserConversions = false,
3689  bool PartialOverloading = false,
3690  OverloadCandidateParamOrder PO = {});
3692  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3693  TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3694  OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3695  bool PartialOverloading = false, bool AllowExplicit = true,
3696  ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3697  OverloadCandidateParamOrder PO = {});
3699  FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3700  ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3701  ConversionSequenceList &Conversions, bool SuppressUserConversions,
3702  CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3703  Expr::Classification ObjectClassification = {},
3704  OverloadCandidateParamOrder PO = {});
3706  CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3707  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3708  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3709  bool AllowExplicit, bool AllowResultConversion = true);
3711  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3712  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3713  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3714  bool AllowExplicit, bool AllowResultConversion = true);
3715  void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3716  DeclAccessPair FoundDecl,
3717  CXXRecordDecl *ActingContext,
3718  const FunctionProtoType *Proto,
3719  Expr *Object, ArrayRef<Expr *> Args,
3720  OverloadCandidateSet& CandidateSet);
3722  const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3723  OverloadCandidateSet &CandidateSet,
3724  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3726  SourceLocation OpLoc, ArrayRef<Expr *> Args,
3727  OverloadCandidateSet &CandidateSet,
3728  OverloadCandidateParamOrder PO = {});
3729  void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3730  OverloadCandidateSet& CandidateSet,
3731  bool IsAssignmentOperator = false,
3732  unsigned NumContextualBoolArguments = 0);
3734  SourceLocation OpLoc, ArrayRef<Expr *> Args,
3735  OverloadCandidateSet& CandidateSet);
3736  void AddArgumentDependentLookupCandidates(DeclarationName Name,
3737  SourceLocation Loc,
3738  ArrayRef<Expr *> Args,
3739  TemplateArgumentListInfo *ExplicitTemplateArgs,
3740  OverloadCandidateSet& CandidateSet,
3741  bool PartialOverloading = false);
3742 
3743  // Emit as a 'note' the specific overload candidate
3744  void NoteOverloadCandidate(
3745  NamedDecl *Found, FunctionDecl *Fn,
3747  QualType DestType = QualType(), bool TakingAddress = false);
3748 
3749  // Emit as a series of 'note's all template and non-templates identified by
3750  // the expression Expr
3751  void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3752  bool TakingAddress = false);
3753 
3754  /// Check the enable_if expressions on the given function. Returns the first
3755  /// failing attribute, or NULL if they were all successful.
3756  EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
3757  ArrayRef<Expr *> Args,
3758  bool MissingImplicitThis = false);
3759 
3760  /// Find the failed Boolean condition within a given Boolean
3761  /// constant expression, and describe it with a string.
3762  std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3763 
3764  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3765  /// non-ArgDependent DiagnoseIfAttrs.
3766  ///
3767  /// Argument-dependent diagnose_if attributes should be checked each time a
3768  /// function is used as a direct callee of a function call.
3769  ///
3770  /// Returns true if any errors were emitted.
3771  bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3772  const Expr *ThisArg,
3773  ArrayRef<const Expr *> Args,
3774  SourceLocation Loc);
3775 
3776  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3777  /// ArgDependent DiagnoseIfAttrs.
3778  ///
3779  /// Argument-independent diagnose_if attributes should be checked on every use
3780  /// of a function.
3781  ///
3782  /// Returns true if any errors were emitted.
3783  bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3784  SourceLocation Loc);
3785 
3786  /// Returns whether the given function's address can be taken or not,
3787  /// optionally emitting a diagnostic if the address can't be taken.
3788  ///
3789  /// Returns false if taking the address of the function is illegal.
3790  bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3791  bool Complain = false,
3792  SourceLocation Loc = SourceLocation());
3793 
3794  // [PossiblyAFunctionType] --> [Return]
3795  // NonFunctionType --> NonFunctionType
3796  // R (A) --> R(A)
3797  // R (*)(A) --> R (A)
3798  // R (&)(A) --> R (A)
3799  // R (S::*)(A) --> R (A)
3800  QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3801 
3802  FunctionDecl *
3803  ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3804  QualType TargetType,
3805  bool Complain,
3806  DeclAccessPair &Found,
3807  bool *pHadMultipleCandidates = nullptr);
3808 
3809  FunctionDecl *
3810  resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3811 
3813  ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3814 
3815  FunctionDecl *
3817  bool Complain = false,
3818  DeclAccessPair *Found = nullptr);
3819 
3821  ExprResult &SrcExpr,
3822  bool DoFunctionPointerConverion = false,
3823  bool Complain = false,
3824  SourceRange OpRangeForComplaining = SourceRange(),
3825  QualType DestTypeForComplaining = QualType(),
3826  unsigned DiagIDForComplaining = 0);
3827 
3828 
3829  Expr *FixOverloadedFunctionReference(Expr *E,
3830  DeclAccessPair FoundDecl,
3831  FunctionDecl *Fn);
3833  DeclAccessPair FoundDecl,
3834  FunctionDecl *Fn);
3835 
3836  void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3837  ArrayRef<Expr *> Args,
3838  OverloadCandidateSet &CandidateSet,
3839  bool PartialOverloading = false);
3841  LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
3842  ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
3843 
3844  // An enum used to represent the different possible results of building a
3845  // range-based for loop.
3850  };
3851 
3853  SourceLocation RangeLoc,
3854  const DeclarationNameInfo &NameInfo,
3855  LookupResult &MemberLookup,
3856  OverloadCandidateSet *CandidateSet,
3857  Expr *Range, ExprResult *CallExpr);
3858 
3860  UnresolvedLookupExpr *ULE,
3861  SourceLocation LParenLoc,
3862  MultiExprArg Args,
3863  SourceLocation RParenLoc,
3864  Expr *ExecConfig,
3865  bool AllowTypoCorrection=true,
3866  bool CalleesAddressIsTaken=false);
3867 
3869  MultiExprArg Args, SourceLocation RParenLoc,
3870  OverloadCandidateSet *CandidateSet,
3871  ExprResult *Result);
3872 
3874  NestedNameSpecifierLoc NNSLoc,
3875  DeclarationNameInfo DNI,
3876  const UnresolvedSetImpl &Fns,
3877  bool PerformADL = true);
3878 
3880  UnaryOperatorKind Opc,
3881  const UnresolvedSetImpl &Fns,
3882  Expr *input, bool RequiresADL = true);
3883 
3884  void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
3886  const UnresolvedSetImpl &Fns,
3887  ArrayRef<Expr *> Args, bool RequiresADL = true);
3889  BinaryOperatorKind Opc,
3890  const UnresolvedSetImpl &Fns,
3891  Expr *LHS, Expr *RHS,
3892  bool RequiresADL = true,
3893  bool AllowRewrittenCandidates = true,
3894  FunctionDecl *DefaultedFn = nullptr);
3896  const UnresolvedSetImpl &Fns,
3897  Expr *LHS, Expr *RHS,
3898  FunctionDecl *DefaultedFn);
3899 
3901  SourceLocation RLoc,
3902  Expr *Base,Expr *Idx);
3903 
3905  SourceLocation LParenLoc,
3906  MultiExprArg Args,
3907  SourceLocation RParenLoc,
3908  Expr *ExecConfig = nullptr,
3909  bool IsExecConfig = false,
3910  bool AllowRecovery = false);
3911  ExprResult
3912  BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3913  MultiExprArg Args,
3914  SourceLocation RParenLoc);
3915 
3917  SourceLocation OpLoc,
3918  bool *NoArrowOperatorFound = nullptr);
3919 
3920  /// CheckCallReturnType - Checks that a call expression's return type is
3921  /// complete. Returns true on failure. The location passed in is the location
3922  /// that best represents the call.
3923  bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3924  CallExpr *CE, FunctionDecl *FD);
3925 
3926  /// Helpers for dealing with blocks and functions.
3928  bool CheckParameterNames);
3932 
3933  /// \name Name lookup
3934  ///
3935  /// These routines provide name lookup that is used during semantic
3936  /// analysis to resolve the various kinds of names (identifiers,
3937  /// overloaded operator names, constructor names, etc.) into zero or
3938  /// more declarations within a particular scope. The major entry
3939  /// points are LookupName, which performs unqualified name lookup,
3940  /// and LookupQualifiedName, which performs qualified name lookup.
3941  ///
3942  /// All name lookup is performed based on some specific criteria,
3943  /// which specify what names will be visible to name lookup and how
3944  /// far name lookup should work. These criteria are important both
3945  /// for capturing language semantics (certain lookups will ignore
3946  /// certain names, for example) and for performance, since name
3947  /// lookup is often a bottleneck in the compilation of C++. Name
3948  /// lookup criteria is specified via the LookupCriteria enumeration.
3949  ///
3950  /// The results of name lookup can vary based on the kind of name
3951  /// lookup performed, the current language, and the translation
3952  /// unit. In C, for example, name lookup will either return nothing
3953  /// (no entity found) or a single declaration. In C++, name lookup
3954  /// can additionally refer to a set of overloaded functions or
3955  /// result in an ambiguity. All of the possible results of name
3956  /// lookup are captured by the LookupResult class, which provides
3957  /// the ability to distinguish among them.
3958  //@{
3959 
3960  /// Describes the kind of name lookup to perform.
3962  /// Ordinary name lookup, which finds ordinary names (functions,
3963  /// variables, typedefs, etc.) in C and most kinds of names
3964  /// (functions, variables, members, types, etc.) in C++.
3966  /// Tag name lookup, which finds the names of enums, classes,
3967  /// structs, and unions.
3969  /// Label name lookup.
3971  /// Member name lookup, which finds the names of
3972  /// class/struct/union members.
3974  /// Look up of an operator name (e.g., operator+) for use with
3975  /// operator overloading. This lookup is similar to ordinary name
3976  /// lookup, but will ignore any declarations that are class members.
3978  /// Look up a name following ~ in a destructor name. This is an ordinary
3979  /// lookup, but prefers tags to typedefs.
3981  /// Look up of a name that precedes the '::' scope resolution
3982  /// operator in C++. This lookup completely ignores operator, object,
3983  /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3985  /// Look up a namespace name within a C++ using directive or
3986  /// namespace alias definition, ignoring non-namespace names (C++
3987  /// [basic.lookup.udir]p1).
3989  /// Look up all declarations in a scope with the given name,
3990  /// including resolved using declarations. This is appropriate
3991  /// for checking redeclarations for a using declaration.
3993  /// Look up an ordinary name that is going to be redeclared as a
3994  /// name with linkage. This lookup ignores any declarations that
3995  /// are outside of the current scope unless they have linkage. See
3996  /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3998  /// Look up a friend of a local class. This lookup does not look
3999  /// outside the innermost non-class scope. See C++11 [class.friend]p11.
4001  /// Look up the name of an Objective-C protocol.
4003  /// Look up implicit 'self' parameter of an objective-c method.
4005  /// Look up the name of an OpenMP user-defined reduction operation.
4007  /// Look up the name of an OpenMP user-defined mapper.
4009  /// Look up any declaration with any name.
4011  };
4012 
4013  /// Specifies whether (or how) name lookup is being performed for a
4014  /// redeclaration (vs. a reference).
4016  /// The lookup is a reference to this name that is not for the
4017  /// purpose of redeclaring the name.
4019  /// The lookup results will be used for redeclaration of a name,
4020  /// if an entity by that name already exists and is visible.
4022  /// The lookup results will be used for redeclaration of a name
4023  /// with external linkage; non-visible lookup results with external linkage
4024  /// may also be found.
4026  };
4027 
4029  // A declaration with an owning module for linkage can never link against
4030  // anything that is not visible. We don't need to check linkage here; if
4031  // the context has internal linkage, redeclaration lookup won't find things
4032  // from other TUs, and we can't safely compute linkage yet in general.
4033  if (cast<Decl>(CurContext)
4034  ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
4035  return ForVisibleRedeclaration;
4036  return ForExternalRedeclaration;
4037  }
4038 
4039  /// The possible outcomes of name lookup for a literal operator.
4041  /// The lookup resulted in an error.
4043  /// The lookup found no match but no diagnostic was issued.
4045  /// The lookup found a single 'cooked' literal operator, which
4046  /// expects a normal literal to be built and passed to it.
4048  /// The lookup found a single 'raw' literal operator, which expects
4049  /// a string literal containing the spelling of the literal token.
4051  /// The lookup found an overload set of literal operator templates,
4052  /// which expect the characters of the spelling of the literal token to be
4053  /// passed as a non-type template argument pack.
4055  /// The lookup found an overload set of literal operator templates,
4056  /// which expect the character type and characters of the spelling of the
4057  /// string literal token to be passed as template arguments.
4059  };
4060 
4061  SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
4063  bool ConstArg,
4064  bool VolatileArg,
4065  bool RValueThis,
4066  bool ConstThis,
4067  bool VolatileThis);
4068 
4069  typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4070  typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4072 
4073 private:
4074  bool CppLookupName(LookupResult &R, Scope *S);
4075 
4076  struct TypoExprState {
4077  std::unique_ptr<TypoCorrectionConsumer> Consumer;
4078  TypoDiagnosticGenerator DiagHandler;
4079  TypoRecoveryCallback RecoveryHandler;
4080  TypoExprState();
4081  TypoExprState(TypoExprState &&other) noexcept;
4082  TypoExprState &operator=(TypoExprState &&other) noexcept;
4083  };
4084 
4085  /// The set of unhandled TypoExprs and their associated state.
4086  llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4087 
4088  /// Creates a new TypoExpr AST node.
4089  TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4091  TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4092 
4093  // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4094  //
4095  // The boolean value will be true to indicate that the namespace was loaded
4096  // from an AST/PCH file, or false otherwise.
4097  llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4098 
4099  /// Whether we have already loaded known namespaces from an extenal
4100  /// source.
4101  bool LoadedExternalKnownNamespaces;
4102 
4103  /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4104  /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4105  /// should be skipped entirely.
4106  std::unique_ptr<TypoCorrectionConsumer>
4107  makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4108  Sema::LookupNameKind LookupKind, Scope *S,
4109  CXXScopeSpec *SS,
4111  DeclContext *MemberContext, bool EnteringContext,
4112  const ObjCObjectPointerType *OPT,
4113  bool ErrorRecovery);
4114 
4115 public:
4116  const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4117 
4118  /// Clears the state of the given TypoExpr.
4119  void clearDelayedTypo(TypoExpr *TE);
4120 
4121  /// Look up a name, looking for a single declaration. Return
4122  /// null if the results were absent, ambiguous, or overloaded.
4123  ///
4124  /// It is preferable to use the elaborated form and explicitly handle
4125  /// ambiguity and overloaded.
4127  SourceLocation Loc,
4128  LookupNameKind NameKind,
4129  RedeclarationKind Redecl
4131  bool LookupBuiltin(LookupResult &R);
4132  void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4133  bool LookupName(LookupResult &R, Scope *S,
4134  bool AllowBuiltinCreation = false);
4135  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4136  bool InUnqualifiedLookup = false);
4137  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4138  CXXScopeSpec &SS);
4140  bool AllowBuiltinCreation = false,
4141  bool EnteringContext = false);
4143  RedeclarationKind Redecl
4145  bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4146 
4148  UnresolvedSetImpl &Functions);
4149 
4151  SourceLocation GnuLabelLoc = SourceLocation());
4152 
4156  unsigned Quals);
4157  CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4158  bool RValueThis, unsigned ThisQuals);
4160  unsigned Quals);
4161  CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4162  bool RValueThis, unsigned ThisQuals);
4164 
4165  bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
4166  bool IsUDSuffix);
4169  bool AllowRaw, bool AllowTemplate,
4170  bool AllowStringTemplate, bool DiagnoseMissing,
4171  StringLiteral *StringLit = nullptr);
4172  bool isKnownName(StringRef name);
4173 
4174  /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4176  Emitted,
4177  CUDADiscarded, // Discarded due to CUDA/HIP hostness
4178  OMPDiscarded, // Discarded due to OpenMP hostness
4179  TemplateDiscarded, // Discarded due to uninstantiated templates
4180  Unknown,
4181  };
4183  bool Final = false);
4184 
4185  // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4187 
4189  ArrayRef<Expr *> Args, ADLResult &Functions);
4190 
4193  bool IncludeGlobalScope = true,
4194  bool LoadExternal = true);
4197  bool IncludeGlobalScope = true,
4198  bool IncludeDependentBases = false,
4199  bool LoadExternal = true);
4200 
4202  CTK_NonError, // CorrectTypo used in a non error recovery situation.
4203  CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4204  };
4205 
4207  Sema::LookupNameKind LookupKind,
4208  Scope *S, CXXScopeSpec *SS,
4210  CorrectTypoKind Mode,
4211  DeclContext *MemberContext = nullptr,
4212  bool EnteringContext = false,
4213  const ObjCObjectPointerType *OPT = nullptr,
4214  bool RecordFailure = true);
4215 
4217  Sema::LookupNameKind LookupKind, Scope *S,
4218  CXXScopeSpec *SS,
4222  DeclContext *MemberContext = nullptr,
4223  bool EnteringContext = false,
4224  const ObjCObjectPointerType *OPT = nullptr);
4225 
4226  /// Process any TypoExprs in the given Expr and its children,
4227  /// generating diagnostics as appropriate and returning a new Expr if there
4228  /// were typos that were all successfully corrected and ExprError if one or
4229  /// more typos could not be corrected.
4230  ///
4231  /// \param E The Expr to check for TypoExprs.
4232  ///
4233  /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4234  /// initializer.
4235  ///
4236  /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4237  /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4238  ///
4239  /// \param Filter A function applied to a newly rebuilt Expr to determine if
4240  /// it is an acceptable/usable result from a single combination of typo
4241  /// corrections. As long as the filter returns ExprError, different
4242  /// combinations of corrections will be tried until all are exhausted.
4244  Expr *E, VarDecl *InitDecl = nullptr,
4245  bool RecoverUncorrectedTypos = false,
4246  llvm::function_ref<ExprResult(Expr *)> Filter =
4247  [](Expr *E) -> ExprResult { return E; });
4248 
4250  ExprResult ER, VarDecl *InitDecl = nullptr,
4251  bool RecoverUncorrectedTypos = false,
4252  llvm::function_ref<ExprResult(Expr *)> Filter =
4253  [](Expr *E) -> ExprResult { return E; }) {
4254  return ER.isInvalid()
4255  ? ER
4256  : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4257  RecoverUncorrectedTypos, Filter);
4258  }
4259 
4260  void diagnoseTypo(const TypoCorrection &Correction,
4261  const PartialDiagnostic &TypoDiag,
4262  bool ErrorRecovery = true);
4263 
4264  void diagnoseTypo(const TypoCorrection &Correction,
4265  const PartialDiagnostic &TypoDiag,
4266  const PartialDiagnostic &PrevNote,
4267  bool ErrorRecovery = true);
4268 
4269  void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4270 
4271  void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4272  ArrayRef<Expr *> Args,
4273  AssociatedNamespaceSet &AssociatedNamespaces,
4274  AssociatedClassSet &AssociatedClasses);
4275 
4276  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4277  bool ConsiderLinkage, bool AllowInlineNamespace);
4278 
4279  bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4280 
4281  void DiagnoseAmbiguousLookup(LookupResult &Result);
4282  //@}
4283 
4284  /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4285  ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4286  ArrayRef<Expr *> SubExprs,
4287  QualType T = QualType());
4288 
4289  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4290  SourceLocation IdLoc,
4291  bool TypoCorrection = false);
4292  FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4293  SourceLocation Loc);
4294  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4295  Scope *S, bool ForRedeclaration,
4296  SourceLocation Loc);
4297  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4298  Scope *S);
4300  FunctionDecl *FD);
4301  void AddKnownFunctionAttributes(FunctionDecl *FD);
4302 
4303  // More parsing and symbol table subroutines.
4304 
4305  void ProcessPragmaWeak(Scope *S, Decl *D);
4306  // Decl attributes - this routine is the top level dispatcher.
4307  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4308  // Helper for delayed processing of attributes.
4309  void ProcessDeclAttributeDelayed(Decl *D,
4310  const ParsedAttributesView &AttrList);
4311  void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
4312  bool IncludeCXX11Attributes = true);
4313  bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4314  const ParsedAttributesView &AttrList);
4315 
4316  void checkUnusedDeclAttributes(Declarator &D);
4317 
4318  /// Handles semantic checking for features that are common to all attributes,
4319  /// such as checking whether a parameter was properly specified, or the
4320  /// correct number of arguments were passed, etc. Returns true if the
4321  /// attribute has been diagnosed.
4322  bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A);
4323  bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A);
4324 
4325  /// Determine if type T is a valid subject for a nonnull and similar
4326  /// attributes. By default, we look through references (the behavior used by
4327  /// nonnull), but if the second parameter is true, then we treat a reference
4328  /// type as valid.
4329  bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4330 
4331  bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4332  bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
4333  const FunctionDecl *FD = nullptr);
4334  bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4335  bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4336  bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4337  StringRef &Str,
4338  SourceLocation *ArgLocation = nullptr);
4339  llvm::Error isValidSectionSpecifier(StringRef Str);
4340  bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4341  bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4343  CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4344  MSInheritanceModel SemanticSpelling);
4345 
4346  void CheckAlignasUnderalignment(Decl *D);
4347 
4348  /// Adjust the calling convention of a method to be the ABI default if it
4349  /// wasn't specified explicitly. This handles method types formed from
4350  /// function type typedefs and typename template arguments.
4351  void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4352  SourceLocation Loc);
4353 
4354  // Check if there is an explicit attribute, but only look through parens.
4355  // The intent is to look for an attribute on the current declarator, but not
4356  // one that came from a typedef.
4357  bool hasExplicitCallingConv(QualType T);
4358 
4359  /// Get the outermost AttributedType node that sets a calling convention.
4360  /// Valid types should not have multiple attributes with different CCs.
4361  const AttributedType *getCallingConvAttributedType(QualType T) const;
4362 
4363  /// Process the attributes before creating an attributed statement. Returns
4364  /// the semantic attributes that have been processed.
4365  void ProcessStmtAttributes(Stmt *Stmt,
4366  const ParsedAttributesWithRange &InAttrs,
4367  SmallVectorImpl<const Attr *> &OutAttrs);
4368 
4369  void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4370  ObjCMethodDecl *MethodDecl,
4371  bool IsProtocolMethodDecl);
4372 
4373  void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4374  ObjCMethodDecl *Overridden,
4375  bool IsProtocolMethodDecl);
4376 
4377  /// WarnExactTypedMethods - This routine issues a warning if method
4378  /// implementation declaration matches exactly that of its declaration.
4379  void WarnExactTypedMethods(ObjCMethodDecl *Method,
4380  ObjCMethodDecl *MethodDecl,
4381  bool IsProtocolMethodDecl);
4382 
4384 
4385  /// CheckImplementationIvars - This routine checks if the instance variables
4386  /// listed in the implelementation match those listed in the interface.
4388  ObjCIvarDecl **Fields, unsigned nIvars,
4389  SourceLocation Loc);
4390 
4391  /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4392  /// remains unimplemented in the class or category \@implementation.
4393  void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4394  ObjCContainerDecl* IDecl,
4395  bool IncompleteImpl = false);
4396 
4397  /// DiagnoseUnimplementedProperties - This routine warns on those properties
4398  /// which must be implemented by this implementation.
4400  ObjCContainerDecl *CDecl,
4401  bool SynthesizeProperties);
4402 
4403  /// Diagnose any null-resettable synthesized setters.
4405 
4406  /// DefaultSynthesizeProperties - This routine default synthesizes all
4407  /// properties which must be synthesized in the class's \@implementation.
4409  ObjCInterfaceDecl *IDecl,
4410  SourceLocation AtEnd);
4412 
4413  /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4414  /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4415  /// declared in class 'IFace'.
4417  ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4418 
4419  /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4420  /// backs the property is not used in the property's accessor.
4422  const ObjCImplementationDecl *ImplD);
4423 
4424  /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4425  /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4426  /// It also returns ivar's property on success.
4428  const ObjCPropertyDecl *&PDecl) const;
4429 
4430  /// Called by ActOnProperty to handle \@property declarations in
4431  /// class extensions.
4433  SourceLocation AtLoc,
4434  SourceLocation LParenLoc,
4435  FieldDeclarator &FD,
4436  Selector GetterSel,
4437  SourceLocation GetterNameLoc,
4438  Selector SetterSel,
4439  SourceLocation SetterNameLoc,
4440  const bool isReadWrite,
4441  unsigned &Attributes,
4442  const unsigned AttributesAsWritten,
4443  QualType T,
4444  TypeSourceInfo *TSI,
4445  tok::ObjCKeywordKind MethodImplKind);
4446 
4447  /// Called by ActOnProperty and HandlePropertyInClassExtension to
4448  /// handle creating the ObjcPropertyDecl for a category or \@interface.
4450  ObjCContainerDecl *CDecl,
4451  SourceLocation AtLoc,
4452  SourceLocation LParenLoc,
4453  FieldDeclarator &FD,
4454  Selector GetterSel,
4455  SourceLocation GetterNameLoc,
4456  Selector SetterSel,
4457  SourceLocation SetterNameLoc,
4458  const bool isReadWrite,
4459  const unsigned Attributes,
4460  const unsigned AttributesAsWritten,
4461  QualType T,
4462  TypeSourceInfo *TSI,
4463  tok::ObjCKeywordKind MethodImplKind,
4464  DeclContext *lexicalDC = nullptr);
4465 
4466  /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4467  /// warning) when atomic property has one but not the other user-declared
4468  /// setter or getter.
4470  ObjCInterfaceDecl* IDecl);
4471 
4473 
4475  const ObjCImplementationDecl *ImplD,
4476  const ObjCInterfaceDecl *IFD);
4477 
4479 
4483  };
4484 
4485  /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4486  /// true, or false, accordingly.
4487  bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4488  const ObjCMethodDecl *PrevMethod,
4489  MethodMatchStrategy strategy = MMS_strict);
4490 
4491  /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4492  /// or protocol against those declared in their implementations.
4493  void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4494  const SelectorSet &ClsMap,
4495  SelectorSet &InsMapSeen,
4496  SelectorSet &ClsMapSeen,
4497  ObjCImplDecl* IMPDecl,
4498  ObjCContainerDecl* IDecl,
4499  bool &IncompleteImpl,
4500  bool ImmediateClass,
4501  bool WarnCategoryMethodImpl=false);
4502 
4503  /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4504  /// category matches with those implemented in its primary class and
4505  /// warns each time an exact match is found.
4507 
4508  /// Add the given method to the list of globally-known methods.
4510 
4511  /// Returns default addr space for method qualifiers.
4513 
4514 private:
4515  /// AddMethodToGlobalPool - Add an instance or factory method to the global
4516  /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4517  void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4518 
4519  /// LookupMethodInGlobalPool - Returns the instance or factory method and
4520  /// optionally warns if there are multiple signatures.
4521  ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4522  bool receiverIdOrClass,
4523  bool instance);
4524 
4525 public:
4526  /// - Returns instance or factory methods in global method pool for
4527  /// given selector. It checks the desired kind first, if none is found, and
4528  /// parameter checkTheOther is set, it then checks the other kind. If no such
4529  /// method or only one method is found, function returns false; otherwise, it
4530  /// returns true.
4531  bool
4534  bool InstanceFirst, bool CheckTheOther,
4535  const ObjCObjectType *TypeBound = nullptr);
4536 
4537  bool
4539  SourceRange R, bool receiverIdOrClass,
4541 
4542  void
4544  Selector Sel, SourceRange R,
4545  bool receiverIdOrClass);
4546 
4547 private:
4548  /// - Returns a selector which best matches given argument list or
4549  /// nullptr if none could be found
4550  ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4551  bool IsInstance,
4553 
4554 
4555  /// Record the typo correction failure and return an empty correction.
4556  TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4557  bool RecordFailure = true) {
4558  if (RecordFailure)
4559  TypoCorrectionFailures[Typo].insert(TypoLoc);
4560  return TypoCorrection();
4561  }
4562 
4563 public:
4564  /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4565  /// unit are added to a global pool. This allows us to efficiently associate
4566  /// a selector with a method declaraation for purposes of typechecking
4567  /// messages sent to "id" (where the class of the object is unknown).
4568  void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4569  AddMethodToGlobalPool(Method, impl, /*instance*/true);
4570  }
4571 
4572  /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4573  void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4574  AddMethodToGlobalPool(Method, impl, /*instance*/false);
4575  }
4576 
4577  /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4578  /// pool.
4579  void AddAnyMethodToGlobalPool(Decl *D);
4580 
4581  /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4582  /// there are multiple signatures.
4584  bool receiverIdOrClass=false) {
4585  return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4586  /*instance*/true);
4587  }
4588 
4589  /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4590  /// there are multiple signatures.
4592  bool receiverIdOrClass=false) {
4593  return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4594  /*instance*/false);
4595  }
4596 
4598  QualType ObjectType=QualType());
4599  /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4600  /// implementation.
4602 
4603  /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4604  /// initialization.
4607 
4608  //===--------------------------------------------------------------------===//
4609  // Statement Parsing Callbacks: SemaStmt.cpp.
4610 public:
4611  class FullExprArg {
4612  public:
4613  FullExprArg() : E(nullptr) { }
4614  FullExprArg(Sema &actions) : E(nullptr) { }
4615 
4617  return E;
4618  }
4619 
4620  Expr *get() const { return E; }
4621 
4623  return E;
4624  }
4625 
4626  private:
4627  // FIXME: No need to make the entire Sema class a friend when it's just
4628  // Sema::MakeFullExpr that needs access to the constructor below.
4629  friend class Sema;
4630 
4631  explicit FullExprArg(Expr *expr) : E(expr) {}
4632 
4633  Expr *E;
4634  };
4635 
4637  return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4638  }
4640  return FullExprArg(
4641  ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4642  }
4644  ExprResult FE =
4645  ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4646  /*DiscardedValue*/ true);
4647  return FullExprArg(FE.get());
4648  }
4649 
4650  StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4652 
4654  bool HasLeadingEmptyMacro = false);
4655 
4656  void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4660