clang  15.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, typename ValueInfoT> class DenseSet;
78  class SmallBitVector;
79  struct InlineAsmIdentifierInfo;
80 }
81 
82 namespace clang {
83  class ADLResult;
84  class ASTConsumer;
85  class ASTContext;
86  class ASTMutationListener;
87  class ASTReader;
88  class ASTWriter;
89  class ArrayType;
90  class ParsedAttr;
91  class BindingDecl;
92  class BlockDecl;
93  class CapturedDecl;
94  class CXXBasePath;
95  class CXXBasePaths;
96  class CXXBindTemporaryExpr;
98  class CXXConstructorDecl;
99  class CXXConversionDecl;
100  class CXXDeleteExpr;
101  class CXXDestructorDecl;
102  class CXXFieldCollector;
103  class CXXMemberCallExpr;
104  class CXXMethodDecl;
105  class CXXScopeSpec;
106  class CXXTemporary;
107  class CXXTryStmt;
108  class CallExpr;
109  class ClassTemplateDecl;
110  class ClassTemplatePartialSpecializationDecl;
111  class ClassTemplateSpecializationDecl;
112  class VarTemplatePartialSpecializationDecl;
113  class CodeCompleteConsumer;
114  class CodeCompletionAllocator;
115  class CodeCompletionTUInfo;
116  class CodeCompletionResult;
117  class CoroutineBodyStmt;
118  class Decl;
119  class DeclAccessPair;
120  class DeclContext;
121  class DeclRefExpr;
122  class DeclaratorDecl;
123  class DeducedTemplateArgument;
124  class DependentDiagnostic;
125  class DesignatedInitExpr;
126  class Designation;
127  class EnableIfAttr;
128  class EnumConstantDecl;
129  class Expr;
130  class ExtVectorType;
131  class FormatAttr;
132  class FriendDecl;
133  class FunctionDecl;
134  class FunctionProtoType;
135  class FunctionTemplateDecl;
136  class ImplicitConversionSequence;
138  class InitListExpr;
139  class InitializationKind;
140  class InitializationSequence;
141  class InitializedEntity;
142  class IntegerLiteral;
143  class LabelStmt;
144  class LambdaExpr;
145  class LangOptions;
146  class LocalInstantiationScope;
147  class LookupResult;
148  class MacroInfo;
150  class ModuleLoader;
151  class MultiLevelTemplateArgumentList;
152  class NamedDecl;
153  class ObjCCategoryDecl;
154  class ObjCCategoryImplDecl;
155  class ObjCCompatibleAliasDecl;
156  class ObjCContainerDecl;
157  class ObjCImplDecl;
158  class ObjCImplementationDecl;
159  class ObjCInterfaceDecl;
160  class ObjCIvarDecl;
161  template <class T> class ObjCList;
162  class ObjCMessageExpr;
163  class ObjCMethodDecl;
164  class ObjCPropertyDecl;
165  class ObjCProtocolDecl;
166  class OMPThreadPrivateDecl;
167  class OMPRequiresDecl;
168  class OMPDeclareReductionDecl;
169  class OMPDeclareSimdDecl;
170  class OMPClause;
171  struct OMPVarListLocTy;
172  struct OverloadCandidate;
173  enum class OverloadCandidateParamOrder : char;
175  class OverloadCandidateSet;
176  class OverloadExpr;
177  class ParenListExpr;
178  class ParmVarDecl;
179  class Preprocessor;
180  class PseudoDestructorTypeStorage;
181  class PseudoObjectExpr;
182  class QualType;
183  class StandardConversionSequence;
184  class Stmt;
185  class StringLiteral;
186  class SwitchStmt;
187  class TemplateArgument;
188  class TemplateArgumentList;
189  class TemplateArgumentLoc;
190  class TemplateDecl;
191  class TemplateInstantiationCallback;
192  class TemplateParameterList;
193  class TemplatePartialOrderingContext;
194  class TemplateTemplateParmDecl;
195  class Token;
196  class TypeAliasDecl;
197  class TypedefDecl;
198  class TypedefNameDecl;
199  class TypeLoc;
200  class TypoCorrectionConsumer;
201  class UnqualifiedId;
202  class UnresolvedLookupExpr;
203  class UnresolvedMemberExpr;
204  class UnresolvedSetImpl;
205  class UnresolvedSetIterator;
206  class UsingDecl;
207  class UsingShadowDecl;
208  class ValueDecl;
209  class VarDecl;
210  class VarTemplateSpecializationDecl;
211  class VisibilityAttr;
212  class VisibleDeclConsumer;
213  class IndirectFieldDecl;
214  struct DeductionFailureInfo;
215  class TemplateSpecCandidateSet;
216 
217 namespace sema {
218  class AccessedEntity;
219  class BlockScopeInfo;
220  class Capture;
221  class CapturedRegionScopeInfo;
222  class CapturingScopeInfo;
223  class CompoundScopeInfo;
224  class DelayedDiagnostic;
225  class DelayedDiagnosticPool;
226  class FunctionScopeInfo;
227  class LambdaScopeInfo;
228  class PossiblyUnreachableDiag;
229  class SemaPPCallbacks;
230  class TemplateDeductionInfo;
231 }
232 
233 namespace threadSafety {
234  class BeforeSet;
235  void threadSafetyCleanup(BeforeSet* Cache);
236 }
237 
238 // FIXME: No way to easily map from TemplateTypeParmTypes to
239 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
240 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
242 
243 /// Describes whether we've seen any nullability information for the given
244 /// file.
246  /// The first pointer declarator (of any pointer kind) in the file that does
247  /// not have a corresponding nullability annotation.
249 
250  /// The end location for the first pointer declarator in the file. Used for
251  /// placing fix-its.
253 
254  /// Which kind of pointer declarator we saw.
255  uint8_t PointerKind;
256 
257  /// Whether we saw any type nullability annotations in the given file.
258  bool SawTypeNullability = false;
259 };
260 
261 /// A mapping from file IDs to a record of whether we've seen nullability
262 /// information in that file.
264  /// A mapping from file IDs to the nullability information for each file ID.
265  llvm::DenseMap<FileID, FileNullability> Map;
266 
267  /// A single-element cache based on the file ID.
268  struct {
271  } Cache;
272 
273 public:
275  // Check the single-element cache.
276  if (file == Cache.File)
277  return Cache.Nullability;
278 
279  // It's not in the single-element cache; flush the cache if we have one.
280  if (!Cache.File.isInvalid()) {
281  Map[Cache.File] = Cache.Nullability;
282  }
283 
284  // Pull this entry into the cache.
285  Cache.File = file;
286  Cache.Nullability = Map[file];
287  return Cache.Nullability;
288  }
289 };
290 
291 /// Tracks expected type during expression parsing, for use in code completion.
292 /// The type is tied to a particular token, all functions that update or consume
293 /// the type take a start location of the token they are looking at as a
294 /// parameter. This avoids updating the type on hot paths in the parser.
296 public:
297  PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
298 
299  void enterCondition(Sema &S, SourceLocation Tok);
300  void enterReturn(Sema &S, SourceLocation Tok);
301  void enterVariableInit(SourceLocation Tok, Decl *D);
302  /// Handles e.g. BaseType{ .D = Tok...
304  const Designation &D);
305  /// Computing a type for the function argument may require running
306  /// overloading, so we postpone its computation until it is actually needed.
307  ///
308  /// Clients should be very careful when using this funciton, as it stores a
309  /// function_ref, clients should make sure all calls to get() with the same
310  /// location happen while function_ref is alive.
311  ///
312  /// The callback should also emit signature help as a side-effect, but only
313  /// if the completion point has been reached.
315  llvm::function_ref<QualType()> ComputeType);
316 
317  void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
318  void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
319  SourceLocation OpLoc);
320  void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
321  void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
322  void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
323  /// Handles all type casts, including C-style cast, C++ casts, etc.
325 
326  /// Get the expected type associated with this location, if any.
327  ///
328  /// If the location is a function argument, determining the expected type
329  /// involves considering all function overloads and the arguments so far.
330  /// In this case, signature help for these function overloads will be reported
331  /// as a side-effect (only if the completion point has been reached).
333  if (!Enabled || Tok != ExpectedLoc)
334  return QualType();
335  if (!Type.isNull())
336  return Type;
337  if (ComputeType)
338  return ComputeType();
339  return QualType();
340  }
341 
342 private:
343  bool Enabled;
344  /// Start position of a token for which we store expected type.
345  SourceLocation ExpectedLoc;
346  /// Expected type for a token starting at ExpectedLoc.
347  QualType Type;
348  /// A function to compute expected type at ExpectedLoc. It is only considered
349  /// if Type is null.
350  llvm::function_ref<QualType()> ComputeType;
351 };
352 
353 /// Sema - This implements semantic analysis and AST building for C.
354 class Sema final {
355  Sema(const Sema &) = delete;
356  void operator=(const Sema &) = delete;
357 
358  ///Source of additional semantic information.
359  ExternalSemaSource *ExternalSource;
360 
361  ///Whether Sema has generated a multiplexer and has to delete it.
362  bool isMultiplexExternalSource;
363 
364  static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
365 
366  bool isVisibleSlow(const NamedDecl *D);
367 
368  /// Determine whether two declarations should be linked together, given that
369  /// the old declaration might not be visible and the new declaration might
370  /// not have external linkage.
371  bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
372  const NamedDecl *New) {
373  if (isVisible(Old))
374  return true;
375  // See comment in below overload for why it's safe to compute the linkage
376  // of the new declaration here.
377  if (New->isExternallyDeclarable()) {
378  assert(Old->isExternallyDeclarable() &&
379  "should not have found a non-externally-declarable previous decl");
380  return true;
381  }
382  return false;
383  }
384  bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
385 
386  void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
387  QualType ResultTy,
388  ArrayRef<QualType> Args);
389 
390 public:
391  /// The maximum alignment, same as in llvm::Value. We duplicate them here
392  /// because that allows us not to duplicate the constants in clang code,
393  /// which we must to since we can't directly use the llvm constants.
394  /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
395  ///
396  /// This is the greatest alignment value supported by load, store, and alloca
397  /// instructions, and global values.
398  static const unsigned MaxAlignmentExponent = 32;
400 
404 
407 
414 
415  /// Flag indicating whether or not to collect detailed statistics.
417 
418  /// Code-completion consumer.
420 
421  /// CurContext - This is the current declaration context of parsing.
423 
424  /// Generally null except when we temporarily switch decl contexts,
425  /// like in \see ActOnObjCTemporaryExitContainerContext.
427 
428  /// VAListTagName - The declaration name corresponding to __va_list_tag.
429  /// This is used as part of a hack to omit that class from ADL results.
431 
432  bool MSStructPragmaOn; // True when \#pragma ms_struct on
433 
434  /// Controls member pointer representation format under the MS ABI.
437 
438  /// Stack of active SEH __finally scopes. Can be empty.
440 
441  /// Source location for newly created implicit MSInheritanceAttrs
443 
444  /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
445  /// `TransformTypos` in order to keep track of any TypoExprs that are created
446  /// recursively during typo correction and wipe them away if the correction
447  /// fails.
449 
450  /// pragma clang section kind
453  PCSK_BSS = 1,
458  };
459 
461  PCSA_Set = 0,
463  };
464 
467  bool Valid = false;
469  };
470 
476 
478  PSK_Reset = 0x0, // #pragma ()
479  PSK_Set = 0x1, // #pragma (value)
480  PSK_Push = 0x2, // #pragma (push[, id])
481  PSK_Pop = 0x4, // #pragma (pop[, id])
482  PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
483  PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
484  PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
485  };
486 
487  // #pragma pack and align.
489  public:
490  // `Native` represents default align mode, which may vary based on the
491  // platform.
492  enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
493 
494  // #pragma pack info constructor
495  AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
496  : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
497  assert(Num == PackNumber && "The pack number has been truncated.");
498  }
499 
500  // #pragma align info constructor
502  : PackAttr(false), AlignMode(M),
503  PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
504 
505  explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
506 
508 
509  // When a AlignPackInfo itself cannot be used, this returns an 32-bit
510  // integer encoding for it. This should only be passed to
511  // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
512  static uint32_t getRawEncoding(const AlignPackInfo &Info) {
513  std::uint32_t Encoding{};
514  if (Info.IsXLStack())
515  Encoding |= IsXLMask;
516 
517  Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
518 
519  if (Info.IsPackAttr())
520  Encoding |= PackAttrMask;
521 
522  Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
523 
524  return Encoding;
525  }
526 
528  bool IsXL = static_cast<bool>(Encoding & IsXLMask);
530  static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
531  int PackNumber = (Encoding & PackNumMask) >> 4;
532 
533  if (Encoding & PackAttrMask)
534  return AlignPackInfo(M, PackNumber, IsXL);
535 
536  return AlignPackInfo(M, IsXL);
537  }
538 
539  bool IsPackAttr() const { return PackAttr; }
540 
541  bool IsAlignAttr() const { return !PackAttr; }
542 
543  Mode getAlignMode() const { return AlignMode; }
544 
545  unsigned getPackNumber() const { return PackNumber; }
546 
547  bool IsPackSet() const {
548  // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
549  // attriute on a decl.
550  return PackNumber != UninitPackVal && PackNumber != 0;
551  }
552 
553  bool IsXLStack() const { return XLStack; }
554 
555  bool operator==(const AlignPackInfo &Info) const {
556  return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
557  std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
558  Info.XLStack);
559  }
560 
561  bool operator!=(const AlignPackInfo &Info) const {
562  return !(*this == Info);
563  }
564 
565  private:
566  /// \brief True if this is a pragma pack attribute,
567  /// not a pragma align attribute.
568  bool PackAttr;
569 
570  /// \brief The alignment mode that is in effect.
571  Mode AlignMode;
572 
573  /// \brief The pack number of the stack.
574  unsigned char PackNumber;
575 
576  /// \brief True if it is a XL #pragma align/pack stack.
577  bool XLStack;
578 
579  /// \brief Uninitialized pack value.
580  static constexpr unsigned char UninitPackVal = -1;
581 
582  // Masks to encode and decode an AlignPackInfo.
583  static constexpr uint32_t IsXLMask{0x0000'0001};
584  static constexpr uint32_t AlignModeMask{0x0000'0006};
585  static constexpr uint32_t PackAttrMask{0x00000'0008};
586  static constexpr uint32_t PackNumMask{0x0000'01F0};
587  };
588 
589  template<typename ValueType>
590  struct PragmaStack {
591  struct Slot {
592  llvm::StringRef StackSlotLabel;
593  ValueType Value;
596  Slot(llvm::StringRef StackSlotLabel, ValueType Value,
601  };
602 
603  void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
604  llvm::StringRef StackSlotLabel, ValueType Value) {
605  if (Action == PSK_Reset) {
607  CurrentPragmaLocation = PragmaLocation;
608  return;
609  }
610  if (Action & PSK_Push)
611  Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
612  PragmaLocation);
613  else if (Action & PSK_Pop) {
614  if (!StackSlotLabel.empty()) {
615  // If we've got a label, try to find it and jump there.
616  auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
617  return x.StackSlotLabel == StackSlotLabel;
618  });
619  // If we found the label so pop from there.
620  if (I != Stack.rend()) {
621  CurrentValue = I->Value;
622  CurrentPragmaLocation = I->PragmaLocation;
623  Stack.erase(std::prev(I.base()), Stack.end());
624  }
625  } else if (!Stack.empty()) {
626  // We do not have a label, just pop the last entry.
627  CurrentValue = Stack.back().Value;
628  CurrentPragmaLocation = Stack.back().PragmaLocation;
629  Stack.pop_back();
630  }
631  }
632  if (Action & PSK_Set) {
634  CurrentPragmaLocation = PragmaLocation;
635  }
636  }
637 
638  // MSVC seems to add artificial slots to #pragma stacks on entering a C++
639  // method body to restore the stacks on exit, so it works like this:
640  //
641  // struct S {
642  // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
643  // void Method {}
644  // #pragma <name>(pop, InternalPragmaSlot)
645  // };
646  //
647  // It works even with #pragma vtordisp, although MSVC doesn't support
648  // #pragma vtordisp(push [, id], n)
649  // syntax.
650  //
651  // Push / pop a named sentinel slot.
652  void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
653  assert((Action == PSK_Push || Action == PSK_Pop) &&
654  "Can only push / pop #pragma stack sentinels!");
656  }
657 
658  // Constructors.
659  explicit PragmaStack(const ValueType &Default)
661 
662  bool hasValue() const { return CurrentValue != DefaultValue; }
663 
665  ValueType DefaultValue; // Value used for PSK_Reset action.
666  ValueType CurrentValue;
668  };
669  // FIXME: We should serialize / deserialize these if they occur in a PCH (but
670  // we shouldn't do so if they're in a module).
671 
672  /// Whether to insert vtordisps prior to virtual bases in the Microsoft
673  /// C++ ABI. Possible values are 0, 1, and 2, which mean:
674  ///
675  /// 0: Suppress all vtordisps
676  /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
677  /// structors
678  /// 2: Always insert vtordisps to support RTTI on partially constructed
679  /// objects
682  // The current #pragma align/pack values and locations at each #include.
687  };
689  // Segment #pragmas.
694 
695  // This stack tracks the current state of Sema.CurFPFeatures.
698  FPOptionsOverride result;
699  if (!FpPragmaStack.hasValue()) {
700  result = FPOptionsOverride();
701  } else {
702  result = FpPragmaStack.CurrentValue;
703  }
704  return result;
705  }
706 
707  // RAII object to push / pop sentinel slots for all MS #pragma stacks.
708  // Actions should be performed only if we enter / exit a C++ method body.
710  public:
711  PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
713 
714  private:
715  Sema &S;
716  StringRef SlotLabel;
717  bool ShouldAct;
718  };
719 
720  /// A mapping that describes the nullability we've seen in each header file.
722 
723  /// Last section used with #pragma init_seg.
726 
727  /// Sections used with #pragma alloc_text.
728  llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
729 
730  /// VisContext - Manages the stack for \#pragma GCC visibility.
731  void *VisContext; // Really a "PragmaVisStack*"
732 
733  /// This an attribute introduced by \#pragma clang attribute.
738  bool IsUsed;
739  };
740 
741  /// A push'd group of PragmaAttributeEntries.
743  /// The location of the push attribute.
745  /// The namespace of this push group.
748  };
749 
751 
752  /// The declaration that is currently receiving an attribute from the
753  /// #pragma attribute stack.
755 
756  /// This represents the last location of a "#pragma clang optimize off"
757  /// directive if such a directive has not been closed by an "on" yet. If
758  /// optimizations are currently "on", this is set to an invalid location.
760 
761  /// Set of no-builtin functions listed by \#pragma function.
763 
764  /// Flag indicating if Sema is building a recovery call expression.
765  ///
766  /// This flag is used to avoid building recovery call expressions
767  /// if Sema is already doing so, which would cause infinite recursions.
769 
770  /// Used to control the generation of ExprWithCleanups.
772 
773  /// ExprCleanupObjects - This is the stack of objects requiring
774  /// cleanup that are created by the current full expression.
776 
777  /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
778  /// to a variable (constant) that may or may not be odr-used in this Expr, and
779  /// we won't know until all lvalue-to-rvalue and discarded value conversions
780  /// have been applied to all subexpressions of the enclosing full expression.
781  /// This is cleared at the end of each full expression.
782  using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
785 
786  std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
787 
788  /// Stack containing information about each of the nested
789  /// function, block, and method scopes that are currently active.
791 
792  /// The index of the first FunctionScope that corresponds to the current
793  /// context.
794  unsigned FunctionScopesStart = 0;
795 
797  return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
798  FunctionScopes.end());
799  }
800 
801  /// Stack containing information needed when in C++2a an 'auto' is encountered
802  /// in a function declaration parameter type specifier in order to invent a
803  /// corresponding template parameter in the enclosing abbreviated function
804  /// template. This information is also present in LambdaScopeInfo, stored in
805  /// the FunctionScopes stack.
807 
808  /// The index of the first InventedParameterInfo that refers to the current
809  /// context.
811 
813  return llvm::makeArrayRef(InventedParameterInfos.begin() +
815  InventedParameterInfos.end());
816  }
817 
821 
822  /// ExtVectorDecls - This is a list all the extended vector types. This allows
823  /// us to associate a raw vector type with one of the ext_vector type names.
824  /// This is only necessary for issuing pretty diagnostics.
826 
827  /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
828  std::unique_ptr<CXXFieldCollector> FieldCollector;
829 
831 
832  /// Set containing all declared private fields that are not used.
834 
835  /// Set containing all typedefs that are likely unused.
838 
839  /// Delete-expressions to be analyzed at the end of translation unit
840  ///
841  /// This list contains class members, and locations of delete-expressions
842  /// that could not be proven as to whether they mismatch with new-expression
843  /// used in initializer of the field.
844  typedef std::pair<SourceLocation, bool> DeleteExprLoc;
846  llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
847 
849 
850  /// PureVirtualClassDiagSet - a set of class declarations which we have
851  /// emitted a list of pure virtual functions. Used to prevent emitting the
852  /// same list more than once.
853  std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
854 
855  /// ParsingInitForAutoVars - a set of declarations with auto types for which
856  /// we are currently parsing the initializer.
858 
859  /// Look for a locally scoped extern "C" declaration by the given name.
861 
865 
866  /// All the tentative definitions encountered in the TU.
868 
869  /// All the external declarations encoutered and used in the TU.
871 
875 
876  /// The set of file scoped decls seen so far that have not been used
877  /// and must warn if not used. Only contains the first declaration.
879 
883 
884  /// All the delegating constructors seen so far in the file, used for
885  /// cycle detection at the end of the TU.
887 
888  /// All the overriding functions seen during a class definition
889  /// that had their exception spec checks delayed, plus the overridden
890  /// function.
893 
894  /// All the function redeclarations seen during a class definition that had
895  /// their exception spec checks delayed, plus the prior declaration they
896  /// should be checked against. Except during error recovery, the new decl
897  /// should always be a friend declaration, as that's the only valid way to
898  /// redeclare a special member before its class is complete.
901 
902  typedef llvm::MapVector<const FunctionDecl *,
903  std::unique_ptr<LateParsedTemplate>>
906 
907  /// Callback to the parser to parse templated functions when needed.
908  typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
909  typedef void LateTemplateParserCleanupCB(void *P);
913 
915  LateTemplateParserCleanupCB *LTPCleanup,
916  void *P) {
917  LateTemplateParser = LTP;
918  LateTemplateParserCleanup = LTPCleanup;
919  OpaqueParser = P;
920  }
921 
922  class DelayedDiagnostics;
923 
925  sema::DelayedDiagnosticPool *SavedPool;
927  };
930 
931  /// A class which encapsulates the logic for delaying diagnostics
932  /// during parsing and other processing.
934  /// The current pool of diagnostics into which delayed
935  /// diagnostics should go.
937 
938  public:
939  DelayedDiagnostics() : CurPool(nullptr) {}
940 
941  /// Adds a delayed diagnostic.
942  void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
943 
944  /// Determines whether diagnostics should be delayed.
945  bool shouldDelayDiagnostics() { return CurPool != nullptr; }
946 
947  /// Returns the current delayed-diagnostics pool.
949  return CurPool;
950  }
951 
952  /// Enter a new scope. Access and deprecation diagnostics will be
953  /// collected in this pool.
956  state.SavedPool = CurPool;
957  CurPool = &pool;
958  return state;
959  }
960 
961  /// Leave a delayed-diagnostic state that was previously pushed.
962  /// Do not emit any of the diagnostics. This is performed as part
963  /// of the bookkeeping of popping a pool "properly".
965  CurPool = state.SavedPool;
966  }
967 
968  /// Enter a new scope where access and deprecation diagnostics are
969  /// not delayed.
972  state.SavedPool = CurPool;
973  CurPool = nullptr;
974  return state;
975  }
976 
977  /// Undo a previous pushUndelayed().
979  assert(CurPool == nullptr);
980  CurPool = state.SavedPool;
981  }
983 
984  /// A RAII object to temporarily push a declaration context.
985  class ContextRAII {
986  private:
987  Sema &S;
988  DeclContext *SavedContext;
989  ProcessingContextState SavedContextState;
990  QualType SavedCXXThisTypeOverride;
991  unsigned SavedFunctionScopesStart;
992  unsigned SavedInventedParameterInfosStart;
993 
994  public:
995  ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
996  : S(S), SavedContext(S.CurContext),
997  SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
998  SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
999  SavedFunctionScopesStart(S.FunctionScopesStart),
1000  SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1001  {
1002  assert(ContextToPush && "pushing null context");
1003  S.CurContext = ContextToPush;
1004  if (NewThisContext)
1005  S.CXXThisTypeOverride = QualType();
1006  // Any saved FunctionScopes do not refer to this context.
1007  S.FunctionScopesStart = S.FunctionScopes.size();
1008  S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1009  }
1010 
1011  void pop() {
1012  if (!SavedContext) return;
1013  S.CurContext = SavedContext;
1014  S.DelayedDiagnostics.popUndelayed(SavedContextState);
1015  S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1016  S.FunctionScopesStart = SavedFunctionScopesStart;
1017  S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1018  SavedContext = nullptr;
1019  }
1020 
1022  pop();
1023  }
1024  };
1025 
1026  /// Whether the AST is currently being rebuilt to correct immediate
1027  /// invocations. Immediate invocation candidates and references to consteval
1028  /// functions aren't tracked when this is set.
1030 
1031  /// Used to change context to isConstantEvaluated without pushing a heavy
1032  /// ExpressionEvaluationContextRecord object.
1034 
1036  return ExprEvalContexts.back().isConstantEvaluated() ||
1038  }
1039 
1040  /// RAII object to handle the state changes required to synthesize
1041  /// a function body.
1043  Sema &S;
1044  Sema::ContextRAII SavedContext;
1045  bool PushedCodeSynthesisContext = false;
1046 
1047  public:
1049  : S(S), SavedContext(S, DC) {
1050  S.PushFunctionScope();
1051  S.PushExpressionEvaluationContext(
1053  if (auto *FD = dyn_cast<FunctionDecl>(DC))
1054  FD->setWillHaveBody(true);
1055  else
1056  assert(isa<ObjCMethodDecl>(DC));
1057  }
1058 
1060  assert(!PushedCodeSynthesisContext);
1061 
1064  Ctx.PointOfInstantiation = UseLoc;
1065  Ctx.Entity = cast<Decl>(S.CurContext);
1066  S.pushCodeSynthesisContext(Ctx);
1067 
1068  PushedCodeSynthesisContext = true;
1069  }
1070 
1072  if (PushedCodeSynthesisContext)
1073  S.popCodeSynthesisContext();
1074  if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1075  FD->setWillHaveBody(false);
1076  S.PopExpressionEvaluationContext();
1077  S.PopFunctionScopeInfo();
1078  }
1079  };
1080 
1081  /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
1082  /// declared. Rare. May alias another identifier, declared or undeclared.
1083  ///
1084  /// For aliases, the target identifier is used as a key for eventual
1085  /// processing when the target is declared. For the single-identifier form,
1086  /// the sole identifier is used as the key. Each entry is a `SetVector`
1087  /// (ordered by parse order) of aliases (identified by the alias name) in case
1088  /// of multiple aliases to the same undeclared identifier.
1089  llvm::MapVector<
1090  IdentifierInfo *,
1091  llvm::SetVector<
1093  llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
1095 
1096  /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1097  /// \#pragma redefine_extname before declared. Used in Solaris system headers
1098  /// to define functions that occur in multiple standards to call the version
1099  /// in the currently selected standard.
1100  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1101 
1102 
1103  /// Load weak undeclared identifiers from the external source.
1105 
1106  /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1107  /// \#pragma weak during processing of other Decls.
1108  /// I couldn't figure out a clean way to generate these in-line, so
1109  /// we store them here and handle separately -- which is a hack.
1110  /// It would be best to refactor this.
1112 
1114 
1115  /// Translation Unit Scope - useful to Objective-C actions that need
1116  /// to lookup file scope declarations in the "ordinary" C decl namespace.
1117  /// For example, user-defined classes, built-in "id" type, etc.
1119 
1120  /// The C++ "std" namespace, where the standard library resides.
1122 
1123  /// The C++ "std::bad_alloc" class, which is defined by the C++
1124  /// standard library.
1126 
1127  /// The C++ "std::align_val_t" enum class, which is defined by the C++
1128  /// standard library.
1130 
1131  /// The C++ "std::experimental" namespace, where the experimental parts
1132  /// of the standard library resides.
1134 
1135  /// The C++ "std::initializer_list" template, which is defined in
1136  /// <initializer_list>.
1138 
1139  /// The C++ "std::coroutine_traits" template, which is defined in
1140  /// <coroutine_traits>
1142  /// The namespace where coroutine components are defined. In standard,
1143  /// they are defined in std namespace. And in the previous implementation,
1144  /// they are defined in std::experimental namespace.
1146 
1147  /// The C++ "type_info" declaration, which is defined in <typeinfo>.
1149 
1150  /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1152 
1153  /// The C++ "std::source_location::__impl" struct, defined in
1154  /// <source_location>.
1156 
1157  /// Caches identifiers/selectors for NSFoundation APIs.
1158  std::unique_ptr<NSAPI> NSAPIObj;
1159 
1160  /// The declaration of the Objective-C NSNumber class.
1162 
1163  /// The declaration of the Objective-C NSValue class.
1165 
1166  /// Pointer to NSNumber type (NSNumber *).
1168 
1169  /// Pointer to NSValue type (NSValue *).
1171 
1172  /// The Objective-C NSNumber methods used to create NSNumber literals.
1174 
1175  /// The declaration of the Objective-C NSString class.
1177 
1178  /// Pointer to NSString type (NSString *).
1180 
1181  /// The declaration of the stringWithUTF8String: method.
1183 
1184  /// The declaration of the valueWithBytes:objCType: method.
1186 
1187  /// The declaration of the Objective-C NSArray class.
1189 
1190  /// The declaration of the arrayWithObjects:count: method.
1192 
1193  /// The declaration of the Objective-C NSDictionary class.
1195 
1196  /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1198 
1199  /// id<NSCopying> type.
1201 
1202  /// will hold 'respondsToSelector:'
1204 
1205  /// A flag to remember whether the implicit forms of operator new and delete
1206  /// have been declared.
1208 
1209  /// Describes how the expressions currently being parsed are
1210  /// evaluated at run-time, if at all.
1212  /// The current expression and its subexpressions occur within an
1213  /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1214  /// \c sizeof, where the type of the expression may be significant but
1215  /// no code will be generated to evaluate the value of the expression at
1216  /// run time.
1217  Unevaluated,
1218 
1219  /// The current expression occurs within a braced-init-list within
1220  /// an unevaluated operand. This is mostly like a regular unevaluated
1221  /// context, except that we still instantiate constexpr functions that are
1222  /// referenced here so that we can perform narrowing checks correctly.
1224 
1225  /// The current expression occurs within a discarded statement.
1226  /// This behaves largely similarly to an unevaluated operand in preventing
1227  /// definitions from being required, but not in other ways.
1229 
1230  /// The current expression occurs within an unevaluated
1231  /// operand that unconditionally permits abstract references to
1232  /// fields, such as a SIZE operator in MS-style inline assembly.
1234 
1235  /// The current context is "potentially evaluated" in C++11 terms,
1236  /// but the expression is evaluated at compile-time (like the values of
1237  /// cases in a switch statement).
1239 
1240  /// In addition of being constant evaluated, the current expression
1241  /// occurs in an immediate function context - either a consteval function
1242  /// or a consteval if function.
1244 
1245  /// The current expression is potentially evaluated at run time,
1246  /// which means that code may be generated to evaluate the value of the
1247  /// expression at run time.
1249 
1250  /// The current expression is potentially evaluated, but any
1251  /// declarations referenced inside that expression are only used if
1252  /// in fact the current expression is used.
1253  ///
1254  /// This value is used when parsing default function arguments, for which
1255  /// we would like to provide diagnostics (e.g., passing non-POD arguments
1256  /// through varargs) but do not want to mark declarations as "referenced"
1257  /// until the default argument is used.
1259  };
1260 
1261  using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1262 
1263  /// Data structure used to record current or nested
1264  /// expression evaluation contexts.
1266  /// The expression evaluation context.
1268 
1269  /// Whether the enclosing context needed a cleanup.
1271 
1272  /// The number of active cleanup objects when we entered
1273  /// this expression evaluation context.
1275 
1276  /// The number of typos encountered during this expression evaluation
1277  /// context (i.e. the number of TypoExprs created).
1278  unsigned NumTypos;
1279 
1281 
1282  /// The lambdas that are present within this context, if it
1283  /// is indeed an unevaluated context.
1285 
1286  /// The declaration that provides context for lambda expressions
1287  /// and block literals if the normal declaration context does not
1288  /// suffice, e.g., in a default function argument.
1290 
1291  /// If we are processing a decltype type, a set of call expressions
1292  /// for which we have deferred checking the completeness of the return type.
1294 
1295  /// If we are processing a decltype type, a set of temporary binding
1296  /// expressions for which we have deferred checking the destructor.
1298 
1300 
1301  /// Expressions appearing as the LHS of a volatile assignment in this
1302  /// context. We produce a warning for these when popping the context if
1303  /// they are not discarded-value expressions nor unevaluated operands.
1305 
1306  /// Set of candidates for starting an immediate invocation.
1308 
1309  /// Set of DeclRefExprs referencing a consteval function when used in a
1310  /// context not already known to be immediately invoked.
1312 
1313  /// \brief Describes whether we are in an expression constext which we have
1314  /// to handle differently.
1317  } ExprContext;
1318 
1319  // A context can be nested in both a discarded statement context and
1320  // an immediate function context, so they need to be tracked independently.
1323 
1325  unsigned NumCleanupObjects,
1333 
1334  bool isUnevaluated() const {
1338  }
1339 
1340  bool isConstantEvaluated() const {
1343  }
1344 
1349  }
1350 
1353  (Context ==
1356  }
1357  };
1358 
1359  /// A stack of expression evaluation contexts.
1361 
1362  /// Emit a warning for all pending noderef expressions that we recorded.
1364 
1365  /// Compute the mangling number context for a lambda expression or
1366  /// block literal. Also return the extra mangling decl if any.
1367  ///
1368  /// \param DC - The DeclContext containing the lambda expression or
1369  /// block literal.
1370  std::tuple<MangleNumberingContext *, Decl *>
1372 
1373 
1374  /// SpecialMemberOverloadResult - The overloading result for a special member
1375  /// function.
1376  ///
1377  /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1378  /// integer are used to determine whether overload resolution succeeded.
1380  public:
1381  enum Kind {
1385  };
1386 
1387  private:
1388  llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1389 
1390  public:
1393  : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1394 
1395  CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1396  void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1397 
1398  Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1399  void setKind(Kind K) { Pair.setInt(K); }
1400  };
1401 
1403  : public llvm::FastFoldingSetNode,
1405  public:
1406  SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1407  : FastFoldingSetNode(ID)
1408  {}
1409  };
1410 
1411  /// A cache of special member function overload resolution results
1412  /// for C++ records.
1413  llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1414 
1415  /// A cache of the flags available in enumerations with the flag_bits
1416  /// attribute.
1417  mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1418 
1419  /// The kind of translation unit we are processing.
1420  ///
1421  /// When we're processing a complete translation unit, Sema will perform
1422  /// end-of-translation-unit semantic tasks (such as creating
1423  /// initializers for tentative definitions in C) once parsing has
1424  /// completed. Modules and precompiled headers perform different kinds of
1425  /// checks.
1427 
1428  llvm::BumpPtrAllocator BumpAlloc;
1429 
1430  /// The number of SFINAE diagnostics that have been trapped.
1432 
1433  typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1435 
1436  /// A mapping from parameters with unparsed default arguments to the
1437  /// set of instantiations of each parameter.
1438  ///
1439  /// This mapping is a temporary data structure used when parsing
1440  /// nested class templates or nested classes of class templates,
1441  /// where we might end up instantiating an inner class before the
1442  /// default arguments of its methods have been parsed.
1444 
1445  // Contains the locations of the beginning of unparsed default
1446  // argument locations.
1447  llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1448 
1449  /// UndefinedInternals - all the used, undefined objects which require a
1450  /// definition in this translation unit.
1451  llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1452 
1453  /// Determine if VD, which must be a variable or function, is an external
1454  /// symbol that nonetheless can't be referenced from outside this translation
1455  /// unit because its type has no linkage and it's not extern "C".
1457 
1458  /// Obtain a sorted list of functions that are undefined but ODR-used.
1459  void getUndefinedButUsed(
1460  SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1461 
1462  /// Retrieves list of suspicious delete-expressions that will be checked at
1463  /// the end of translation unit.
1464  const llvm::MapVector<FieldDecl *, DeleteLocs> &
1466 
1468  public:
1469  using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1470  using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1471  iterator begin() { return Methods.begin(); }
1472  iterator end() { return Methods.end(); }
1473  iterator find(Selector Sel) { return Methods.find(Sel); }
1474  std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1475  return Methods.insert(Val);
1476  }
1477  int count(Selector Sel) const { return Methods.count(Sel); }
1478  bool empty() const { return Methods.empty(); }
1479 
1480  private:
1481  llvm::DenseMap<Selector, Lists> Methods;
1482  };
1483 
1484  /// Method Pool - allows efficient lookup when typechecking messages to "id".
1485  /// We need to maintain a list, since selectors can have differing signatures
1486  /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1487  /// of selectors are "overloaded").
1488  /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1489  /// methods inside categories with a particular selector.
1491 
1492  /// Method selectors used in a \@selector expression. Used for implementation
1493  /// of -Wselector.
1494  llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1495 
1496  /// List of SourceLocations where 'self' is implicitly retained inside a
1497  /// block.
1500 
1501  /// Kinds of C++ special members.
1510  };
1511 
1512  typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1514 
1515  /// The C++ special members which we are currently in the process of
1516  /// declaring. If this process recursively triggers the declaration of the
1517  /// same special member, we should act as if it is not yet declared.
1519 
1520  /// Kinds of defaulted comparison operator functions.
1521  enum class DefaultedComparisonKind : unsigned char {
1522  /// This is not a defaultable comparison operator.
1523  None,
1524  /// This is an operator== that should be implemented as a series of
1525  /// subobject comparisons.
1526  Equal,
1527  /// This is an operator<=> that should be implemented as a series of
1528  /// subobject comparisons.
1529  ThreeWay,
1530  /// This is an operator!= that should be implemented as a rewrite in terms
1531  /// of a == comparison.
1532  NotEqual,
1533  /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1534  /// terms of a <=> comparison.
1535  Relational,
1536  };
1537 
1538  /// The function definitions which were renamed as part of typo-correction
1539  /// to match their respective declarations. We want to keep track of them
1540  /// to ensure that we don't emit a "redefinition" error if we encounter a
1541  /// correctly named definition after the renamed definition.
1543 
1544  /// Stack of types that correspond to the parameter entities that are
1545  /// currently being copy-initialized. Can be empty.
1547 
1548  void ReadMethodPool(Selector Sel);
1550 
1551  /// Private Helper predicate to check for 'self'.
1552  bool isSelfExpr(Expr *RExpr);
1553  bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1554 
1555  /// Cause the active diagnostic on the DiagosticsEngine to be
1556  /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1557  /// should not be used elsewhere.
1558  void EmitCurrentDiagnostic(unsigned DiagID);
1559 
1560  /// Records and restores the CurFPFeatures state on entry/exit of compound
1561  /// statements.
1563  public:
1566  FPOptionsOverride getOverrides() { return OldOverrides; }
1567 
1568  private:
1569  Sema& S;
1570  FPOptions OldFPFeaturesState;
1571  FPOptionsOverride OldOverrides;
1572  LangOptions::FPEvalMethodKind OldEvalMethod;
1573  SourceLocation OldFPPragmaLocation;
1574  };
1575 
1576  void addImplicitTypedef(StringRef Name, QualType T);
1577 
1578  bool WarnedStackExhausted = false;
1579 
1580  /// Increment when we find a reference; decrement when we find an ignored
1581  /// assignment. Ultimately the value is 0 if every reference is an ignored
1582  /// assignment.
1583  llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1584 
1585 private:
1586  Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1587 
1588  bool WarnedDarwinSDKInfoMissing = false;
1589 
1590 public:
1591  Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1593  CodeCompleteConsumer *CompletionConsumer = nullptr);
1594  ~Sema();
1595 
1596  /// Perform initialization that occurs after the parser has been
1597  /// initialized but before it parses anything.
1598  void Initialize();
1599 
1600  /// This virtual key function only exists to limit the emission of debug info
1601  /// describing the Sema class. GCC and Clang only emit debug info for a class
1602  /// with a vtable when the vtable is emitted. Sema is final and not
1603  /// polymorphic, but the debug info size savings are so significant that it is
1604  /// worth adding a vtable just to take advantage of this optimization.
1605  virtual void anchor();
1606 
1607  const LangOptions &getLangOpts() const { return LangOpts; }
1610 
1613  Preprocessor &getPreprocessor() const { return PP; }
1614  ASTContext &getASTContext() const { return Context; }
1615  ASTConsumer &getASTConsumer() const { return Consumer; }
1617  ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1618 
1620  StringRef Platform);
1622 
1623  ///Registers an external source. If an external source already exists,
1624  /// creates a multiplex external source and appends to it.
1625  ///
1626  ///\param[in] E - A non-null external sema source.
1627  ///
1629 
1630  void PrintStats() const;
1631 
1632  /// Warn that the stack is nearly exhausted.
1634 
1635  /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1636  /// guaranteed). Produces a warning if we're low on stack space and allocates
1637  /// more in that case. Use this in code that may recurse deeply (for example,
1638  /// in template instantiation) to avoid stack overflow.
1640  llvm::function_ref<void()> Fn);
1641 
1642  /// Helper class that creates diagnostics with optional
1643  /// template instantiation stacks.
1644  ///
1645  /// This class provides a wrapper around the basic DiagnosticBuilder
1646  /// class that emits diagnostics. ImmediateDiagBuilder is
1647  /// responsible for emitting the diagnostic (as DiagnosticBuilder
1648  /// does) and, if the diagnostic comes from inside a template
1649  /// instantiation, printing the template instantiation stack as
1650  /// well.
1652  Sema &SemaRef;
1653  unsigned DiagID;
1654 
1655  public:
1656  ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1657  : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1658  ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1659  : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1660 
1661  // This is a cunning lie. DiagnosticBuilder actually performs move
1662  // construction in its copy constructor (but due to varied uses, it's not
1663  // possible to conveniently express this as actual move construction). So
1664  // the default copy ctor here is fine, because the base class disables the
1665  // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1666  // in that case anwyay.
1667  ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1668 
1670  // If we aren't active, there is nothing to do.
1671  if (!isActive()) return;
1672 
1673  // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1674  // builder itself so it won't emit the diagnostic in its own destructor.
1675  //
1676  // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1677  // do its own needless checks to see if the diagnostic needs to be
1678  // emitted. However, because we take care to ensure that the builder
1679  // objects never escape, a sufficiently smart compiler will be able to
1680  // eliminate that code.
1681  Clear();
1682 
1683  // Dispatch to Sema to emit the diagnostic.
1684  SemaRef.EmitCurrentDiagnostic(DiagID);
1685  }
1686 
1687  /// Teach operator<< to produce an object of the correct type.
1688  template <typename T>
1689  friend const ImmediateDiagBuilder &
1691  const DiagnosticBuilder &BaseDiag = Diag;
1692  BaseDiag << Value;
1693  return Diag;
1694  }
1695 
1696  // It is necessary to limit this to rvalue reference to avoid calling this
1697  // function with a bitfield lvalue argument since non-const reference to
1698  // bitfield is not allowed.
1699  template <typename T, typename = typename std::enable_if<
1700  !std::is_lvalue_reference<T>::value>::type>
1701  const ImmediateDiagBuilder &operator<<(T &&V) const {
1702  const DiagnosticBuilder &BaseDiag = *this;
1703  BaseDiag << std::move(V);
1704  return *this;
1705  }
1706  };
1707 
1708  /// A generic diagnostic builder for errors which may or may not be deferred.
1709  ///
1710  /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1711  /// which are not allowed to appear inside __device__ functions and are
1712  /// allowed to appear in __host__ __device__ functions only if the host+device
1713  /// function is never codegen'ed.
1714  ///
1715  /// To handle this, we use the notion of "deferred diagnostics", where we
1716  /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1717  ///
1718  /// This class lets you emit either a regular diagnostic, a deferred
1719  /// diagnostic, or no diagnostic at all, according to an argument you pass to
1720  /// its constructor, thus simplifying the process of creating these "maybe
1721  /// deferred" diagnostics.
1723  public:
1724  enum Kind {
1725  /// Emit no diagnostics.
1727  /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1729  /// Emit the diagnostic immediately, and, if it's a warning or error, also
1730  /// emit a call stack showing how this function can be reached by an a
1731  /// priori known-emitted function.
1733  /// Create a deferred diagnostic, which is emitted only if the function
1734  /// it's attached to is codegen'ed. Also emit a call stack as with
1735  /// K_ImmediateWithCallStack.
1737  };
1738 
1739  SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1740  FunctionDecl *Fn, Sema &S);
1742  SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1744 
1745  bool isImmediate() const { return ImmediateDiag.has_value(); }
1746 
1747  /// Convertible to bool: True if we immediately emitted an error, false if
1748  /// we didn't emit an error or we created a deferred error.
1749  ///
1750  /// Example usage:
1751  ///
1752  /// if (SemaDiagnosticBuilder(...) << foo << bar)
1753  /// return ExprError();
1754  ///
1755  /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1756  /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1757  operator bool() const { return isImmediate(); }
1758 
1759  template <typename T>
1760  friend const SemaDiagnosticBuilder &
1762  if (Diag.ImmediateDiag.hasValue())
1763  *Diag.ImmediateDiag << Value;
1764  else if (Diag.PartialDiagId.hasValue())
1765  Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1766  << Value;
1767  return Diag;
1768  }
1769 
1770  // It is necessary to limit this to rvalue reference to avoid calling this
1771  // function with a bitfield lvalue argument since non-const reference to
1772  // bitfield is not allowed.
1773  template <typename T, typename = typename std::enable_if<
1774  !std::is_lvalue_reference<T>::value>::type>
1775  const SemaDiagnosticBuilder &operator<<(T &&V) const {
1776  if (ImmediateDiag.hasValue())
1777  *ImmediateDiag << std::move(V);
1778  else if (PartialDiagId.hasValue())
1779  S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1780  return *this;
1781  }
1782 
1783  friend const SemaDiagnosticBuilder &
1785  if (Diag.ImmediateDiag.hasValue())
1786  PD.Emit(*Diag.ImmediateDiag);
1787  else if (Diag.PartialDiagId.hasValue())
1788  Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1789  return Diag;
1790  }
1791 
1792  void AddFixItHint(const FixItHint &Hint) const {
1793  if (ImmediateDiag.hasValue())
1794  ImmediateDiag->AddFixItHint(Hint);
1795  else if (PartialDiagId.hasValue())
1796  S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1797  }
1798 
1800  return ExprError();
1801  }
1803  return StmtError();
1804  }
1805  operator ExprResult() const { return ExprError(); }
1806  operator StmtResult() const { return StmtError(); }
1807  operator TypeResult() const { return TypeError(); }
1808  operator DeclResult() const { return DeclResult(true); }
1809  operator MemInitResult() const { return MemInitResult(true); }
1810 
1811  private:
1812  Sema &S;
1813  SourceLocation Loc;
1814  unsigned DiagID;
1815  FunctionDecl *Fn;
1816  bool ShowCallStack;
1817 
1818  // Invariant: At most one of these Optionals has a value.
1819  // FIXME: Switch these to a Variant once that exists.
1821  llvm::Optional<unsigned> PartialDiagId;
1822  };
1823 
1824  /// Is the last error level diagnostic immediate. This is used to determined
1825  /// whether the next info diagnostic should be immediate.
1827 
1828  /// Emit a diagnostic.
1829  SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1830  bool DeferHint = false);
1831 
1832  /// Emit a partial diagnostic.
1834  bool DeferHint = false);
1835 
1836  /// Build a partial diagnostic.
1837  PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1838 
1839  /// Whether deferrable diagnostics should be deferred.
1840  bool DeferDiags = false;
1841 
1842  /// RAII class to control scope of DeferDiags.
1844  Sema &S;
1845  bool SavedDeferDiags = false;
1846 
1847  public:
1849  : S(S), SavedDeferDiags(S.DeferDiags) {
1850  S.DeferDiags = DeferDiags;
1851  }
1852  ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1853  };
1854 
1855  /// Whether uncompilable error has occurred. This includes error happens
1856  /// in deferred diagnostics.
1857  bool hasUncompilableErrorOccurred() const;
1858 
1859  bool findMacroSpelling(SourceLocation &loc, StringRef name);
1860 
1861  /// Get a string to suggest for zero-initialization of a type.
1862  std::string
1865 
1866  /// Calls \c Lexer::getLocForEndOfToken()
1868 
1869  /// Retrieve the module loader associated with the preprocessor.
1870  ModuleLoader &getModuleLoader() const;
1871 
1872  /// Invent a new identifier for parameters of abbreviated templates.
1873  IdentifierInfo *
1875  unsigned Index);
1876 
1878 
1879  private:
1880  /// Function or variable declarations to be checked for whether the deferred
1881  /// diagnostics should be emitted.
1882  llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1883 
1884  public:
1885  // Emit all deferred diagnostics.
1886  void emitDeferredDiags();
1887 
1889  /// The global module fragment, between 'module;' and a module-declaration.
1891  /// A normal translation unit fragment. For a non-module unit, this is the
1892  /// entire translation unit. Otherwise, it runs from the module-declaration
1893  /// to the private-module-fragment (if any) or the end of the TU (if not).
1895  /// The private module fragment, between 'module :private;' and the end of
1896  /// the translation unit.
1898  };
1899 
1903 
1905 
1907 
1908  void PushFunctionScope();
1909  void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1911 
1912  /// This is used to inform Sema what the current TemplateParameterDepth
1913  /// is during Parsing. Currently it is used to pass on the depth
1914  /// when parsing generic lambda 'auto' parameters.
1916 
1917  void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1919  unsigned OpenMPCaptureLevel = 0);
1920 
1921  /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1922  /// time after they've been popped.
1924  Sema *Self;
1925 
1926  public:
1927  explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1929  };
1930 
1931  using PoppedFunctionScopePtr =
1932  std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1933 
1936  const Decl *D = nullptr,
1937  QualType BlockType = QualType());
1938 
1940  return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1941  }
1942 
1944 
1948  void setFunctionHasMustTail();
1949 
1950  void PushCompoundScope(bool IsStmtExpr);
1951  void PopCompoundScope();
1952 
1954 
1956 
1957  /// Retrieve the current block, if any.
1959 
1960  /// Get the innermost lambda enclosing the current location, if any. This
1961  /// looks through intervening non-lambda scopes such as local functions and
1962  /// blocks.
1964 
1965  /// Retrieve the current lambda scope info, if any.
1966  /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1967  /// lambda scope info ignoring all inner capturing scopes that are not
1968  /// lambda scopes.
1970  getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1971 
1972  /// Retrieve the current generic lambda info, if any.
1974 
1975  /// Retrieve the current captured region, if any.
1977 
1978  /// Retrieve the current function, if any, that should be analyzed for
1979  /// potential availability violations.
1981 
1982  /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1984 
1985  /// Called before parsing a function declarator belonging to a function
1986  /// declaration.
1988  unsigned TemplateParameterDepth);
1989 
1990  /// Called after parsing a function declarator belonging to a function
1991  /// declaration.
1993 
1994  void ActOnComment(SourceRange Comment);
1995 
1996  //===--------------------------------------------------------------------===//
1997  // Type Analysis / Processing: SemaType.cpp.
1998  //
1999 
2001  const DeclSpec *DS = nullptr);
2002  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2003  const DeclSpec *DS = nullptr);
2005  SourceLocation Loc, DeclarationName Entity);
2006  QualType BuildReferenceType(QualType T, bool LValueRef,
2007  SourceLocation Loc, DeclarationName Entity);
2009  Expr *ArraySize, unsigned Quals,
2010  SourceRange Brackets, DeclarationName Entity);
2011  QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2012  QualType BuildExtVectorType(QualType T, Expr *ArraySize,
2013  SourceLocation AttrLoc);
2014  QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2015  SourceLocation AttrLoc);
2016 
2017  QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2018  SourceLocation AttrLoc);
2019 
2020  /// Same as above, but constructs the AddressSpace index if not provided.
2022  SourceLocation AttrLoc);
2023 
2025 
2027 
2028  /// Build a function type.
2029  ///
2030  /// This routine checks the function type according to C++ rules and
2031  /// under the assumption that the result type and parameter types have
2032  /// just been instantiated from a template. It therefore duplicates
2033  /// some of the behavior of GetTypeForDeclarator, but in a much
2034  /// simpler form that is only suitable for this narrow use case.
2035  ///
2036  /// \param T The return type of the function.
2037  ///
2038  /// \param ParamTypes The parameter types of the function. This array
2039  /// will be modified to account for adjustments to the types of the
2040  /// function parameters.
2041  ///
2042  /// \param Loc The location of the entity whose type involves this
2043  /// function type or, if there is no such entity, the location of the
2044  /// type that will have function type.
2045  ///
2046  /// \param Entity The name of the entity that involves the function
2047  /// type, if known.
2048  ///
2049  /// \param EPI Extra information about the function type. Usually this will
2050  /// be taken from an existing function with the same prototype.
2051  ///
2052  /// \returns A suitable function type, if there are no errors. The
2053  /// unqualified type will always be a FunctionProtoType.
2054  /// Otherwise, returns a NULL type.
2056  MutableArrayRef<QualType> ParamTypes,
2057  SourceLocation Loc, DeclarationName Entity,
2058  const FunctionProtoType::ExtProtoInfo &EPI);
2059 
2061  SourceLocation Loc,
2062  DeclarationName Entity);
2064  SourceLocation Loc, DeclarationName Entity);
2068  SourceLocation Loc);
2070  SourceLocation Loc);
2071  QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2072 
2075 
2076  /// Package the given type and TSI into a ParsedType.
2081  TypeSourceInfo **TInfo = nullptr);
2082  CanThrowResult canThrow(const Stmt *E);
2083  /// Determine whether the callee of a particular function call can throw.
2084  /// E, D and Loc are all optional.
2085  static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2086  SourceLocation Loc = SourceLocation());
2088  const FunctionProtoType *FPT);
2095  const FunctionProtoType *Old, SourceLocation OldLoc,
2096  const FunctionProtoType *New, SourceLocation NewLoc);
2098  const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2099  const FunctionProtoType *Old, SourceLocation OldLoc,
2100  const FunctionProtoType *New, SourceLocation NewLoc);
2101  bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2102  bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2103  const PartialDiagnostic &NestedDiagID,
2104  const PartialDiagnostic &NoteID,
2105  const PartialDiagnostic &NoThrowDiagID,
2106  const FunctionProtoType *Superset,
2107  SourceLocation SuperLoc,
2108  const FunctionProtoType *Subset,
2109  SourceLocation SubLoc);
2110  bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2111  const PartialDiagnostic &NoteID,
2112  const FunctionProtoType *Target,
2113  SourceLocation TargetLoc,
2114  const FunctionProtoType *Source,
2115  SourceLocation SourceLoc);
2116 
2118 
2119  /// The parser has parsed the context-sensitive type 'instancetype'
2120  /// in an Objective-C message declaration. Return the appropriate type.
2122 
2123  /// Abstract class used to diagnose incomplete types.
2124  struct TypeDiagnoser {
2126 
2127  virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2128  virtual ~TypeDiagnoser() {}
2129  };
2130 
2131  static int getPrintable(int I) { return I; }
2132  static unsigned getPrintable(unsigned I) { return I; }
2133  static bool getPrintable(bool B) { return B; }
2134  static const char * getPrintable(const char *S) { return S; }
2135  static StringRef getPrintable(StringRef S) { return S; }
2136  static const std::string &getPrintable(const std::string &S) { return S; }
2137  static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2138  return II;
2139  }
2141  static QualType getPrintable(QualType T) { return T; }
2142  static SourceRange getPrintable(SourceRange R) { return R; }
2143  static SourceRange getPrintable(SourceLocation L) { return L; }
2144  static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2145  static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2146 
2147  template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2148  protected:
2149  unsigned DiagID;
2150  std::tuple<const Ts &...> Args;
2151 
2152  template <std::size_t... Is>
2153  void emit(const SemaDiagnosticBuilder &DB,
2154  std::index_sequence<Is...>) const {
2155  // Apply all tuple elements to the builder in order.
2156  bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2157  (void)Dummy;
2158  }
2159 
2160  public:
2161  BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2162  : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2163  assert(DiagID != 0 && "no diagnostic for type diagnoser");
2164  }
2165 
2166  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2167  const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2168  emit(DB, std::index_sequence_for<Ts...>());
2169  DB << T;
2170  }
2171  };
2172 
2173  /// Do a check to make sure \p Name looks like a legal argument for the
2174  /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2175  /// is invalid for the given declaration.
2176  ///
2177  /// \p AL is used to provide caret diagnostics in case of a malformed name.
2178  ///
2179  /// \returns true if the name is a valid swift name for \p D, false otherwise.
2180  bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2181  const ParsedAttr &AL, bool IsAsync);
2182 
2183  /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2184  /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2185  /// For example, a diagnostic with no other parameters would generally have
2186  /// the form "...%select{incomplete|sizeless}0 type %1...".
2187  template <typename... Ts>
2189  public:
2190  SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2191  : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2192 
2193  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2194  const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2195  this->emit(DB, std::index_sequence_for<Ts...>());
2196  DB << T->isSizelessType() << T;
2197  }
2198  };
2199 
2200  enum class CompleteTypeKind {
2201  /// Apply the normal rules for complete types. In particular,
2202  /// treat all sizeless types as incomplete.
2203  Normal,
2204 
2205  /// Relax the normal rules for complete types so that they include
2206  /// sizeless built-in types.
2208 
2209  // FIXME: Eventually we should flip the default to Normal and opt in
2210  // to AcceptSizeless rather than opt out of it.
2212  };
2213 
2214 private:
2215  /// Methods for marking which expressions involve dereferencing a pointer
2216  /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2217  /// they are parsed, meaning that a noderef pointer may not be accessed. For
2218  /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2219  /// `*p`, but need to check that `address of` is called on it. This requires
2220  /// keeping a container of all pending expressions and checking if the address
2221  /// of them are eventually taken.
2222  void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2223  void CheckAddressOfNoDeref(const Expr *E);
2224  void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2225 
2226  bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2227  CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2228 
2229  struct ModuleScope {
2230  SourceLocation BeginLoc;
2231  clang::Module *Module = nullptr;
2232  bool ModuleInterface = false;
2233  bool IsPartition = false;
2234  bool ImplicitGlobalModuleFragment = false;
2235  VisibleModuleSet OuterVisibleModules;
2236  };
2237  /// The modules we're currently parsing.
2239  /// The global module fragment of the current translation unit.
2240  clang::Module *GlobalModuleFragment = nullptr;
2241 
2242  /// The modules we imported directly.
2243  llvm::SmallPtrSet<clang::Module *, 8> DirectModuleImports;
2244 
2245  /// Namespace definitions that we will export when they finish.
2246  llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2247 
2248  /// Get the module unit whose scope we are currently within.
2249  Module *getCurrentModule() const {
2250  return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2251  }
2252 
2253  /// Helper function to judge if we are in module purview.
2254  /// Return false if we are not in a module.
2255  bool isCurrentModulePurview() const {
2256  return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2257  }
2258 
2259  /// Enter the scope of the global module.
2260  Module *PushGlobalModuleFragment(SourceLocation BeginLoc, bool IsImplicit);
2261  /// Leave the scope of the global module.
2262  void PopGlobalModuleFragment();
2263 
2264  VisibleModuleSet VisibleModules;
2265 
2266  /// Cache for module units which is usable for current module.
2267  llvm::DenseSet<const Module *> UsableModuleUnitsCache;
2268 
2269  bool isUsableModule(const Module *M);
2270 
2271 public:
2272  /// Get the module owning an entity.
2273  Module *getOwningModule(const Decl *Entity) {
2274  return Entity->getOwningModule();
2275  }
2276 
2278  return DirectModuleImports.contains(M);
2279  }
2280 
2281  /// Make a merged definition of an existing hidden definition \p ND
2282  /// visible at the specified location.
2284 
2285  bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2286 
2287  // When loading a non-modular PCH files, this is used to restore module
2288  // visibility.
2289  void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2290  VisibleModules.setVisible(Mod, ImportLoc);
2291  }
2292 
2293  /// Determine whether a declaration is visible to name lookup.
2294  bool isVisible(const NamedDecl *D) {
2295  return D->isUnconditionallyVisible() || isVisibleSlow(D);
2296  }
2297 
2298  /// Determine whether any declaration of an entity is visible.
2299  bool
2301  llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2302  return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2303  }
2304  bool hasVisibleDeclarationSlow(const NamedDecl *D,
2306 
2309 
2310  /// Determine if \p D and \p Suggested have a structurally compatible
2311  /// layout as described in C11 6.2.7/1.
2312  bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2313 
2314  /// Determine if \p D has a visible definition. If not, suggest a declaration
2315  /// that should be made visible to expose the definition.
2316  bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2317  bool OnlyNeedComplete = false);
2319  NamedDecl *Hidden;
2320  return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2321  }
2322 
2323  /// Determine if the template parameter \p D has a visible default argument.
2324  bool
2326  llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2327 
2328  /// Determine if there is a visible declaration of \p D that is an explicit
2329  /// specialization declaration for a specialization of a template. (For a
2330  /// member specialization, use hasVisibleMemberSpecialization.)
2332  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2333 
2334  /// Determine if there is a visible declaration of \p D that is a member
2335  /// specialization declaration (as opposed to an instantiated declaration).
2337  const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2338 
2339  /// Determine if \p A and \p B are equivalent internal linkage declarations
2340  /// from different modules, and thus an ambiguity error can be downgraded to
2341  /// an extension warning.
2343  const NamedDecl *B);
2345  SourceLocation Loc, const NamedDecl *D,
2347 
2349 
2352  return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2353  }
2355  CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2357  CompleteTypeKind Kind, unsigned DiagID);
2358 
2360  TypeDiagnoser &Diagnoser) {
2361  return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2362  }
2363  bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2364  return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2365  }
2366 
2367  template <typename... Ts>
2368  bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2369  const Ts &...Args) {
2370  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2371  return RequireCompleteType(Loc, T, Diagnoser);
2372  }
2373 
2374  template <typename... Ts>
2375  bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2376  const Ts &... Args) {
2377  SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2378  return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2379  }
2380 
2381  /// Get the type of expression E, triggering instantiation to complete the
2382  /// type if necessary -- that is, if the expression refers to a templated
2383  /// static data member of incomplete array type.
2384  ///
2385  /// May still return an incomplete type if instantiation was not possible or
2386  /// if the type is incomplete for a different reason. Use
2387  /// RequireCompleteExprType instead if a diagnostic is expected for an
2388  /// incomplete expression type.
2390 
2391  void completeExprArrayBound(Expr *E);
2393  TypeDiagnoser &Diagnoser);
2394  bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2395 
2396  template <typename... Ts>
2397  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2398  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2399  return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2400  }
2401 
2402  template <typename... Ts>
2403  bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2404  const Ts &... Args) {
2405  SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2406  return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2407  }
2408 
2410  TypeDiagnoser &Diagnoser);
2411  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2412 
2413  template <typename... Ts>
2414  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2415  const Ts &...Args) {
2416  BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2417  return RequireLiteralType(Loc, T, Diagnoser);
2418  }
2419 
2421  const CXXScopeSpec &SS, QualType T,
2422  TagDecl *OwnedTagDecl = nullptr);
2423 
2424  // Returns the underlying type of a decltype with the given expression.
2426 
2428  /// If AsUnevaluated is false, E is treated as though it were an evaluated
2429  /// context, such as when building a type for decltype(auto).
2430  QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2433  SourceLocation Loc);
2434 
2435  //===--------------------------------------------------------------------===//
2436  // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2437  //
2438 
2439  struct SkipBodyInfo {
2442  New(nullptr) {}
2447  };
2448 
2449  DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2450 
2452 
2454 
2456  Scope *S, CXXScopeSpec *SS = nullptr,
2457  bool isClassName = false, bool HasTrailingDot = false,
2458  ParsedType ObjectType = nullptr,
2459  bool IsCtorOrDtorName = false,
2460  bool WantNontrivialTypeSourceInfo = false,
2461  bool IsClassTemplateDeductionContext = true,
2462  IdentifierInfo **CorrectedII = nullptr);
2464  bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2466  SourceLocation IILoc,
2467  Scope *S,
2468  CXXScopeSpec *SS,
2469  ParsedType &SuggestedType,
2470  bool IsTemplateName = false);
2471 
2472  /// Attempt to behave like MSVC in situations where lookup of an unqualified
2473  /// type name has failed in a dependent context. In these situations, we
2474  /// automatically form a DependentTypeName that will retry lookup in a related
2475  /// scope during instantiation.
2477  SourceLocation NameLoc,
2478  bool IsTemplateTypeArg);
2479 
2480  /// Describes the result of the name lookup and resolution performed
2481  /// by \c ClassifyName().
2483  /// This name is not a type or template in this context, but might be
2484  /// something else.
2486  /// Classification failed; an error has been produced.
2488  /// The name has been typo-corrected to a keyword.
2490  /// The name was classified as a type.
2492  /// The name was classified as a specific non-type, non-template
2493  /// declaration. ActOnNameClassifiedAsNonType should be called to
2494  /// convert the declaration to an expression.
2496  /// The name was classified as an ADL-only function name.
2497  /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2498  /// result to an expression.
2500  /// The name denotes a member of a dependent type that could not be
2501  /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2502  /// convert the result to an expression.
2504  /// The name was classified as an overload set, and an expression
2505  /// representing that overload set has been formed.
2506  /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2507  /// expression referencing the overload set.
2509  /// The name was classified as a template whose specializations are types.
2511  /// The name was classified as a variable template name.
2513  /// The name was classified as a function template name.
2515  /// The name was classified as an ADL-only function template name.
2517  /// The name was classified as a concept name.
2519  };
2520 
2523  union {
2528  };
2529 
2530  explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2531 
2532  public:
2534 
2535  NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2536 
2538  return NameClassification(NC_Error);
2539  }
2540 
2543  }
2544 
2547  Result.Expr = E;
2548  return Result;
2549  }
2550 
2553  Result.NonTypeDecl = D;
2554  return Result;
2555  }
2556 
2559  }
2560 
2563  }
2564 
2567  Result.Template = Name;
2568  return Result;
2569  }
2570 
2573  Result.Template = Name;
2574  return Result;
2575  }
2576 
2579  Result.Template = Name;
2580  return Result;
2581  }
2582 
2585  Result.Template = Name;
2586  return Result;
2587  }
2588 
2591  Result.Template = Name;
2592  return Result;
2593  }
2594 
2595  NameClassificationKind getKind() const { return Kind; }
2596 
2598  assert(Kind == NC_OverloadSet);
2599  return Expr;
2600  }
2601 
2603  assert(Kind == NC_Type);
2604  return Type;
2605  }
2606 
2608  assert(Kind == NC_NonType);
2609  return NonTypeDecl;
2610  }
2611 
2613  assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2614  Kind == NC_VarTemplate || Kind == NC_Concept ||
2615  Kind == NC_UndeclaredTemplate);
2616  return Template;
2617  }
2618 
2620  switch (Kind) {
2621  case NC_TypeTemplate:
2622  return TNK_Type_template;
2623  case NC_FunctionTemplate:
2624  return TNK_Function_template;
2625  case NC_VarTemplate:
2626  return TNK_Var_template;
2627  case NC_Concept:
2628  return TNK_Concept_template;
2629  case NC_UndeclaredTemplate:
2630  return TNK_Undeclared_template;
2631  default:
2632  llvm_unreachable("unsupported name classification.");
2633  }
2634  }
2635  };
2636 
2637  /// Perform name lookup on the given name, classifying it based on
2638  /// the results of name lookup and the following token.
2639  ///
2640  /// This routine is used by the parser to resolve identifiers and help direct
2641  /// parsing. When the identifier cannot be found, this routine will attempt
2642  /// to correct the typo and classify based on the resulting name.
2643  ///
2644  /// \param S The scope in which we're performing name lookup.
2645  ///
2646  /// \param SS The nested-name-specifier that precedes the name.
2647  ///
2648  /// \param Name The identifier. If typo correction finds an alternative name,
2649  /// this pointer parameter will be updated accordingly.
2650  ///
2651  /// \param NameLoc The location of the identifier.
2652  ///
2653  /// \param NextToken The token following the identifier. Used to help
2654  /// disambiguate the name.
2655  ///
2656  /// \param CCC The correction callback, if typo correction is desired.
2657  NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2658  IdentifierInfo *&Name, SourceLocation NameLoc,
2659  const Token &NextToken,
2660  CorrectionCandidateCallback *CCC = nullptr);
2661 
2662  /// Act on the result of classifying a name as an undeclared (ADL-only)
2663  /// non-type declaration.
2665  SourceLocation NameLoc);
2666  /// Act on the result of classifying a name as an undeclared member of a
2667  /// dependent base class.
2669  IdentifierInfo *Name,
2670  SourceLocation NameLoc,
2671  bool IsAddressOfOperand);
2672  /// Act on the result of classifying a name as a specific non-type
2673  /// declaration.
2675  NamedDecl *Found,
2676  SourceLocation NameLoc,
2677  const Token &NextToken);
2678  /// Act on the result of classifying a name as an overload set.
2680 
2681  /// Describes the detailed kind of a template name. Used in diagnostics.
2683  ClassTemplate,
2685  VarTemplate,
2686  AliasTemplate,
2688  Concept,
2690  };
2693 
2694  /// Determine whether it's plausible that E was intended to be a
2695  /// template-name.
2696  bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2697  if (!getLangOpts().CPlusPlus || E.isInvalid())
2698  return false;
2699  Dependent = false;
2700  if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2701  return !DRE->hasExplicitTemplateArgs();
2702  if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2703  return !ME->hasExplicitTemplateArgs();
2704  Dependent = true;
2705  if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2706  return !DSDRE->hasExplicitTemplateArgs();
2707  if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2708  return !DSME->hasExplicitTemplateArgs();
2709  // Any additional cases recognized here should also be handled by
2710  // diagnoseExprIntendedAsTemplateName.
2711  return false;
2712  }
2714  SourceLocation Less,
2715  SourceLocation Greater);
2716 
2717  void warnOnReservedIdentifier(const NamedDecl *D);
2718 
2720 
2722  MultiTemplateParamsArg TemplateParameterLists);
2724  QualType &T, SourceLocation Loc,
2725  unsigned FailedFoldDiagID);
2729  DeclarationName Name, SourceLocation Loc,
2730  bool IsTemplateId);
2731  void
2732  diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2733  SourceLocation FallbackLoc,
2734  SourceLocation ConstQualLoc = SourceLocation(),
2735  SourceLocation VolatileQualLoc = SourceLocation(),
2736  SourceLocation RestrictQualLoc = SourceLocation(),
2737  SourceLocation AtomicQualLoc = SourceLocation(),
2738  SourceLocation UnalignedQualLoc = SourceLocation());
2739 
2740  static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2741  void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2743  const LookupResult &R);
2746  const LookupResult &R);
2747  void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2748  const LookupResult &R);
2749  void CheckShadow(Scope *S, VarDecl *D);
2750 
2751  /// Warn if 'E', which is an expression that is about to be modified, refers
2752  /// to a shadowing declaration.
2754 
2756 
2757 private:
2758  /// Map of current shadowing declarations to shadowed declarations. Warn if
2759  /// it looks like the user is trying to modify the shadowing declaration.
2760  llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2761 
2762 public:
2763  void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2764  void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2765  void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2766  TypedefNameDecl *NewTD);
2769  TypeSourceInfo *TInfo,
2772  LookupResult &Previous, bool &Redeclaration);
2774  TypeSourceInfo *TInfo,
2776  MultiTemplateParamsArg TemplateParamLists,
2777  bool &AddToScope,
2779  NamedDecl *
2781  MultiTemplateParamsArg TemplateParamLists);
2782  // Returns true if the variable declaration is a redeclaration
2785  bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2786  Expr *Init);
2790 
2792  TypeSourceInfo *TInfo,
2794  MultiTemplateParamsArg TemplateParamLists,
2795  bool &AddToScope);
2797 
2798  enum class CheckConstexprKind {
2799  /// Diagnose issues that are non-constant or that are extensions.
2800  Diagnose,
2801  /// Identify whether this function satisfies the formal rules for constexpr
2802  /// functions in the current lanugage mode (with no extensions).
2803  CheckValid
2804  };
2805 
2808 
2811  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2813  SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2814  // Returns true if the function declaration is a redeclaration
2817  bool IsMemberSpecialization, bool DeclIsDefn);
2818  bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2820  QualType NewT, QualType OldT);
2821  void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2824  bool IsDefinition);
2828  SourceLocation Loc,
2829  QualType T);
2831  SourceLocation NameLoc, IdentifierInfo *Name,
2832  QualType T, TypeSourceInfo *TSInfo,
2833  StorageClass SC);
2834  void ActOnParamDefaultArgument(Decl *param,
2835  SourceLocation EqualLoc,
2836  Expr *defarg);
2838  SourceLocation ArgLoc);
2839  void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2841  SourceLocation EqualLoc);
2842  void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2843  SourceLocation EqualLoc);
2844 
2845  // Contexts where using non-trivial C union types can be disallowed. This is
2846  // passed to err_non_trivial_c_union_in_invalid_context.
2848  // Function parameter.
2850  // Function return.
2852  // Default-initialized object.
2854  // Variable with automatic storage duration.
2856  // Initializer expression that might copy from another object.
2858  // Assignment.
2860  // Compound literal.
2862  // Block capture.
2864  // lvalue-to-rvalue conversion of volatile type.
2866  };
2867 
2868  /// Emit diagnostics if the initializer or any of its explicit or
2869  /// implicitly-generated subexpressions require copying or
2870  /// default-initializing a type that is or contains a C union type that is
2871  /// non-trivial to copy or default-initialize.
2873 
2874  // These flags are passed to checkNonTrivialCUnion.
2876  NTCUK_Init = 0x1,
2878  NTCUK_Copy = 0x4,
2879  };
2880 
2881  /// Emit diagnostics if a non-trivial C union type or a struct that contains
2882  /// a non-trivial C union is used in an invalid context.
2884  NonTrivialCUnionContext UseContext,
2885  unsigned NonTrivialKind);
2886 
2887  void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2888  void ActOnUninitializedDecl(Decl *dcl);
2889  void ActOnInitializerError(Decl *Dcl);
2890 
2891  void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2892  void ActOnCXXForRangeDecl(Decl *D);
2894  IdentifierInfo *Ident,
2895  ParsedAttributes &Attrs);
2896  void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2897  void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2899  void FinalizeDeclaration(Decl *D);
2903 
2904  /// Should be called on all declarations that might have attached
2905  /// documentation comments.
2906  void ActOnDocumentableDecl(Decl *D);
2908 
2909  enum class FnBodyKind {
2910  /// C++ [dcl.fct.def.general]p1
2911  /// function-body:
2912  /// ctor-initializer[opt] compound-statement
2913  /// function-try-block
2914  Other,
2915  /// = default ;
2916  Default,
2917  /// = delete ;
2918  Delete
2919  };
2920 
2922  SourceLocation LocAfterDecls);
2924  FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2925  SkipBodyInfo *SkipBody = nullptr);
2927  MultiTemplateParamsArg TemplateParamLists,
2928  SkipBodyInfo *SkipBody = nullptr,
2929  FnBodyKind BodyKind = FnBodyKind::Other);
2931  SkipBodyInfo *SkipBody = nullptr,
2932  FnBodyKind BodyKind = FnBodyKind::Other);
2933  void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
2936  ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
2937  void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2939  return D && isa<ObjCMethodDecl>(D);
2940  }
2941 
2942  /// Determine whether we can delay parsing the body of a function or
2943  /// function template until it is used, assuming we don't care about emitting
2944  /// code for that function.
2945  ///
2946  /// This will be \c false if we may need the body of the function in the
2947  /// middle of parsing an expression (where it's impractical to switch to
2948  /// parsing a different function), for instance, if it's constexpr in C++11
2949  /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2950  bool canDelayFunctionBody(const Declarator &D);
2951 
2952  /// Determine whether we can skip parsing the body of a function
2953  /// definition, assuming we don't care about analyzing its body or emitting
2954  /// code for that function.
2955  ///
2956  /// This will be \c false only if we may need the body of the function in
2957  /// order to parse the rest of the program (for instance, if it is
2958  /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2959  bool canSkipFunctionBody(Decl *D);
2960 
2963  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2966 
2967  /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2968  /// attribute for which parsing is delayed.
2970 
2971  /// Diagnose any unused parameters in the given sequence of
2972  /// ParmVarDecl pointers.
2974 
2975  /// Diagnose whether the size of parameters or return value of a
2976  /// function or obj-c method definition is pass-by-value and larger than a
2977  /// specified threshold.
2978  void
2980  QualType ReturnTy, NamedDecl *D);
2981 
2982  void DiagnoseInvalidJumps(Stmt *Body);
2984  SourceLocation AsmLoc,
2985  SourceLocation RParenLoc);
2986 
2987  /// Handle a C++11 empty-declaration and attribute-declaration.
2989  SourceLocation SemiLoc);
2990 
2991  enum class ModuleDeclKind {
2992  Interface, ///< 'export module X;'
2993  Implementation, ///< 'module X;'
2994  PartitionInterface, ///< 'export module X:Y;'
2995  PartitionImplementation, ///< 'module X:Y;'
2996  };
2997 
2998  /// An enumeration to represent the transition of states in parsing module
2999  /// fragments and imports. If we are not parsing a C++20 TU, or we find
3000  /// an error in state transition, the state is set to NotACXX20Module.
3001  enum class ModuleImportState {
3002  FirstDecl, ///< Parsing the first decl in a TU.
3003  GlobalFragment, ///< after 'module;' but before 'module X;'
3004  ImportAllowed, ///< after 'module X;' but before any non-import decl.
3005  ImportFinished, ///< after any non-import decl.
3006  PrivateFragment, ///< after 'module :private;'.
3007  NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
3008  };
3009 
3010 private:
3011  /// The parser has begun a translation unit to be compiled as a C++20
3012  /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3013  void HandleStartOfHeaderUnit();
3014 
3015 public:
3016  /// The parser has processed a module-declaration that begins the definition
3017  /// of a module interface or implementation.
3019  SourceLocation ModuleLoc, ModuleDeclKind MDK,
3020  ModuleIdPath Path, ModuleIdPath Partition,
3021  ModuleImportState &ImportState);
3022 
3023  /// The parser has processed a global-module-fragment declaration that begins
3024  /// the definition of the global module fragment of the current module unit.
3025  /// \param ModuleLoc The location of the 'module' keyword.
3027 
3028  /// The parser has processed a private-module-fragment declaration that begins
3029  /// the definition of the private module fragment of the current module unit.
3030  /// \param ModuleLoc The location of the 'module' keyword.
3031  /// \param PrivateLoc The location of the 'private' keyword.
3033  SourceLocation PrivateLoc);
3034 
3035  /// The parser has processed a module import declaration.
3036  ///
3037  /// \param StartLoc The location of the first token in the declaration. This
3038  /// could be the location of an '@', 'export', or 'import'.
3039  /// \param ExportLoc The location of the 'export' keyword, if any.
3040  /// \param ImportLoc The location of the 'import' keyword.
3041  /// \param Path The module toplevel name as an access path.
3042  /// \param IsPartition If the name is for a partition.
3044  SourceLocation ExportLoc,
3045  SourceLocation ImportLoc, ModuleIdPath Path,
3046  bool IsPartition = false);
3048  SourceLocation ExportLoc,
3049  SourceLocation ImportLoc, Module *M,
3050  ModuleIdPath Path = {});
3051 
3052  /// The parser has processed a module import translated from a
3053  /// #include or similar preprocessing directive.
3054  void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3055  void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3056 
3057  /// The parsed has entered a submodule.
3058  void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3059  /// The parser has left a submodule.
3060  void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3061 
3062  /// Create an implicit import of the given module at the given
3063  /// source location, for error recovery, if possible.
3064  ///
3065  /// This routine is typically used when an entity found by name lookup
3066  /// is actually hidden within a module that we know about but the user
3067  /// has forgotten to import.
3068  void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3069  Module *Mod);
3070 
3071  /// Kinds of missing import. Note, the values of these enumerators correspond
3072  /// to %select values in diagnostics.
3073  enum class MissingImportKind {
3074  Declaration,
3075  Definition,
3079  };
3080 
3081  /// Diagnose that the specified declaration needs to be visible but
3082  /// isn't, and suggest a module import that would resolve the problem.
3084  MissingImportKind MIK, bool Recover = true);
3086  SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3087  MissingImportKind MIK, bool Recover);
3088 
3090  SourceLocation LBraceLoc);
3092  SourceLocation RBraceLoc);
3093 
3094  /// We've found a use of a templated declaration that would trigger an
3095  /// implicit instantiation. Check that any relevant explicit specializations
3096  /// and partial specializations are visible, and diagnose if not.
3098 
3099  /// Retrieve a suitable printing policy for diagnostics.
3101  return getPrintingPolicy(Context, PP);
3102  }
3103 
3104  /// Retrieve a suitable printing policy for diagnostics.
3105  static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3106  const Preprocessor &PP);
3107 
3108  /// Scope actions.
3109  void ActOnPopScope(SourceLocation Loc, Scope *S);
3111 
3113  RecordDecl *&AnonRecord);
3115  MultiTemplateParamsArg TemplateParams,
3116  bool IsExplicitInstantiation,
3117  RecordDecl *&AnonRecord);
3118 
3120  AccessSpecifier AS,
3121  RecordDecl *Record,
3122  const PrintingPolicy &Policy);
3123 
3125  RecordDecl *Record);
3126 
3127  /// Common ways to introduce type names without a tag for use in diagnostics.
3128  /// Keep in sync with err_tag_reference_non_tag.
3129  enum NonTagKind {
3139  };
3140 
3141  /// Given a non-tag type declaration, returns an enum useful for indicating
3142  /// what kind of non-tag type this is.
3144 
3146  TagTypeKind NewTag, bool isDefinition,
3147  SourceLocation NewTagLoc,
3148  const IdentifierInfo *Name);
3149 
3150  enum TagUseKind {
3151  TUK_Reference, // Reference to a tag: 'struct foo *X;'
3152  TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3153  TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3154  TUK_Friend // Friend declaration: 'friend struct foo;'
3155  };
3156 
3157  Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3158  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
3159  SourceLocation NameLoc, const ParsedAttributesView &Attr,
3160  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
3161  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
3162  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
3163  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3164  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3165  SkipBodyInfo *SkipBody = nullptr);
3166 
3168  unsigned TagSpec, SourceLocation TagLoc,
3169  CXXScopeSpec &SS, IdentifierInfo *Name,
3170  SourceLocation NameLoc,
3171  const ParsedAttributesView &Attr,
3172  MultiTemplateParamsArg TempParamLists);
3173 
3175  unsigned TagSpec,
3176  TagUseKind TUK,
3177  const CXXScopeSpec &SS,
3178  IdentifierInfo *Name,
3179  SourceLocation TagLoc,
3180  SourceLocation NameLoc);
3181 
3182  void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3183  IdentifierInfo *ClassName,
3184  SmallVectorImpl<Decl *> &Decls);
3185  Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3186  Declarator &D, Expr *BitfieldWidth);
3187 
3188  FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3189  Declarator &D, Expr *BitfieldWidth,
3190  InClassInitStyle InitStyle,
3191  AccessSpecifier AS);
3193  SourceLocation DeclStart, Declarator &D,
3194  Expr *BitfieldWidth,
3195  InClassInitStyle InitStyle,
3196  AccessSpecifier AS,
3197  const ParsedAttr &MSPropertyAttr);
3198 
3200  TypeSourceInfo *TInfo,
3201  RecordDecl *Record, SourceLocation Loc,
3202  bool Mutable, Expr *BitfieldWidth,
3203  InClassInitStyle InitStyle,
3204  SourceLocation TSSL,
3205  AccessSpecifier AS, NamedDecl *PrevDecl,
3206  Declarator *D = nullptr);
3207 
3208  bool CheckNontrivialField(FieldDecl *FD);
3209  void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3210 
3212  /// The triviality of a method unaffected by "trivial_abi".
3214 
3215  /// The triviality of a method affected by "trivial_abi".
3217  };
3218 
3221  bool Diagnose = false);
3222 
3223  /// For a defaulted function, the kind of defaulted function that it is.
3225  CXXSpecialMember SpecialMember : 8;
3226  DefaultedComparisonKind Comparison : 8;
3227 
3228  public:
3230  : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3231  }
3233  : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3235  : SpecialMember(CXXInvalid), Comparison(Comp) {}
3236 
3237  bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3238  bool isComparison() const {
3239  return Comparison != DefaultedComparisonKind::None;
3240  }
3241 
3242  explicit operator bool() const {
3243  return isSpecialMember() || isComparison();
3244  }
3245 
3246  CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3247  DefaultedComparisonKind asComparison() const { return Comparison; }
3248 
3249  /// Get the index of this function kind for use in diagnostics.
3250  unsigned getDiagnosticIndex() const {
3251  static_assert(CXXInvalid > CXXDestructor,
3252  "invalid should have highest index");
3253  static_assert((unsigned)DefaultedComparisonKind::None == 0,
3254  "none should be equal to zero");
3255  return SpecialMember + (unsigned)Comparison;
3256  }
3257  };
3258 
3259  DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3260 
3263  }
3266  }
3267 
3268  void ActOnLastBitfield(SourceLocation DeclStart,
3269  SmallVectorImpl<Decl *> &AllIvarDecls);
3270  Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3271  Declarator &D, Expr *BitfieldWidth,
3272  tok::ObjCKeywordKind visibility);
3273 
3274  // This is used for both record definitions and ObjC interface declarations.
3275  void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3276  ArrayRef<Decl *> Fields, SourceLocation LBrac,
3277  SourceLocation RBrac, const ParsedAttributesView &AttrList);
3278 
3279  /// ActOnTagStartDefinition - Invoked when we have entered the
3280  /// scope of a tag's definition (e.g., for an enumeration, class,
3281  /// struct, or union).
3283 
3284  /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3285  /// Differently from C++, actually parse the body and reject / error out
3286  /// in case of a structural mismatch.
3287  bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3288 
3290 
3291  /// Invoked when we enter a tag definition that we're skipping.
3293 
3295 
3296  /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3297  /// C++ record definition's base-specifiers clause and are starting its
3298  /// member declarations.
3300  SourceLocation FinalLoc,
3301  bool IsFinalSpelledSealed,
3302  bool IsAbstract,
3303  SourceLocation LBraceLoc);
3304 
3305  /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3306  /// the definition of a tag (enumeration, class, struct, or union).
3308  SourceRange BraceRange);
3309 
3311 
3313 
3314  /// Invoked when we must temporarily exit the objective-c container
3315  /// scope for parsing/looking-up C constructs.
3316  ///
3317  /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3320 
3321  /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3322  /// error parsing the definition of a tag.
3324 
3326  EnumConstantDecl *LastEnumConst,
3327  SourceLocation IdLoc,
3328  IdentifierInfo *Id,
3329  Expr *val);
3331  bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3332  QualType EnumUnderlyingTy, bool IsFixed,
3333  const EnumDecl *Prev);
3334 
3335  /// Determine whether the body of an anonymous enumeration should be skipped.
3336  /// \param II The name of the first enumerator.
3338  SourceLocation IILoc);
3339 
3340  Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3342  const ParsedAttributesView &Attrs,
3343  SourceLocation EqualLoc, Expr *Val);
3344  void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3345  Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3346  const ParsedAttributesView &Attr);
3347 
3348  /// Set the current declaration context until it gets popped.
3349  void PushDeclContext(Scope *S, DeclContext *DC);
3350  void PopDeclContext();
3351 
3352  /// EnterDeclaratorContext - Used when we must lookup names in the context
3353  /// of a declarator's nested name specifier.
3355  void ExitDeclaratorContext(Scope *S);
3356 
3357  /// Enter a template parameter scope, after it's been associated with a particular
3358  /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3359  /// in the correct order.
3360  void EnterTemplatedContext(Scope *S, DeclContext *DC);
3361 
3362  /// Push the parameters of D, which must be a function, into scope.
3363  void ActOnReenterFunctionContext(Scope* S, Decl* D);
3364  void ActOnExitFunctionContext();
3365 
3366  /// If \p AllowLambda is true, treat lambda as function.
3367  DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false);
3368 
3369  /// Returns a pointer to the innermost enclosing function, or nullptr if the
3370  /// current context is not inside a function. If \p AllowLambda is true,
3371  /// this can return the call operator of an enclosing lambda, otherwise
3372  /// lambdas are skipped when looking for an enclosing function.
3373  FunctionDecl *getCurFunctionDecl(bool AllowLambda = false);
3374 
3375  /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3376  /// the method decl for the method being parsed. If we're currently
3377  /// in a 'block', this returns the containing context.
3379 
3380  /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3381  /// or C function we're in, otherwise return null. If we're currently
3382  /// in a 'block', this returns the containing context.
3384 
3385  /// Add this decl to the scope shadowed decl chains.
3386  void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3387 
3388  /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3389  /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3390  /// true if 'D' belongs to the given declaration context.
3391  ///
3392  /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3393  /// enclosing namespace set of the context, rather than contained
3394  /// directly within it.
3395  bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3396  bool AllowInlineNamespace = false);
3397 
3398  /// Finds the scope corresponding to the given decl context, if it
3399  /// happens to be an enclosing scope. Otherwise return NULL.
3400  static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3401 
3402  /// Subroutines of ActOnDeclarator().
3404  TypeSourceInfo *TInfo);
3406 
3407  /// Describes the kind of merge to perform for availability
3408  /// attributes (including "deprecated", "unavailable", and "availability").
3410  /// Don't merge availability attributes at all.
3412  /// Merge availability attributes for a redeclaration, which requires
3413  /// an exact match.
3415  /// Merge availability attributes for an override, which requires
3416  /// an exact match or a weakening of constraints.
3418  /// Merge availability attributes for an implementation of
3419  /// a protocol requirement.
3421  /// Merge availability attributes for an implementation of
3422  /// an optional protocol requirement.
3424  };
3425 
3426  /// Describes the kind of priority given to an availability attribute.
3427  ///
3428  /// The sum of priorities deteremines the final priority of the attribute.
3429  /// The final priority determines how the attribute will be merged.
3430  /// An attribute with a lower priority will always remove higher priority
3431  /// attributes for the specified platform when it is being applied. An
3432  /// attribute with a higher priority will not be applied if the declaration
3433  /// already has an availability attribute with a lower priority for the
3434  /// specified platform. The final prirority values are not expected to match
3435  /// the values in this enumeration, but instead should be treated as a plain
3436  /// integer value. This enumeration just names the priority weights that are
3437  /// used to calculate that final vaue.
3439  /// The availability attribute was specified explicitly next to the
3440  /// declaration.
3442 
3443  /// The availability attribute was applied using '#pragma clang attribute'.
3445 
3446  /// The availability attribute for a specific platform was inferred from
3447  /// an availability attribute for another platform.
3449  };
3450 
3451  /// Attribute merging methods. Return true if a new attribute was added.
3452  AvailabilityAttr *
3454  IdentifierInfo *Platform, bool Implicit,
3455  VersionTuple Introduced, VersionTuple Deprecated,
3456  VersionTuple Obsoleted, bool IsUnavailable,
3457  StringRef Message, bool IsStrict, StringRef Replacement,
3458  AvailabilityMergeKind AMK, int Priority);
3459  TypeVisibilityAttr *
3461  TypeVisibilityAttr::VisibilityType Vis);
3462  VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3463  VisibilityAttr::VisibilityType Vis);
3464  UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3465  StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3466  DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3467  DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3468  MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3469  const AttributeCommonInfo &CI,
3470  bool BestCase,
3471  MSInheritanceModel Model);
3472  ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3473  StringRef NewUserDiagnostic);
3474  FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3475  IdentifierInfo *Format, int FormatIdx,
3476  int FirstArg);
3477  SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3478  StringRef Name);
3479  CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3480  StringRef Name);
3481  AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3482  const AttributeCommonInfo &CI,
3483  const IdentifierInfo *Ident);
3484  MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3485  SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3486  StringRef Name);
3487  OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3488  const AttributeCommonInfo &CI);
3489  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3490  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3491  const InternalLinkageAttr &AL);
3492  WebAssemblyImportNameAttr *mergeImportNameAttr(
3493  Decl *D, const WebAssemblyImportNameAttr &AL);
3494  WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3495  Decl *D, const WebAssemblyImportModuleAttr &AL);
3496  EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3497  EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3498  const EnforceTCBLeafAttr &AL);
3499  BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3500  HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D,
3501  const AttributeCommonInfo &AL,
3502  int X, int Y, int Z);
3503  HLSLShaderAttr *mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
3504  HLSLShaderAttr::ShaderType ShaderType);
3505 
3506  void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3509  LookupResult &OldDecls);
3510  bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3511  bool MergeTypeWithOld, bool NewDeclIsDefn);
3513  Scope *S, bool MergeTypeWithOld);
3516  void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3517  void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3518  bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3519  void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3520  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3521 
3522  // AssignmentAction - This is used by all the assignment diagnostic functions
3523  // to represent what is actually causing the operation
3533  };
3534 
3535  /// C++ Overloading.
3537  /// This is a legitimate overload: the existing declarations are
3538  /// functions or function templates with different signatures.
3540 
3541  /// This is not an overload because the signature exactly matches
3542  /// an existing declaration.
3544 
3545  /// This is not an overload because the lookup results contain a
3546  /// non-function.
3548  };
3550  FunctionDecl *New,
3551  const LookupResult &OldDecls,
3552  NamedDecl *&OldDecl,
3553  bool IsForUsingDecl);
3554  bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
3555  bool ConsiderCudaAttrs = true,
3556  bool ConsiderRequiresClauses = true);
3557 
3558  enum class AllowedExplicit {
3559  /// Allow no explicit functions to be used.
3560  None,
3561  /// Allow explicit conversion functions but not explicit constructors.
3562  Conversions,
3563  /// Allow both explicit conversion functions and explicit constructors.
3564  All
3565  };
3566 
3568  TryImplicitConversion(Expr *From, QualType ToType,
3569  bool SuppressUserConversions,
3570  AllowedExplicit AllowExplicit,
3571  bool InOverloadResolution,
3572  bool CStyle,
3573  bool AllowObjCWritebackConversion);
3574 
3575  bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3576  bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3577  bool IsComplexPromotion(QualType FromType, QualType ToType);
3578  bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3579  bool InOverloadResolution,
3580  QualType& ConvertedType, bool &IncompatibleObjC);
3581  bool isObjCPointerConversion(QualType FromType, QualType ToType,
3582  QualType& ConvertedType, bool &IncompatibleObjC);
3583  bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3584  QualType &ConvertedType);
3585  bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3586  QualType& ConvertedType);
3587  bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3588  const FunctionProtoType *NewType,
3589  unsigned *ArgPos = nullptr,
3590  bool Reversed = false);
3592  QualType FromType, QualType ToType);
3593 
3596  bool CheckPointerConversion(Expr *From, QualType ToType,
3597  CastKind &Kind,
3598  CXXCastPath& BasePath,
3599  bool IgnoreBaseAccess,
3600  bool Diagnose = true);
3601  bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3602  bool InOverloadResolution,
3603  QualType &ConvertedType);
3604  bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3605  CastKind &Kind,
3606  CXXCastPath &BasePath,
3607  bool IgnoreBaseAccess);
3608  bool IsQualificationConversion(QualType FromType, QualType ToType,
3609  bool CStyle, bool &ObjCLifetimeConversion);
3610  bool IsFunctionConversion(QualType FromType, QualType ToType,
3611  QualType &ResultTy);
3614 
3616  const InitializedEntity &Entity, InitListExpr *From);
3617 
3618  bool IsStringInit(Expr *Init, const ArrayType *AT);
3619 
3621  ExprResult Init);
3623  SourceLocation EqualLoc,
3624  ExprResult Init,
3625  bool TopLevelOfInitList = false,
3626  bool AllowExplicit = false);
3628  NestedNameSpecifier *Qualifier,
3629  NamedDecl *FoundDecl,
3630  CXXMethodDecl *Method);
3631 
3632  /// Check that the lifetime of the initializer (and its subobjects) is
3633  /// sufficient for initializing the entity, and perform lifetime extension
3634  /// (when permitted) if not.
3635  void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3636 
3639 
3640  /// Contexts in which a converted constant expression is required.
3641  enum CCEKind {
3642  CCEK_CaseValue, ///< Expression in a case label.
3643  CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
3644  CCEK_TemplateArg, ///< Value of a non-type template parameter.
3645  CCEK_ArrayBound, ///< Array bound in array declarator or new-expression.
3646  CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3647  CCEK_Noexcept ///< Condition in a noexcept(bool) specifier.
3648  };
3650  llvm::APSInt &Value, CCEKind CCE);
3652  APValue &Value, CCEKind CCE,
3653  NamedDecl *Dest = nullptr);
3654 
3655  /// Abstract base class used to perform a contextual implicit
3656  /// conversion from an expression to any type passing a filter.
3658  public:
3659  bool Suppress;
3661 
3663  bool SuppressConversion = false)
3665 
3666  /// Determine whether the specified type is a valid destination type
3667  /// for this conversion.
3668  virtual bool match(QualType T) = 0;
3669 
3670  /// Emits a diagnostic complaining that the expression does not have
3671  /// integral or enumeration type.
3672  virtual SemaDiagnosticBuilder
3673  diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3674 
3675  /// Emits a diagnostic when the expression has incomplete class type.
3676  virtual SemaDiagnosticBuilder
3678 
3679  /// Emits a diagnostic when the only matching conversion function
3680  /// is explicit.
3682  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3683 
3684  /// Emits a note for the explicit conversion function.
3685  virtual SemaDiagnosticBuilder
3686  noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3687 
3688  /// Emits a diagnostic when there are multiple possible conversion
3689  /// functions.
3690  virtual SemaDiagnosticBuilder
3692 
3693  /// Emits a note for one of the candidate conversions.
3694  virtual SemaDiagnosticBuilder
3695  noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3696 
3697  /// Emits a diagnostic when we picked a conversion function
3698  /// (for cases when we are not allowed to pick a conversion function).
3700  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3701 
3703  };
3704 
3706  bool AllowScopedEnumerations;
3707 
3708  public:
3709  ICEConvertDiagnoser(bool AllowScopedEnumerations,
3710  bool Suppress, bool SuppressConversion)
3712  AllowScopedEnumerations(AllowScopedEnumerations) {}
3713 
3714  /// Match an integral or (possibly scoped) enumeration type.
3715  bool match(QualType T) override;
3716 
3719  return diagnoseNotInt(S, Loc, T);
3720  }
3721 
3722  /// Emits a diagnostic complaining that the expression does not have
3723  /// integral or enumeration type.
3724  virtual SemaDiagnosticBuilder
3725  diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3726  };
3727 
3728  /// Perform a contextual implicit conversion.
3730  SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3731 
3732 
3737  };
3739 
3740  // Note that LK_String is intentionally after the other literals, as
3741  // this is used for diagnostics logic.
3750  };
3752 
3754  NestedNameSpecifier *Qualifier,
3755  NamedDecl *FoundDecl,
3756  NamedDecl *Member);
3757 
3758  // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3759  // TODO: make this is a typesafe union.
3762 
3764 
3765  void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3766  ArrayRef<Expr *> Args,
3767  OverloadCandidateSet &CandidateSet,
3768  bool SuppressUserConversions = false,
3769  bool PartialOverloading = false,
3770  bool AllowExplicit = true,
3771  bool AllowExplicitConversion = false,
3772  ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3773  ConversionSequenceList EarlyConversions = None,
3774  OverloadCandidateParamOrder PO = {});
3775  void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3776  ArrayRef<Expr *> Args,
3777  OverloadCandidateSet &CandidateSet,
3778  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3779  bool SuppressUserConversions = false,
3780  bool PartialOverloading = false,
3781  bool FirstArgumentIsBase = false);
3782  void AddMethodCandidate(DeclAccessPair FoundDecl,
3783  QualType ObjectType,
3784  Expr::Classification ObjectClassification,
3785  ArrayRef<Expr *> Args,
3786  OverloadCandidateSet& CandidateSet,
3787  bool SuppressUserConversion = false,
3788  OverloadCandidateParamOrder PO = {});
3789  void AddMethodCandidate(CXXMethodDecl *Method,
3790  DeclAccessPair FoundDecl,
3791  CXXRecordDecl *ActingContext, QualType ObjectType,
3792  Expr::Classification ObjectClassification,
3793  ArrayRef<Expr *> Args,
3794  OverloadCandidateSet& CandidateSet,
3795  bool SuppressUserConversions = false,
3796  bool PartialOverloading = false,
3797  ConversionSequenceList EarlyConversions = None,
3798  OverloadCandidateParamOrder PO = {});
3799  void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3800  DeclAccessPair FoundDecl,
3801  CXXRecordDecl *ActingContext,
3802  TemplateArgumentListInfo *ExplicitTemplateArgs,
3803  QualType ObjectType,
3804  Expr::Classification ObjectClassification,
3805  ArrayRef<Expr *> Args,
3806  OverloadCandidateSet& CandidateSet,
3807  bool SuppressUserConversions = false,
3808  bool PartialOverloading = false,
3809  OverloadCandidateParamOrder PO = {});
3811  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3812  TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3813  OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3814  bool PartialOverloading = false, bool AllowExplicit = true,
3815  ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3816  OverloadCandidateParamOrder PO = {});
3818  FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3819  ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3820  ConversionSequenceList &Conversions, bool SuppressUserConversions,
3821  CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3822  Expr::Classification ObjectClassification = {},
3823  OverloadCandidateParamOrder PO = {});
3825  CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3826  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3827  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3828  bool AllowExplicit, bool AllowResultConversion = true);
3830  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3831  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3832  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3833  bool AllowExplicit, bool AllowResultConversion = true);
3834  void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3835  DeclAccessPair FoundDecl,
3836  CXXRecordDecl *ActingContext,
3837  const FunctionProtoType *Proto,
3838  Expr *Object, ArrayRef<Expr *> Args,
3839  OverloadCandidateSet& CandidateSet);
3841  const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3842  OverloadCandidateSet &CandidateSet,
3843  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3845  SourceLocation OpLoc, ArrayRef<Expr *> Args,
3846  OverloadCandidateSet &CandidateSet,
3847  OverloadCandidateParamOrder PO = {});
3848  void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3849  OverloadCandidateSet& CandidateSet,
3850  bool IsAssignmentOperator = false,
3851  unsigned NumContextualBoolArguments = 0);
3853  SourceLocation OpLoc, ArrayRef<Expr *> Args,
3854  OverloadCandidateSet& CandidateSet);
3855  void AddArgumentDependentLookupCandidates(DeclarationName Name,
3856  SourceLocation Loc,
3857  ArrayRef<Expr *> Args,
3858  TemplateArgumentListInfo *ExplicitTemplateArgs,
3859  OverloadCandidateSet& CandidateSet,
3860  bool PartialOverloading = false);
3861 
3862  // Emit as a 'note' the specific overload candidate
3863  void NoteOverloadCandidate(
3864  NamedDecl *Found, FunctionDecl *Fn,
3866  QualType DestType = QualType(), bool TakingAddress = false);
3867 
3868  // Emit as a series of 'note's all template and non-templates identified by
3869  // the expression Expr
3870  void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3871  bool TakingAddress = false);
3872 
3873  /// Check the enable_if expressions on the given function. Returns the first
3874  /// failing attribute, or NULL if they were all successful.
3875  EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
3876  ArrayRef<Expr *> Args,
3877  bool MissingImplicitThis = false);
3878 
3879  /// Find the failed Boolean condition within a given Boolean
3880  /// constant expression, and describe it with a string.
3881  std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3882 
3883  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3884  /// non-ArgDependent DiagnoseIfAttrs.
3885  ///
3886  /// Argument-dependent diagnose_if attributes should be checked each time a
3887  /// function is used as a direct callee of a function call.
3888  ///
3889  /// Returns true if any errors were emitted.
3890  bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3891  const Expr *ThisArg,
3892  ArrayRef<const Expr *> Args,
3893  SourceLocation Loc);
3894 
3895  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3896  /// ArgDependent DiagnoseIfAttrs.
3897  ///
3898  /// Argument-independent diagnose_if attributes should be checked on every use
3899  /// of a function.
3900  ///
3901  /// Returns true if any errors were emitted.
3902  bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3903  SourceLocation Loc);
3904 
3905  /// Returns whether the given function's address can be taken or not,
3906  /// optionally emitting a diagnostic if the address can't be taken.
3907  ///
3908  /// Returns false if taking the address of the function is illegal.
3909  bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3910  bool Complain = false,
3911  SourceLocation Loc = SourceLocation());
3912 
3913  // [PossiblyAFunctionType] --> [Return]
3914  // NonFunctionType --> NonFunctionType
3915  // R (A) --> R(A)
3916  // R (*)(A) --> R (A)
3917  // R (&)(A) --> R (A)
3918  // R (S::*)(A) --> R (A)
3919  QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3920 
3921  FunctionDecl *
3922  ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3923  QualType TargetType,
3924  bool Complain,
3925  DeclAccessPair &Found,
3926  bool *pHadMultipleCandidates = nullptr);
3927 
3928  FunctionDecl *
3929  resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3930 
3932  ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3933 
3934  FunctionDecl *
3936  bool Complain = false,
3937  DeclAccessPair *Found = nullptr);
3938 
3940  ExprResult &SrcExpr,
3941  bool DoFunctionPointerConverion = false,
3942  bool Complain = false,
3943  SourceRange OpRangeForComplaining = SourceRange(),
3944  QualType DestTypeForComplaining = QualType(),
3945  unsigned DiagIDForComplaining = 0);
3946 
3947 
3948  Expr *FixOverloadedFunctionReference(Expr *E,
3949  DeclAccessPair FoundDecl,
3950  FunctionDecl *Fn);
3952  DeclAccessPair FoundDecl,
3953  FunctionDecl *Fn);
3954 
3955  void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3956  ArrayRef<Expr *> Args,
3957  OverloadCandidateSet &CandidateSet,
3958  bool PartialOverloading = false);
3960  LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
3961  ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
3962 
3963  // An enum used to represent the different possible results of building a
3964  // range-based for loop.
3969  };
3970 
3972  SourceLocation RangeLoc,
3973  const DeclarationNameInfo &NameInfo,
3974  LookupResult &MemberLookup,
3975  OverloadCandidateSet *CandidateSet,
3976  Expr *Range, ExprResult *CallExpr);
3977 
3979  UnresolvedLookupExpr *ULE,
3980  SourceLocation LParenLoc,
3981  MultiExprArg Args,
3982  SourceLocation RParenLoc,
3983  Expr *ExecConfig,
3984  bool AllowTypoCorrection=true,
3985  bool CalleesAddressIsTaken=false);
3986 
3988  MultiExprArg Args, SourceLocation RParenLoc,
3989  OverloadCandidateSet *CandidateSet,
3990  ExprResult *Result);
3991 
3993  NestedNameSpecifierLoc NNSLoc,
3994  DeclarationNameInfo DNI,
3995  const UnresolvedSetImpl &Fns,
3996  bool PerformADL = true);
3997 
3999  UnaryOperatorKind Opc,
4000  const UnresolvedSetImpl &Fns,
4001  Expr *input, bool RequiresADL = true);
4002 
4003  void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
4005  const UnresolvedSetImpl &Fns,
4006  ArrayRef<Expr *> Args, bool RequiresADL = true);
4008  BinaryOperatorKind Opc,
4009  const UnresolvedSetImpl &Fns,
4010  Expr *LHS, Expr *RHS,
4011  bool RequiresADL = true,
4012  bool AllowRewrittenCandidates = true,
4013  FunctionDecl *DefaultedFn = nullptr);
4015  const UnresolvedSetImpl &Fns,
4016  Expr *LHS, Expr *RHS,
4017  FunctionDecl *DefaultedFn);
4018 
4020  SourceLocation RLoc, Expr *Base,
4021  MultiExprArg Args);
4022 
4024  SourceLocation LParenLoc,
4025  MultiExprArg Args,
4026  SourceLocation RParenLoc,
4027  Expr *ExecConfig = nullptr,
4028  bool IsExecConfig = false,
4029  bool AllowRecovery = false);
4030  ExprResult
4031  BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
4032  MultiExprArg Args,
4033  SourceLocation RParenLoc);
4034 
4036  SourceLocation OpLoc,
4037  bool *NoArrowOperatorFound = nullptr);
4038 
4039  /// CheckCallReturnType - Checks that a call expression's return type is
4040  /// complete. Returns true on failure. The location passed in is the location
4041  /// that best represents the call.
4042  bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
4043  CallExpr *CE, FunctionDecl *FD);
4044 
4045  /// Helpers for dealing with blocks and functions.
4047  bool CheckParameterNames);
4051 
4052  /// \name Name lookup
4053  ///
4054  /// These routines provide name lookup that is used during semantic
4055  /// analysis to resolve the various kinds of names (identifiers,
4056  /// overloaded operator names, constructor names, etc.) into zero or
4057  /// more declarations within a particular scope. The major entry
4058  /// points are LookupName, which performs unqualified name lookup,
4059  /// and LookupQualifiedName, which performs qualified name lookup.
4060  ///
4061  /// All name lookup is performed based on some specific criteria,
4062  /// which specify what names will be visible to name lookup and how
4063  /// far name lookup should work. These criteria are important both
4064  /// for capturing language semantics (certain lookups will ignore
4065  /// certain names, for example) and for performance, since name
4066  /// lookup is often a bottleneck in the compilation of C++. Name
4067  /// lookup criteria is specified via the LookupCriteria enumeration.
4068  ///
4069  /// The results of name lookup can vary based on the kind of name
4070  /// lookup performed, the current language, and the translation
4071  /// unit. In C, for example, name lookup will either return nothing
4072  /// (no entity found) or a single declaration. In C++, name lookup
4073  /// can additionally refer to a set of overloaded functions or
4074  /// result in an ambiguity. All of the possible results of name
4075  /// lookup are captured by the LookupResult class, which provides
4076  /// the ability to distinguish among them.
4077  //@{
4078 
4079  /// Describes the kind of name lookup to perform.
4081  /// Ordinary name lookup, which finds ordinary names (functions,
4082  /// variables, typedefs, etc.) in C and most kinds of names
4083  /// (functions, variables, members, types, etc.) in C++.
4085  /// Tag name lookup, which finds the names of enums, classes,
4086  /// structs, and unions.
4088  /// Label name lookup.
4090  /// Member name lookup, which finds the names of
4091  /// class/struct/union members.
4093  /// Look up of an operator name (e.g., operator+) for use with
4094  /// operator overloading. This lookup is similar to ordinary name
4095  /// lookup, but will ignore any declarations that are class members.
4097  /// Look up a name following ~ in a destructor name. This is an ordinary
4098  /// lookup, but prefers tags to typedefs.
4100  /// Look up of a name that precedes the '::' scope resolution
4101  /// operator in C++. This lookup completely ignores operator, object,
4102  /// function, and enumerator names (C++ [basic.lookup.qual]p1).
4104  /// Look up a namespace name within a C++ using directive or
4105  /// namespace alias definition, ignoring non-namespace names (C++
4106  /// [basic.lookup.udir]p1).
4108  /// Look up all declarations in a scope with the given name,
4109  /// including resolved using declarations. This is appropriate
4110  /// for checking redeclarations for a using declaration.
4112  /// Look up an ordinary name that is going to be redeclared as a
4113  /// name with linkage. This lookup ignores any declarations that
4114  /// are outside of the current scope unless they have linkage. See
4115  /// C99 6.2.2p4-5 and C++ [basic.link]p6.
4117  /// Look up a friend of a local class. This lookup does not look
4118  /// outside the innermost non-class scope. See C++11 [class.friend]p11.
4120  /// Look up the name of an Objective-C protocol.
4122  /// Look up implicit 'self' parameter of an objective-c method.
4124  /// Look up the name of an OpenMP user-defined reduction operation.
4126  /// Look up the name of an OpenMP user-defined mapper.
4128  /// Look up any declaration with any name.
4130  };
4131 
4132  /// Specifies whether (or how) name lookup is being performed for a
4133  /// redeclaration (vs. a reference).
4135  /// The lookup is a reference to this name that is not for the
4136  /// purpose of redeclaring the name.
4138  /// The lookup results will be used for redeclaration of a name,
4139  /// if an entity by that name already exists and is visible.
4141  /// The lookup results will be used for redeclaration of a name
4142  /// with external linkage; non-visible lookup results with external linkage
4143  /// may also be found.
4145  };
4146 
4148  // A declaration with an owning module for linkage can never link against
4149  // anything that is not visible. We don't need to check linkage here; if
4150  // the context has internal linkage, redeclaration lookup won't find things
4151  // from other TUs, and we can't safely compute linkage yet in general.
4152  if (cast<Decl>(CurContext)
4153  ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
4154  return ForVisibleRedeclaration;
4155  return ForExternalRedeclaration;
4156  }
4157 
4158  /// The possible outcomes of name lookup for a literal operator.
4160  /// The lookup resulted in an error.
4162  /// The lookup found no match but no diagnostic was issued.
4164  /// The lookup found a single 'cooked' literal operator, which
4165  /// expects a normal literal to be built and passed to it.
4167  /// The lookup found a single 'raw' literal operator, which expects
4168  /// a string literal containing the spelling of the literal token.
4170  /// The lookup found an overload set of literal operator templates,
4171  /// which expect the characters of the spelling of the literal token to be
4172  /// passed as a non-type template argument pack.
4174  /// The lookup found an overload set of literal operator templates,
4175  /// which expect the character type and characters of the spelling of the
4176  /// string literal token to be passed as template arguments.
4178  };
4179 
4180  SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
4182  bool ConstArg,
4183  bool VolatileArg,
4184  bool RValueThis,
4185  bool ConstThis,
4186  bool VolatileThis);
4187 
4188  typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4189  typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4191 
4192 private:
4193  bool CppLookupName(LookupResult &R, Scope *S);
4194 
4195  struct TypoExprState {
4196  std::unique_ptr<TypoCorrectionConsumer> Consumer;
4197  TypoDiagnosticGenerator DiagHandler;
4198  TypoRecoveryCallback RecoveryHandler;
4199  TypoExprState();
4200  TypoExprState(TypoExprState &&other) noexcept;
4201  TypoExprState &operator=(TypoExprState &&other) noexcept;
4202  };
4203 
4204  /// The set of unhandled TypoExprs and their associated state.
4205  llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4206 
4207  /// Creates a new TypoExpr AST node.
4208  TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4210  TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4211 
4212  // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4213  //
4214  // The boolean value will be true to indicate that the namespace was loaded
4215  // from an AST/PCH file, or false otherwise.
4216  llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4217 
4218  /// Whether we have already loaded known namespaces from an extenal
4219  /// source.
4220  bool LoadedExternalKnownNamespaces;
4221 
4222  /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4223  /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4224  /// should be skipped entirely.
4225  std::unique_ptr<TypoCorrectionConsumer>
4226  makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4227  Sema::LookupNameKind LookupKind, Scope *S,
4228  CXXScopeSpec *SS,
4230  DeclContext *MemberContext, bool EnteringContext,
4231  const ObjCObjectPointerType *OPT,
4232  bool ErrorRecovery);
4233 
4234 public:
4235  const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4236 
4237  /// Clears the state of the given TypoExpr.
4238  void clearDelayedTypo(TypoExpr *TE);
4239 
4240  /// Look up a name, looking for a single declaration. Return
4241  /// null if the results were absent, ambiguous, or overloaded.
4242  ///
4243  /// It is preferable to use the elaborated form and explicitly handle
4244  /// ambiguity and overloaded.
4246  SourceLocation Loc,
4247  LookupNameKind NameKind,
4248  RedeclarationKind Redecl
4250  bool LookupBuiltin(LookupResult &R);
4251  void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4252  bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
4253  bool ForceNoCPlusPlus = false);
4254  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4255  bool InUnqualifiedLookup = false);
4256  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4257  CXXScopeSpec &SS);
4259  bool AllowBuiltinCreation = false,
4260  bool EnteringContext = false);
4262  RedeclarationKind Redecl
4264  bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4265 
4267  UnresolvedSetImpl &Functions);
4268 
4270  SourceLocation GnuLabelLoc = SourceLocation());
4271 
4275  unsigned Quals);
4276  CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4277  bool RValueThis, unsigned ThisQuals);
4279  unsigned Quals);
4280  CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4281  bool RValueThis, unsigned ThisQuals);
4283 
4284  bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
4285  bool IsUDSuffix);
4288  bool AllowRaw, bool AllowTemplate,
4289  bool AllowStringTemplate, bool DiagnoseMissing,
4290  StringLiteral *StringLit = nullptr);
4291  bool isKnownName(StringRef name);
4292 
4293  /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4295  Emitted,
4296  CUDADiscarded, // Discarded due to CUDA/HIP hostness
4297  OMPDiscarded, // Discarded due to OpenMP hostness
4298  TemplateDiscarded, // Discarded due to uninstantiated templates
4299  Unknown,
4300  };
4302  bool Final = false);
4303 
4304  // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4306 
4308  ArrayRef<Expr *> Args, ADLResult &Functions);
4309 
4312  bool IncludeGlobalScope = true,
4313  bool LoadExternal = true);
4316  bool IncludeGlobalScope = true,
4317  bool IncludeDependentBases = false,
4318  bool LoadExternal = true);
4319 
4321  CTK_NonError, // CorrectTypo used in a non error recovery situation.
4322  CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4323  };
4324 
4326  Sema::LookupNameKind LookupKind,
4327  Scope *S, CXXScopeSpec *SS,
4329  CorrectTypoKind Mode,
4330  DeclContext *MemberContext = nullptr,
4331  bool EnteringContext = false,
4332  const ObjCObjectPointerType *OPT = nullptr,
4333  bool RecordFailure = true);
4334 
4336  Sema::LookupNameKind LookupKind, Scope *S,
4337  CXXScopeSpec *SS,
4341  DeclContext *MemberContext = nullptr,
4342  bool EnteringContext = false,
4343  const ObjCObjectPointerType *OPT = nullptr);
4344 
4345  /// Process any TypoExprs in the given Expr and its children,
4346  /// generating diagnostics as appropriate and returning a new Expr if there
4347  /// were typos that were all successfully corrected and ExprError if one or
4348  /// more typos could not be corrected.
4349  ///
4350  /// \param E The Expr to check for TypoExprs.
4351  ///
4352  /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4353  /// initializer.
4354  ///
4355  /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4356  /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4357  ///
4358  /// \param Filter A function applied to a newly rebuilt Expr to determine if
4359  /// it is an acceptable/usable result from a single combination of typo
4360  /// corrections. As long as the filter returns ExprError, different
4361  /// combinations of corrections will be tried until all are exhausted.
4363  Expr *E, VarDecl *InitDecl = nullptr,
4364  bool RecoverUncorrectedTypos = false,
4365  llvm::function_ref<ExprResult(Expr *)> Filter =
4366  [](Expr *E) -> ExprResult { return E; });
4367 
4369  ExprResult ER, VarDecl *InitDecl = nullptr,
4370  bool RecoverUncorrectedTypos = false,
4371  llvm::function_ref<ExprResult(Expr *)> Filter =
4372  [](Expr *E) -> ExprResult { return E; }) {
4373  return ER.isInvalid()
4374  ? ER
4375  : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4376  RecoverUncorrectedTypos, Filter);
4377  }
4378 
4379  void diagnoseTypo(const TypoCorrection &Correction,
4380  const PartialDiagnostic &TypoDiag,
4381  bool ErrorRecovery = true);
4382 
4383  void diagnoseTypo(const TypoCorrection &Correction,
4384  const PartialDiagnostic &TypoDiag,
4385  const PartialDiagnostic &PrevNote,
4386  bool ErrorRecovery = true);
4387 
4388  void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4389 
4390  void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4391  ArrayRef<Expr *> Args,
4392  AssociatedNamespaceSet &AssociatedNamespaces,
4393  AssociatedClassSet &AssociatedClasses);
4394 
4395  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4396  bool ConsiderLinkage, bool AllowInlineNamespace);
4397 
4398  bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4399  bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4400  bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4401 
4402  void DiagnoseAmbiguousLookup(LookupResult &Result);
4403  //@}
4404 
4405  /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4406  ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4407  ArrayRef<Expr *> SubExprs,
4408  QualType T = QualType());
4409 
4410  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4411  SourceLocation IdLoc,
4412  bool TypoCorrection = false);
4413  FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4414  SourceLocation Loc);
4415  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4416  Scope *S, bool ForRedeclaration,
4417  SourceLocation Loc);
4418  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4419  Scope *S);
4421  FunctionDecl *FD);
4422  void AddKnownFunctionAttributes(FunctionDecl *FD);
4423 
4424  // More parsing and symbol table subroutines.
4425 
4426  void ProcessPragmaWeak(Scope *S, Decl *D);
4427  // Decl attributes - this routine is the top level dispatcher.
4428  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4429  // Helper for delayed processing of attributes.
4430  void ProcessDeclAttributeDelayed(Decl *D,
4431  const ParsedAttributesView &AttrList);
4432 
4433  // Options for ProcessDeclAttributeList().
4437 
4439  ProcessDeclAttributeOptions Result = *this;
4440  Result.IncludeCXX11Attributes = Val;
4441  return Result;
4442  }
4443 
4445  ProcessDeclAttributeOptions Result = *this;
4446  Result.IgnoreTypeAttributes = Val;
4447  return Result;
4448  }
4449 
4450  // Should C++11 attributes be processed?
4452 
4453  // Should any type attributes encountered be ignored?
4454  // If this option is false, a diagnostic will be emitted for any type
4455  // attributes of a kind that does not "slide" from the declaration to
4456  // the decl-specifier-seq.
4458  };
4459 
4460  void ProcessDeclAttributeList(Scope *S, Decl *D,
4461  const ParsedAttributesView &AttrList,
4462  const ProcessDeclAttributeOptions &Options =
4465  const ParsedAttributesView &AttrList);
4466 
4468 
4469  /// Handles semantic checking for features that are common to all attributes,
4470  /// such as checking whether a parameter was properly specified, or the
4471  /// correct number of arguments were passed, etc. Returns true if the
4472  /// attribute has been diagnosed.
4473  bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
4474  bool SkipArgCountCheck = false);
4475  bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
4476  bool SkipArgCountCheck = false);
4477 
4478  /// Determine if type T is a valid subject for a nonnull and similar
4479  /// attributes. By default, we look through references (the behavior used by
4480  /// nonnull), but if the second parameter is true, then we treat a reference
4481  /// type as valid.
4482  bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4483 
4484  bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4486  const FunctionDecl *FD = nullptr);
4487  bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4488  bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4490  const Expr *E, StringRef &Str,
4491  SourceLocation *ArgLocation = nullptr);
4492  bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4493  StringRef &Str,
4494  SourceLocation *ArgLocation = nullptr);
4495  llvm::Error isValidSectionSpecifier(StringRef Str);
4496  bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4497  bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4498  bool checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str,
4499  const StringLiteral *Literal,
4500  bool &HasDefault, bool &HasCommas,
4501  SmallVectorImpl<StringRef> &Strings);
4503  CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4504  MSInheritanceModel SemanticSpelling);
4505 
4507 
4508  /// Adjust the calling convention of a method to be the ABI default if it
4509  /// wasn't specified explicitly. This handles method types formed from
4510  /// function type typedefs and typename template arguments.
4511  void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4512  SourceLocation Loc);
4513 
4514  // Check if there is an explicit attribute, but only look through parens.
4515  // The intent is to look for an attribute on the current declarator, but not
4516  // one that came from a typedef.
4518 
4519  /// Get the outermost AttributedType node that sets a calling convention.
4520  /// Valid types should not have multiple attributes with different CCs.
4522 
4523  /// Process the attributes before creating an attributed statement. Returns
4524  /// the semantic attributes that have been processed.
4525  void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
4526  SmallVectorImpl<const Attr *> &OutAttrs);
4527 
4529  ObjCMethodDecl *MethodDecl,
4530  bool IsProtocolMethodDecl);
4531 
4533  ObjCMethodDecl *Overridden,
4534  bool IsProtocolMethodDecl);
4535 
4536  /// WarnExactTypedMethods - This routine issues a warning if method
4537  /// implementation declaration matches exactly that of its declaration.
4539  ObjCMethodDecl *MethodDecl,
4540  bool IsProtocolMethodDecl);
4541 
4543 
4544  /// CheckImplementationIvars - This routine checks if the instance variables
4545  /// listed in the implelementation match those listed in the interface.
4547  ObjCIvarDecl **Fields, unsigned nIvars,
4548  SourceLocation Loc);
4549 
4550  /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4551  /// remains unimplemented in the class or category \@implementation.
4552  void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4553  ObjCContainerDecl* IDecl,
4554  bool IncompleteImpl = false);
4555 
4556  /// DiagnoseUnimplementedProperties - This routine warns on those properties
4557  /// which must be implemented by this implementation.
4559  ObjCContainerDecl *CDecl,
4560  bool SynthesizeProperties);
4561 
4562  /// Diagnose any null-resettable synthesized setters.
4564 
4565  /// DefaultSynthesizeProperties - This routine default synthesizes all
4566  /// properties which must be synthesized in the class's \@implementation.
4568  ObjCInterfaceDecl *IDecl,
4569  SourceLocation AtEnd);
4571 
4572  /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4573  /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4574  /// declared in class 'IFace'.
4576  ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4577 
4578  /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4579  /// backs the property is not used in the property's accessor.
4581  const ObjCImplementationDecl *ImplD);
4582 
4583  /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4584  /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4585  /// It also returns ivar's property on success.
4587  const ObjCPropertyDecl *&PDecl) const;
4588 
4589  /// Called by ActOnProperty to handle \@property declarations in
4590  /// class extensions.
4592  SourceLocation AtLoc,
4593  SourceLocation LParenLoc,
4594  FieldDeclarator &FD,
4595  Selector GetterSel,
4596  SourceLocation GetterNameLoc,
4597  Selector SetterSel,
4598  SourceLocation SetterNameLoc,
4599  const bool isReadWrite,
4600  unsigned &Attributes,
4601  const unsigned AttributesAsWritten,
4602  QualType T,
4603  TypeSourceInfo *TSI,
4604  tok::ObjCKeywordKind MethodImplKind);
4605 
4606  /// Called by ActOnProperty and HandlePropertyInClassExtension to
4607  /// handle creating the ObjcPropertyDecl for a category or \@interface.
4609  ObjCContainerDecl *CDecl,
4610  SourceLocation AtLoc,
4611  SourceLocation LParenLoc,
4612  FieldDeclarator &FD,
4613  Selector GetterSel,
4614  SourceLocation GetterNameLoc,
4615  Selector SetterSel,
4616  SourceLocation SetterNameLoc,
4617  const bool isReadWrite,
4618  const unsigned Attributes,
4619  const unsigned AttributesAsWritten,
4620  QualType T,
4621  TypeSourceInfo *TSI,
4622  tok::ObjCKeywordKind MethodImplKind,
4623  DeclContext *lexicalDC = nullptr);
4624 
4625  /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4626  /// warning) when atomic property has one but not the other user-declared
4627  /// setter or getter.
4629  ObjCInterfaceDecl* IDecl);
4630 
4632 
4634  const ObjCImplementationDecl *ImplD,
4635  const ObjCInterfaceDecl *IFD);
4636 
4638