xref: /freebsd/contrib/llvm-project/clang/include/clang/Sema/Sema.h (revision e64bea71c21eb42e97aa615188ba91f6cce0d36d)
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/APINotes/APINotesManager.h"
18 #include "clang/AST/ASTFwd.h"
19 #include "clang/AST/ASTLambda.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/AttrIterator.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/DeclarationName.h"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/ExprCXX.h"
29 #include "clang/AST/ExprConcepts.h"
30 #include "clang/AST/ExternalASTSource.h"
31 #include "clang/AST/NestedNameSpecifier.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/StmtCXX.h"
34 #include "clang/AST/Type.h"
35 #include "clang/AST/TypeLoc.h"
36 #include "clang/Basic/AttrSubjectMatchRules.h"
37 #include "clang/Basic/Builtins.h"
38 #include "clang/Basic/CapturedStmt.h"
39 #include "clang/Basic/Cuda.h"
40 #include "clang/Basic/DiagnosticSema.h"
41 #include "clang/Basic/ExceptionSpecificationType.h"
42 #include "clang/Basic/ExpressionTraits.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/Lambda.h"
45 #include "clang/Basic/LangOptions.h"
46 #include "clang/Basic/Module.h"
47 #include "clang/Basic/OpenCLOptions.h"
48 #include "clang/Basic/OperatorKinds.h"
49 #include "clang/Basic/PartialDiagnostic.h"
50 #include "clang/Basic/PragmaKinds.h"
51 #include "clang/Basic/SourceLocation.h"
52 #include "clang/Basic/Specifiers.h"
53 #include "clang/Basic/StackExhaustionHandler.h"
54 #include "clang/Basic/TemplateKinds.h"
55 #include "clang/Basic/TokenKinds.h"
56 #include "clang/Basic/TypeTraits.h"
57 #include "clang/Sema/AnalysisBasedWarnings.h"
58 #include "clang/Sema/Attr.h"
59 #include "clang/Sema/CleanupInfo.h"
60 #include "clang/Sema/DeclSpec.h"
61 #include "clang/Sema/ExternalSemaSource.h"
62 #include "clang/Sema/IdentifierResolver.h"
63 #include "clang/Sema/Ownership.h"
64 #include "clang/Sema/ParsedAttr.h"
65 #include "clang/Sema/Redeclaration.h"
66 #include "clang/Sema/Scope.h"
67 #include "clang/Sema/SemaBase.h"
68 #include "clang/Sema/TypoCorrection.h"
69 #include "clang/Sema/Weak.h"
70 #include "llvm/ADT/APInt.h"
71 #include "llvm/ADT/ArrayRef.h"
72 #include "llvm/ADT/BitmaskEnum.h"
73 #include "llvm/ADT/DenseMap.h"
74 #include "llvm/ADT/DenseSet.h"
75 #include "llvm/ADT/FloatingPointMode.h"
76 #include "llvm/ADT/FoldingSet.h"
77 #include "llvm/ADT/MapVector.h"
78 #include "llvm/ADT/PointerIntPair.h"
79 #include "llvm/ADT/PointerUnion.h"
80 #include "llvm/ADT/STLExtras.h"
81 #include "llvm/ADT/STLForwardCompat.h"
82 #include "llvm/ADT/STLFunctionalExtras.h"
83 #include "llvm/ADT/SetVector.h"
84 #include "llvm/ADT/SmallBitVector.h"
85 #include "llvm/ADT/SmallPtrSet.h"
86 #include "llvm/ADT/SmallSet.h"
87 #include "llvm/ADT/SmallVector.h"
88 #include "llvm/ADT/StringExtras.h"
89 #include "llvm/ADT/StringMap.h"
90 #include "llvm/ADT/TinyPtrVector.h"
91 #include "llvm/Support/Allocator.h"
92 #include "llvm/Support/Compiler.h"
93 #include "llvm/Support/Error.h"
94 #include "llvm/Support/ErrorHandling.h"
95 #include <cassert>
96 #include <climits>
97 #include <cstddef>
98 #include <cstdint>
99 #include <deque>
100 #include <functional>
101 #include <iterator>
102 #include <memory>
103 #include <optional>
104 #include <string>
105 #include <tuple>
106 #include <type_traits>
107 #include <utility>
108 #include <vector>
109 
110 namespace llvm {
111 struct InlineAsmIdentifierInfo;
112 } // namespace llvm
113 
114 namespace clang {
115 class ADLResult;
116 class APValue;
117 struct ASTConstraintSatisfaction;
118 class ASTConsumer;
119 class ASTContext;
120 class ASTDeclReader;
121 class ASTMutationListener;
122 class ASTReader;
123 class ASTWriter;
124 class CXXBasePath;
125 class CXXBasePaths;
126 class CXXFieldCollector;
127 class CodeCompleteConsumer;
128 enum class ComparisonCategoryType : unsigned char;
129 class ConstraintSatisfaction;
130 class DarwinSDKInfo;
131 class DeclGroupRef;
132 class DeducedTemplateArgument;
133 struct DeductionFailureInfo;
134 class DependentDiagnostic;
135 class Designation;
136 class IdentifierInfo;
137 class ImplicitConversionSequence;
138 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
139 class InitializationKind;
140 class InitializationSequence;
141 class InitializedEntity;
142 enum class LangAS : unsigned int;
143 class LocalInstantiationScope;
144 class LookupResult;
145 class MangleNumberingContext;
146 typedef ArrayRef<IdentifierLoc> ModuleIdPath;
147 class ModuleLoader;
148 class MultiLevelTemplateArgumentList;
149 struct NormalizedConstraint;
150 class ObjCInterfaceDecl;
151 class ObjCMethodDecl;
152 struct OverloadCandidate;
153 enum class OverloadCandidateParamOrder : char;
154 enum OverloadCandidateRewriteKind : unsigned;
155 class OverloadCandidateSet;
156 class Preprocessor;
157 class SemaAMDGPU;
158 class SemaARM;
159 class SemaAVR;
160 class SemaBPF;
161 class SemaCodeCompletion;
162 class SemaCUDA;
163 class SemaDirectX;
164 class SemaHLSL;
165 class SemaHexagon;
166 class SemaLoongArch;
167 class SemaM68k;
168 class SemaMIPS;
169 class SemaMSP430;
170 class SemaNVPTX;
171 class SemaObjC;
172 class SemaOpenACC;
173 class SemaOpenCL;
174 class SemaOpenMP;
175 class SemaPPC;
176 class SemaPseudoObject;
177 class SemaRISCV;
178 class SemaSPIRV;
179 class SemaSYCL;
180 class SemaSwift;
181 class SemaSystemZ;
182 class SemaWasm;
183 class SemaX86;
184 class StandardConversionSequence;
185 class TemplateArgument;
186 class TemplateArgumentLoc;
187 class TemplateInstantiationCallback;
188 class TemplatePartialOrderingContext;
189 class TemplateSpecCandidateSet;
190 class Token;
191 class TypeConstraint;
192 class TypoCorrectionConsumer;
193 class UnresolvedSetImpl;
194 class UnresolvedSetIterator;
195 class VisibleDeclConsumer;
196 
197 namespace sema {
198 class BlockScopeInfo;
199 class Capture;
200 class CapturedRegionScopeInfo;
201 class CapturingScopeInfo;
202 class CompoundScopeInfo;
203 class DelayedDiagnostic;
204 class DelayedDiagnosticPool;
205 class FunctionScopeInfo;
206 class LambdaScopeInfo;
207 class SemaPPCallbacks;
208 class TemplateDeductionInfo;
209 } // namespace sema
210 
211 // AssignmentAction - This is used by all the assignment diagnostic functions
212 // to represent what is actually causing the operation
213 enum class AssignmentAction {
214   Assigning,
215   Passing,
216   Returning,
217   Converting,
218   Initializing,
219   Sending,
220   Casting,
221   Passing_CFAudited
222 };
223 
224 namespace threadSafety {
225 class BeforeSet;
226 void threadSafetyCleanup(BeforeSet *Cache);
227 } // namespace threadSafety
228 
229 // FIXME: No way to easily map from TemplateTypeParmTypes to
230 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
231 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *>,
232                   SourceLocation>
233     UnexpandedParameterPack;
234 
235 /// Describes whether we've seen any nullability information for the given
236 /// file.
237 struct FileNullability {
238   /// The first pointer declarator (of any pointer kind) in the file that does
239   /// not have a corresponding nullability annotation.
240   SourceLocation PointerLoc;
241 
242   /// The end location for the first pointer declarator in the file. Used for
243   /// placing fix-its.
244   SourceLocation PointerEndLoc;
245 
246   /// Which kind of pointer declarator we saw.
247   uint8_t PointerKind;
248 
249   /// Whether we saw any type nullability annotations in the given file.
250   bool SawTypeNullability = false;
251 };
252 
253 /// A mapping from file IDs to a record of whether we've seen nullability
254 /// information in that file.
255 class FileNullabilityMap {
256   /// A mapping from file IDs to the nullability information for each file ID.
257   llvm::DenseMap<FileID, FileNullability> Map;
258 
259   /// A single-element cache based on the file ID.
260   struct {
261     FileID File;
262     FileNullability Nullability;
263   } Cache;
264 
265 public:
266   FileNullability &operator[](FileID file) {
267     // Check the single-element cache.
268     if (file == Cache.File)
269       return Cache.Nullability;
270 
271     // It's not in the single-element cache; flush the cache if we have one.
272     if (!Cache.File.isInvalid()) {
273       Map[Cache.File] = Cache.Nullability;
274     }
275 
276     // Pull this entry into the cache.
277     Cache.File = file;
278     Cache.Nullability = Map[file];
279     return Cache.Nullability;
280   }
281 };
282 
283 /// Tracks expected type during expression parsing, for use in code completion.
284 /// The type is tied to a particular token, all functions that update or consume
285 /// the type take a start location of the token they are looking at as a
286 /// parameter. This avoids updating the type on hot paths in the parser.
287 class PreferredTypeBuilder {
288 public:
PreferredTypeBuilder(ASTContext * Ctx,bool Enabled)289   PreferredTypeBuilder(ASTContext *Ctx, bool Enabled)
290       : Ctx(Ctx), Enabled(Enabled) {}
291 
292   void enterCondition(Sema &S, SourceLocation Tok);
293   void enterReturn(Sema &S, SourceLocation Tok);
294   void enterVariableInit(SourceLocation Tok, Decl *D);
295   /// Handles e.g. BaseType{ .D = Tok...
296   void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
297                                   const Designation &D);
298   /// Computing a type for the function argument may require running
299   /// overloading, so we postpone its computation until it is actually needed.
300   ///
301   /// Clients should be very careful when using this function, as it stores a
302   /// function_ref, clients should make sure all calls to get() with the same
303   /// location happen while function_ref is alive.
304   ///
305   /// The callback should also emit signature help as a side-effect, but only
306   /// if the completion point has been reached.
307   void enterFunctionArgument(SourceLocation Tok,
308                              llvm::function_ref<QualType()> ComputeType);
309 
310   void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
311   void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
312                   SourceLocation OpLoc);
313   void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
314   void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
315   void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
316   /// Handles all type casts, including C-style cast, C++ casts, etc.
317   void enterTypeCast(SourceLocation Tok, QualType CastType);
318 
319   /// Get the expected type associated with this location, if any.
320   ///
321   /// If the location is a function argument, determining the expected type
322   /// involves considering all function overloads and the arguments so far.
323   /// In this case, signature help for these function overloads will be reported
324   /// as a side-effect (only if the completion point has been reached).
get(SourceLocation Tok)325   QualType get(SourceLocation Tok) const {
326     if (!Enabled || Tok != ExpectedLoc)
327       return QualType();
328     if (!Type.isNull())
329       return Type;
330     if (ComputeType)
331       return ComputeType();
332     return QualType();
333   }
334 
335 private:
336   ASTContext *Ctx;
337   bool Enabled;
338   /// Start position of a token for which we store expected type.
339   SourceLocation ExpectedLoc;
340   /// Expected type for a token starting at ExpectedLoc.
341   QualType Type;
342   /// A function to compute expected type at ExpectedLoc. It is only considered
343   /// if Type is null.
344   llvm::function_ref<QualType()> ComputeType;
345 };
346 
347 struct SkipBodyInfo {
348   SkipBodyInfo() = default;
349   bool ShouldSkip = false;
350   bool CheckSameAsPrevious = false;
351   NamedDecl *Previous = nullptr;
352   NamedDecl *New = nullptr;
353 };
354 
355 /// Describes the result of template argument deduction.
356 ///
357 /// The TemplateDeductionResult enumeration describes the result of
358 /// template argument deduction, as returned from
359 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
360 /// structure provides additional information about the results of
361 /// template argument deduction, e.g., the deduced template argument
362 /// list (if successful) or the specific template parameters or
363 /// deduced arguments that were involved in the failure.
364 enum class TemplateDeductionResult {
365   /// Template argument deduction was successful.
366   Success = 0,
367   /// The declaration was invalid; do nothing.
368   Invalid,
369   /// Template argument deduction exceeded the maximum template
370   /// instantiation depth (which has already been diagnosed).
371   InstantiationDepth,
372   /// Template argument deduction did not deduce a value
373   /// for every template parameter.
374   Incomplete,
375   /// Template argument deduction did not deduce a value for every
376   /// expansion of an expanded template parameter pack.
377   IncompletePack,
378   /// Template argument deduction produced inconsistent
379   /// deduced values for the given template parameter.
380   Inconsistent,
381   /// Template argument deduction failed due to inconsistent
382   /// cv-qualifiers on a template parameter type that would
383   /// otherwise be deduced, e.g., we tried to deduce T in "const T"
384   /// but were given a non-const "X".
385   Underqualified,
386   /// Substitution of the deduced template argument values
387   /// resulted in an error.
388   SubstitutionFailure,
389   /// After substituting deduced template arguments, a dependent
390   /// parameter type did not match the corresponding argument.
391   DeducedMismatch,
392   /// After substituting deduced template arguments, an element of
393   /// a dependent parameter type did not match the corresponding element
394   /// of the corresponding argument (when deducing from an initializer list).
395   DeducedMismatchNested,
396   /// A non-depnedent component of the parameter did not match the
397   /// corresponding component of the argument.
398   NonDeducedMismatch,
399   /// When performing template argument deduction for a function
400   /// template, there were too many call arguments.
401   TooManyArguments,
402   /// When performing template argument deduction for a function
403   /// template, there were too few call arguments.
404   TooFewArguments,
405   /// The explicitly-specified template arguments were not valid
406   /// template arguments for the given template.
407   InvalidExplicitArguments,
408   /// Checking non-dependent argument conversions failed.
409   NonDependentConversionFailure,
410   /// The deduced arguments did not satisfy the constraints associated
411   /// with the template.
412   ConstraintsNotSatisfied,
413   /// Deduction failed; that's all we know.
414   MiscellaneousDeductionFailure,
415   /// CUDA Target attributes do not match.
416   CUDATargetMismatch,
417   /// Some error which was already diagnosed.
418   AlreadyDiagnosed
419 };
420 
421 /// Kinds of C++ special members.
422 enum class CXXSpecialMemberKind {
423   DefaultConstructor,
424   CopyConstructor,
425   MoveConstructor,
426   CopyAssignment,
427   MoveAssignment,
428   Destructor,
429   Invalid
430 };
431 
432 /// The kind of conversion being performed.
433 enum class CheckedConversionKind {
434   /// An implicit conversion.
435   Implicit,
436   /// A C-style cast.
437   CStyleCast,
438   /// A functional-style cast.
439   FunctionalCast,
440   /// A cast other than a C-style cast.
441   OtherCast,
442   /// A conversion for an operand of a builtin overloaded operator.
443   ForBuiltinOverloadedOp
444 };
445 
446 enum class TagUseKind {
447   Reference,   // Reference to a tag:  'struct foo *X;'
448   Declaration, // Fwd decl of a tag:   'struct foo;'
449   Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
450   Friend       // Friend declaration:  'friend struct foo;'
451 };
452 
453 /// Used with attributes/effects with a boolean condition, e.g. `nonblocking`.
454 enum class FunctionEffectMode : uint8_t {
455   None,     // effect is not present.
456   False,    // effect(false).
457   True,     // effect(true).
458   Dependent // effect(expr) where expr is dependent.
459 };
460 
461 /// pragma clang section kind
462 enum class PragmaClangSectionKind {
463   Invalid = 0,
464   BSS = 1,
465   Data = 2,
466   Rodata = 3,
467   Text = 4,
468   Relro = 5
469 };
470 
471 enum class PragmaClangSectionAction { Set = 0, Clear = 1 };
472 
473 enum class PragmaOptionsAlignKind {
474   Native,  // #pragma options align=native
475   Natural, // #pragma options align=natural
476   Packed,  // #pragma options align=packed
477   Power,   // #pragma options align=power
478   Mac68k,  // #pragma options align=mac68k
479   Reset    // #pragma options align=reset
480 };
481 
482 enum class TUFragmentKind {
483   /// The global module fragment, between 'module;' and a module-declaration.
484   Global,
485   /// A normal translation unit fragment. For a non-module unit, this is the
486   /// entire translation unit. Otherwise, it runs from the module-declaration
487   /// to the private-module-fragment (if any) or the end of the TU (if not).
488   Normal,
489   /// The private module fragment, between 'module :private;' and the end of
490   /// the translation unit.
491   Private
492 };
493 
494 enum class FormatStringType {
495   Scanf,
496   Printf,
497   NSString,
498   Strftime,
499   Strfmon,
500   Kprintf,
501   FreeBSDKPrintf,
502   OSTrace,
503   OSLog,
504   Syslog,
505   Unknown
506 };
507 
508 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
509 enum class VariadicCallType {
510   Function,
511   Block,
512   Method,
513   Constructor,
514   DoesNotApply
515 };
516 
517 enum class BuiltinCountedByRefKind {
518   Assignment,
519   Initializer,
520   FunctionArg,
521   ReturnArg,
522   ArraySubscript,
523   BinaryExpr,
524 };
525 
526 // Contexts where using non-trivial C union types can be disallowed. This is
527 // passed to err_non_trivial_c_union_in_invalid_context.
528 enum class NonTrivialCUnionContext {
529   // Function parameter.
530   FunctionParam,
531   // Function return.
532   FunctionReturn,
533   // Default-initialized object.
534   DefaultInitializedObject,
535   // Variable with automatic storage duration.
536   AutoVar,
537   // Initializer expression that might copy from another object.
538   CopyInit,
539   // Assignment.
540   Assignment,
541   // Compound literal.
542   CompoundLiteral,
543   // Block capture.
544   BlockCapture,
545   // lvalue-to-rvalue conversion of volatile type.
546   LValueToRValueVolatile,
547 };
548 
549 /// Describes the result of the name lookup and resolution performed
550 /// by \c Sema::ClassifyName().
551 enum class NameClassificationKind {
552   /// This name is not a type or template in this context, but might be
553   /// something else.
554   Unknown,
555   /// Classification failed; an error has been produced.
556   Error,
557   /// The name has been typo-corrected to a keyword.
558   Keyword,
559   /// The name was classified as a type.
560   Type,
561   /// The name was classified as a specific non-type, non-template
562   /// declaration. ActOnNameClassifiedAsNonType should be called to
563   /// convert the declaration to an expression.
564   NonType,
565   /// The name was classified as an ADL-only function name.
566   /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
567   /// result to an expression.
568   UndeclaredNonType,
569   /// The name denotes a member of a dependent type that could not be
570   /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
571   /// convert the result to an expression.
572   DependentNonType,
573   /// The name was classified as an overload set, and an expression
574   /// representing that overload set has been formed.
575   /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
576   /// expression referencing the overload set.
577   OverloadSet,
578   /// The name was classified as a template whose specializations are types.
579   TypeTemplate,
580   /// The name was classified as a variable template name.
581   VarTemplate,
582   /// The name was classified as a function template name.
583   FunctionTemplate,
584   /// The name was classified as an ADL-only function template name.
585   UndeclaredTemplate,
586   /// The name was classified as a concept name.
587   Concept,
588 };
589 
590 enum class PointerAuthDiscArgKind {
591   // Address discrimination argument of __ptrauth.
592   Addr,
593 
594   // Extra discriminator argument of __ptrauth.
595   Extra,
596 };
597 
598 /// Common ways to introduce type names without a tag for use in diagnostics.
599 /// Keep in sync with err_tag_reference_non_tag.
600 enum class NonTagKind {
601   NonStruct,
602   NonClass,
603   NonUnion,
604   NonEnum,
605   Typedef,
606   TypeAlias,
607   Template,
608   TypeAliasTemplate,
609   TemplateTemplateArgument,
610 };
611 
612 enum class OffsetOfKind {
613   // Not parsing a type within __builtin_offsetof.
614   Outside,
615   // Parsing a type within __builtin_offsetof.
616   Builtin,
617   // Parsing a type within macro "offsetof", defined in __buitin_offsetof
618   // To improve our diagnostic message.
619   Macro,
620 };
621 
622 /// Describes the kind of merge to perform for availability
623 /// attributes (including "deprecated", "unavailable", and "availability").
624 enum class AvailabilityMergeKind {
625   /// Don't merge availability attributes at all.
626   None,
627   /// Merge availability attributes for a redeclaration, which requires
628   /// an exact match.
629   Redeclaration,
630   /// Merge availability attributes for an override, which requires
631   /// an exact match or a weakening of constraints.
632   Override,
633   /// Merge availability attributes for an implementation of
634   /// a protocol requirement.
635   ProtocolImplementation,
636   /// Merge availability attributes for an implementation of
637   /// an optional protocol requirement.
638   OptionalProtocolImplementation
639 };
640 
641 enum class TrivialABIHandling {
642   /// The triviality of a method unaffected by "trivial_abi".
643   IgnoreTrivialABI,
644 
645   /// The triviality of a method affected by "trivial_abi".
646   ConsiderTrivialABI
647 };
648 
649 enum class TryCaptureKind { Implicit, ExplicitByVal, ExplicitByRef };
650 
651 enum class AllowFoldKind {
652   No,
653   Allow,
654 };
655 
656 /// Context in which we're performing a usual arithmetic conversion.
657 enum class ArithConvKind {
658   /// An arithmetic operation.
659   Arithmetic,
660   /// A bitwise operation.
661   BitwiseOp,
662   /// A comparison.
663   Comparison,
664   /// A conditional (?:) operator.
665   Conditional,
666   /// A compound assignment expression.
667   CompAssign,
668 };
669 
670 // Used for determining in which context a type is allowed to be passed to a
671 // vararg function.
672 enum class VarArgKind {
673   Valid,
674   ValidInCXX11,
675   Undefined,
676   MSVCUndefined,
677   Invalid
678 };
679 
680 /// AssignConvertType - All of the 'assignment' semantic checks return this
681 /// enum to indicate whether the assignment was allowed.  These checks are
682 /// done for simple assignments, as well as initialization, return from
683 /// function, argument passing, etc.  The query is phrased in terms of a
684 /// source and destination type.
685 enum class AssignConvertType {
686   /// Compatible - the types are compatible according to the standard.
687   Compatible,
688 
689   /// CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because
690   /// a void * can implicitly convert to another pointer type, which we
691   /// differentiate for better diagnostic behavior.
692   CompatibleVoidPtrToNonVoidPtr,
693 
694   /// PointerToInt - The assignment converts a pointer to an int, which we
695   /// accept as an extension.
696   PointerToInt,
697 
698   /// IntToPointer - The assignment converts an int to a pointer, which we
699   /// accept as an extension.
700   IntToPointer,
701 
702   /// FunctionVoidPointer - The assignment is between a function pointer and
703   /// void*, which the standard doesn't allow, but we accept as an extension.
704   FunctionVoidPointer,
705 
706   /// IncompatiblePointer - The assignment is between two pointers types that
707   /// are not compatible, but we accept them as an extension.
708   IncompatiblePointer,
709 
710   /// IncompatibleFunctionPointer - The assignment is between two function
711   /// pointers types that are not compatible, but we accept them as an
712   /// extension.
713   IncompatibleFunctionPointer,
714 
715   /// IncompatibleFunctionPointerStrict - The assignment is between two
716   /// function pointer types that are not identical, but are compatible,
717   /// unless compiled with -fsanitize=cfi, in which case the type mismatch
718   /// may trip an indirect call runtime check.
719   IncompatibleFunctionPointerStrict,
720 
721   /// IncompatiblePointerSign - The assignment is between two pointers types
722   /// which point to integers which have a different sign, but are otherwise
723   /// identical. This is a subset of the above, but broken out because it's by
724   /// far the most common case of incompatible pointers.
725   IncompatiblePointerSign,
726 
727   /// CompatiblePointerDiscardsQualifiers - The assignment discards
728   /// c/v/r qualifiers, which we accept as an extension.
729   CompatiblePointerDiscardsQualifiers,
730 
731   /// IncompatiblePointerDiscardsQualifiers - The assignment
732   /// discards qualifiers that we don't permit to be discarded,
733   /// like address spaces.
734   IncompatiblePointerDiscardsQualifiers,
735 
736   /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
737   /// changes address spaces in nested pointer types which is not allowed.
738   /// For instance, converting __private int ** to __generic int ** is
739   /// illegal even though __private could be converted to __generic.
740   IncompatibleNestedPointerAddressSpaceMismatch,
741 
742   /// IncompatibleNestedPointerQualifiers - The assignment is between two
743   /// nested pointer types, and the qualifiers other than the first two
744   /// levels differ e.g. char ** -> const char **, but we accept them as an
745   /// extension.
746   IncompatibleNestedPointerQualifiers,
747 
748   /// IncompatibleVectors - The assignment is between two vector types that
749   /// have the same size, which we accept as an extension.
750   IncompatibleVectors,
751 
752   /// IntToBlockPointer - The assignment converts an int to a block
753   /// pointer. We disallow this.
754   IntToBlockPointer,
755 
756   /// IncompatibleBlockPointer - The assignment is between two block
757   /// pointers types that are not compatible.
758   IncompatibleBlockPointer,
759 
760   /// IncompatibleObjCQualifiedId - The assignment is between a qualified
761   /// id type and something else (that is incompatible with it). For example,
762   /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
763   IncompatibleObjCQualifiedId,
764 
765   /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
766   /// object with __weak qualifier.
767   IncompatibleObjCWeakRef,
768 
769   /// Incompatible - We reject this conversion outright, it is invalid to
770   /// represent it in the AST.
771   Incompatible
772 };
773 
774 /// The scope in which to find allocation functions.
775 enum class AllocationFunctionScope {
776   /// Only look for allocation functions in the global scope.
777   Global,
778   /// Only look for allocation functions in the scope of the
779   /// allocated class.
780   Class,
781   /// Look for allocation functions in both the global scope
782   /// and in the scope of the allocated class.
783   Both
784 };
785 
786 /// Describes the result of an "if-exists" condition check.
787 enum class IfExistsResult {
788   /// The symbol exists.
789   Exists,
790 
791   /// The symbol does not exist.
792   DoesNotExist,
793 
794   /// The name is a dependent name, so the results will differ
795   /// from one instantiation to the next.
796   Dependent,
797 
798   /// An error occurred.
799   Error
800 };
801 
802 enum class CorrectTypoKind {
803   NonError,     // CorrectTypo used in a non error recovery situation.
804   ErrorRecovery // CorrectTypo used in normal error recovery.
805 };
806 
807 enum class OverloadKind {
808   /// This is a legitimate overload: the existing declarations are
809   /// functions or function templates with different signatures.
810   Overload,
811 
812   /// This is not an overload because the signature exactly matches
813   /// an existing declaration.
814   Match,
815 
816   /// This is not an overload because the lookup results contain a
817   /// non-function.
818   NonFunction
819 };
820 
821 /// Contexts in which a converted constant expression is required.
822 enum class CCEKind {
823   CaseValue,     ///< Expression in a case label.
824   Enumerator,    ///< Enumerator value with fixed underlying type.
825   TemplateArg,   ///< Value of a non-type template parameter.
826   TempArgStrict, ///< As above, but applies strict template checking
827                  ///< rules.
828   ArrayBound,    ///< Array bound in array declarator or new-expression.
829   ExplicitBool,  ///< Condition in an explicit(bool) specifier.
830   Noexcept,      ///< Condition in a noexcept(bool) specifier.
831   StaticAssertMessageSize, ///< Call to size() in a static assert
832                            ///< message.
833   StaticAssertMessageData, ///< Call to data() in a static assert
834                            ///< message.
835 };
836 
837 void inferNoReturnAttr(Sema &S, const Decl *D);
838 
839 /// Sema - This implements semantic analysis and AST building for C.
840 /// \nosubgrouping
841 class Sema final : public SemaBase {
842   // Table of Contents
843   // -----------------
844   // 1. Semantic Analysis (Sema.cpp)
845   // 2. API Notes (SemaAPINotes.cpp)
846   // 3. C++ Access Control (SemaAccess.cpp)
847   // 4. Attributes (SemaAttr.cpp)
848   // 5. Availability Attribute Handling (SemaAvailability.cpp)
849   // 6. Bounds Safety (SemaBoundsSafety.cpp)
850   // 7. Casts (SemaCast.cpp)
851   // 8. Extra Semantic Checking (SemaChecking.cpp)
852   // 9. C++ Coroutines (SemaCoroutine.cpp)
853   // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
854   // 11. Declarations (SemaDecl.cpp)
855   // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
856   // 13. C++ Declarations (SemaDeclCXX.cpp)
857   // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
858   // 15. Expressions (SemaExpr.cpp)
859   // 16. C++ Expressions (SemaExprCXX.cpp)
860   // 17. Member Access Expressions (SemaExprMember.cpp)
861   // 18. Initializers (SemaInit.cpp)
862   // 19. C++ Lambda Expressions (SemaLambda.cpp)
863   // 20. Name Lookup (SemaLookup.cpp)
864   // 21. Modules (SemaModule.cpp)
865   // 22. C++ Overloading (SemaOverload.cpp)
866   // 23. Statements (SemaStmt.cpp)
867   // 24. `inline asm` Statement (SemaStmtAsm.cpp)
868   // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
869   // 26. C++ Templates (SemaTemplate.cpp)
870   // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
871   // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
872   // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
873   // 30. C++ Template Declaration Instantiation
874   //     (SemaTemplateInstantiateDecl.cpp)
875   // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
876   // 32. Constraints and Concepts (SemaConcept.cpp)
877   // 33. Types (SemaType.cpp)
878   // 34. FixIt Helpers (SemaFixItUtils.cpp)
879   // 35. Function Effects (SemaFunctionEffects.cpp)
880 
881   /// \name Semantic Analysis
882   /// Implementations are in Sema.cpp
883   ///@{
884 
885 public:
886   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
887        TranslationUnitKind TUKind = TU_Complete,
888        CodeCompleteConsumer *CompletionConsumer = nullptr);
889   ~Sema();
890 
891   /// Perform initialization that occurs after the parser has been
892   /// initialized but before it parses anything.
893   void Initialize();
894 
895   /// This virtual key function only exists to limit the emission of debug info
896   /// describing the Sema class. GCC and Clang only emit debug info for a class
897   /// with a vtable when the vtable is emitted. Sema is final and not
898   /// polymorphic, but the debug info size savings are so significant that it is
899   /// worth adding a vtable just to take advantage of this optimization.
900   LLVM_DECLARE_VIRTUAL_ANCHOR_FUNCTION();
901 
getLangOpts()902   const LangOptions &getLangOpts() const { return LangOpts; }
getOpenCLOptions()903   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
getCurFPFeatures()904   FPOptions &getCurFPFeatures() { return CurFPFeatures; }
905 
getDiagnostics()906   DiagnosticsEngine &getDiagnostics() const { return Diags; }
getSourceManager()907   SourceManager &getSourceManager() const { return SourceMgr; }
getPreprocessor()908   Preprocessor &getPreprocessor() const { return PP; }
getASTContext()909   ASTContext &getASTContext() const { return Context; }
getASTConsumer()910   ASTConsumer &getASTConsumer() const { return Consumer; }
911   ASTMutationListener *getASTMutationListener() const;
getExternalSource()912   ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
913 
914   DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
915                                                          StringRef Platform);
916   DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
917 
918   /// Registers an external source. If an external source already exists,
919   ///  creates a multiplex external source and appends to it.
920   ///
921   ///\param[in] E - A non-null external sema source.
922   ///
923   void addExternalSource(ExternalSemaSource *E);
924 
925   /// Print out statistics about the semantic analysis.
926   void PrintStats() const;
927 
928   /// Run some code with "sufficient" stack space. (Currently, at least 256K is
929   /// guaranteed). Produces a warning if we're low on stack space and allocates
930   /// more in that case. Use this in code that may recurse deeply (for example,
931   /// in template instantiation) to avoid stack overflow.
932   void runWithSufficientStackSpace(SourceLocation Loc,
933                                    llvm::function_ref<void()> Fn);
934 
935   /// Returns default addr space for method qualifiers.
936   LangAS getDefaultCXXMethodAddrSpace() const;
937 
938   /// Load weak undeclared identifiers from the external source.
939   void LoadExternalWeakUndeclaredIdentifiers();
940 
941   /// Determine if VD, which must be a variable or function, is an external
942   /// symbol that nonetheless can't be referenced from outside this translation
943   /// unit because its type has no linkage and it's not extern "C".
944   bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
945 
946   /// Obtain a sorted list of functions that are undefined but ODR-used.
947   void getUndefinedButUsed(
948       SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
949 
950   typedef std::pair<SourceLocation, bool> DeleteExprLoc;
951   typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
952   /// Retrieves list of suspicious delete-expressions that will be checked at
953   /// the end of translation unit.
954   const llvm::MapVector<FieldDecl *, DeleteLocs> &
955   getMismatchingDeleteExpressions() const;
956 
957   /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
958   /// This is closely coupled to the SemaDiagnosticBuilder class and
959   /// should not be used elsewhere.
960   void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
961 
962   void addImplicitTypedef(StringRef Name, QualType T);
963 
964   /// Whether uncompilable error has occurred. This includes error happens
965   /// in deferred diagnostics.
966   bool hasUncompilableErrorOccurred() const;
967 
968   /// Looks through the macro-expansion chain for the given
969   /// location, looking for a macro expansion with the given name.
970   /// If one is found, returns true and sets the location to that
971   /// expansion loc.
972   bool findMacroSpelling(SourceLocation &loc, StringRef name);
973 
974   /// Calls \c Lexer::getLocForEndOfToken()
975   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
976 
977   /// Calls \c Lexer::findNextToken() to find the next token, and if the
978   /// locations of both ends of the token can be resolved it return that
979   /// range; Otherwise it returns an invalid SourceRange.
980   SourceRange getRangeForNextToken(
981       SourceLocation Loc, bool IncludeMacros, bool IncludeComments,
982       std::optional<tok::TokenKind> ExpectedToken = std::nullopt);
983 
984   /// Retrieve the module loader associated with the preprocessor.
985   ModuleLoader &getModuleLoader() const;
986 
987   /// Invent a new identifier for parameters of abbreviated templates.
988   IdentifierInfo *
989   InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName,
990                                              unsigned Index);
991 
992   void emitAndClearUnusedLocalTypedefWarnings();
993 
994   // Emit all deferred diagnostics.
995   void emitDeferredDiags();
996 
997   /// This is called before the very first declaration in the translation unit
998   /// is parsed. Note that the ASTContext may have already injected some
999   /// declarations.
1000   void ActOnStartOfTranslationUnit();
1001   /// ActOnEndOfTranslationUnit - This is called at the very end of the
1002   /// translation unit when EOF is reached and all but the top-level scope is
1003   /// popped.
1004   void ActOnEndOfTranslationUnit();
1005   void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1006 
1007   /// Determines the active Scope associated with the given declaration
1008   /// context.
1009   ///
1010   /// This routine maps a declaration context to the active Scope object that
1011   /// represents that declaration context in the parser. It is typically used
1012   /// from "scope-less" code (e.g., template instantiation, lazy creation of
1013   /// declarations) that injects a name for name-lookup purposes and, therefore,
1014   /// must update the Scope.
1015   ///
1016   /// \returns The scope corresponding to the given declaraion context, or NULL
1017   /// if no such scope is open.
1018   Scope *getScopeForContext(DeclContext *Ctx);
1019 
1020   void PushFunctionScope();
1021   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1022   sema::LambdaScopeInfo *PushLambdaScope();
1023 
1024   /// This is used to inform Sema what the current TemplateParameterDepth
1025   /// is during Parsing.  Currently it is used to pass on the depth
1026   /// when parsing generic lambda 'auto' parameters.
1027   void RecordParsingTemplateParameterDepth(unsigned Depth);
1028 
1029   void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1030                                RecordDecl *RD, CapturedRegionKind K,
1031                                unsigned OpenMPCaptureLevel = 0);
1032 
1033   /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1034   /// time after they've been popped.
1035   class PoppedFunctionScopeDeleter {
1036     Sema *Self;
1037 
1038   public:
PoppedFunctionScopeDeleter(Sema * Self)1039     explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1040     void operator()(sema::FunctionScopeInfo *Scope) const;
1041   };
1042 
1043   using PoppedFunctionScopePtr =
1044       std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1045 
1046   /// Pop a function (or block or lambda or captured region) scope from the
1047   /// stack.
1048   ///
1049   /// \param WP The warning policy to use for CFG-based warnings, or null if
1050   ///        such warnings should not be produced.
1051   /// \param D The declaration corresponding to this function scope, if
1052   ///        producing CFG-based warnings.
1053   /// \param BlockType The type of the block expression, if D is a BlockDecl.
1054   PoppedFunctionScopePtr
1055   PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1056                        const Decl *D = nullptr,
1057                        QualType BlockType = QualType());
1058 
1059   sema::FunctionScopeInfo *getEnclosingFunction() const;
1060 
1061   void setFunctionHasBranchIntoScope();
1062   void setFunctionHasBranchProtectedScope();
1063   void setFunctionHasIndirectGoto();
1064   void setFunctionHasMustTail();
1065 
1066   void PushCompoundScope(bool IsStmtExpr);
1067   void PopCompoundScope();
1068 
1069   /// Determine whether any errors occurred within this function/method/
1070   /// block.
1071   bool hasAnyUnrecoverableErrorsInThisFunction() const;
1072 
1073   /// Retrieve the current block, if any.
1074   sema::BlockScopeInfo *getCurBlock();
1075 
1076   /// Get the innermost lambda or block enclosing the current location, if any.
1077   /// This looks through intervening non-lambda, non-block scopes such as local
1078   /// functions.
1079   sema::CapturingScopeInfo *getEnclosingLambdaOrBlock() const;
1080 
1081   /// Retrieve the current lambda scope info, if any.
1082   /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1083   /// lambda scope info ignoring all inner capturing scopes that are not
1084   /// lambda scopes.
1085   sema::LambdaScopeInfo *
1086   getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1087 
1088   /// Retrieve the current generic lambda info, if any.
1089   sema::LambdaScopeInfo *getCurGenericLambda();
1090 
1091   /// Retrieve the current captured region, if any.
1092   sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1093 
1094   void ActOnComment(SourceRange Comment);
1095 
1096   /// Retrieve the parser's current scope.
1097   ///
1098   /// This routine must only be used when it is certain that semantic analysis
1099   /// and the parser are in precisely the same context, which is not the case
1100   /// when, e.g., we are performing any kind of template instantiation.
1101   /// Therefore, the only safe places to use this scope are in the parser
1102   /// itself and in routines directly invoked from the parser and *never* from
1103   /// template substitution or instantiation.
getCurScope()1104   Scope *getCurScope() const { return CurScope; }
1105 
1106   IdentifierInfo *getSuperIdentifier() const;
1107 
getCurLexicalContext()1108   DeclContext *getCurLexicalContext() const {
1109     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
1110   }
1111 
1112   SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1113                                    const FunctionDecl *FD = nullptr);
1114   SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
1115                                    const PartialDiagnostic &PD,
1116                                    const FunctionDecl *FD = nullptr) {
1117     return targetDiag(Loc, PD.getDiagID(), FD) << PD;
1118   }
1119 
1120   /// Check if the type is allowed to be used for the current target.
1121   void checkTypeSupport(QualType Ty, SourceLocation Loc,
1122                         ValueDecl *D = nullptr);
1123 
1124   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1125   /// cast.  If there is already an implicit cast, merge into the existing one.
1126   /// If isLvalue, the result of the cast is an lvalue.
1127   ExprResult ImpCastExprToType(
1128       Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue,
1129       const CXXCastPath *BasePath = nullptr,
1130       CheckedConversionKind CCK = CheckedConversionKind::Implicit);
1131 
1132   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1133   /// to the conversion from scalar type ScalarTy to the Boolean type.
1134   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
1135 
1136   /// If \p AllowLambda is true, treat lambda as function.
1137   DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1138 
1139   /// Returns a pointer to the innermost enclosing function, or nullptr if the
1140   /// current context is not inside a function. If \p AllowLambda is true,
1141   /// this can return the call operator of an enclosing lambda, otherwise
1142   /// lambdas are skipped when looking for an enclosing function.
1143   FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1144 
1145   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1146   /// the method decl for the method being parsed.  If we're currently
1147   /// in a 'block', this returns the containing context.
1148   ObjCMethodDecl *getCurMethodDecl();
1149 
1150   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1151   /// or C function we're in, otherwise return null.  If we're currently
1152   /// in a 'block', this returns the containing context.
1153   NamedDecl *getCurFunctionOrMethodDecl() const;
1154 
1155   /// Warn if we're implicitly casting from a _Nullable pointer type to a
1156   /// _Nonnull one.
1157   void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
1158                                            SourceLocation Loc);
1159 
1160   /// Warn when implicitly casting 0 to nullptr.
1161   void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1162 
1163   /// Warn when implicitly changing function effects.
1164   void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType,
1165                                         SourceLocation Loc);
1166 
1167   /// makeUnavailableInSystemHeader - There is an error in the current
1168   /// context.  If we're still in a system header, and we can plausibly
1169   /// make the relevant declaration unavailable instead of erroring, do
1170   /// so and return true.
1171   bool makeUnavailableInSystemHeader(SourceLocation loc,
1172                                      UnavailableAttr::ImplicitReason reason);
1173 
1174   /// Retrieve a suitable printing policy for diagnostics.
getPrintingPolicy()1175   PrintingPolicy getPrintingPolicy() const {
1176     return getPrintingPolicy(Context, PP);
1177   }
1178 
1179   /// Retrieve a suitable printing policy for diagnostics.
1180   static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1181                                           const Preprocessor &PP);
1182 
1183   /// Scope actions.
1184   void ActOnTranslationUnitScope(Scope *S);
1185 
1186   /// Determine whether \param D is function like (function or function
1187   /// template) for parsing.
1188   bool isDeclaratorFunctionLike(Declarator &D);
1189 
1190   /// The maximum alignment, same as in llvm::Value. We duplicate them here
1191   /// because that allows us not to duplicate the constants in clang code,
1192   /// which we must to since we can't directly use the llvm constants.
1193   /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1194   ///
1195   /// This is the greatest alignment value supported by load, store, and alloca
1196   /// instructions, and global values.
1197   static const unsigned MaxAlignmentExponent = 32;
1198   static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1199 
1200   /// Flag indicating whether or not to collect detailed statistics.
1201   bool CollectStats;
1202 
1203   std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1204 
1205   /// Stack containing information about each of the nested
1206   /// function, block, and method scopes that are currently active.
1207   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
1208 
1209   /// The index of the first FunctionScope that corresponds to the current
1210   /// context.
1211   unsigned FunctionScopesStart = 0;
1212 
1213   /// Track the number of currently active capturing scopes.
1214   unsigned CapturingFunctionScopes = 0;
1215 
1216   llvm::BumpPtrAllocator BumpAlloc;
1217 
1218   /// The kind of translation unit we are processing.
1219   ///
1220   /// When we're processing a complete translation unit, Sema will perform
1221   /// end-of-translation-unit semantic tasks (such as creating
1222   /// initializers for tentative definitions in C) once parsing has
1223   /// completed. Modules and precompiled headers perform different kinds of
1224   /// checks.
1225   const TranslationUnitKind TUKind;
1226 
1227   /// Translation Unit Scope - useful to Objective-C actions that need
1228   /// to lookup file scope declarations in the "ordinary" C decl namespace.
1229   /// For example, user-defined classes, built-in "id" type, etc.
1230   Scope *TUScope;
1231 
incrementMSManglingNumber()1232   void incrementMSManglingNumber() const {
1233     return CurScope->incrementMSManglingNumber();
1234   }
1235 
1236   /// Try to recover by turning the given expression into a
1237   /// call.  Returns true if recovery was attempted or an error was
1238   /// emitted; this may also leave the ExprResult invalid.
1239   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1240                             bool ForceComplain = false,
1241                             bool (*IsPlausibleResult)(QualType) = nullptr);
1242 
1243   /// Figure out if an expression could be turned into a call.
1244   ///
1245   /// Use this when trying to recover from an error where the programmer may
1246   /// have written just the name of a function instead of actually calling it.
1247   ///
1248   /// \param E - The expression to examine.
1249   /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1250   ///  with no arguments, this parameter is set to the type returned by such a
1251   ///  call; otherwise, it is set to an empty QualType.
1252   /// \param OverloadSet - If the expression is an overloaded function
1253   ///  name, this parameter is populated with the decls of the various
1254   ///  overloads.
1255   bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1256                      UnresolvedSetImpl &NonTemplateOverloads);
1257 
1258   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
1259   typedef OpaquePtr<TemplateName> TemplateTy;
1260   typedef OpaquePtr<QualType> TypeTy;
1261 
1262   OpenCLOptions OpenCLFeatures;
1263   FPOptions CurFPFeatures;
1264 
1265   const LangOptions &LangOpts;
1266   Preprocessor &PP;
1267   ASTContext &Context;
1268   ASTConsumer &Consumer;
1269   DiagnosticsEngine &Diags;
1270   SourceManager &SourceMgr;
1271   api_notes::APINotesManager APINotes;
1272 
1273   /// A RAII object to enter scope of a compound statement.
1274   class CompoundScopeRAII {
1275   public:
S(S)1276     CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1277       S.ActOnStartOfCompoundStmt(IsStmtExpr);
1278     }
1279 
~CompoundScopeRAII()1280     ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1281 
1282   private:
1283     Sema &S;
1284   };
1285 
1286   /// An RAII helper that pops function a function scope on exit.
1287   struct FunctionScopeRAII {
1288     Sema &S;
1289     bool Active;
FunctionScopeRAIIFunctionScopeRAII1290     FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
~FunctionScopeRAIIFunctionScopeRAII1291     ~FunctionScopeRAII() {
1292       if (Active)
1293         S.PopFunctionScopeInfo();
1294     }
disableFunctionScopeRAII1295     void disable() { Active = false; }
1296   };
1297 
getCurFunction()1298   sema::FunctionScopeInfo *getCurFunction() const {
1299     return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1300   }
1301 
1302   /// Worker object for performing CFG-based warnings.
1303   sema::AnalysisBasedWarnings AnalysisWarnings;
1304   threadSafety::BeforeSet *ThreadSafetyDeclCache;
1305 
1306   /// Callback to the parser to parse templated functions when needed.
1307   typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1308   typedef void LateTemplateParserCleanupCB(void *P);
1309   LateTemplateParserCB *LateTemplateParser;
1310   LateTemplateParserCleanupCB *LateTemplateParserCleanup;
1311   void *OpaqueParser;
1312 
SetLateTemplateParser(LateTemplateParserCB * LTP,LateTemplateParserCleanupCB * LTPCleanup,void * P)1313   void SetLateTemplateParser(LateTemplateParserCB *LTP,
1314                              LateTemplateParserCleanupCB *LTPCleanup, void *P) {
1315     LateTemplateParser = LTP;
1316     LateTemplateParserCleanup = LTPCleanup;
1317     OpaqueParser = P;
1318   }
1319 
1320   /// Callback to the parser to parse a type expressed as a string.
1321   std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1322       ParseTypeFromStringCallback;
1323 
1324   /// VAListTagName - The declaration name corresponding to __va_list_tag.
1325   /// This is used as part of a hack to omit that class from ADL results.
1326   DeclarationName VAListTagName;
1327 
1328   /// Is the last error level diagnostic immediate. This is used to determined
1329   /// whether the next info diagnostic should be immediate.
1330   bool IsLastErrorImmediate = true;
1331 
1332   class DelayedDiagnostics;
1333 
1334   class DelayedDiagnosticsState {
1335     sema::DelayedDiagnosticPool *SavedPool = nullptr;
1336     friend class Sema::DelayedDiagnostics;
1337   };
1338   typedef DelayedDiagnosticsState ParsingDeclState;
1339   typedef DelayedDiagnosticsState ProcessingContextState;
1340 
1341   /// A class which encapsulates the logic for delaying diagnostics
1342   /// during parsing and other processing.
1343   class DelayedDiagnostics {
1344     /// The current pool of diagnostics into which delayed
1345     /// diagnostics should go.
1346     sema::DelayedDiagnosticPool *CurPool = nullptr;
1347 
1348   public:
1349     DelayedDiagnostics() = default;
1350 
1351     /// Adds a delayed diagnostic.
1352     void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1353 
1354     /// Determines whether diagnostics should be delayed.
shouldDelayDiagnostics()1355     bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1356 
1357     /// Returns the current delayed-diagnostics pool.
getCurrentPool()1358     sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1359 
1360     /// Enter a new scope.  Access and deprecation diagnostics will be
1361     /// collected in this pool.
push(sema::DelayedDiagnosticPool & pool)1362     DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
1363       DelayedDiagnosticsState state;
1364       state.SavedPool = CurPool;
1365       CurPool = &pool;
1366       return state;
1367     }
1368 
1369     /// Leave a delayed-diagnostic state that was previously pushed.
1370     /// Do not emit any of the diagnostics.  This is performed as part
1371     /// of the bookkeeping of popping a pool "properly".
popWithoutEmitting(DelayedDiagnosticsState state)1372     void popWithoutEmitting(DelayedDiagnosticsState state) {
1373       CurPool = state.SavedPool;
1374     }
1375 
1376     /// Enter a new scope where access and deprecation diagnostics are
1377     /// not delayed.
pushUndelayed()1378     DelayedDiagnosticsState pushUndelayed() {
1379       DelayedDiagnosticsState state;
1380       state.SavedPool = CurPool;
1381       CurPool = nullptr;
1382       return state;
1383     }
1384 
1385     /// Undo a previous pushUndelayed().
popUndelayed(DelayedDiagnosticsState state)1386     void popUndelayed(DelayedDiagnosticsState state) {
1387       assert(CurPool == nullptr);
1388       CurPool = state.SavedPool;
1389     }
1390   } DelayedDiagnostics;
1391 
PushParsingDeclaration(sema::DelayedDiagnosticPool & pool)1392   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
1393     return DelayedDiagnostics.push(pool);
1394   }
1395 
1396   /// Diagnostics that are emitted only if we discover that the given function
1397   /// must be codegen'ed.  Because handling these correctly adds overhead to
1398   /// compilation, this is currently only enabled for CUDA compilations.
1399   SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1400 
1401   /// CurContext - This is the current declaration context of parsing.
1402   DeclContext *CurContext;
1403 
AMDGPU()1404   SemaAMDGPU &AMDGPU() {
1405     assert(AMDGPUPtr);
1406     return *AMDGPUPtr;
1407   }
1408 
ARM()1409   SemaARM &ARM() {
1410     assert(ARMPtr);
1411     return *ARMPtr;
1412   }
1413 
AVR()1414   SemaAVR &AVR() {
1415     assert(AVRPtr);
1416     return *AVRPtr;
1417   }
1418 
BPF()1419   SemaBPF &BPF() {
1420     assert(BPFPtr);
1421     return *BPFPtr;
1422   }
1423 
CodeCompletion()1424   SemaCodeCompletion &CodeCompletion() {
1425     assert(CodeCompletionPtr);
1426     return *CodeCompletionPtr;
1427   }
1428 
CUDA()1429   SemaCUDA &CUDA() {
1430     assert(CUDAPtr);
1431     return *CUDAPtr;
1432   }
1433 
DirectX()1434   SemaDirectX &DirectX() {
1435     assert(DirectXPtr);
1436     return *DirectXPtr;
1437   }
1438 
HLSL()1439   SemaHLSL &HLSL() {
1440     assert(HLSLPtr);
1441     return *HLSLPtr;
1442   }
1443 
Hexagon()1444   SemaHexagon &Hexagon() {
1445     assert(HexagonPtr);
1446     return *HexagonPtr;
1447   }
1448 
LoongArch()1449   SemaLoongArch &LoongArch() {
1450     assert(LoongArchPtr);
1451     return *LoongArchPtr;
1452   }
1453 
M68k()1454   SemaM68k &M68k() {
1455     assert(M68kPtr);
1456     return *M68kPtr;
1457   }
1458 
MIPS()1459   SemaMIPS &MIPS() {
1460     assert(MIPSPtr);
1461     return *MIPSPtr;
1462   }
1463 
MSP430()1464   SemaMSP430 &MSP430() {
1465     assert(MSP430Ptr);
1466     return *MSP430Ptr;
1467   }
1468 
NVPTX()1469   SemaNVPTX &NVPTX() {
1470     assert(NVPTXPtr);
1471     return *NVPTXPtr;
1472   }
1473 
ObjC()1474   SemaObjC &ObjC() {
1475     assert(ObjCPtr);
1476     return *ObjCPtr;
1477   }
1478 
OpenACC()1479   SemaOpenACC &OpenACC() {
1480     assert(OpenACCPtr);
1481     return *OpenACCPtr;
1482   }
1483 
OpenCL()1484   SemaOpenCL &OpenCL() {
1485     assert(OpenCLPtr);
1486     return *OpenCLPtr;
1487   }
1488 
OpenMP()1489   SemaOpenMP &OpenMP() {
1490     assert(OpenMPPtr && "SemaOpenMP is dead");
1491     return *OpenMPPtr;
1492   }
1493 
PPC()1494   SemaPPC &PPC() {
1495     assert(PPCPtr);
1496     return *PPCPtr;
1497   }
1498 
PseudoObject()1499   SemaPseudoObject &PseudoObject() {
1500     assert(PseudoObjectPtr);
1501     return *PseudoObjectPtr;
1502   }
1503 
RISCV()1504   SemaRISCV &RISCV() {
1505     assert(RISCVPtr);
1506     return *RISCVPtr;
1507   }
1508 
SPIRV()1509   SemaSPIRV &SPIRV() {
1510     assert(SPIRVPtr);
1511     return *SPIRVPtr;
1512   }
1513 
SYCL()1514   SemaSYCL &SYCL() {
1515     assert(SYCLPtr);
1516     return *SYCLPtr;
1517   }
1518 
Swift()1519   SemaSwift &Swift() {
1520     assert(SwiftPtr);
1521     return *SwiftPtr;
1522   }
1523 
SystemZ()1524   SemaSystemZ &SystemZ() {
1525     assert(SystemZPtr);
1526     return *SystemZPtr;
1527   }
1528 
Wasm()1529   SemaWasm &Wasm() {
1530     assert(WasmPtr);
1531     return *WasmPtr;
1532   }
1533 
X86()1534   SemaX86 &X86() {
1535     assert(X86Ptr);
1536     return *X86Ptr;
1537   }
1538 
1539   /// Source of additional semantic information.
1540   IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
1541 
1542 protected:
1543   friend class Parser;
1544   friend class InitializationSequence;
1545   friend class ASTReader;
1546   friend class ASTDeclReader;
1547   friend class ASTWriter;
1548 
1549 private:
1550   std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1551   bool WarnedDarwinSDKInfoMissing = false;
1552 
1553   StackExhaustionHandler StackHandler;
1554 
1555   Sema(const Sema &) = delete;
1556   void operator=(const Sema &) = delete;
1557 
1558   /// The handler for the FileChanged preprocessor events.
1559   ///
1560   /// Used for diagnostics that implement custom semantic analysis for #include
1561   /// directives, like -Wpragma-pack.
1562   sema::SemaPPCallbacks *SemaPPCallbackHandler;
1563 
1564   /// The parser's current scope.
1565   ///
1566   /// The parser maintains this state here.
1567   Scope *CurScope;
1568 
1569   mutable IdentifierInfo *Ident_super;
1570 
1571   std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1572   std::unique_ptr<SemaARM> ARMPtr;
1573   std::unique_ptr<SemaAVR> AVRPtr;
1574   std::unique_ptr<SemaBPF> BPFPtr;
1575   std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1576   std::unique_ptr<SemaCUDA> CUDAPtr;
1577   std::unique_ptr<SemaDirectX> DirectXPtr;
1578   std::unique_ptr<SemaHLSL> HLSLPtr;
1579   std::unique_ptr<SemaHexagon> HexagonPtr;
1580   std::unique_ptr<SemaLoongArch> LoongArchPtr;
1581   std::unique_ptr<SemaM68k> M68kPtr;
1582   std::unique_ptr<SemaMIPS> MIPSPtr;
1583   std::unique_ptr<SemaMSP430> MSP430Ptr;
1584   std::unique_ptr<SemaNVPTX> NVPTXPtr;
1585   std::unique_ptr<SemaObjC> ObjCPtr;
1586   std::unique_ptr<SemaOpenACC> OpenACCPtr;
1587   std::unique_ptr<SemaOpenCL> OpenCLPtr;
1588   std::unique_ptr<SemaOpenMP> OpenMPPtr;
1589   std::unique_ptr<SemaPPC> PPCPtr;
1590   std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1591   std::unique_ptr<SemaRISCV> RISCVPtr;
1592   std::unique_ptr<SemaSPIRV> SPIRVPtr;
1593   std::unique_ptr<SemaSYCL> SYCLPtr;
1594   std::unique_ptr<SemaSwift> SwiftPtr;
1595   std::unique_ptr<SemaSystemZ> SystemZPtr;
1596   std::unique_ptr<SemaWasm> WasmPtr;
1597   std::unique_ptr<SemaX86> X86Ptr;
1598 
1599   ///@}
1600 
1601   //
1602   //
1603   // -------------------------------------------------------------------------
1604   //
1605   //
1606 
1607   /// \name API Notes
1608   /// Implementations are in SemaAPINotes.cpp
1609   ///@{
1610 
1611 public:
1612   /// Map any API notes provided for this declaration to attributes on the
1613   /// declaration.
1614   ///
1615   /// Triggered by declaration-attribute processing.
1616   void ProcessAPINotes(Decl *D);
1617   /// Apply the 'Nullability:' annotation to the specified declaration
1618   void ApplyNullability(Decl *D, NullabilityKind Nullability);
1619   /// Apply the 'Type:' annotation to the specified declaration
1620   void ApplyAPINotesType(Decl *D, StringRef TypeString);
1621 
1622   /// Whether APINotes should be gathered for all applicable Swift language
1623   /// versions, without being applied. Leaving clients of the current module
1624   /// to select and apply the correct version.
captureSwiftVersionIndependentAPINotes()1625   bool captureSwiftVersionIndependentAPINotes() {
1626     return APINotes.captureVersionIndependentSwift();
1627   }
1628   ///@}
1629 
1630   //
1631   //
1632   // -------------------------------------------------------------------------
1633   //
1634   //
1635 
1636   /// \name C++ Access Control
1637   /// Implementations are in SemaAccess.cpp
1638   ///@{
1639 
1640 public:
1641   enum AccessResult {
1642     AR_accessible,
1643     AR_inaccessible,
1644     AR_dependent,
1645     AR_delayed
1646   };
1647 
1648   /// SetMemberAccessSpecifier - Set the access specifier of a member.
1649   /// Returns true on error (when the previous member decl access specifier
1650   /// is different from the new member decl access specifier).
1651   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1652                                 NamedDecl *PrevMemberDecl,
1653                                 AccessSpecifier LexicalAS);
1654 
1655   /// Perform access-control checking on a previously-unresolved member
1656   /// access which has now been resolved to a member.
1657   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
1658                                            DeclAccessPair FoundDecl);
1659   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
1660                                            DeclAccessPair FoundDecl);
1661 
1662   /// Checks access to an overloaded operator new or delete.
1663   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
1664                                      SourceRange PlacementRange,
1665                                      CXXRecordDecl *NamingClass,
1666                                      DeclAccessPair FoundDecl,
1667                                      bool Diagnose = true);
1668 
1669   /// Checks access to a constructor.
1670   AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1671                                       DeclAccessPair FoundDecl,
1672                                       const InitializedEntity &Entity,
1673                                       bool IsCopyBindingRefToTemp = false);
1674 
1675   /// Checks access to a constructor.
1676   AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1677                                       DeclAccessPair FoundDecl,
1678                                       const InitializedEntity &Entity,
1679                                       const PartialDiagnostic &PDiag);
1680   AccessResult CheckDestructorAccess(SourceLocation Loc,
1681                                      CXXDestructorDecl *Dtor,
1682                                      const PartialDiagnostic &PDiag,
1683                                      QualType objectType = QualType());
1684 
1685   /// Checks access to the target of a friend declaration.
1686   AccessResult CheckFriendAccess(NamedDecl *D);
1687 
1688   /// Checks access to a member.
1689   AccessResult CheckMemberAccess(SourceLocation UseLoc,
1690                                  CXXRecordDecl *NamingClass,
1691                                  DeclAccessPair Found);
1692 
1693   /// Checks implicit access to a member in a structured binding.
1694   AccessResult
1695   CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
1696                                      CXXRecordDecl *DecomposedClass,
1697                                      DeclAccessPair Field);
1698   AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1699                                          const SourceRange &,
1700                                          DeclAccessPair FoundDecl);
1701 
1702   /// Checks access to an overloaded member operator, including
1703   /// conversion operators.
1704   AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1705                                          Expr *ArgExpr,
1706                                          DeclAccessPair FoundDecl);
1707   AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1708                                          ArrayRef<Expr *> ArgExprs,
1709                                          DeclAccessPair FoundDecl);
1710   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
1711                                           DeclAccessPair FoundDecl);
1712 
1713   /// Checks access for a hierarchy conversion.
1714   ///
1715   /// \param ForceCheck true if this check should be performed even if access
1716   ///     control is disabled;  some things rely on this for semantics
1717   /// \param ForceUnprivileged true if this check should proceed as if the
1718   ///     context had no special privileges
1719   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base,
1720                                     QualType Derived, const CXXBasePath &Path,
1721                                     unsigned DiagID, bool ForceCheck = false,
1722                                     bool ForceUnprivileged = false);
1723 
1724   AccessResult CheckBaseClassAccess(
1725       SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1726       const CXXBasePath &Path, unsigned DiagID,
1727       llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1728       bool ForceCheck = false, bool ForceUnprivileged = false);
1729 
1730   /// Checks access to all the declarations in the given result set.
1731   void CheckLookupAccess(const LookupResult &R);
1732 
1733   /// Checks access to Target from the given class. The check will take access
1734   /// specifiers into account, but no member access expressions and such.
1735   ///
1736   /// \param Target the declaration to check if it can be accessed
1737   /// \param NamingClass the class in which the lookup was started.
1738   /// \param BaseType type of the left side of member access expression.
1739   ///        \p BaseType and \p NamingClass are used for C++ access control.
1740   ///        Depending on the lookup case, they should be set to the following:
1741   ///        - lhs.target (member access without a qualifier):
1742   ///          \p BaseType and \p NamingClass are both the type of 'lhs'.
1743   ///        - lhs.X::target (member access with a qualifier):
1744   ///          BaseType is the type of 'lhs', NamingClass is 'X'
1745   ///        - X::target (qualified lookup without member access):
1746   ///          BaseType is null, NamingClass is 'X'.
1747   ///        - target (unqualified lookup).
1748   ///          BaseType is null, NamingClass is the parent class of 'target'.
1749   /// \return true if the Target is accessible from the Class, false otherwise.
1750   bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1751                           QualType BaseType);
1752 
1753   /// Is the given member accessible for the purposes of deciding whether to
1754   /// define a special member function as deleted?
1755   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1756                                      DeclAccessPair Found, QualType ObjectType,
1757                                      SourceLocation Loc,
1758                                      const PartialDiagnostic &Diag);
isMemberAccessibleForDeletion(CXXRecordDecl * NamingClass,DeclAccessPair Found,QualType ObjectType)1759   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1760                                      DeclAccessPair Found,
1761                                      QualType ObjectType) {
1762     return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1763                                          SourceLocation(), PDiag());
1764   }
1765 
1766   void HandleDependentAccessCheck(
1767       const DependentDiagnostic &DD,
1768       const MultiLevelTemplateArgumentList &TemplateArgs);
1769   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
1770 
1771   ///@}
1772 
1773   //
1774   //
1775   // -------------------------------------------------------------------------
1776   //
1777   //
1778 
1779   /// \name Attributes
1780   /// Implementations are in SemaAttr.cpp
1781   ///@{
1782 
1783 public:
1784   /// Controls member pointer representation format under the MS ABI.
1785   LangOptions::PragmaMSPointersToMembersKind
1786       MSPointerToMemberRepresentationMethod;
1787 
1788   bool MSStructPragmaOn; // True when \#pragma ms_struct on
1789 
1790   /// Source location for newly created implicit MSInheritanceAttrs
1791   SourceLocation ImplicitMSInheritanceAttrLoc;
1792 
1793   struct PragmaClangSection {
1794     std::string SectionName;
1795     bool Valid = false;
1796     SourceLocation PragmaLocation;
1797   };
1798 
1799   PragmaClangSection PragmaClangBSSSection;
1800   PragmaClangSection PragmaClangDataSection;
1801   PragmaClangSection PragmaClangRodataSection;
1802   PragmaClangSection PragmaClangRelroSection;
1803   PragmaClangSection PragmaClangTextSection;
1804 
1805   enum PragmaMsStackAction {
1806     PSK_Reset = 0x0,                   // #pragma ()
1807     PSK_Set = 0x1,                     // #pragma (value)
1808     PSK_Push = 0x2,                    // #pragma (push[, id])
1809     PSK_Pop = 0x4,                     // #pragma (pop[, id])
1810     PSK_Show = 0x8,                    // #pragma (show) -- only for "pack"!
1811     PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1812     PSK_Pop_Set = PSK_Pop | PSK_Set,   // #pragma (pop[, id], value)
1813   };
1814 
1815   struct PragmaPackInfo {
1816     PragmaMsStackAction Action;
1817     StringRef SlotLabel;
1818     Token Alignment;
1819   };
1820 
1821   // #pragma pack and align.
1822   class AlignPackInfo {
1823   public:
1824     // `Native` represents default align mode, which may vary based on the
1825     // platform.
1826     enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1827 
1828     // #pragma pack info constructor
AlignPackInfo(AlignPackInfo::Mode M,unsigned Num,bool IsXL)1829     AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1830         : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1831       assert(Num == PackNumber && "The pack number has been truncated.");
1832     }
1833 
1834     // #pragma align info constructor
AlignPackInfo(AlignPackInfo::Mode M,bool IsXL)1835     AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
1836         : PackAttr(false), AlignMode(M),
1837           PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1838 
AlignPackInfo(bool IsXL)1839     explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1840 
AlignPackInfo()1841     AlignPackInfo() : AlignPackInfo(Native, false) {}
1842 
1843     // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1844     // integer encoding for it. This should only be passed to
1845     // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
getRawEncoding(const AlignPackInfo & Info)1846     static uint32_t getRawEncoding(const AlignPackInfo &Info) {
1847       std::uint32_t Encoding{};
1848       if (Info.IsXLStack())
1849         Encoding |= IsXLMask;
1850 
1851       Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1852 
1853       if (Info.IsPackAttr())
1854         Encoding |= PackAttrMask;
1855 
1856       Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1857 
1858       return Encoding;
1859     }
1860 
getFromRawEncoding(unsigned Encoding)1861     static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1862       bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1863       AlignPackInfo::Mode M =
1864           static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1865       int PackNumber = (Encoding & PackNumMask) >> 4;
1866 
1867       if (Encoding & PackAttrMask)
1868         return AlignPackInfo(M, PackNumber, IsXL);
1869 
1870       return AlignPackInfo(M, IsXL);
1871     }
1872 
IsPackAttr()1873     bool IsPackAttr() const { return PackAttr; }
1874 
IsAlignAttr()1875     bool IsAlignAttr() const { return !PackAttr; }
1876 
getAlignMode()1877     Mode getAlignMode() const { return AlignMode; }
1878 
getPackNumber()1879     unsigned getPackNumber() const { return PackNumber; }
1880 
IsPackSet()1881     bool IsPackSet() const {
1882       // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1883       // attriute on a decl.
1884       return PackNumber != UninitPackVal && PackNumber != 0;
1885     }
1886 
IsXLStack()1887     bool IsXLStack() const { return XLStack; }
1888 
1889     bool operator==(const AlignPackInfo &Info) const {
1890       return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
1891              std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
1892                       Info.XLStack);
1893     }
1894 
1895     bool operator!=(const AlignPackInfo &Info) const {
1896       return !(*this == Info);
1897     }
1898 
1899   private:
1900     /// \brief True if this is a pragma pack attribute,
1901     ///         not a pragma align attribute.
1902     bool PackAttr;
1903 
1904     /// \brief The alignment mode that is in effect.
1905     Mode AlignMode;
1906 
1907     /// \brief The pack number of the stack.
1908     unsigned char PackNumber;
1909 
1910     /// \brief True if it is a XL #pragma align/pack stack.
1911     bool XLStack;
1912 
1913     /// \brief Uninitialized pack value.
1914     static constexpr unsigned char UninitPackVal = -1;
1915 
1916     // Masks to encode and decode an AlignPackInfo.
1917     static constexpr uint32_t IsXLMask{0x0000'0001};
1918     static constexpr uint32_t AlignModeMask{0x0000'0006};
1919     static constexpr uint32_t PackAttrMask{0x00000'0008};
1920     static constexpr uint32_t PackNumMask{0x0000'01F0};
1921   };
1922 
1923   template <typename ValueType> struct PragmaStack {
1924     struct Slot {
1925       llvm::StringRef StackSlotLabel;
1926       ValueType Value;
1927       SourceLocation PragmaLocation;
1928       SourceLocation PragmaPushLocation;
SlotPragmaStack::Slot1929       Slot(llvm::StringRef StackSlotLabel, ValueType Value,
1930            SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
1931           : StackSlotLabel(StackSlotLabel), Value(Value),
1932             PragmaLocation(PragmaLocation),
1933             PragmaPushLocation(PragmaPushLocation) {}
1934     };
1935 
ActPragmaStack1936     void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
1937              llvm::StringRef StackSlotLabel, ValueType Value) {
1938       if (Action == PSK_Reset) {
1939         CurrentValue = DefaultValue;
1940         CurrentPragmaLocation = PragmaLocation;
1941         return;
1942       }
1943       if (Action & PSK_Push)
1944         Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
1945                            PragmaLocation);
1946       else if (Action & PSK_Pop) {
1947         if (!StackSlotLabel.empty()) {
1948           // If we've got a label, try to find it and jump there.
1949           auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
1950             return x.StackSlotLabel == StackSlotLabel;
1951           });
1952           // If we found the label so pop from there.
1953           if (I != Stack.rend()) {
1954             CurrentValue = I->Value;
1955             CurrentPragmaLocation = I->PragmaLocation;
1956             Stack.erase(std::prev(I.base()), Stack.end());
1957           }
1958         } else if (!Stack.empty()) {
1959           // We do not have a label, just pop the last entry.
1960           CurrentValue = Stack.back().Value;
1961           CurrentPragmaLocation = Stack.back().PragmaLocation;
1962           Stack.pop_back();
1963         }
1964       }
1965       if (Action & PSK_Set) {
1966         CurrentValue = Value;
1967         CurrentPragmaLocation = PragmaLocation;
1968       }
1969     }
1970 
1971     // MSVC seems to add artificial slots to #pragma stacks on entering a C++
1972     // method body to restore the stacks on exit, so it works like this:
1973     //
1974     //   struct S {
1975     //     #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
1976     //     void Method {}
1977     //     #pragma <name>(pop, InternalPragmaSlot)
1978     //   };
1979     //
1980     // It works even with #pragma vtordisp, although MSVC doesn't support
1981     //   #pragma vtordisp(push [, id], n)
1982     // syntax.
1983     //
1984     // Push / pop a named sentinel slot.
SentinelActionPragmaStack1985     void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
1986       assert((Action == PSK_Push || Action == PSK_Pop) &&
1987              "Can only push / pop #pragma stack sentinels!");
1988       Act(CurrentPragmaLocation, Action, Label, CurrentValue);
1989     }
1990 
1991     // Constructors.
PragmaStackPragmaStack1992     explicit PragmaStack(const ValueType &Default)
1993         : DefaultValue(Default), CurrentValue(Default) {}
1994 
hasValuePragmaStack1995     bool hasValue() const { return CurrentValue != DefaultValue; }
1996 
1997     SmallVector<Slot, 2> Stack;
1998     ValueType DefaultValue; // Value used for PSK_Reset action.
1999     ValueType CurrentValue;
2000     SourceLocation CurrentPragmaLocation;
2001   };
2002   // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2003   // we shouldn't do so if they're in a module).
2004 
2005   /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2006   /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
2007   ///
2008   /// 0: Suppress all vtordisps
2009   /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2010   ///    structors
2011   /// 2: Always insert vtordisps to support RTTI on partially constructed
2012   ///    objects
2013   PragmaStack<MSVtorDispMode> VtorDispStack;
2014   PragmaStack<AlignPackInfo> AlignPackStack;
2015   // The current #pragma align/pack values and locations at each #include.
2016   struct AlignPackIncludeState {
2017     AlignPackInfo CurrentValue;
2018     SourceLocation CurrentPragmaLocation;
2019     bool HasNonDefaultValue, ShouldWarnOnInclude;
2020   };
2021   SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
2022   // Segment #pragmas.
2023   PragmaStack<StringLiteral *> DataSegStack;
2024   PragmaStack<StringLiteral *> BSSSegStack;
2025   PragmaStack<StringLiteral *> ConstSegStack;
2026   PragmaStack<StringLiteral *> CodeSegStack;
2027 
2028   // #pragma strict_gs_check.
2029   PragmaStack<bool> StrictGuardStackCheckStack;
2030 
2031   // This stack tracks the current state of Sema.CurFPFeatures.
2032   PragmaStack<FPOptionsOverride> FpPragmaStack;
CurFPFeatureOverrides()2033   FPOptionsOverride CurFPFeatureOverrides() {
2034     FPOptionsOverride result;
2035     if (!FpPragmaStack.hasValue()) {
2036       result = FPOptionsOverride();
2037     } else {
2038       result = FpPragmaStack.CurrentValue;
2039     }
2040     return result;
2041   }
2042 
2043   enum PragmaSectionKind {
2044     PSK_DataSeg,
2045     PSK_BSSSeg,
2046     PSK_ConstSeg,
2047     PSK_CodeSeg,
2048   };
2049 
2050   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2051   // Actions should be performed only if we enter / exit a C++ method body.
2052   class PragmaStackSentinelRAII {
2053   public:
2054     PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2055     ~PragmaStackSentinelRAII();
2056 
2057   private:
2058     Sema &S;
2059     StringRef SlotLabel;
2060     bool ShouldAct;
2061   };
2062 
2063   /// Last section used with #pragma init_seg.
2064   StringLiteral *CurInitSeg;
2065   SourceLocation CurInitSegLoc;
2066 
2067   /// Sections used with #pragma alloc_text.
2068   llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2069 
2070   /// VisContext - Manages the stack for \#pragma GCC visibility.
2071   void *VisContext; // Really a "PragmaVisStack*"
2072 
2073   /// This an attribute introduced by \#pragma clang attribute.
2074   struct PragmaAttributeEntry {
2075     SourceLocation Loc;
2076     ParsedAttr *Attribute;
2077     SmallVector<attr::SubjectMatchRule, 4> MatchRules;
2078     bool IsUsed;
2079   };
2080 
2081   /// A push'd group of PragmaAttributeEntries.
2082   struct PragmaAttributeGroup {
2083     /// The location of the push attribute.
2084     SourceLocation Loc;
2085     /// The namespace of this push group.
2086     const IdentifierInfo *Namespace;
2087     SmallVector<PragmaAttributeEntry, 2> Entries;
2088   };
2089 
2090   SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
2091 
2092   /// The declaration that is currently receiving an attribute from the
2093   /// #pragma attribute stack.
2094   const Decl *PragmaAttributeCurrentTargetDecl;
2095 
2096   /// This represents the last location of a "#pragma clang optimize off"
2097   /// directive if such a directive has not been closed by an "on" yet. If
2098   /// optimizations are currently "on", this is set to an invalid location.
2099   SourceLocation OptimizeOffPragmaLocation;
2100 
2101   /// Get the location for the currently active "\#pragma clang optimize
2102   /// off". If this location is invalid, then the state of the pragma is "on".
getOptimizeOffPragmaLocation()2103   SourceLocation getOptimizeOffPragmaLocation() const {
2104     return OptimizeOffPragmaLocation;
2105   }
2106 
2107   /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2108   /// whether the optimizations in the list passed to the pragma should be
2109   /// turned off or on. This boolean is true by default because command line
2110   /// options are honored when `#pragma optimize("", on)`.
2111   /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2112   bool MSPragmaOptimizeIsOn = true;
2113 
2114   /// Set of no-builtin functions listed by \#pragma function.
2115   llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
2116 
2117   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2118   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2119   void AddAlignmentAttributesForRecord(RecordDecl *RD);
2120 
2121   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2122   void AddMsStructLayoutForRecord(RecordDecl *RD);
2123 
2124   /// Add gsl::Pointer attribute to std::container::iterator
2125   /// \param ND The declaration that introduces the name
2126   /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2127   void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2128 
2129   /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2130   void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
2131 
2132   /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2133   void inferLifetimeBoundAttribute(FunctionDecl *FD);
2134 
2135   /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2136   void inferLifetimeCaptureByAttribute(FunctionDecl *FD);
2137 
2138   /// Add [[gsl::Pointer]] attributes for std:: types.
2139   void inferGslPointerAttribute(TypedefNameDecl *TD);
2140 
2141   LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2142                                                     StringRef ParamName);
2143   // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2144   // can be the name of a function parameter, we need to parse the function
2145   // declaration and rest of the parameters before processesing 'X'. Therefore
2146   // do this lazily instead of processing while parsing the annotation itself.
2147   void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD);
2148 
2149   /// Add _Nullable attributes for std:: types.
2150   void inferNullableClassAttribute(CXXRecordDecl *CRD);
2151 
2152   /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2153   void ActOnPragmaClangSection(SourceLocation PragmaLoc,
2154                                PragmaClangSectionAction Action,
2155                                PragmaClangSectionKind SecKind,
2156                                StringRef SecName);
2157 
2158   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2159   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
2160                                SourceLocation PragmaLoc);
2161 
2162   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2163   void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2164                        StringRef SlotLabel, Expr *Alignment);
2165 
2166   /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2167   /// (unless they are value dependent or type dependent). Returns false
2168   /// and emits a diagnostic if one or more of the arguments could not be
2169   /// folded into a constant.
2170   bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
2171                             MutableArrayRef<Expr *> Args);
2172 
2173   enum class PragmaAlignPackDiagnoseKind {
2174     NonDefaultStateAtInclude,
2175     ChangedStateAtExit
2176   };
2177 
2178   void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
2179                                          SourceLocation IncludeLoc);
2180   void DiagnoseUnterminatedPragmaAlignPack();
2181 
2182   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2183   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
2184 
2185   /// ActOnPragmaMSComment - Called on well formed
2186   /// \#pragma comment(kind, "arg").
2187   void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
2188                             StringRef Arg);
2189 
2190   /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2191   void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2192                                  StringRef Value);
2193 
2194   /// Are precise floating point semantics currently enabled?
isPreciseFPEnabled()2195   bool isPreciseFPEnabled() {
2196     return !CurFPFeatures.getAllowFPReassociate() &&
2197            !CurFPFeatures.getNoSignedZero() &&
2198            !CurFPFeatures.getAllowReciprocal() &&
2199            !CurFPFeatures.getAllowApproxFunc();
2200   }
2201 
2202   void ActOnPragmaFPEvalMethod(SourceLocation Loc,
2203                                LangOptions::FPEvalMethodKind Value);
2204 
2205   /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2206   void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2207                                PragmaFloatControlKind Value);
2208 
2209   /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2210   /// pointers_to_members(representation method[, general purpose
2211   /// representation]).
2212   void ActOnPragmaMSPointersToMembers(
2213       LangOptions::PragmaMSPointersToMembersKind Kind,
2214       SourceLocation PragmaLoc);
2215 
2216   /// Called on well formed \#pragma vtordisp().
2217   void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2218                              SourceLocation PragmaLoc, MSVtorDispMode Value);
2219 
2220   bool UnifySection(StringRef SectionName, int SectionFlags,
2221                     NamedDecl *TheDecl);
2222   bool UnifySection(StringRef SectionName, int SectionFlags,
2223                     SourceLocation PragmaSectionLocation);
2224 
2225   /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2226   void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2227                         PragmaMsStackAction Action,
2228                         llvm::StringRef StackSlotLabel,
2229                         StringLiteral *SegmentName, llvm::StringRef PragmaName);
2230 
2231   /// Called on well formed \#pragma section().
2232   void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2233                             StringLiteral *SegmentName);
2234 
2235   /// Called on well-formed \#pragma init_seg().
2236   void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2237                             StringLiteral *SegmentName);
2238 
2239   /// Called on well-formed \#pragma alloc_text().
2240   void ActOnPragmaMSAllocText(
2241       SourceLocation PragmaLocation, StringRef Section,
2242       const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2243           &Functions);
2244 
2245   /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2246   /// strict_gs_check.
2247   void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
2248                                           PragmaMsStackAction Action,
2249                                           bool Value);
2250 
2251   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2252   void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2253                          SourceLocation PragmaLoc);
2254 
2255   void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
2256                                      SourceLocation PragmaLoc,
2257                                      attr::ParsedSubjectMatchRuleSet Rules);
2258   void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
2259                                      const IdentifierInfo *Namespace);
2260 
2261   /// Called on well-formed '\#pragma clang attribute pop'.
2262   void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
2263                                const IdentifierInfo *Namespace);
2264 
2265   /// Adds the attributes that have been specified using the
2266   /// '\#pragma clang attribute push' directives to the given declaration.
2267   void AddPragmaAttributes(Scope *S, Decl *D);
2268 
2269   using InstantiationContextDiagFuncRef =
2270       llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
getDefaultDiagFunc()2271   auto getDefaultDiagFunc() {
2272     return [this](SourceLocation Loc, PartialDiagnostic PD) {
2273       // This bypasses a lot of the filters in the diag engine, as it's
2274       // to be used to attach notes to diagnostics which have already
2275       // been filtered through.
2276       DiagnosticBuilder Builder(Diags.Report(Loc, PD.getDiagID()));
2277       PD.Emit(Builder);
2278     };
2279   }
2280 
2281   void PrintPragmaAttributeInstantiationPoint(
2282       InstantiationContextDiagFuncRef DiagFunc);
PrintPragmaAttributeInstantiationPoint()2283   void PrintPragmaAttributeInstantiationPoint() {
2284     PrintPragmaAttributeInstantiationPoint(getDefaultDiagFunc());
2285   }
2286 
2287   void DiagnoseUnterminatedPragmaAttribute();
2288 
2289   /// Called on well formed \#pragma clang optimize.
2290   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2291 
2292   /// #pragma optimize("[optimization-list]", on | off).
2293   void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2294 
2295   /// Call on well formed \#pragma function.
2296   void
2297   ActOnPragmaMSFunction(SourceLocation Loc,
2298                         const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2299 
2300   /// Only called on function definitions; if there is a pragma in scope
2301   /// with the effect of a range-based optnone, consider marking the function
2302   /// with attribute optnone.
2303   void AddRangeBasedOptnone(FunctionDecl *FD);
2304 
2305   /// Only called on function definitions; if there is a `#pragma alloc_text`
2306   /// that decides which code section the function should be in, add
2307   /// attribute section to the function.
2308   void AddSectionMSAllocText(FunctionDecl *FD);
2309 
2310   /// Adds the 'optnone' attribute to the function declaration if there
2311   /// are no conflicts; Loc represents the location causing the 'optnone'
2312   /// attribute to be added (usually because of a pragma).
2313   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
2314 
2315   /// Only called on function definitions; if there is a MSVC #pragma optimize
2316   /// in scope, consider changing the function's attributes based on the
2317   /// optimization list passed to the pragma.
2318   void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
2319 
2320   /// Only called on function definitions; if there is a pragma in scope
2321   /// with the effect of a range-based no_builtin, consider marking the function
2322   /// with attribute no_builtin.
2323   void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
2324 
2325   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2326   /// add an appropriate visibility attribute.
2327   void AddPushedVisibilityAttribute(Decl *RD);
2328 
2329   /// FreeVisContext - Deallocate and null out VisContext.
2330   void FreeVisContext();
2331 
2332   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2333   void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2334                              SourceLocation PragmaLoc);
2335 
2336   /// ActOnPragmaFPContract - Called on well formed
2337   /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2338   /// \#pragma clang fp contract
2339   void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
2340 
2341   /// Called on well formed
2342   /// \#pragma clang fp reassociate
2343   /// or
2344   /// \#pragma clang fp reciprocal
2345   void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind,
2346                                         bool IsEnabled);
2347 
2348   /// ActOnPragmaFenvAccess - Called on well formed
2349   /// \#pragma STDC FENV_ACCESS
2350   void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2351 
2352   /// ActOnPragmaCXLimitedRange - Called on well formed
2353   /// \#pragma STDC CX_LIMITED_RANGE
2354   void ActOnPragmaCXLimitedRange(SourceLocation Loc,
2355                                  LangOptions::ComplexRangeKind Range);
2356 
2357   /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2358   void ActOnPragmaFPExceptions(SourceLocation Loc,
2359                                LangOptions::FPExceptionModeKind);
2360 
2361   /// Called to set constant rounding mode for floating point operations.
2362   void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2363 
2364   /// Called to set exception behavior for floating point operations.
2365   void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
2366 
2367   /// PushNamespaceVisibilityAttr - Note that we've entered a
2368   /// namespace with a visibility attribute.
2369   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2370                                    SourceLocation Loc);
2371 
2372   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2373   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2374   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2375 
2376   /// Handles semantic checking for features that are common to all attributes,
2377   /// such as checking whether a parameter was properly specified, or the
2378   /// correct number of arguments were passed, etc. Returns true if the
2379   /// attribute has been diagnosed.
2380   bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2381                                     bool SkipArgCountCheck = false);
2382   bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2383                                     bool SkipArgCountCheck = false);
2384 
2385   ///@}
2386 
2387   //
2388   //
2389   // -------------------------------------------------------------------------
2390   //
2391   //
2392 
2393   /// \name Availability Attribute Handling
2394   /// Implementations are in SemaAvailability.cpp
2395   ///@{
2396 
2397 public:
2398   /// Issue any -Wunguarded-availability warnings in \c FD
2399   void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
2400 
2401   void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2402 
2403   /// Retrieve the current function, if any, that should be analyzed for
2404   /// potential availability violations.
2405   sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2406 
2407   void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
2408                                   const ObjCInterfaceDecl *UnknownObjCClass,
2409                                   bool ObjCPropertyAccess,
2410                                   bool AvoidPartialAvailabilityChecks,
2411                                   ObjCInterfaceDecl *ClassReceiver);
2412 
2413   void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs);
2414 
2415   std::pair<AvailabilityResult, const NamedDecl *>
2416   ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2417                                    ObjCInterfaceDecl *ClassReceiver);
2418   ///@}
2419 
2420   //
2421   //
2422   // -------------------------------------------------------------------------
2423   //
2424   //
2425 
2426   /// \name Bounds Safety
2427   /// Implementations are in SemaBoundsSafety.cpp
2428   ///@{
2429 public:
2430   /// Check if applying the specified attribute variant from the "counted by"
2431   /// family of attributes to FieldDecl \p FD is semantically valid. If
2432   /// semantically invalid diagnostics will be emitted explaining the problems.
2433   ///
2434   /// \param FD The FieldDecl to apply the attribute to
2435   /// \param E The count expression on the attribute
2436   /// \param CountInBytes If true the attribute is from the "sized_by" family of
2437   ///                     attributes. If the false the attribute is from
2438   ///                     "counted_by" family of attributes.
2439   /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2440   ///               of attributes. If false the attribute does not have the
2441   ///               suffix.
2442   ///
2443   /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2444   /// \p CountInBytes and \p OrNull both being true indicates the
2445   /// `counted_by_or_null` attribute.
2446   ///
2447   /// \returns false iff semantically valid.
2448   bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2449                                  bool OrNull);
2450 
2451   /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2452   /// `__counted_by_or_null` pointer type \param LHSTy.
2453   ///
2454   /// \param LHSTy The type being assigned to. Checks will only be performed if
2455   ///              the type is a `counted_by` or `counted_by_or_null ` pointer.
2456   /// \param RHSExpr The expression being assigned from.
2457   /// \param Action The type assignment being performed
2458   /// \param Loc The SourceLocation to use for error diagnostics
2459   /// \param Assignee The ValueDecl being assigned. This is used to compute
2460   ///        the name of the assignee. If the assignee isn't known this can
2461   ///        be set to nullptr.
2462   /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2463   ///        Assignee to compute the name of the assignee use the fully
2464   ///        qualified name, otherwise use the unqualified name.
2465   ///
2466   /// \returns True iff no diagnostic where emitted, false otherwise.
2467   bool BoundsSafetyCheckAssignmentToCountAttrPtr(
2468       QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2469       SourceLocation Loc, const ValueDecl *Assignee,
2470       bool ShowFullyQualifiedAssigneeName);
2471 
2472   /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2473   /// pointer.
2474   ///
2475   /// \param Entity The entity being initialized
2476   /// \param Kind The kind of initialization being performed
2477   /// \param Action The type assignment being performed
2478   /// \param LHSTy The type being assigned to. Checks will only be performed if
2479   ///              the type is a `counted_by` or `counted_by_or_null ` pointer.
2480   /// \param RHSExpr The expression being used for initialization.
2481   ///
2482   /// \returns True iff no diagnostic where emitted, false otherwise.
2483   bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity,
2484                                        const InitializationKind &Kind,
2485                                        AssignmentAction Action,
2486                                        QualType LHSType, Expr *RHSExpr);
2487 
2488   /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2489   /// or counted_by_or_null pointers in \param E.
2490   ///
2491   /// \param E the expression to check
2492   ///
2493   /// \returns True iff no diagnostic where emitted, false otherwise.
2494   bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E);
2495   ///@}
2496 
2497   //
2498   //
2499   // -------------------------------------------------------------------------
2500   //
2501   //
2502 
2503   /// \name Casts
2504   /// Implementations are in SemaCast.cpp
2505   ///@{
2506 
2507 public:
isCast(CheckedConversionKind CCK)2508   static bool isCast(CheckedConversionKind CCK) {
2509     return CCK == CheckedConversionKind::CStyleCast ||
2510            CCK == CheckedConversionKind::FunctionalCast ||
2511            CCK == CheckedConversionKind::OtherCast;
2512   }
2513 
2514   /// ActOnCXXNamedCast - Parse
2515   /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2516   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2517                                SourceLocation LAngleBracketLoc, Declarator &D,
2518                                SourceLocation RAngleBracketLoc,
2519                                SourceLocation LParenLoc, Expr *E,
2520                                SourceLocation RParenLoc);
2521 
2522   ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2523                                TypeSourceInfo *Ty, Expr *E,
2524                                SourceRange AngleBrackets, SourceRange Parens);
2525 
2526   ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
2527                                      ExprResult Operand,
2528                                      SourceLocation RParenLoc);
2529 
2530   ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
2531                                      Expr *Operand, SourceLocation RParenLoc);
2532 
2533   // Checks that reinterpret casts don't have undefined behavior.
2534   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2535                                       bool IsDereference, SourceRange Range);
2536 
2537   // Checks that the vector type should be initialized from a scalar
2538   // by splatting the value rather than populating a single element.
2539   // This is the case for AltiVecVector types as well as with
2540   // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2541   bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2542 
2543   // Checks if the -faltivec-src-compat=gcc option is specified.
2544   // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2545   // treated the same way as they are when trying to initialize
2546   // these vectors on gcc (an error is emitted).
2547   bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
2548                                   QualType SrcTy);
2549 
2550   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
2551                                  SourceLocation RParenLoc, Expr *Op);
2552 
2553   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
2554                                         SourceLocation LParenLoc,
2555                                         Expr *CastExpr,
2556                                         SourceLocation RParenLoc);
2557 
2558   ///@}
2559 
2560   //
2561   //
2562   // -------------------------------------------------------------------------
2563   //
2564   //
2565 
2566   /// \name Extra Semantic Checking
2567   /// Implementations are in SemaChecking.cpp
2568   ///@{
2569 
2570 public:
2571   /// Used to change context to isConstantEvaluated without pushing a heavy
2572   /// ExpressionEvaluationContextRecord object.
2573   bool isConstantEvaluatedOverride = false;
2574 
isConstantEvaluatedContext()2575   bool isConstantEvaluatedContext() const {
2576     return currentEvaluationContext().isConstantEvaluated() ||
2577            isConstantEvaluatedOverride;
2578   }
2579 
2580   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
2581                                                 unsigned ByteNo) const;
2582 
2583   enum FormatArgumentPassingKind {
2584     FAPK_Fixed,    // values to format are fixed (no C-style variadic arguments)
2585     FAPK_Variadic, // values to format are passed as variadic arguments
2586     FAPK_VAList,   // values to format are passed in a va_list
2587     FAPK_Elsewhere, // values to format are not passed to this function
2588   };
2589 
2590   // Used to grab the relevant information from a FormatAttr and a
2591   // FunctionDeclaration.
2592   struct FormatStringInfo {
2593     unsigned FormatIdx;
2594     unsigned FirstDataArg;
2595     FormatArgumentPassingKind ArgPassingKind;
2596   };
2597 
2598   /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2599   /// populate the FomatStringInfo parameter with the attribute's correct
2600   /// format_idx and firstDataArg. Returns true when the format fits the
2601   /// function and the FormatStringInfo has been populated.
2602   static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2603                                   unsigned FirstArg, FormatStringInfo *FSI);
2604   static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2605                                   bool IsCXXMember, bool IsVariadic,
2606                                   FormatStringInfo *FSI);
2607 
2608   // Used by C++ template instantiation.
2609   ExprResult BuiltinShuffleVector(CallExpr *TheCall);
2610 
2611   /// ConvertVectorExpr - Handle __builtin_convertvector
2612   ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2613                                SourceLocation BuiltinLoc,
2614                                SourceLocation RParenLoc);
2615 
2616   static StringRef GetFormatStringTypeName(FormatStringType FST);
2617   static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2618   static FormatStringType GetFormatStringType(const FormatAttr *Format);
2619   static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2620 
2621   bool FormatStringHasSArg(const StringLiteral *FExpr);
2622 
2623   /// Check for comparisons of floating-point values using == and !=. Issue a
2624   /// warning if the comparison is not likely to do what the programmer
2625   /// intended.
2626   void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2627                             const Expr *RHS, BinaryOperatorKind Opcode);
2628 
2629   /// Register a magic integral constant to be used as a type tag.
2630   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2631                                   uint64_t MagicValue, QualType Type,
2632                                   bool LayoutCompatible, bool MustBeNull);
2633 
2634   struct TypeTagData {
TypeTagDataTypeTagData2635     TypeTagData() {}
2636 
TypeTagDataTypeTagData2637     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
2638         : Type(Type), LayoutCompatible(LayoutCompatible),
2639           MustBeNull(MustBeNull) {}
2640 
2641     QualType Type;
2642 
2643     /// If true, \c Type should be compared with other expression's types for
2644     /// layout-compatibility.
2645     LLVM_PREFERRED_TYPE(bool)
2646     unsigned LayoutCompatible : 1;
2647     LLVM_PREFERRED_TYPE(bool)
2648     unsigned MustBeNull : 1;
2649   };
2650 
2651   /// A pair of ArgumentKind identifier and magic value.  This uniquely
2652   /// identifies the magic value.
2653   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2654 
2655   /// Diagnoses the current set of gathered accesses. This typically
2656   /// happens at full expression level. The set is cleared after emitting the
2657   /// diagnostics.
2658   void DiagnoseMisalignedMembers();
2659 
2660   /// This function checks if the expression is in the sef of potentially
2661   /// misaligned members and it is converted to some pointer type T with lower
2662   /// or equal alignment requirements. If so it removes it. This is used when
2663   /// we do not want to diagnose such misaligned access (e.g. in conversions to
2664   /// void*).
2665   void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2666 
2667   /// Returns true if `From` is a function or pointer to a function with the
2668   /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2669   /// function without this attribute.
2670   bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2671 
2672   /// Returns true if `From` is a function or pointer to a function without the
2673   /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2674   /// function with this attribute.
2675   bool AddingCFIUncheckedCallee(QualType From, QualType To) const;
2676 
2677   /// This function calls Action when it determines that E designates a
2678   /// misaligned member due to the packed attribute. This is used to emit
2679   /// local diagnostics like in reference binding.
2680   void RefersToMemberWithReducedAlignment(
2681       Expr *E,
2682       llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2683           Action);
2684 
2685   enum class AtomicArgumentOrder { API, AST };
2686   ExprResult
2687   BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2688                   SourceLocation RParenLoc, MultiExprArg Args,
2689                   AtomicExpr::AtomicOp Op,
2690                   AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
2691 
2692   /// Check to see if a given expression could have '.c_str()' called on it.
2693   bool hasCStrMethod(const Expr *E);
2694 
2695   /// Diagnose pointers that are always non-null.
2696   /// \param E the expression containing the pointer
2697   /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2698   /// compared to a null pointer
2699   /// \param IsEqual True when the comparison is equal to a null pointer
2700   /// \param Range Extra SourceRange to highlight in the diagnostic
2701   void DiagnoseAlwaysNonNullPointer(Expr *E,
2702                                     Expr::NullPointerConstantKind NullType,
2703                                     bool IsEqual, SourceRange Range);
2704 
2705   /// CheckParmsForFunctionDef - Check that the parameters of the given
2706   /// function are appropriate for the definition of a function. This
2707   /// takes care of any checks that cannot be performed on the
2708   /// declaration itself, e.g., that the types of each of the function
2709   /// parameters are complete.
2710   bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2711                                 bool CheckParameterNames);
2712 
2713   /// CheckCastAlign - Implements -Wcast-align, which warns when a
2714   /// pointer cast increases the alignment requirements.
2715   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2716 
2717   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2718   /// to weak/__unsafe_unretained type.
2719   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2720 
2721   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2722   /// to weak/__unsafe_unretained expression.
2723   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2724 
2725   /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2726   /// statement as a \p Body, and it is located on the same line.
2727   ///
2728   /// This helps prevent bugs due to typos, such as:
2729   ///     if (condition);
2730   ///       do_stuff();
2731   void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2732                              unsigned DiagID);
2733 
2734   /// Warn if a for/while loop statement \p S, which is followed by
2735   /// \p PossibleBody, has a suspicious null statement as a body.
2736   void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2737 
2738   /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2739   void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2740                         SourceLocation OpLoc);
2741 
2742   bool IsLayoutCompatible(QualType T1, QualType T2) const;
2743   bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
2744                                        const TypeSourceInfo *Derived);
2745 
2746   /// CheckFunctionCall - Check a direct function call for various correctness
2747   /// and safety properties not strictly enforced by the C type system.
2748   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2749                          const FunctionProtoType *Proto);
2750 
2751   enum class EltwiseBuiltinArgTyRestriction {
2752     None,
2753     FloatTy,
2754     IntegerTy,
2755     SignedIntOrFloatTy,
2756   };
2757 
2758   /// \param FPOnly restricts the arguments to floating-point types.
2759   std::optional<QualType>
2760   BuiltinVectorMath(CallExpr *TheCall,
2761                     EltwiseBuiltinArgTyRestriction ArgTyRestr =
2762                         EltwiseBuiltinArgTyRestriction::None);
2763   bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2764 
2765   void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2766                               const Expr *ThisArg, ArrayRef<const Expr *> Args);
2767 
2768   /// Handles the checks for format strings, non-POD arguments to vararg
2769   /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2770   /// attributes and AArch64 SME attributes.
2771   void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2772                  const Expr *ThisArg, ArrayRef<const Expr *> Args,
2773                  bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2774                  VariadicCallType CallType);
2775 
2776   /// Verify that two format strings (as understood by attribute(format) and
2777   /// attribute(format_matches) are compatible. If they are incompatible,
2778   /// diagnostics are emitted with the assumption that \c
2779   /// AuthoritativeFormatString is correct and
2780   /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2781   /// diagnostics will point to it and a note will refer to \c
2782   /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2783   bool
2784   CheckFormatStringsCompatible(FormatStringType FST,
2785                                const StringLiteral *AuthoritativeFormatString,
2786                                const StringLiteral *TestedFormatString,
2787                                const Expr *FunctionCallArg = nullptr);
2788 
2789   /// Verify that one format string (as understood by attribute(format)) is
2790   /// self-consistent; for instance, that it doesn't have multiple positional
2791   /// arguments referring to the same argument in incompatible ways. Diagnose
2792   /// if it isn't.
2793   bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str);
2794 
2795   /// \brief Enforce the bounds of a TCB
2796   /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2797   /// directly calls other functions in the same TCB as marked by the
2798   /// enforce_tcb and enforce_tcb_leaf attributes.
2799   void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2800                            const NamedDecl *Callee);
2801 
2802   void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2803 
2804   /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2805   /// TheCall is a constant expression.
2806   bool BuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result);
2807 
2808   /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2809   /// TheCall is a constant expression in the range [Low, High].
2810   bool BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High,
2811                                bool RangeIsError = true);
2812 
2813   /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2814   /// TheCall is a constant expression is a multiple of Num..
2815   bool BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
2816                                   unsigned Multiple);
2817 
2818   /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2819   /// constant expression representing a power of 2.
2820   bool BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
2821 
2822   /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2823   /// a constant expression representing an arbitrary byte value shifted left by
2824   /// a multiple of 8 bits.
2825   bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
2826                                      unsigned ArgBits);
2827 
2828   /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2829   /// TheCall is a constant expression representing either a shifted byte value,
2830   /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2831   /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2832   /// Arm MVE intrinsics.
2833   bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
2834                                            unsigned ArgBits);
2835 
2836   /// Checks that a call expression's argument count is at least the desired
2837   /// number. This is useful when doing custom type-checking on a variadic
2838   /// function. Returns true on error.
2839   bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2840 
2841   /// Checks that a call expression's argument count is at most the desired
2842   /// number. This is useful when doing custom type-checking on a variadic
2843   /// function. Returns true on error.
2844   bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
2845 
2846   /// Checks that a call expression's argument count is in the desired range.
2847   /// This is useful when doing custom type-checking on a variadic function.
2848   /// Returns true on error.
2849   bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
2850                           unsigned MaxArgCount);
2851 
2852   /// Checks that a call expression's argument count is the desired number.
2853   /// This is useful when doing custom type-checking.  Returns true on error.
2854   bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
2855 
2856   /// Returns true if the argument consists of one contiguous run of 1s with any
2857   /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
2858   /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
2859   /// since all 1s are not contiguous.
2860   bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2861 
2862   void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
2863                                bool *ICContext = nullptr,
2864                                bool IsListInit = false);
2865 
2866   bool
2867   BuiltinElementwiseTernaryMath(CallExpr *TheCall,
2868                                 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2869                                     EltwiseBuiltinArgTyRestriction::FloatTy);
2870   bool PrepareBuiltinElementwiseMathOneArgCall(
2871       CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
2872                              EltwiseBuiltinArgTyRestriction::None);
2873 
2874 private:
2875   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2876                         const ArraySubscriptExpr *ASE = nullptr,
2877                         bool AllowOnePastEnd = true, bool IndexNegated = false);
2878   void CheckArrayAccess(const Expr *E);
2879 
2880   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2881                         const FunctionProtoType *Proto);
2882 
2883   /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2884   /// such as function pointers returned from functions.
2885   bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
2886 
2887   /// CheckConstructorCall - Check a constructor call for correctness and safety
2888   /// properties not enforced by the C type system.
2889   void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
2890                             ArrayRef<const Expr *> Args,
2891                             const FunctionProtoType *Proto, SourceLocation Loc);
2892 
2893   /// Warn if a pointer or reference argument passed to a function points to an
2894   /// object that is less aligned than the parameter. This can happen when
2895   /// creating a typedef with a lower alignment than the original type and then
2896   /// calling functions defined in terms of the original type.
2897   void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
2898                          StringRef ParamName, QualType ArgTy, QualType ParamTy);
2899 
2900   ExprResult CheckOSLogFormatStringArg(Expr *Arg);
2901 
2902   ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2903                                       CallExpr *TheCall);
2904 
2905   bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2906                                   CallExpr *TheCall);
2907 
2908   void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
2909 
2910   /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
2911   /// or '__builtin_c23_va_start' for validity. Emit an error and return true
2912   /// on failure; return false on success.
2913   bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
2914   bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
2915 
2916   /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2917   /// friends.  This is declared to take (...), so we have to check everything.
2918   bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
2919 
2920   /// BuiltinSemaBuiltinFPClassification - Handle functions like
2921   /// __builtin_isnan and friends.  This is declared to take (...), so we have
2922   /// to check everything.
2923   bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
2924                                unsigned BuiltinID);
2925 
2926   /// Perform semantic analysis for a call to __builtin_complex.
2927   bool BuiltinComplex(CallExpr *TheCall);
2928   bool BuiltinOSLogFormat(CallExpr *TheCall);
2929 
2930   /// BuiltinPrefetch - Handle __builtin_prefetch.
2931   /// This is declared to take (const void*, ...) and can take two
2932   /// optional constant int args.
2933   bool BuiltinPrefetch(CallExpr *TheCall);
2934 
2935   /// Handle __builtin_alloca_with_align. This is declared
2936   /// as (size_t, size_t) where the second size_t must be a power of 2 greater
2937   /// than 8.
2938   bool BuiltinAllocaWithAlign(CallExpr *TheCall);
2939 
2940   /// BuiltinArithmeticFence - Handle __arithmetic_fence.
2941   bool BuiltinArithmeticFence(CallExpr *TheCall);
2942 
2943   /// BuiltinAssume - Handle __assume (MS Extension).
2944   /// __assume does not evaluate its arguments, and should warn if its argument
2945   /// has side effects.
2946   bool BuiltinAssume(CallExpr *TheCall);
2947 
2948   /// Handle __builtin_assume_aligned. This is declared
2949   /// as (const void*, size_t, ...) and can take one optional constant int arg.
2950   bool BuiltinAssumeAligned(CallExpr *TheCall);
2951 
2952   /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
2953   /// This checks that the target supports __builtin_longjmp and
2954   /// that val is a constant 1.
2955   bool BuiltinLongjmp(CallExpr *TheCall);
2956 
2957   /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2958   /// This checks that the target supports __builtin_setjmp.
2959   bool BuiltinSetjmp(CallExpr *TheCall);
2960 
2961   /// We have a call to a function like __sync_fetch_and_add, which is an
2962   /// overloaded function based on the pointer type of its first argument.
2963   /// The main BuildCallExpr routines have already promoted the types of
2964   /// arguments because all of these calls are prototyped as void(...).
2965   ///
2966   /// This function goes through and does final semantic checking for these
2967   /// builtins, as well as generating any warnings.
2968   ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
2969 
2970   /// BuiltinNontemporalOverloaded - We have a call to
2971   /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2972   /// overloaded function based on the pointer type of its last argument.
2973   ///
2974   /// This function goes through and does final semantic checking for these
2975   /// builtins.
2976   ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
2977   ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
2978                                  AtomicExpr::AtomicOp Op);
2979 
2980   /// \param FPOnly restricts the arguments to floating-point types.
2981   bool BuiltinElementwiseMath(CallExpr *TheCall,
2982                               EltwiseBuiltinArgTyRestriction ArgTyRestr =
2983                                   EltwiseBuiltinArgTyRestriction::None);
2984   bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
2985 
2986   bool BuiltinNonDeterministicValue(CallExpr *TheCall);
2987 
2988   bool CheckInvalidBuiltinCountedByRef(const Expr *E,
2989                                        BuiltinCountedByRefKind K);
2990   bool BuiltinCountedByRef(CallExpr *TheCall);
2991 
2992   // Matrix builtin handling.
2993   ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
2994   ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
2995                                           ExprResult CallResult);
2996   ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
2997                                            ExprResult CallResult);
2998 
2999   /// CheckFormatArguments - Check calls to printf and scanf (and similar
3000   /// functions) for correct use of format strings.
3001   /// Returns true if a format string has been fully checked.
3002   bool CheckFormatArguments(const FormatAttr *Format,
3003                             ArrayRef<const Expr *> Args, bool IsCXXMember,
3004                             VariadicCallType CallType, SourceLocation Loc,
3005                             SourceRange Range,
3006                             llvm::SmallBitVector &CheckedVarArgs);
3007   bool CheckFormatString(const FormatMatchesAttr *Format,
3008                          ArrayRef<const Expr *> Args, bool IsCXXMember,
3009                          VariadicCallType CallType, SourceLocation Loc,
3010                          SourceRange Range,
3011                          llvm::SmallBitVector &CheckedVarArgs);
3012   bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3013                             FormatArgumentPassingKind FAPK,
3014                             const StringLiteral *ReferenceFormatString,
3015                             unsigned format_idx, unsigned firstDataArg,
3016                             FormatStringType Type, VariadicCallType CallType,
3017                             SourceLocation Loc, SourceRange range,
3018                             llvm::SmallBitVector &CheckedVarArgs);
3019 
3020   void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3021 
3022   /// Warn when using the wrong abs() function.
3023   void CheckAbsoluteValueFunction(const CallExpr *Call,
3024                                   const FunctionDecl *FDecl);
3025 
3026   void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3027 
3028   /// Check for dangerous or invalid arguments to memset().
3029   ///
3030   /// This issues warnings on known problematic, dangerous or unspecified
3031   /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3032   /// function calls.
3033   ///
3034   /// \param Call The call expression to diagnose.
3035   void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3036                                IdentifierInfo *FnName);
3037 
3038   // Warn if the user has made the 'size' argument to strlcpy or strlcat
3039   // be the size of the source, instead of the destination.
3040   void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3041 
3042   // Warn on anti-patterns as the 'size' argument to strncat.
3043   // The correct size argument should look like following:
3044   //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3045   void CheckStrncatArguments(const CallExpr *Call,
3046                              const IdentifierInfo *FnName);
3047 
3048   /// Alerts the user that they are attempting to free a non-malloc'd object.
3049   void CheckFreeArguments(const CallExpr *E);
3050 
3051   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3052                           SourceLocation ReturnLoc, bool isObjCMethod = false,
3053                           const AttrVec *Attrs = nullptr,
3054                           const FunctionDecl *FD = nullptr);
3055 
3056   /// Diagnoses "dangerous" implicit conversions within the given
3057   /// expression (which is a full expression).  Implements -Wconversion
3058   /// and -Wsign-compare.
3059   ///
3060   /// \param CC the "context" location of the implicit conversion, i.e.
3061   ///   the most location of the syntactic entity requiring the implicit
3062   ///   conversion
3063   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3064 
3065   /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3066   /// Input argument E is a logical expression.
3067   void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
3068 
3069   /// Diagnose when expression is an integer constant expression and its
3070   /// evaluation results in integer overflow
3071   void CheckForIntOverflow(const Expr *E);
3072   void CheckUnsequencedOperations(const Expr *E);
3073 
3074   /// Perform semantic checks on a completed expression. This will either
3075   /// be a full-expression or a default argument expression.
3076   void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3077                           bool IsConstexpr = false);
3078 
3079   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3080                                    Expr *Init);
3081 
3082   /// A map from magic value to type information.
3083   std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3084       TypeTagForDatatypeMagicValues;
3085 
3086   /// Peform checks on a call of a function with argument_with_type_tag
3087   /// or pointer_with_type_tag attributes.
3088   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3089                                 const ArrayRef<const Expr *> ExprArgs,
3090                                 SourceLocation CallSiteLoc);
3091 
3092   /// Check if we are taking the address of a packed field
3093   /// as this may be a problem if the pointer value is dereferenced.
3094   void CheckAddressOfPackedMember(Expr *rhs);
3095 
3096   /// Helper class that collects misaligned member designations and
3097   /// their location info for delayed diagnostics.
3098   struct MisalignedMember {
3099     Expr *E;
3100     RecordDecl *RD;
3101     ValueDecl *MD;
3102     CharUnits Alignment;
3103 
MisalignedMemberMisalignedMember3104     MisalignedMember() : E(), RD(), MD() {}
MisalignedMemberMisalignedMember3105     MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3106                      CharUnits Alignment)
3107         : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
MisalignedMemberMisalignedMember3108     explicit MisalignedMember(Expr *E)
3109         : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3110 
3111     bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3112   };
3113   /// Small set of gathered accesses to potentially misaligned members
3114   /// due to the packed attribute.
3115   SmallVector<MisalignedMember, 4> MisalignedMembers;
3116 
3117   /// Adds an expression to the set of gathered misaligned members.
3118   void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3119                                      CharUnits Alignment);
3120   ///@}
3121 
3122   //
3123   //
3124   // -------------------------------------------------------------------------
3125   //
3126   //
3127 
3128   /// \name C++ Coroutines
3129   /// Implementations are in SemaCoroutine.cpp
3130   ///@{
3131 
3132 public:
3133   /// The C++ "std::coroutine_traits" template, which is defined in
3134   /// \<coroutine_traits>
3135   ClassTemplateDecl *StdCoroutineTraitsCache;
3136 
3137   bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
3138                                StringRef Keyword);
3139   ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3140   ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3141   StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
3142 
3143   ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
3144   ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
3145                                       UnresolvedLookupExpr *Lookup);
3146   ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3147                                       Expr *Awaiter, bool IsImplicit = false);
3148   ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3149                                         UnresolvedLookupExpr *Lookup);
3150   ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
3151   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
3152                                bool IsImplicit = false);
3153   StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
3154   bool buildCoroutineParameterMoves(SourceLocation Loc);
3155   VarDecl *buildCoroutinePromise(SourceLocation Loc);
3156   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
3157 
3158   // As a clang extension, enforces that a non-coroutine function must be marked
3159   // with [[clang::coro_wrapper]] if it returns a type marked with
3160   // [[clang::coro_return_type]].
3161   // Expects that FD is not a coroutine.
3162   void CheckCoroutineWrapper(FunctionDecl *FD);
3163   /// Lookup 'coroutine_traits' in std namespace and std::experimental
3164   /// namespace. The namespace found is recorded in Namespace.
3165   ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
3166                                            SourceLocation FuncLoc);
3167   /// Check that the expression co_await promise.final_suspend() shall not be
3168   /// potentially-throwing.
3169   bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3170 
3171   ///@}
3172 
3173   //
3174   //
3175   // -------------------------------------------------------------------------
3176   //
3177   //
3178 
3179   /// \name C++ Scope Specifiers
3180   /// Implementations are in SemaCXXScopeSpec.cpp
3181   ///@{
3182 
3183 public:
3184   // Marks SS invalid if it represents an incomplete type.
3185   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
3186   // Complete an enum decl, maybe without a scope spec.
3187   bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
3188                                CXXScopeSpec *SS = nullptr);
3189 
3190   /// Compute the DeclContext that is associated with the given type.
3191   ///
3192   /// \param T the type for which we are attempting to find a DeclContext.
3193   ///
3194   /// \returns the declaration context represented by the type T,
3195   /// or NULL if the declaration context cannot be computed (e.g., because it is
3196   /// dependent and not the current instantiation).
3197   DeclContext *computeDeclContext(QualType T);
3198 
3199   /// Compute the DeclContext that is associated with the given
3200   /// scope specifier.
3201   ///
3202   /// \param SS the C++ scope specifier as it appears in the source
3203   ///
3204   /// \param EnteringContext when true, we will be entering the context of
3205   /// this scope specifier, so we can retrieve the declaration context of a
3206   /// class template or class template partial specialization even if it is
3207   /// not the current instantiation.
3208   ///
3209   /// \returns the declaration context represented by the scope specifier @p SS,
3210   /// or NULL if the declaration context cannot be computed (e.g., because it is
3211   /// dependent and not the current instantiation).
3212   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
3213                                   bool EnteringContext = false);
3214   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
3215 
3216   /// If the given nested name specifier refers to the current
3217   /// instantiation, return the declaration that corresponds to that
3218   /// current instantiation (C++0x [temp.dep.type]p1).
3219   ///
3220   /// \param NNS a dependent nested name specifier.
3221   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
3222 
3223   /// The parser has parsed a global nested-name-specifier '::'.
3224   ///
3225   /// \param CCLoc The location of the '::'.
3226   ///
3227   /// \param SS The nested-name-specifier, which will be updated in-place
3228   /// to reflect the parsed nested-name-specifier.
3229   ///
3230   /// \returns true if an error occurred, false otherwise.
3231   bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
3232 
3233   /// The parser has parsed a '__super' nested-name-specifier.
3234   ///
3235   /// \param SuperLoc The location of the '__super' keyword.
3236   ///
3237   /// \param ColonColonLoc The location of the '::'.
3238   ///
3239   /// \param SS The nested-name-specifier, which will be updated in-place
3240   /// to reflect the parsed nested-name-specifier.
3241   ///
3242   /// \returns true if an error occurred, false otherwise.
3243   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
3244                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3245 
3246   /// Determines whether the given declaration is an valid acceptable
3247   /// result for name lookup of a nested-name-specifier.
3248   /// \param SD Declaration checked for nested-name-specifier.
3249   /// \param IsExtension If not null and the declaration is accepted as an
3250   /// extension, the pointed variable is assigned true.
3251   bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
3252                                        bool *CanCorrect = nullptr);
3253 
3254   /// If the given nested-name-specifier begins with a bare identifier
3255   /// (e.g., Base::), perform name lookup for that identifier as a
3256   /// nested-name-specifier within the given scope, and return the result of
3257   /// that name lookup.
3258   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
3259 
3260   /// Keeps information about an identifier in a nested-name-spec.
3261   ///
3262   struct NestedNameSpecInfo {
3263     /// The type of the object, if we're parsing nested-name-specifier in
3264     /// a member access expression.
3265     ParsedType ObjectType;
3266 
3267     /// The identifier preceding the '::'.
3268     IdentifierInfo *Identifier;
3269 
3270     /// The location of the identifier.
3271     SourceLocation IdentifierLoc;
3272 
3273     /// The location of the '::'.
3274     SourceLocation CCLoc;
3275 
3276     /// Creates info object for the most typical case.
3277     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3278                        SourceLocation ColonColonLoc,
3279                        ParsedType ObjectType = ParsedType())
ObjectTypeNestedNameSpecInfo3280         : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
3281           CCLoc(ColonColonLoc) {}
3282 
NestedNameSpecInfoNestedNameSpecInfo3283     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3284                        SourceLocation ColonColonLoc, QualType ObjectType)
3285         : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
3286           IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3287   };
3288 
3289   /// Build a new nested-name-specifier for "identifier::", as described
3290   /// by ActOnCXXNestedNameSpecifier.
3291   ///
3292   /// \param S Scope in which the nested-name-specifier occurs.
3293   /// \param IdInfo Parser information about an identifier in the
3294   ///        nested-name-spec.
3295   /// \param EnteringContext If true, enter the context specified by the
3296   ///        nested-name-specifier.
3297   /// \param SS Optional nested name specifier preceding the identifier.
3298   /// \param ScopeLookupResult Provides the result of name lookup within the
3299   ///        scope of the nested-name-specifier that was computed at template
3300   ///        definition time.
3301   /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3302   ///        error recovery and what kind of recovery is performed.
3303   /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3304   ///        are allowed.  The bool value pointed by this parameter is set to
3305   ///       'true' if the identifier is treated as if it was followed by ':',
3306   ///        not '::'.
3307   /// \param OnlyNamespace If true, only considers namespaces in lookup.
3308   ///
3309   /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3310   /// that it contains an extra parameter \p ScopeLookupResult, which provides
3311   /// the result of name lookup within the scope of the nested-name-specifier
3312   /// that was computed at template definition time.
3313   ///
3314   /// If ErrorRecoveryLookup is true, then this call is used to improve error
3315   /// recovery.  This means that it should not emit diagnostics, it should
3316   /// just return true on failure.  It also means it should only return a valid
3317   /// scope if it *knows* that the result is correct.  It should not return in a
3318   /// dependent context, for example. Nor will it extend \p SS with the scope
3319   /// specifier.
3320   bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3321                                    bool EnteringContext, CXXScopeSpec &SS,
3322                                    NamedDecl *ScopeLookupResult,
3323                                    bool ErrorRecoveryLookup,
3324                                    bool *IsCorrectedToColon = nullptr,
3325                                    bool OnlyNamespace = false);
3326 
3327   /// The parser has parsed a nested-name-specifier 'identifier::'.
3328   ///
3329   /// \param S The scope in which this nested-name-specifier occurs.
3330   ///
3331   /// \param IdInfo Parser information about an identifier in the
3332   /// nested-name-spec.
3333   ///
3334   /// \param EnteringContext Whether we're entering the context nominated by
3335   /// this nested-name-specifier.
3336   ///
3337   /// \param SS The nested-name-specifier, which is both an input
3338   /// parameter (the nested-name-specifier before this type) and an
3339   /// output parameter (containing the full nested-name-specifier,
3340   /// including this new type).
3341   ///
3342   /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3343   /// are allowed.  The bool value pointed by this parameter is set to 'true'
3344   /// if the identifier is treated as if it was followed by ':', not '::'.
3345   ///
3346   /// \param OnlyNamespace If true, only considers namespaces in lookup.
3347   ///
3348   /// \returns true if an error occurred, false otherwise.
3349   bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3350                                    bool EnteringContext, CXXScopeSpec &SS,
3351                                    bool *IsCorrectedToColon = nullptr,
3352                                    bool OnlyNamespace = false);
3353 
3354   /// The parser has parsed a nested-name-specifier
3355   /// 'template[opt] template-name < template-args >::'.
3356   ///
3357   /// \param S The scope in which this nested-name-specifier occurs.
3358   ///
3359   /// \param SS The nested-name-specifier, which is both an input
3360   /// parameter (the nested-name-specifier before this type) and an
3361   /// output parameter (containing the full nested-name-specifier,
3362   /// including this new type).
3363   ///
3364   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3365   /// \param TemplateName the template name.
3366   /// \param TemplateNameLoc The location of the template name.
3367   /// \param LAngleLoc The location of the opening angle bracket  ('<').
3368   /// \param TemplateArgs The template arguments.
3369   /// \param RAngleLoc The location of the closing angle bracket  ('>').
3370   /// \param CCLoc The location of the '::'.
3371   ///
3372   /// \param EnteringContext Whether we're entering the context of the
3373   /// nested-name-specifier.
3374   ///
3375   ///
3376   /// \returns true if an error occurred, false otherwise.
3377   bool ActOnCXXNestedNameSpecifier(
3378       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3379       TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3380       SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3381       SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3382 
3383   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS,
3384                                            SourceLocation ColonColonLoc);
3385 
3386   bool ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS,
3387                                               const DeclSpec &DS,
3388                                               SourceLocation ColonColonLoc,
3389                                               QualType Type);
3390 
3391   /// IsInvalidUnlessNestedName - This method is used for error recovery
3392   /// purposes to determine whether the specified identifier is only valid as
3393   /// a nested name specifier, for example a namespace name.  It is
3394   /// conservatively correct to always return false from this method.
3395   ///
3396   /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3397   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3398                                  NestedNameSpecInfo &IdInfo,
3399                                  bool EnteringContext);
3400 
3401   /// Given a C++ nested-name-specifier, produce an annotation value
3402   /// that the parser can use later to reconstruct the given
3403   /// nested-name-specifier.
3404   ///
3405   /// \param SS A nested-name-specifier.
3406   ///
3407   /// \returns A pointer containing all of the information in the
3408   /// nested-name-specifier \p SS.
3409   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3410 
3411   /// Given an annotation pointer for a nested-name-specifier, restore
3412   /// the nested-name-specifier structure.
3413   ///
3414   /// \param Annotation The annotation pointer, produced by
3415   /// \c SaveNestedNameSpecifierAnnotation().
3416   ///
3417   /// \param AnnotationRange The source range corresponding to the annotation.
3418   ///
3419   /// \param SS The nested-name-specifier that will be updated with the contents
3420   /// of the annotation pointer.
3421   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3422                                             SourceRange AnnotationRange,
3423                                             CXXScopeSpec &SS);
3424 
3425   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3426 
3427   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3428   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3429   /// After this method is called, according to [C++ 3.4.3p3], names should be
3430   /// looked up in the declarator-id's scope, until the declarator is parsed and
3431   /// ActOnCXXExitDeclaratorScope is called.
3432   /// The 'SS' should be a non-empty valid CXXScopeSpec.
3433   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
3434 
3435   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3436   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3437   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3438   /// Used to indicate that names should revert to being looked up in the
3439   /// defining scope.
3440   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3441 
3442   ///@}
3443 
3444   //
3445   //
3446   // -------------------------------------------------------------------------
3447   //
3448   //
3449 
3450   /// \name Declarations
3451   /// Implementations are in SemaDecl.cpp
3452   ///@{
3453 
3454 public:
3455   IdentifierResolver IdResolver;
3456 
3457   /// The index of the first InventedParameterInfo that refers to the current
3458   /// context.
3459   unsigned InventedParameterInfosStart = 0;
3460 
3461   /// A RAII object to temporarily push a declaration context.
3462   class ContextRAII {
3463   private:
3464     Sema &S;
3465     DeclContext *SavedContext;
3466     ProcessingContextState SavedContextState;
3467     QualType SavedCXXThisTypeOverride;
3468     unsigned SavedFunctionScopesStart;
3469     unsigned SavedInventedParameterInfosStart;
3470 
3471   public:
3472     ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
S(S)3473         : S(S), SavedContext(S.CurContext),
3474           SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3475           SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3476           SavedFunctionScopesStart(S.FunctionScopesStart),
3477           SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3478       assert(ContextToPush && "pushing null context");
3479       S.CurContext = ContextToPush;
3480       if (NewThisContext)
3481         S.CXXThisTypeOverride = QualType();
3482       // Any saved FunctionScopes do not refer to this context.
3483       S.FunctionScopesStart = S.FunctionScopes.size();
3484       S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3485     }
3486 
pop()3487     void pop() {
3488       if (!SavedContext)
3489         return;
3490       S.CurContext = SavedContext;
3491       S.DelayedDiagnostics.popUndelayed(SavedContextState);
3492       S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3493       S.FunctionScopesStart = SavedFunctionScopesStart;
3494       S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3495       SavedContext = nullptr;
3496     }
3497 
~ContextRAII()3498     ~ContextRAII() { pop(); }
3499   };
3500 
3501   void DiagnoseInvalidJumps(Stmt *Body);
3502 
3503   /// The function definitions which were renamed as part of typo-correction
3504   /// to match their respective declarations. We want to keep track of them
3505   /// to ensure that we don't emit a "redefinition" error if we encounter a
3506   /// correctly named definition after the renamed definition.
3507   llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
3508 
3509   /// A cache of the flags available in enumerations with the flag_bits
3510   /// attribute.
3511   mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3512 
3513   /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3514   /// declared. Rare. May alias another identifier, declared or undeclared.
3515   ///
3516   /// For aliases, the target identifier is used as a key for eventual
3517   /// processing when the target is declared. For the single-identifier form,
3518   /// the sole identifier is used as the key. Each entry is a `SetVector`
3519   /// (ordered by parse order) of aliases (identified by the alias name) in case
3520   /// of multiple aliases to the same undeclared identifier.
3521   llvm::MapVector<
3522       IdentifierInfo *,
3523       llvm::SetVector<
3524           WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
3525           llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3526       WeakUndeclaredIdentifiers;
3527 
3528   /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3529   /// \#pragma redefine_extname before declared.  Used in Solaris system headers
3530   /// to define functions that occur in multiple standards to call the version
3531   /// in the currently selected standard.
3532   llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *> ExtnameUndeclaredIdentifiers;
3533 
3534   /// Set containing all typedefs that are likely unused.
3535   llvm::SmallSetVector<const TypedefNameDecl *, 4>
3536       UnusedLocalTypedefNameCandidates;
3537 
3538   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
3539                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
3540       UnusedFileScopedDeclsType;
3541 
3542   /// The set of file scoped decls seen so far that have not been used
3543   /// and must warn if not used. Only contains the first declaration.
3544   UnusedFileScopedDeclsType UnusedFileScopedDecls;
3545 
3546   typedef LazyVector<VarDecl *, ExternalSemaSource,
3547                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
3548       TentativeDefinitionsType;
3549 
3550   /// All the tentative definitions encountered in the TU.
3551   TentativeDefinitionsType TentativeDefinitions;
3552 
3553   /// All the external declarations encoutered and used in the TU.
3554   SmallVector<DeclaratorDecl *, 4> ExternalDeclarations;
3555 
3556   /// Generally null except when we temporarily switch decl contexts,
3557   /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3558   DeclContext *OriginalLexicalContext;
3559 
3560   /// Is the module scope we are in a C++ Header Unit?
currentModuleIsHeaderUnit()3561   bool currentModuleIsHeaderUnit() const {
3562     return ModuleScopes.empty() ? false
3563                                 : ModuleScopes.back().Module->isHeaderUnit();
3564   }
3565 
3566   /// Get the module owning an entity.
getOwningModule(const Decl * Entity)3567   Module *getOwningModule(const Decl *Entity) {
3568     return Entity->getOwningModule();
3569   }
3570 
3571   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3572 
3573   enum class DiagCtorKind { None, Implicit, Typename };
3574   /// Returns the TypeDeclType for the given type declaration,
3575   /// as ASTContext::getTypeDeclType would, but
3576   /// performs the required semantic checks for name lookup of said entity.
3577   QualType getTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK,
3578                            TypeDecl *TD, SourceLocation NameLoc);
3579 
3580   /// If the identifier refers to a type name within this scope,
3581   /// return the declaration of that type.
3582   ///
3583   /// This routine performs ordinary name lookup of the identifier II
3584   /// within the given scope, with optional C++ scope specifier SS, to
3585   /// determine whether the name refers to a type. If so, returns an
3586   /// opaque pointer (actually a QualType) corresponding to that
3587   /// type. Otherwise, returns NULL.
3588   ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
3589                          Scope *S, CXXScopeSpec *SS = nullptr,
3590                          bool isClassName = false, bool HasTrailingDot = false,
3591                          ParsedType ObjectType = nullptr,
3592                          bool IsCtorOrDtorName = false,
3593                          bool WantNontrivialTypeSourceInfo = false,
3594                          bool IsClassTemplateDeductionContext = true,
3595                          ImplicitTypenameContext AllowImplicitTypename =
3596                              ImplicitTypenameContext::No,
3597                          IdentifierInfo **CorrectedII = nullptr);
3598 
3599   /// isTagName() - This method is called *for error recovery purposes only*
3600   /// to determine if the specified name is a valid tag name ("struct foo").  If
3601   /// so, this returns the TST for the tag corresponding to it (TST_enum,
3602   /// TST_union, TST_struct, TST_interface, TST_class).  This is used to
3603   /// diagnose cases in C where the user forgot to specify the tag.
3604   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
3605 
3606   /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3607   /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3608   /// then downgrade the missing typename error to a warning.
3609   /// This is needed for MSVC compatibility; Example:
3610   /// @code
3611   /// template<class T> class A {
3612   /// public:
3613   ///   typedef int TYPE;
3614   /// };
3615   /// template<class T> class B : public A<T> {
3616   /// public:
3617   ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
3618   /// };
3619   /// @endcode
3620   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3621   void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc,
3622                                Scope *S, CXXScopeSpec *SS,
3623                                ParsedType &SuggestedType,
3624                                bool IsTemplateName = false);
3625 
3626   /// Attempt to behave like MSVC in situations where lookup of an unqualified
3627   /// type name has failed in a dependent context. In these situations, we
3628   /// automatically form a DependentTypeName that will retry lookup in a related
3629   /// scope during instantiation.
3630   ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
3631                                       SourceLocation NameLoc,
3632                                       bool IsTemplateTypeArg);
3633 
3634   class NameClassification {
3635     NameClassificationKind Kind;
3636     union {
3637       ExprResult Expr;
3638       NamedDecl *NonTypeDecl;
3639       TemplateName Template;
3640       ParsedType Type;
3641     };
3642 
NameClassification(NameClassificationKind Kind)3643     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3644 
3645   public:
NameClassification(ParsedType Type)3646     NameClassification(ParsedType Type)
3647         : Kind(NameClassificationKind::Type), Type(Type) {}
3648 
NameClassification(const IdentifierInfo * Keyword)3649     NameClassification(const IdentifierInfo *Keyword)
3650         : Kind(NameClassificationKind::Keyword) {}
3651 
Error()3652     static NameClassification Error() {
3653       return NameClassification(NameClassificationKind::Error);
3654     }
3655 
Unknown()3656     static NameClassification Unknown() {
3657       return NameClassification(NameClassificationKind::Unknown);
3658     }
3659 
OverloadSet(ExprResult E)3660     static NameClassification OverloadSet(ExprResult E) {
3661       NameClassification Result(NameClassificationKind::OverloadSet);
3662       Result.Expr = E;
3663       return Result;
3664     }
3665 
NonType(NamedDecl * D)3666     static NameClassification NonType(NamedDecl *D) {
3667       NameClassification Result(NameClassificationKind::NonType);
3668       Result.NonTypeDecl = D;
3669       return Result;
3670     }
3671 
UndeclaredNonType()3672     static NameClassification UndeclaredNonType() {
3673       return NameClassification(NameClassificationKind::UndeclaredNonType);
3674     }
3675 
DependentNonType()3676     static NameClassification DependentNonType() {
3677       return NameClassification(NameClassificationKind::DependentNonType);
3678     }
3679 
TypeTemplate(TemplateName Name)3680     static NameClassification TypeTemplate(TemplateName Name) {
3681       NameClassification Result(NameClassificationKind::TypeTemplate);
3682       Result.Template = Name;
3683       return Result;
3684     }
3685 
VarTemplate(TemplateName Name)3686     static NameClassification VarTemplate(TemplateName Name) {
3687       NameClassification Result(NameClassificationKind::VarTemplate);
3688       Result.Template = Name;
3689       return Result;
3690     }
3691 
FunctionTemplate(TemplateName Name)3692     static NameClassification FunctionTemplate(TemplateName Name) {
3693       NameClassification Result(NameClassificationKind::FunctionTemplate);
3694       Result.Template = Name;
3695       return Result;
3696     }
3697 
Concept(TemplateName Name)3698     static NameClassification Concept(TemplateName Name) {
3699       NameClassification Result(NameClassificationKind::Concept);
3700       Result.Template = Name;
3701       return Result;
3702     }
3703 
UndeclaredTemplate(TemplateName Name)3704     static NameClassification UndeclaredTemplate(TemplateName Name) {
3705       NameClassification Result(NameClassificationKind::UndeclaredTemplate);
3706       Result.Template = Name;
3707       return Result;
3708     }
3709 
getKind()3710     NameClassificationKind getKind() const { return Kind; }
3711 
getExpression()3712     ExprResult getExpression() const {
3713       assert(Kind == NameClassificationKind::OverloadSet);
3714       return Expr;
3715     }
3716 
getType()3717     ParsedType getType() const {
3718       assert(Kind == NameClassificationKind::Type);
3719       return Type;
3720     }
3721 
getNonTypeDecl()3722     NamedDecl *getNonTypeDecl() const {
3723       assert(Kind == NameClassificationKind::NonType);
3724       return NonTypeDecl;
3725     }
3726 
getTemplateName()3727     TemplateName getTemplateName() const {
3728       assert(Kind == NameClassificationKind::TypeTemplate ||
3729              Kind == NameClassificationKind::FunctionTemplate ||
3730              Kind == NameClassificationKind::VarTemplate ||
3731              Kind == NameClassificationKind::Concept ||
3732              Kind == NameClassificationKind::UndeclaredTemplate);
3733       return Template;
3734     }
3735 
getTemplateNameKind()3736     TemplateNameKind getTemplateNameKind() const {
3737       switch (Kind) {
3738       case NameClassificationKind::TypeTemplate:
3739         return TNK_Type_template;
3740       case NameClassificationKind::FunctionTemplate:
3741         return TNK_Function_template;
3742       case NameClassificationKind::VarTemplate:
3743         return TNK_Var_template;
3744       case NameClassificationKind::Concept:
3745         return TNK_Concept_template;
3746       case NameClassificationKind::UndeclaredTemplate:
3747         return TNK_Undeclared_template;
3748       default:
3749         llvm_unreachable("unsupported name classification.");
3750       }
3751     }
3752   };
3753 
3754   /// Perform name lookup on the given name, classifying it based on
3755   /// the results of name lookup and the following token.
3756   ///
3757   /// This routine is used by the parser to resolve identifiers and help direct
3758   /// parsing. When the identifier cannot be found, this routine will attempt
3759   /// to correct the typo and classify based on the resulting name.
3760   ///
3761   /// \param S The scope in which we're performing name lookup.
3762   ///
3763   /// \param SS The nested-name-specifier that precedes the name.
3764   ///
3765   /// \param Name The identifier. If typo correction finds an alternative name,
3766   /// this pointer parameter will be updated accordingly.
3767   ///
3768   /// \param NameLoc The location of the identifier.
3769   ///
3770   /// \param NextToken The token following the identifier. Used to help
3771   /// disambiguate the name.
3772   ///
3773   /// \param CCC The correction callback, if typo correction is desired.
3774   NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3775                                   IdentifierInfo *&Name, SourceLocation NameLoc,
3776                                   const Token &NextToken,
3777                                   CorrectionCandidateCallback *CCC = nullptr);
3778 
3779   /// Act on the result of classifying a name as an undeclared (ADL-only)
3780   /// non-type declaration.
3781   ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
3782                                                     SourceLocation NameLoc);
3783   /// Act on the result of classifying a name as an undeclared member of a
3784   /// dependent base class.
3785   ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
3786                                                    IdentifierInfo *Name,
3787                                                    SourceLocation NameLoc,
3788                                                    bool IsAddressOfOperand);
3789   /// Act on the result of classifying a name as a specific non-type
3790   /// declaration.
3791   ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
3792                                           NamedDecl *Found,
3793                                           SourceLocation NameLoc,
3794                                           const Token &NextToken);
3795   /// Act on the result of classifying a name as an overload set.
3796   ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
3797 
3798   /// Describes the detailed kind of a template name. Used in diagnostics.
3799   enum class TemplateNameKindForDiagnostics {
3800     ClassTemplate,
3801     FunctionTemplate,
3802     VarTemplate,
3803     AliasTemplate,
3804     TemplateTemplateParam,
3805     Concept,
3806     DependentTemplate
3807   };
3808   TemplateNameKindForDiagnostics
3809   getTemplateNameKindForDiagnostics(TemplateName Name);
3810 
3811   /// Determine whether it's plausible that E was intended to be a
3812   /// template-name.
mightBeIntendedToBeTemplateName(ExprResult E,bool & Dependent)3813   bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
3814     if (!getLangOpts().CPlusPlus || E.isInvalid())
3815       return false;
3816     Dependent = false;
3817     if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
3818       return !DRE->hasExplicitTemplateArgs();
3819     if (auto *ME = dyn_cast<MemberExpr>(E.get()))
3820       return !ME->hasExplicitTemplateArgs();
3821     Dependent = true;
3822     if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
3823       return !DSDRE->hasExplicitTemplateArgs();
3824     if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
3825       return !DSME->hasExplicitTemplateArgs();
3826     // Any additional cases recognized here should also be handled by
3827     // diagnoseExprIntendedAsTemplateName.
3828     return false;
3829   }
3830 
3831   void warnOnReservedIdentifier(const NamedDecl *D);
3832   void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D);
3833 
3834   Decl *ActOnDeclarator(Scope *S, Declarator &D);
3835 
3836   NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
3837                               MultiTemplateParamsArg TemplateParameterLists);
3838 
3839   /// Attempt to fold a variable-sized type to a constant-sized type, returning
3840   /// true if we were successful.
3841   bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T,
3842                                        SourceLocation Loc,
3843                                        unsigned FailedFoldDiagID);
3844 
3845   /// Register the given locally-scoped extern "C" declaration so
3846   /// that it can be found later for redeclarations. We include any extern "C"
3847   /// declaration that is not visible in the translation unit here, not just
3848   /// function-scope declarations.
3849   void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
3850 
3851   /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3852   ///   If T is the name of a class, then each of the following shall have a
3853   ///   name different from T:
3854   ///     - every static data member of class T;
3855   ///     - every member function of class T
3856   ///     - every member of class T that is itself a type;
3857   /// \returns true if the declaration name violates these rules.
3858   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
3859 
3860   /// Diagnose a declaration whose declarator-id has the given
3861   /// nested-name-specifier.
3862   ///
3863   /// \param SS The nested-name-specifier of the declarator-id.
3864   ///
3865   /// \param DC The declaration context to which the nested-name-specifier
3866   /// resolves.
3867   ///
3868   /// \param Name The name of the entity being declared.
3869   ///
3870   /// \param Loc The location of the name of the entity being declared.
3871   ///
3872   /// \param IsMemberSpecialization Whether we are declaring a member
3873   /// specialization.
3874   ///
3875   /// \param TemplateId The template-id, if any.
3876   ///
3877   /// \returns true if we cannot safely recover from this error, false
3878   /// otherwise.
3879   bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3880                                     DeclarationName Name, SourceLocation Loc,
3881                                     TemplateIdAnnotation *TemplateId,
3882                                     bool IsMemberSpecialization);
3883 
3884   bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range);
3885 
3886   bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
3887 
3888   bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind,
3889                                         unsigned &IntVal);
3890 
3891   /// Diagnose function specifiers on a declaration of an identifier that
3892   /// does not identify a function.
3893   void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
3894 
3895   /// Return the declaration shadowed by the given typedef \p D, or null
3896   /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3897   NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
3898                                     const LookupResult &R);
3899 
3900   /// Return the declaration shadowed by the given variable \p D, or null
3901   /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3902   NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
3903 
3904   /// Return the declaration shadowed by the given variable \p D, or null
3905   /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3906   NamedDecl *getShadowedDeclaration(const BindingDecl *D,
3907                                     const LookupResult &R);
3908   /// Diagnose variable or built-in function shadowing.  Implements
3909   /// -Wshadow.
3910   ///
3911   /// This method is called whenever a VarDecl is added to a "useful"
3912   /// scope.
3913   ///
3914   /// \param ShadowedDecl the declaration that is shadowed by the given variable
3915   /// \param R the lookup of the name
3916   void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
3917                    const LookupResult &R);
3918 
3919   /// Check -Wshadow without the advantage of a previous lookup.
3920   void CheckShadow(Scope *S, VarDecl *D);
3921 
3922   /// Warn if 'E', which is an expression that is about to be modified, refers
3923   /// to a shadowing declaration.
3924   void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
3925 
3926   /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
3927   /// when these variables are captured by the lambda.
3928   void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
3929 
3930   void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
3931   void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3932                                     TypedefNameDecl *NewTD);
3933   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
3934   NamedDecl *ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC,
3935                                     TypeSourceInfo *TInfo,
3936                                     LookupResult &Previous);
3937 
3938   /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3939   /// declares a typedef-name, either using the 'typedef' type specifier or via
3940   /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3941   NamedDecl *ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D,
3942                                   LookupResult &Previous, bool &Redeclaration);
3943   NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
3944                                      TypeSourceInfo *TInfo,
3945                                      LookupResult &Previous,
3946                                      MultiTemplateParamsArg TemplateParamLists,
3947                                      bool &AddToScope,
3948                                      ArrayRef<BindingDecl *> Bindings = {});
3949 
3950   /// Perform semantic checking on a newly-created variable
3951   /// declaration.
3952   ///
3953   /// This routine performs all of the type-checking required for a
3954   /// variable declaration once it has been built. It is used both to
3955   /// check variables after they have been parsed and their declarators
3956   /// have been translated into a declaration, and to check variables
3957   /// that have been instantiated from a template.
3958   ///
3959   /// Sets NewVD->isInvalidDecl() if an error was encountered.
3960   ///
3961   /// Returns true if the variable declaration is a redeclaration.
3962   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
3963   void CheckVariableDeclarationType(VarDecl *NewVD);
3964   void CheckCompleteVariableDeclaration(VarDecl *VD);
3965 
3966   NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
3967                                      TypeSourceInfo *TInfo,
3968                                      LookupResult &Previous,
3969                                      MultiTemplateParamsArg TemplateParamLists,
3970                                      bool &AddToScope);
3971 
3972   /// AddOverriddenMethods - See if a method overrides any in the base classes,
3973   /// and if so, check that it's a valid override and remember it.
3974   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
3975 
3976   /// Perform semantic checking of a new function declaration.
3977   ///
3978   /// Performs semantic analysis of the new function declaration
3979   /// NewFD. This routine performs all semantic checking that does not
3980   /// require the actual declarator involved in the declaration, and is
3981   /// used both for the declaration of functions as they are parsed
3982   /// (called via ActOnDeclarator) and for the declaration of functions
3983   /// that have been instantiated via C++ template instantiation (called
3984   /// via InstantiateDecl).
3985   ///
3986   /// \param IsMemberSpecialization whether this new function declaration is
3987   /// a member specialization (that replaces any definition provided by the
3988   /// previous declaration).
3989   ///
3990   /// This sets NewFD->isInvalidDecl() to true if there was an error.
3991   ///
3992   /// \returns true if the function declaration is a redeclaration.
3993   bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
3994                                 LookupResult &Previous,
3995                                 bool IsMemberSpecialization, bool DeclIsDefn);
3996 
3997   /// Checks if the new declaration declared in dependent context must be
3998   /// put in the same redeclaration chain as the specified declaration.
3999   ///
4000   /// \param D Declaration that is checked.
4001   /// \param PrevDecl Previous declaration found with proper lookup method for
4002   ///                 the same declaration name.
4003   /// \returns True if D must be added to the redeclaration chain which PrevDecl
4004   ///          belongs to.
4005   bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4006 
4007   /// Determines if we can perform a correct type check for \p D as a
4008   /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4009   /// best-effort check.
4010   ///
4011   /// \param NewD The new declaration.
4012   /// \param OldD The old declaration.
4013   /// \param NewT The portion of the type of the new declaration to check.
4014   /// \param OldT The portion of the type of the old declaration to check.
4015   bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4016                                       QualType NewT, QualType OldT);
4017   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4018   void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4019 
4020   /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4021   /// containing class. Otherwise it will return implicit SectionAttr if the
4022   /// function is a definition and there is an active value on CodeSegStack
4023   /// (from the current #pragma code-seg value).
4024   ///
4025   /// \param FD Function being declared.
4026   /// \param IsDefinition Whether it is a definition or just a declaration.
4027   /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4028   ///          nullptr if no attribute should be added.
4029   Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4030                                                    bool IsDefinition);
4031 
4032   /// Common checks for a parameter-declaration that should apply to both
4033   /// function parameters and non-type template parameters.
4034   void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4035 
4036   /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4037   /// to introduce parameters into function prototype scope.
4038   Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4039                              SourceLocation ExplicitThisLoc = {});
4040 
4041   /// Synthesizes a variable for a parameter arising from a
4042   /// typedef.
4043   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4044                                           QualType T);
4045   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4046                               SourceLocation NameLoc,
4047                               const IdentifierInfo *Name, QualType T,
4048                               TypeSourceInfo *TSInfo, StorageClass SC);
4049 
4050   /// Emit diagnostics if the initializer or any of its explicit or
4051   /// implicitly-generated subexpressions require copying or
4052   /// default-initializing a type that is or contains a C union type that is
4053   /// non-trivial to copy or default-initialize.
4054   void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4055 
4056   // These flags are passed to checkNonTrivialCUnion.
4057   enum NonTrivialCUnionKind {
4058     NTCUK_Init = 0x1,
4059     NTCUK_Destruct = 0x2,
4060     NTCUK_Copy = 0x4,
4061   };
4062 
4063   /// Emit diagnostics if a non-trivial C union type or a struct that contains
4064   /// a non-trivial C union is used in an invalid context.
4065   void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
4066                              NonTrivialCUnionContext UseContext,
4067                              unsigned NonTrivialKind);
4068 
4069   /// Certain globally-unique variables might be accidentally duplicated if
4070   /// built into multiple shared libraries with hidden visibility. This can
4071   /// cause problems if the variable is mutable, its initialization is
4072   /// effectful, or its address is taken.
4073   bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl);
4074   void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl);
4075 
4076   /// AddInitializerToDecl - Adds the initializer Init to the
4077   /// declaration dcl. If DirectInit is true, this is C++ direct
4078   /// initialization rather than copy initialization.
4079   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4080   void ActOnUninitializedDecl(Decl *dcl);
4081 
4082   /// ActOnInitializerError - Given that there was an error parsing an
4083   /// initializer for the given declaration, try to at least re-establish
4084   /// invariants such as whether a variable's type is either dependent or
4085   /// complete.
4086   void ActOnInitializerError(Decl *Dcl);
4087 
4088   void ActOnCXXForRangeDecl(Decl *D);
4089   StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
4090                                         IdentifierInfo *Ident,
4091                                         ParsedAttributes &Attrs);
4092 
4093   /// Check if VD needs to be dllexport/dllimport due to being in a
4094   /// dllexport/import function.
4095   void CheckStaticLocalForDllExport(VarDecl *VD);
4096   void CheckThreadLocalForLargeAlignment(VarDecl *VD);
4097 
4098   /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4099   /// any semantic actions necessary after any initializer has been attached.
4100   void FinalizeDeclaration(Decl *D);
4101   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4102                                          ArrayRef<Decl *> Group);
4103 
4104   /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4105   /// group, performing any necessary semantic checking.
4106   DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
4107 
4108   /// Should be called on all declarations that might have attached
4109   /// documentation comments.
4110   void ActOnDocumentableDecl(Decl *D);
4111   void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
4112 
4113   enum class FnBodyKind {
4114     /// C++26 [dcl.fct.def.general]p1
4115     /// function-body:
4116     ///   ctor-initializer[opt] compound-statement
4117     ///   function-try-block
4118     Other,
4119     ///   = default ;
4120     Default,
4121     ///   deleted-function-body
4122     ///
4123     /// deleted-function-body:
4124     ///   = delete ;
4125     ///   = delete ( unevaluated-string ) ;
4126     Delete
4127   };
4128 
4129   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4130                                        SourceLocation LocAfterDecls);
4131   void CheckForFunctionRedefinition(
4132       FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4133       SkipBodyInfo *SkipBody = nullptr);
4134   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
4135                                 MultiTemplateParamsArg TemplateParamLists,
4136                                 SkipBodyInfo *SkipBody = nullptr,
4137                                 FnBodyKind BodyKind = FnBodyKind::Other);
4138   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
4139                                 SkipBodyInfo *SkipBody = nullptr,
4140                                 FnBodyKind BodyKind = FnBodyKind::Other);
4141   void applyFunctionAttributesBeforeParsingBody(Decl *FD);
4142 
4143   /// Determine whether we can delay parsing the body of a function or
4144   /// function template until it is used, assuming we don't care about emitting
4145   /// code for that function.
4146   ///
4147   /// This will be \c false if we may need the body of the function in the
4148   /// middle of parsing an expression (where it's impractical to switch to
4149   /// parsing a different function), for instance, if it's constexpr in C++11
4150   /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4151   bool canDelayFunctionBody(const Declarator &D);
4152 
4153   /// Determine whether we can skip parsing the body of a function
4154   /// definition, assuming we don't care about analyzing its body or emitting
4155   /// code for that function.
4156   ///
4157   /// This will be \c false only if we may need the body of the function in
4158   /// order to parse the rest of the program (for instance, if it is
4159   /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4160   bool canSkipFunctionBody(Decl *D);
4161 
4162   /// Given the set of return statements within a function body,
4163   /// compute the variables that are subject to the named return value
4164   /// optimization.
4165   ///
4166   /// Each of the variables that is subject to the named return value
4167   /// optimization will be marked as NRVO variables in the AST, and any
4168   /// return statement that has a marked NRVO variable as its NRVO candidate can
4169   /// use the named return value optimization.
4170   ///
4171   /// This function applies a very simplistic algorithm for NRVO: if every
4172   /// return statement in the scope of a variable has the same NRVO candidate,
4173   /// that candidate is an NRVO variable.
4174   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
4175   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
4176   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
4177   Decl *ActOnSkippedFunctionBody(Decl *Decl);
4178   void ActOnFinishInlineFunctionDef(FunctionDecl *D);
4179 
4180   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4181   /// attribute for which parsing is delayed.
4182   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
4183 
4184   /// Diagnose any unused parameters in the given sequence of
4185   /// ParmVarDecl pointers.
4186   void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
4187 
4188   /// Diagnose whether the size of parameters or return value of a
4189   /// function or obj-c method definition is pass-by-value and larger than a
4190   /// specified threshold.
4191   void
4192   DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
4193                                          QualType ReturnTy, NamedDecl *D);
4194 
4195   Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc,
4196                               SourceLocation RParenLoc);
4197 
4198   TopLevelStmtDecl *ActOnStartTopLevelStmtDecl(Scope *S);
4199   void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement);
4200 
4201   void ActOnPopScope(SourceLocation Loc, Scope *S);
4202 
4203   /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4204   /// no declarator (e.g. "struct foo;") is parsed.
4205   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4206                                    const ParsedAttributesView &DeclAttrs,
4207                                    RecordDecl *&AnonRecord);
4208 
4209   /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4210   /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4211   /// parameters to cope with template friend declarations.
4212   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4213                                    const ParsedAttributesView &DeclAttrs,
4214                                    MultiTemplateParamsArg TemplateParams,
4215                                    bool IsExplicitInstantiation,
4216                                    RecordDecl *&AnonRecord,
4217                                    SourceLocation EllipsisLoc = {});
4218 
4219   /// BuildAnonymousStructOrUnion - Handle the declaration of an
4220   /// anonymous structure or union. Anonymous unions are a C++ feature
4221   /// (C++ [class.union]) and a C11 feature; anonymous structures
4222   /// are a C11 feature and GNU C++ extension.
4223   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4224                                     RecordDecl *Record,
4225                                     const PrintingPolicy &Policy);
4226 
4227   /// Called once it is known whether
4228   /// a tag declaration is an anonymous union or struct.
4229   void ActOnDefinedDeclarationSpecifier(Decl *D);
4230 
4231   /// Emit diagnostic warnings for placeholder members.
4232   /// We can only do that after the class is fully constructed,
4233   /// as anonymous union/structs can insert placeholders
4234   /// in their parent scope (which might be a Record).
4235   void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record);
4236 
4237   /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4238   /// Microsoft C anonymous structure.
4239   /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4240   /// Example:
4241   ///
4242   /// struct A { int a; };
4243   /// struct B { struct A; int b; };
4244   ///
4245   /// void foo() {
4246   ///   B var;
4247   ///   var.a = 3;
4248   /// }
4249   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4250                                        RecordDecl *Record);
4251 
4252   /// Given a non-tag type declaration, returns an enum useful for indicating
4253   /// what kind of non-tag type this is.
4254   NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4255 
4256   /// Determine whether a tag with a given kind is acceptable
4257   /// as a redeclaration of the given tag declaration.
4258   ///
4259   /// \returns true if the new tag kind is acceptable, false otherwise.
4260   bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag,
4261                                     bool isDefinition, SourceLocation NewTagLoc,
4262                                     const IdentifierInfo *Name);
4263 
4264   /// This is invoked when we see 'struct foo' or 'struct {'.  In the
4265   /// former case, Name will be non-null.  In the later case, Name will be null.
4266   /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4267   /// a reference/declaration/definition of a tag.
4268   ///
4269   /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4270   /// trailing-type-specifier) other than one in an alias-declaration.
4271   ///
4272   /// \param SkipBody If non-null, will be set to indicate if the caller should
4273   /// skip the definition of this tag and treat it as if it were a declaration.
4274   DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4275                       SourceLocation KWLoc, CXXScopeSpec &SS,
4276                       IdentifierInfo *Name, SourceLocation NameLoc,
4277                       const ParsedAttributesView &Attr, AccessSpecifier AS,
4278                       SourceLocation ModulePrivateLoc,
4279                       MultiTemplateParamsArg TemplateParameterLists,
4280                       bool &OwnedDecl, bool &IsDependent,
4281                       SourceLocation ScopedEnumKWLoc,
4282                       bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4283                       bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4284                       OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4285 
4286   /// ActOnField - Each field of a C struct/union is passed into this in order
4287   /// to create a FieldDecl object for it.
4288   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4289                    Declarator &D, Expr *BitfieldWidth);
4290 
4291   /// HandleField - Analyze a field of a C struct or a C++ data member.
4292   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4293                          Declarator &D, Expr *BitfieldWidth,
4294                          InClassInitStyle InitStyle, AccessSpecifier AS);
4295 
4296   /// Build a new FieldDecl and check its well-formedness.
4297   ///
4298   /// This routine builds a new FieldDecl given the fields name, type,
4299   /// record, etc. \p PrevDecl should refer to any previous declaration
4300   /// with the same name and in the same scope as the field to be
4301   /// created.
4302   ///
4303   /// \returns a new FieldDecl.
4304   ///
4305   /// \todo The Declarator argument is a hack. It will be removed once
4306   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4307                             TypeSourceInfo *TInfo, RecordDecl *Record,
4308                             SourceLocation Loc, bool Mutable,
4309                             Expr *BitfieldWidth, InClassInitStyle InitStyle,
4310                             SourceLocation TSSL, AccessSpecifier AS,
4311                             NamedDecl *PrevDecl, Declarator *D = nullptr);
4312 
4313   bool CheckNontrivialField(FieldDecl *FD);
4314 
4315   /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4316   /// class and class extensions. For every class \@interface and class
4317   /// extension \@interface, if the last ivar is a bitfield of any type,
4318   /// then add an implicit `char :0` ivar to the end of that interface.
4319   void ActOnLastBitfield(SourceLocation DeclStart,
4320                          SmallVectorImpl<Decl *> &AllIvarDecls);
4321 
4322   // This is used for both record definitions and ObjC interface declarations.
4323   void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4324                    ArrayRef<Decl *> Fields, SourceLocation LBrac,
4325                    SourceLocation RBrac, const ParsedAttributesView &AttrList);
4326 
4327   /// ActOnTagStartDefinition - Invoked when we have entered the
4328   /// scope of a tag's definition (e.g., for an enumeration, class,
4329   /// struct, or union).
4330   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4331 
4332   /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4333   /// Differently from C++, actually parse the body and reject / error out
4334   /// in case of a structural mismatch.
4335   bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4336 
4337   typedef void *SkippedDefinitionContext;
4338 
4339   /// Invoked when we enter a tag definition that we're skipping.
4340   SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
4341 
4342   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4343   /// C++ record definition's base-specifiers clause and are starting its
4344   /// member declarations.
4345   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
4346                                        SourceLocation FinalLoc,
4347                                        bool IsFinalSpelledSealed,
4348                                        bool IsAbstract,
4349                                        SourceLocation TriviallyRelocatable,
4350                                        SourceLocation Replaceable,
4351                                        SourceLocation LBraceLoc);
4352 
4353   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4354   /// the definition of a tag (enumeration, class, struct, or union).
4355   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
4356                                 SourceRange BraceRange);
4357 
4358   ASTContext::CXXRecordDeclRelocationInfo
4359   CheckCXX2CRelocatableAndReplaceable(const clang::CXXRecordDecl *D);
4360 
4361   void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
4362 
4363   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4364   /// error parsing the definition of a tag.
4365   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
4366 
4367   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
4368                                       EnumConstantDecl *LastEnumConst,
4369                                       SourceLocation IdLoc, IdentifierInfo *Id,
4370                                       Expr *val);
4371 
4372   /// Check that this is a valid underlying type for an enum declaration.
4373   bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
4374 
4375   /// Check whether this is a valid redeclaration of a previous enumeration.
4376   /// \return true if the redeclaration was invalid.
4377   bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4378                               QualType EnumUnderlyingTy, bool IsFixed,
4379                               const EnumDecl *Prev);
4380 
4381   /// Determine whether the body of an anonymous enumeration should be skipped.
4382   /// \param II The name of the first enumerator.
4383   SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
4384                                       SourceLocation IILoc);
4385 
4386   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4387                           SourceLocation IdLoc, IdentifierInfo *Id,
4388                           const ParsedAttributesView &Attrs,
4389                           SourceLocation EqualLoc, Expr *Val,
4390                           SkipBodyInfo *SkipBody = nullptr);
4391   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4392                      Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4393                      const ParsedAttributesView &Attr);
4394 
4395   /// Set the current declaration context until it gets popped.
4396   void PushDeclContext(Scope *S, DeclContext *DC);
4397   void PopDeclContext();
4398 
4399   /// EnterDeclaratorContext - Used when we must lookup names in the context
4400   /// of a declarator's nested name specifier.
4401   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
4402   void ExitDeclaratorContext(Scope *S);
4403 
4404   /// Enter a template parameter scope, after it's been associated with a
4405   /// particular DeclContext. Causes lookup within the scope to chain through
4406   /// enclosing contexts in the correct order.
4407   void EnterTemplatedContext(Scope *S, DeclContext *DC);
4408 
4409   /// Push the parameters of D, which must be a function, into scope.
4410   void ActOnReenterFunctionContext(Scope *S, Decl *D);
4411   void ActOnExitFunctionContext();
4412 
4413   /// Add this decl to the scope shadowed decl chains.
4414   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4415 
4416   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4417   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4418   /// true if 'D' belongs to the given declaration context.
4419   ///
4420   /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4421   ///        enclosing namespace set of the context, rather than contained
4422   ///        directly within it.
4423   bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4424                      bool AllowInlineNamespace = false) const;
4425 
4426   /// Finds the scope corresponding to the given decl context, if it
4427   /// happens to be an enclosing scope.  Otherwise return NULL.
4428   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
4429 
4430   /// Subroutines of ActOnDeclarator().
4431   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4432                                 TypeSourceInfo *TInfo);
4433   bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New);
4434 
4435   /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4436   void mergeDeclAttributes(
4437       NamedDecl *New, Decl *Old,
4438       AvailabilityMergeKind AMK = AvailabilityMergeKind::Redeclaration);
4439 
4440   /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4441   /// same name and scope as a previous declaration 'Old'.  Figure out
4442   /// how to resolve this situation, merging decls or emitting
4443   /// diagnostics as appropriate. If there was an error, set New to be invalid.
4444   void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
4445                             LookupResult &OldDecls);
4446 
4447   /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4448   /// definition visible.
4449   /// This method performs any necessary cleanup on the parser state to discard
4450   /// child nodes from newly parsed decl we are retiring.
4451   void CleanupMergedEnum(Scope *S, Decl *New);
4452 
4453   /// MergeFunctionDecl - We just parsed a function 'New' from
4454   /// declarator D which has the same name and scope as a previous
4455   /// declaration 'Old'.  Figure out how to resolve this situation,
4456   /// merging decls or emitting diagnostics as appropriate.
4457   ///
4458   /// In C++, New and Old must be declarations that are not
4459   /// overloaded. Use IsOverload to determine whether New and Old are
4460   /// overloaded, and to select the Old declaration that New should be
4461   /// merged with.
4462   ///
4463   /// Returns true if there was an error, false otherwise.
4464   bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
4465                          bool MergeTypeWithOld, bool NewDeclIsDefn);
4466 
4467   /// Completes the merge of two function declarations that are
4468   /// known to be compatible.
4469   ///
4470   /// This routine handles the merging of attributes and other
4471   /// properties of function declarations from the old declaration to
4472   /// the new declaration, once we know that New is in fact a
4473   /// redeclaration of Old.
4474   ///
4475   /// \returns false
4476   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4477                                     Scope *S, bool MergeTypeWithOld);
4478   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
4479 
4480   /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4481   /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4482   /// situation, merging decls or emitting diagnostics as appropriate.
4483   ///
4484   /// Tentative definition rules (C99 6.9.2p2) are checked by
4485   /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4486   /// definitions here, since the initializer hasn't been attached.
4487   void MergeVarDecl(VarDecl *New, LookupResult &Previous);
4488 
4489   /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4490   /// scope as a previous declaration 'Old'.  Figure out how to merge their
4491   /// types, emitting diagnostics as appropriate.
4492   ///
4493   /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4494   /// back to here in AddInitializerToDecl. We can't check them before the
4495   /// initializer is attached.
4496   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4497 
4498   /// We've just determined that \p Old and \p New both appear to be definitions
4499   /// of the same variable. Either diagnose or fix the problem.
4500   bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4501   void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
4502 
4503   /// Filters out lookup results that don't fall within the given scope
4504   /// as determined by isDeclInScope.
4505   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4506                             bool ConsiderLinkage, bool AllowInlineNamespace);
4507 
4508   /// We've determined that \p New is a redeclaration of \p Old. Check that they
4509   /// have compatible owning modules.
4510   bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4511 
4512   /// [module.interface]p6:
4513   /// A redeclaration of an entity X is implicitly exported if X was introduced
4514   /// by an exported declaration; otherwise it shall not be exported.
4515   bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4516 
4517   /// A wrapper function for checking the semantic restrictions of
4518   /// a redeclaration within a module.
4519   bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4520 
4521   /// Check the redefinition in C++20 Modules.
4522   ///
4523   /// [basic.def.odr]p14:
4524   /// For any definable item D with definitions in multiple translation units,
4525   /// - if D is a non-inline non-templated function or variable, or
4526   /// - if the definitions in different translation units do not satisfy the
4527   /// following requirements,
4528   ///   the program is ill-formed; a diagnostic is required only if the
4529   ///   definable item is attached to a named module and a prior definition is
4530   ///   reachable at the point where a later definition occurs.
4531   /// - Each such definition shall not be attached to a named module
4532   /// ([module.unit]).
4533   /// - Each such definition shall consist of the same sequence of tokens, ...
4534   /// ...
4535   ///
4536   /// Return true if the redefinition is not allowed. Return false otherwise.
4537   bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4538 
4539   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4540 
4541   /// If it's a file scoped decl that must warn if not used, keep track
4542   /// of it.
4543   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4544 
4545   typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4546       DiagReceiverTy;
4547 
4548   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4549   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
4550                                     DiagReceiverTy DiagReceiver);
4551   void DiagnoseUnusedDecl(const NamedDecl *ND);
4552 
4553   /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4554   /// unless they are marked attr(unused).
4555   void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4556 
4557   /// If VD is set but not otherwise used, diagnose, for a parameter or a
4558   /// variable.
4559   void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4560 
4561   /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4562   /// from S, where a non-field would be declared. This routine copes
4563   /// with the difference between C and C++ scoping rules in structs and
4564   /// unions. For example, the following code is well-formed in C but
4565   /// ill-formed in C++:
4566   /// @code
4567   /// struct S6 {
4568   ///   enum { BAR } e;
4569   /// };
4570   ///
4571   /// void test_S6() {
4572   ///   struct S6 a;
4573   ///   a.e = BAR;
4574   /// }
4575   /// @endcode
4576   /// For the declaration of BAR, this routine will return a different
4577   /// scope. The scope S will be the scope of the unnamed enumeration
4578   /// within S6. In C++, this routine will return the scope associated
4579   /// with S6, because the enumeration's scope is a transparent
4580   /// context but structures can contain non-field names. In C, this
4581   /// routine will return the translation unit scope, since the
4582   /// enumeration's scope is a transparent context and structures cannot
4583   /// contain non-field names.
4584   Scope *getNonFieldDeclScope(Scope *S);
4585 
4586   FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4587                               SourceLocation Loc);
4588 
4589   /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4590   /// file scope.  lazily create a decl for it. ForRedeclaration is true
4591   /// if we're creating this built-in in anticipation of redeclaring the
4592   /// built-in.
4593   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4594                                  bool ForRedeclaration, SourceLocation Loc);
4595 
4596   /// Get the outermost AttributedType node that sets a calling convention.
4597   /// Valid types should not have multiple attributes with different CCs.
4598   const AttributedType *getCallingConvAttributedType(QualType T) const;
4599 
4600   /// GetNameForDeclarator - Determine the full declaration name for the
4601   /// given Declarator.
4602   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
4603 
4604   /// Retrieves the declaration name from a parsed unqualified-id.
4605   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
4606 
4607   /// ParsingInitForAutoVars - a set of declarations with auto types for which
4608   /// we are currently parsing the initializer.
4609   llvm::SmallPtrSet<const Decl *, 4> ParsingInitForAutoVars;
4610 
4611   /// Look for a locally scoped extern "C" declaration by the given name.
4612   NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
4613 
4614   void deduceOpenCLAddressSpace(ValueDecl *decl);
4615   void deduceHLSLAddressSpace(VarDecl *decl);
4616 
4617   /// Adjust the \c DeclContext for a function or variable that might be a
4618   /// function-local external declaration.
4619   static bool adjustContextForLocalExternDecl(DeclContext *&DC);
4620 
4621   void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4622 
4623   /// Checks if the variant/multiversion functions are compatible.
4624   bool areMultiversionVariantFunctionsCompatible(
4625       const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4626       const PartialDiagnostic &NoProtoDiagID,
4627       const PartialDiagnosticAt &NoteCausedDiagIDAt,
4628       const PartialDiagnosticAt &NoSupportDiagIDAt,
4629       const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4630       bool ConstexprSupported, bool CLinkageMayDiffer);
4631 
4632   /// type checking declaration initializers (C99 6.7.8)
4633   bool CheckForConstantInitializer(
4634       Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4635 
4636   QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
4637                                         QualType Type, TypeSourceInfo *TSI,
4638                                         SourceRange Range, bool DirectInit,
4639                                         Expr *Init);
4640 
4641   bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
4642                                      Expr *Init);
4643 
4644   sema::LambdaScopeInfo *RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator);
4645 
4646   // Heuristically tells if the function is `get_return_object` member of a
4647   // coroutine promise_type by matching the function name.
4648   static bool CanBeGetReturnObject(const FunctionDecl *FD);
4649   static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4650 
4651   /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4652   /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4653   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4654                                       Scope *S);
4655 
4656   /// If this function is a C++ replaceable global allocation function
4657   /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4658   /// adds any function attributes that we know a priori based on the standard.
4659   ///
4660   /// We need to check for duplicate attributes both here and where user-written
4661   /// attributes are applied to declarations.
4662   void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4663       FunctionDecl *FD);
4664 
4665   /// Adds any function attributes that we know a priori based on
4666   /// the declaration of this function.
4667   ///
4668   /// These attributes can apply both to implicitly-declared builtins
4669   /// (like __builtin___printf_chk) or to library-declared functions
4670   /// like NSLog or printf.
4671   ///
4672   /// We need to check for duplicate attributes both here and where user-written
4673   /// attributes are applied to declarations.
4674   void AddKnownFunctionAttributes(FunctionDecl *FD);
4675 
4676   /// VerifyBitField - verifies that a bit field expression is an ICE and has
4677   /// the correct width, and that the field type is valid.
4678   /// Returns false on success.
4679   ExprResult VerifyBitField(SourceLocation FieldLoc,
4680                             const IdentifierInfo *FieldName, QualType FieldTy,
4681                             bool IsMsStruct, Expr *BitWidth);
4682 
4683   /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4684   /// enum. If AllowMask is true, then we also allow the complement of a valid
4685   /// value, to be used as a mask.
4686   bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4687                          bool AllowMask) const;
4688 
4689   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4690   void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4691                          SourceLocation WeakNameLoc);
4692 
4693   /// ActOnPragmaRedefineExtname - Called on well formed
4694   /// \#pragma redefine_extname oldname newname.
4695   void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName,
4696                                   IdentifierInfo *AliasName,
4697                                   SourceLocation PragmaLoc,
4698                                   SourceLocation WeakNameLoc,
4699                                   SourceLocation AliasNameLoc);
4700 
4701   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4702   void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4703                             SourceLocation PragmaLoc,
4704                             SourceLocation WeakNameLoc,
4705                             SourceLocation AliasNameLoc);
4706 
4707   /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4708   enum class FunctionEmissionStatus {
4709     Emitted,
4710     CUDADiscarded,     // Discarded due to CUDA/HIP hostness
4711     OMPDiscarded,      // Discarded due to OpenMP hostness
4712     TemplateDiscarded, // Discarded due to uninstantiated templates
4713     Unknown,
4714   };
4715   FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4716                                            bool Final = false);
4717 
4718   // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4719   bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4720 
4721   /// Function or variable declarations to be checked for whether the deferred
4722   /// diagnostics should be emitted.
4723   llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
4724 
4725 private:
4726   /// Map of current shadowing declarations to shadowed declarations. Warn if
4727   /// it looks like the user is trying to modify the shadowing declaration.
4728   llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4729 
4730   // We need this to handle
4731   //
4732   // typedef struct {
4733   //   void *foo() { return 0; }
4734   // } A;
4735   //
4736   // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4737   // for example. If 'A', foo will have external linkage. If we have '*A',
4738   // foo will have no linkage. Since we can't know until we get to the end
4739   // of the typedef, this function finds out if D might have non-external
4740   // linkage. Callers should verify at the end of the TU if it D has external
4741   // linkage or not.
4742   static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4743 
4744   ///@}
4745 
4746   //
4747   //
4748   // -------------------------------------------------------------------------
4749   //
4750   //
4751 
4752   /// \name Declaration Attribute Handling
4753   /// Implementations are in SemaDeclAttr.cpp
4754   ///@{
4755 
4756 public:
4757   /// Describes the kind of priority given to an availability attribute.
4758   ///
4759   /// The sum of priorities deteremines the final priority of the attribute.
4760   /// The final priority determines how the attribute will be merged.
4761   /// An attribute with a lower priority will always remove higher priority
4762   /// attributes for the specified platform when it is being applied. An
4763   /// attribute with a higher priority will not be applied if the declaration
4764   /// already has an availability attribute with a lower priority for the
4765   /// specified platform. The final prirority values are not expected to match
4766   /// the values in this enumeration, but instead should be treated as a plain
4767   /// integer value. This enumeration just names the priority weights that are
4768   /// used to calculate that final vaue.
4769   enum AvailabilityPriority : int {
4770     /// The availability attribute was specified explicitly next to the
4771     /// declaration.
4772     AP_Explicit = 0,
4773 
4774     /// The availability attribute was applied using '#pragma clang attribute'.
4775     AP_PragmaClangAttribute = 1,
4776 
4777     /// The availability attribute for a specific platform was inferred from
4778     /// an availability attribute for another platform.
4779     AP_InferredFromOtherPlatform = 2
4780   };
4781 
4782   /// Describes the reason a calling convention specification was ignored, used
4783   /// for diagnostics.
4784   enum class CallingConventionIgnoredReason {
4785     ForThisTarget = 0,
4786     VariadicFunction,
4787     ConstructorDestructor,
4788     BuiltinFunction
4789   };
4790 
4791   /// A helper function to provide Attribute Location for the Attr types
4792   /// AND the ParsedAttr.
4793   template <typename AttrInfo>
4794   static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
getAttrLoc(const AttrInfo & AL)4795   getAttrLoc(const AttrInfo &AL) {
4796     return AL.getLocation();
4797   }
4798   SourceLocation getAttrLoc(const AttributeCommonInfo &CI);
4799 
4800   /// If Expr is a valid integer constant, get the value of the integer
4801   /// expression and return success or failure. May output an error.
4802   ///
4803   /// Negative argument is implicitly converted to unsigned, unless
4804   /// \p StrictlyUnsigned is true.
4805   template <typename AttrInfo>
4806   bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
4807                            unsigned Idx = UINT_MAX,
4808                            bool StrictlyUnsigned = false) {
4809     std::optional<llvm::APSInt> I = llvm::APSInt(32);
4810     if (Expr->isTypeDependent() ||
4811         !(I = Expr->getIntegerConstantExpr(Context))) {
4812       if (Idx != UINT_MAX)
4813         Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
4814             << &AI << Idx << AANT_ArgumentIntegerConstant
4815             << Expr->getSourceRange();
4816       else
4817         Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
4818             << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
4819       return false;
4820     }
4821 
4822     if (!I->isIntN(32)) {
4823       Diag(Expr->getExprLoc(), diag::err_ice_too_large)
4824           << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
4825       return false;
4826     }
4827 
4828     if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
4829       Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
4830           << &AI << /*non-negative*/ 1;
4831       return false;
4832     }
4833 
4834     Val = (uint32_t)I->getZExtValue();
4835     return true;
4836   }
4837 
4838   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
4839   /// \#pragma weak during processing of other Decls.
4840   /// I couldn't figure out a clean way to generate these in-line, so
4841   /// we store them here and handle separately -- which is a hack.
4842   /// It would be best to refactor this.
4843   SmallVector<Decl *, 2> WeakTopLevelDecl;
4844 
4845   /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
WeakTopLevelDecls()4846   SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
4847 
4848   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
4849                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
4850       ExtVectorDeclsType;
4851 
4852   /// ExtVectorDecls - This is a list all the extended vector types. This allows
4853   /// us to associate a raw vector type with one of the ext_vector type names.
4854   /// This is only necessary for issuing pretty diagnostics.
4855   ExtVectorDeclsType ExtVectorDecls;
4856 
4857   /// Check if the argument \p E is a ASCII string literal. If not emit an error
4858   /// and return false, otherwise set \p Str to the value of the string literal
4859   /// and return true.
4860   bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
4861                                       const Expr *E, StringRef &Str,
4862                                       SourceLocation *ArgLocation = nullptr);
4863 
4864   /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
4865   /// If not emit an error and return false. If the argument is an identifier it
4866   /// will emit an error with a fixit hint and treat it as if it was a string
4867   /// literal.
4868   bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4869                                       StringRef &Str,
4870                                       SourceLocation *ArgLocation = nullptr);
4871 
4872   /// Determine if type T is a valid subject for a nonnull and similar
4873   /// attributes. Dependent types are considered valid so they can be checked
4874   /// during instantiation time. By default, we look through references (the
4875   /// behavior used by nonnull), but if the second parameter is true, then we
4876   /// treat a reference type as valid.
4877   bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4878 
4879   /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
4880   /// declaration.
4881   void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4882                             Expr *OE);
4883 
4884   /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
4885   /// declaration.
4886   void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
4887                          Expr *ParamExpr);
4888 
4889   bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4890   bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4891 
4892   AvailabilityAttr *mergeAvailabilityAttr(
4893       NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
4894       bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
4895       VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
4896       bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
4897       int Priority, IdentifierInfo *IIEnvironment);
4898 
4899   TypeVisibilityAttr *
4900   mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
4901                           TypeVisibilityAttr::VisibilityType Vis);
4902   VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
4903                                       VisibilityAttr::VisibilityType Vis);
4904   SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
4905                                 StringRef Name);
4906 
4907   /// Used to implement to perform semantic checking on
4908   /// attribute((section("foo"))) specifiers.
4909   ///
4910   /// In this case, "foo" is passed in to be checked.  If the section
4911   /// specifier is invalid, return an Error that indicates the problem.
4912   ///
4913   /// This is a simple quality of implementation feature to catch errors
4914   /// and give good diagnostics in cases when the assembler or code generator
4915   /// would otherwise reject the section specifier.
4916   llvm::Error isValidSectionSpecifier(StringRef Str);
4917   bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4918   CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
4919                                 StringRef Name);
4920 
4921   // Check for things we'd like to warn about. Multiversioning issues are
4922   // handled later in the process, once we know how many exist.
4923   bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4924 
4925   /// Check Target Version attrs
4926   bool checkTargetVersionAttr(SourceLocation Loc, Decl *D, StringRef Str);
4927   bool checkTargetClonesAttrString(
4928       SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal,
4929       Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault,
4930       SmallVectorImpl<SmallString<64>> &StringsBuffer);
4931 
4932   ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
4933                             StringRef NewUserDiagnostic);
4934   FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
4935                               IdentifierInfo *Format, int FormatIdx,
4936                               int FirstArg);
4937   FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
4938                                             const AttributeCommonInfo &CI,
4939                                             IdentifierInfo *Format,
4940                                             int FormatIdx,
4941                                             StringLiteral *FormatStr);
4942 
4943   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
4944   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4945                       bool IsPackExpansion);
4946   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
4947                       bool IsPackExpansion);
4948 
4949   /// AddAlignValueAttr - Adds an align_value attribute to a particular
4950   /// declaration.
4951   void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
4952 
4953   /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
4954   Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
4955                              MutableArrayRef<Expr *> Args);
4956   Attr *CreateAnnotationAttr(const ParsedAttr &AL);
4957 
4958   bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range,
4959                                           bool BestCase,
4960                                           MSInheritanceModel SemanticSpelling);
4961 
4962   void CheckAlignasUnderalignment(Decl *D);
4963 
4964   /// AddModeAttr - Adds a mode attribute to a particular declaration.
4965   void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
4966                    bool InInstantiation = false);
4967   AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
4968                                           const AttributeCommonInfo &CI,
4969                                           const IdentifierInfo *Ident);
4970   MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
4971   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
4972                                           const AttributeCommonInfo &CI);
4973   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
4974   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
4975                                                 const InternalLinkageAttr &AL);
4976 
4977   /// Check validaty of calling convention attribute \p attr. If \p FD
4978   /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
4979   /// target. Otherwise, it is specified by \p CFT.
4980   bool CheckCallingConvAttr(
4981       const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
4982       CUDAFunctionTarget CFT = CUDAFunctionTarget::InvalidTarget);
4983 
4984   /// Checks a regparm attribute, returning true if it is ill-formed and
4985   /// otherwise setting numParams to the appropriate value.
4986   bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4987 
4988   /// Create an CUDALaunchBoundsAttr attribute.
4989   CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
4990                                                Expr *MaxThreads,
4991                                                Expr *MinBlocks,
4992                                                Expr *MaxBlocks);
4993 
4994   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
4995   /// declaration.
4996   void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
4997                            Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
4998 
4999   enum class RetainOwnershipKind { NS, CF, OS };
5000 
5001   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5002                           StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5003 
5004   BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5005 
5006   DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5007   DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5008   MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5009                                             const AttributeCommonInfo &CI,
5010                                             bool BestCase,
5011                                             MSInheritanceModel Model);
5012 
5013   EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5014   EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5015                                               const EnforceTCBLeafAttr &AL);
5016 
5017   /// Helper for delayed processing TransparentUnion or
5018   /// BPFPreserveAccessIndexAttr attribute.
5019   void ProcessDeclAttributeDelayed(Decl *D,
5020                                    const ParsedAttributesView &AttrList);
5021 
5022   // Options for ProcessDeclAttributeList().
5023   struct ProcessDeclAttributeOptions {
ProcessDeclAttributeOptionsProcessDeclAttributeOptions5024     ProcessDeclAttributeOptions()
5025         : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
5026 
WithIncludeCXX11AttributesProcessDeclAttributeOptions5027     ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
5028       ProcessDeclAttributeOptions Result = *this;
5029       Result.IncludeCXX11Attributes = Val;
5030       return Result;
5031     }
5032 
WithIgnoreTypeAttributesProcessDeclAttributeOptions5033     ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
5034       ProcessDeclAttributeOptions Result = *this;
5035       Result.IgnoreTypeAttributes = Val;
5036       return Result;
5037     }
5038 
5039     // Should C++11 attributes be processed?
5040     bool IncludeCXX11Attributes;
5041 
5042     // Should any type attributes encountered be ignored?
5043     // If this option is false, a diagnostic will be emitted for any type
5044     // attributes of a kind that does not "slide" from the declaration to
5045     // the decl-specifier-seq.
5046     bool IgnoreTypeAttributes;
5047   };
5048 
5049   /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5050   /// attribute list to the specified decl, ignoring any type attributes.
5051   void ProcessDeclAttributeList(Scope *S, Decl *D,
5052                                 const ParsedAttributesView &AttrList,
5053                                 const ProcessDeclAttributeOptions &Options =
5054                                     ProcessDeclAttributeOptions());
5055 
5056   /// Annotation attributes are the only attributes allowed after an access
5057   /// specifier.
5058   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5059                                       const ParsedAttributesView &AttrList);
5060 
5061   /// checkUnusedDeclAttributes - Given a declarator which is not being
5062   /// used to build a declaration, complain about any decl attributes
5063   /// which might be lying around on it.
5064   void checkUnusedDeclAttributes(Declarator &D);
5065 
5066   void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5067 
5068   /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5069   /// \#pragma weak needs a non-definition decl and source may not have one.
5070   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
5071                                  SourceLocation Loc);
5072 
5073   /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5074   /// applied to it, possibly with an alias.
5075   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5076 
5077   void ProcessPragmaWeak(Scope *S, Decl *D);
5078   // Decl attributes - this routine is the top level dispatcher.
5079   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5080 
5081   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5082 
5083   /// Given a set of delayed diagnostics, re-emit them as if they had
5084   /// been delayed in the current context instead of in the given pool.
5085   /// Essentially, this just moves them to the current pool.
5086   void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5087 
5088   /// Check if IdxExpr is a valid parameter index for a function or
5089   /// instance method D.  May output an error.
5090   ///
5091   /// \returns true if IdxExpr is a valid index.
5092   template <typename AttrInfo>
5093   bool checkFunctionOrMethodParameterIndex(
5094       const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5095       const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5096       bool CanIndexVariadicArguments = false) {
5097     assert(isFunctionOrMethodOrBlockForAttrSubject(D));
5098 
5099     // In C++ the implicit 'this' function parameter also counts.
5100     // Parameters are counted from one.
5101     bool HP = hasFunctionProto(D);
5102     bool HasImplicitThisParam = isInstanceMethod(D);
5103     bool IV = HP && isFunctionOrMethodVariadic(D);
5104     unsigned NumParams =
5105         (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
5106 
5107     std::optional<llvm::APSInt> IdxInt;
5108     if (IdxExpr->isTypeDependent() ||
5109         !(IdxInt = IdxExpr->getIntegerConstantExpr(Context))) {
5110       Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5111           << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5112           << IdxExpr->getSourceRange();
5113       return false;
5114     }
5115 
5116     unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX);
5117     if (IdxSource < 1 ||
5118         ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5119       Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5120           << &AI << AttrArgNum << IdxExpr->getSourceRange();
5121       return false;
5122     }
5123     if (HasImplicitThisParam && !CanIndexImplicitThis) {
5124       if (IdxSource == 1) {
5125         Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5126             << &AI << IdxExpr->getSourceRange();
5127         return false;
5128       }
5129     }
5130 
5131     Idx = ParamIdx(IdxSource, D);
5132     return true;
5133   }
5134 
5135   ///@}
5136 
5137   //
5138   //
5139   // -------------------------------------------------------------------------
5140   //
5141   //
5142 
5143   /// \name C++ Declarations
5144   /// Implementations are in SemaDeclCXX.cpp
5145   ///@{
5146 
5147 public:
5148   void CheckDelegatingCtorCycles();
5149 
5150   /// Called before parsing a function declarator belonging to a function
5151   /// declaration.
5152   void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
5153                                                unsigned TemplateParameterDepth);
5154 
5155   /// Called after parsing a function declarator belonging to a function
5156   /// declaration.
5157   void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
5158 
5159   // Act on C++ namespaces
5160   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5161                                SourceLocation NamespaceLoc,
5162                                SourceLocation IdentLoc, IdentifierInfo *Ident,
5163                                SourceLocation LBrace,
5164                                const ParsedAttributesView &AttrList,
5165                                UsingDirectiveDecl *&UsingDecl, bool IsNested);
5166 
5167   /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5168   /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5169   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5170 
5171   NamespaceDecl *getStdNamespace() const;
5172 
5173   /// Retrieve the special "std" namespace, which may require us to
5174   /// implicitly define the namespace.
5175   NamespaceDecl *getOrCreateStdNamespace();
5176 
5177   CXXRecordDecl *getStdBadAlloc() const;
5178   EnumDecl *getStdAlignValT() const;
5179 
5180   TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const;
5181   FunctionDecl *BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl,
5182                                           QualType AllocType, SourceLocation);
5183 
5184   ValueDecl *tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
5185                                            const IdentifierInfo *MemberOrBase);
5186 
5187   enum class ComparisonCategoryUsage {
5188     /// The '<=>' operator was used in an expression and a builtin operator
5189     /// was selected.
5190     OperatorInExpression,
5191     /// A defaulted 'operator<=>' needed the comparison category. This
5192     /// typically only applies to 'std::strong_ordering', due to the implicit
5193     /// fallback return value.
5194     DefaultedOperator,
5195   };
5196 
5197   /// Lookup the specified comparison category types in the standard
5198   ///   library, an check the VarDecls possibly returned by the operator<=>
5199   ///   builtins for that type.
5200   ///
5201   /// \return The type of the comparison category type corresponding to the
5202   ///   specified Kind, or a null type if an error occurs
5203   QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5204                                        SourceLocation Loc,
5205                                        ComparisonCategoryUsage Usage);
5206 
5207   /// Tests whether Ty is an instance of std::initializer_list and, if
5208   /// it is and Element is not NULL, assigns the element type to Element.
5209   bool isStdInitializerList(QualType Ty, QualType *Element);
5210 
5211   /// Tests whether Ty is an instance of std::type_identity and, if
5212   /// it is and TypeArgument is not NULL, assigns the element type to Element.
5213   /// If MalformedDecl is not null, and type_identity was ruled out due to being
5214   /// incorrectly structured despite having the correct name, the faulty Decl
5215   /// will be assigned to MalformedDecl.
5216   bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5217                          const Decl **MalformedDecl = nullptr);
5218 
5219   /// Looks for the std::initializer_list template and instantiates it
5220   /// with Element, or emits an error if it's not found.
5221   ///
5222   /// \returns The instantiated template, or null on error.
5223   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5224 
5225   /// Looks for the std::type_identity template and instantiates it
5226   /// with Type, or returns a null type if type_identity has not been declared
5227   ///
5228   /// \returns The instantiated template, or null if std::type_identity is not
5229   /// declared
5230   QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc);
5231 
5232   /// Determine whether Ctor is an initializer-list constructor, as
5233   /// defined in [dcl.init.list]p2.
5234   bool isInitListConstructor(const FunctionDecl *Ctor);
5235 
5236   Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5237                             SourceLocation NamespcLoc, CXXScopeSpec &SS,
5238                             SourceLocation IdentLoc,
5239                             IdentifierInfo *NamespcName,
5240                             const ParsedAttributesView &AttrList);
5241 
5242   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5243 
5244   Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5245                                SourceLocation AliasLoc, IdentifierInfo *Alias,
5246                                CXXScopeSpec &SS, SourceLocation IdentLoc,
5247                                IdentifierInfo *Ident);
5248 
5249   /// Remove decls we can't actually see from a lookup being used to declare
5250   /// shadow using decls.
5251   ///
5252   /// \param S - The scope of the potential shadow decl
5253   /// \param Previous - The lookup of a potential shadow decl's name.
5254   void FilterUsingLookup(Scope *S, LookupResult &lookup);
5255 
5256   /// Hides a using shadow declaration.  This is required by the current
5257   /// using-decl implementation when a resolvable using declaration in a
5258   /// class is followed by a declaration which would hide or override
5259   /// one or more of the using decl's targets; for example:
5260   ///
5261   ///   struct Base { void foo(int); };
5262   ///   struct Derived : Base {
5263   ///     using Base::foo;
5264   ///     void foo(int);
5265   ///   };
5266   ///
5267   /// The governing language is C++03 [namespace.udecl]p12:
5268   ///
5269   ///   When a using-declaration brings names from a base class into a
5270   ///   derived class scope, member functions in the derived class
5271   ///   override and/or hide member functions with the same name and
5272   ///   parameter types in a base class (rather than conflicting).
5273   ///
5274   /// There are two ways to implement this:
5275   ///   (1) optimistically create shadow decls when they're not hidden
5276   ///       by existing declarations, or
5277   ///   (2) don't create any shadow decls (or at least don't make them
5278   ///       visible) until we've fully parsed/instantiated the class.
5279   /// The problem with (1) is that we might have to retroactively remove
5280   /// a shadow decl, which requires several O(n) operations because the
5281   /// decl structures are (very reasonably) not designed for removal.
5282   /// (2) avoids this but is very fiddly and phase-dependent.
5283   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5284 
5285   /// Determines whether to create a using shadow decl for a particular
5286   /// decl, given the set of decls existing prior to this using lookup.
5287   bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5288                             const LookupResult &PreviousDecls,
5289                             UsingShadowDecl *&PrevShadow);
5290 
5291   /// Builds a shadow declaration corresponding to a 'using' declaration.
5292   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5293                                         NamedDecl *Target,
5294                                         UsingShadowDecl *PrevDecl);
5295 
5296   /// Checks that the given using declaration is not an invalid
5297   /// redeclaration.  Note that this is checking only for the using decl
5298   /// itself, not for any ill-formedness among the UsingShadowDecls.
5299   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5300                                    bool HasTypenameKeyword,
5301                                    const CXXScopeSpec &SS,
5302                                    SourceLocation NameLoc,
5303                                    const LookupResult &Previous);
5304 
5305   /// Checks that the given nested-name qualifier used in a using decl
5306   /// in the current context is appropriately related to the current
5307   /// scope.  If an error is found, diagnoses it and returns true.
5308   /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5309   /// the result of that lookup. UD is likewise nullptr, except when we have an
5310   /// already-populated UsingDecl whose shadow decls contain the same
5311   /// information (i.e. we're instantiating a UsingDecl with non-dependent
5312   /// scope).
5313   bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5314                                const CXXScopeSpec &SS,
5315                                const DeclarationNameInfo &NameInfo,
5316                                SourceLocation NameLoc,
5317                                const LookupResult *R = nullptr,
5318                                const UsingDecl *UD = nullptr);
5319 
5320   /// Builds a using declaration.
5321   ///
5322   /// \param IsInstantiation - Whether this call arises from an
5323   ///   instantiation of an unresolved using declaration.  We treat
5324   ///   the lookup differently for these declarations.
5325   NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5326                                    SourceLocation UsingLoc,
5327                                    bool HasTypenameKeyword,
5328                                    SourceLocation TypenameLoc, CXXScopeSpec &SS,
5329                                    DeclarationNameInfo NameInfo,
5330                                    SourceLocation EllipsisLoc,
5331                                    const ParsedAttributesView &AttrList,
5332                                    bool IsInstantiation, bool IsUsingIfExists);
5333   NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
5334                                        SourceLocation UsingLoc,
5335                                        SourceLocation EnumLoc,
5336                                        SourceLocation NameLoc,
5337                                        TypeSourceInfo *EnumType, EnumDecl *ED);
5338   NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5339                                 ArrayRef<NamedDecl *> Expansions);
5340 
5341   /// Additional checks for a using declaration referring to a constructor name.
5342   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5343 
5344   /// Given a derived-class using shadow declaration for a constructor and the
5345   /// correspnding base class constructor, find or create the implicit
5346   /// synthesized derived class constructor to use for this initialization.
5347   CXXConstructorDecl *
5348   findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5349                             ConstructorUsingShadowDecl *DerivedShadow);
5350 
5351   Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5352                               SourceLocation UsingLoc,
5353                               SourceLocation TypenameLoc, CXXScopeSpec &SS,
5354                               UnqualifiedId &Name, SourceLocation EllipsisLoc,
5355                               const ParsedAttributesView &AttrList);
5356   Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
5357                                   SourceLocation UsingLoc,
5358                                   SourceLocation EnumLoc, SourceRange TyLoc,
5359                                   const IdentifierInfo &II, ParsedType Ty,
5360                                   CXXScopeSpec *SS = nullptr);
5361   Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5362                               MultiTemplateParamsArg TemplateParams,
5363                               SourceLocation UsingLoc, UnqualifiedId &Name,
5364                               const ParsedAttributesView &AttrList,
5365                               TypeResult Type, Decl *DeclFromDeclSpec);
5366 
5367   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5368   /// including handling of its default argument expressions.
5369   ///
5370   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5371   ExprResult BuildCXXConstructExpr(
5372       SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5373       CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5374       bool HadMultipleCandidates, bool IsListInitialization,
5375       bool IsStdInitListInitialization, bool RequiresZeroInit,
5376       CXXConstructionKind ConstructKind, SourceRange ParenRange);
5377 
5378   /// Build a CXXConstructExpr whose constructor has already been resolved if
5379   /// it denotes an inherited constructor.
5380   ExprResult BuildCXXConstructExpr(
5381       SourceLocation ConstructLoc, QualType DeclInitType,
5382       CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5383       bool HadMultipleCandidates, bool IsListInitialization,
5384       bool IsStdInitListInitialization, bool RequiresZeroInit,
5385       CXXConstructionKind ConstructKind, SourceRange ParenRange);
5386 
5387   // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5388   // the constructor can be elidable?
5389   ExprResult BuildCXXConstructExpr(
5390       SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5391       CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5392       bool HadMultipleCandidates, bool IsListInitialization,
5393       bool IsStdInitListInitialization, bool RequiresZeroInit,
5394       CXXConstructionKind ConstructKind, SourceRange ParenRange);
5395 
5396   ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr,
5397                                                 SourceLocation InitLoc);
5398 
5399   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5400   /// constructed variable.
5401   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5402 
5403   /// Helper class that collects exception specifications for
5404   /// implicitly-declared special member functions.
5405   class ImplicitExceptionSpecification {
5406     // Pointer to allow copying
5407     Sema *Self;
5408     // We order exception specifications thus:
5409     // noexcept is the most restrictive, but is only used in C++11.
5410     // throw() comes next.
5411     // Then a throw(collected exceptions)
5412     // Finally no specification, which is expressed as noexcept(false).
5413     // throw(...) is used instead if any called function uses it.
5414     ExceptionSpecificationType ComputedEST;
5415     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5416     SmallVector<QualType, 4> Exceptions;
5417 
ClearExceptions()5418     void ClearExceptions() {
5419       ExceptionsSeen.clear();
5420       Exceptions.clear();
5421     }
5422 
5423   public:
ImplicitExceptionSpecification(Sema & Self)5424     explicit ImplicitExceptionSpecification(Sema &Self)
5425         : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5426       if (!Self.getLangOpts().CPlusPlus11)
5427         ComputedEST = EST_DynamicNone;
5428     }
5429 
5430     /// Get the computed exception specification type.
getExceptionSpecType()5431     ExceptionSpecificationType getExceptionSpecType() const {
5432       assert(!isComputedNoexcept(ComputedEST) &&
5433              "noexcept(expr) should not be a possible result");
5434       return ComputedEST;
5435     }
5436 
5437     /// The number of exceptions in the exception specification.
size()5438     unsigned size() const { return Exceptions.size(); }
5439 
5440     /// The set of exceptions in the exception specification.
data()5441     const QualType *data() const { return Exceptions.data(); }
5442 
5443     /// Integrate another called method into the collected data.
5444     void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5445 
5446     /// Integrate an invoked expression into the collected data.
CalledExpr(Expr * E)5447     void CalledExpr(Expr *E) { CalledStmt(E); }
5448 
5449     /// Integrate an invoked statement into the collected data.
5450     void CalledStmt(Stmt *S);
5451 
5452     /// Overwrite an EPI's exception specification with this
5453     /// computed exception specification.
getExceptionSpec()5454     FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5455       FunctionProtoType::ExceptionSpecInfo ESI;
5456       ESI.Type = getExceptionSpecType();
5457       if (ESI.Type == EST_Dynamic) {
5458         ESI.Exceptions = Exceptions;
5459       } else if (ESI.Type == EST_None) {
5460         /// C++11 [except.spec]p14:
5461         ///   The exception-specification is noexcept(false) if the set of
5462         ///   potential exceptions of the special member function contains "any"
5463         ESI.Type = EST_NoexceptFalse;
5464         ESI.NoexceptExpr =
5465             Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get();
5466       }
5467       return ESI;
5468     }
5469   };
5470 
5471   /// Evaluate the implicit exception specification for a defaulted
5472   /// special member function.
5473   void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5474 
5475   /// Check the given exception-specification and update the
5476   /// exception specification information with the results.
5477   void checkExceptionSpecification(bool IsTopLevel,
5478                                    ExceptionSpecificationType EST,
5479                                    ArrayRef<ParsedType> DynamicExceptions,
5480                                    ArrayRef<SourceRange> DynamicExceptionRanges,
5481                                    Expr *NoexceptExpr,
5482                                    SmallVectorImpl<QualType> &Exceptions,
5483                                    FunctionProtoType::ExceptionSpecInfo &ESI);
5484 
5485   /// Add an exception-specification to the given member or friend function
5486   /// (or function template). The exception-specification was parsed
5487   /// after the function itself was declared.
5488   void actOnDelayedExceptionSpecification(
5489       Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5490       ArrayRef<ParsedType> DynamicExceptions,
5491       ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5492 
5493   class InheritedConstructorInfo;
5494 
5495   /// Determine if a special member function should have a deleted
5496   /// definition when it is defaulted.
5497   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
5498                                  InheritedConstructorInfo *ICI = nullptr,
5499                                  bool Diagnose = false);
5500 
5501   /// Produce notes explaining why a defaulted function was defined as deleted.
5502   void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5503 
5504   /// Declare the implicit default constructor for the given class.
5505   ///
5506   /// \param ClassDecl The class declaration into which the implicit
5507   /// default constructor will be added.
5508   ///
5509   /// \returns The implicitly-declared default constructor.
5510   CXXConstructorDecl *
5511   DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl);
5512 
5513   /// DefineImplicitDefaultConstructor - Checks for feasibility of
5514   /// defining this constructor as the default constructor.
5515   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5516                                         CXXConstructorDecl *Constructor);
5517 
5518   /// Declare the implicit destructor for the given class.
5519   ///
5520   /// \param ClassDecl The class declaration into which the implicit
5521   /// destructor will be added.
5522   ///
5523   /// \returns The implicitly-declared destructor.
5524   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5525 
5526   /// DefineImplicitDestructor - Checks for feasibility of
5527   /// defining this destructor as the default destructor.
5528   void DefineImplicitDestructor(SourceLocation CurrentLocation,
5529                                 CXXDestructorDecl *Destructor);
5530 
5531   /// Build an exception spec for destructors that don't have one.
5532   ///
5533   /// C++11 says that user-defined destructors with no exception spec get one
5534   /// that looks as if the destructor was implicitly declared.
5535   void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5536 
5537   /// Define the specified inheriting constructor.
5538   void DefineInheritingConstructor(SourceLocation UseLoc,
5539                                    CXXConstructorDecl *Constructor);
5540 
5541   /// Declare the implicit copy constructor for the given class.
5542   ///
5543   /// \param ClassDecl The class declaration into which the implicit
5544   /// copy constructor will be added.
5545   ///
5546   /// \returns The implicitly-declared copy constructor.
5547   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5548 
5549   /// DefineImplicitCopyConstructor - Checks for feasibility of
5550   /// defining this constructor as the copy constructor.
5551   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5552                                      CXXConstructorDecl *Constructor);
5553 
5554   /// Declare the implicit move constructor for the given class.
5555   ///
5556   /// \param ClassDecl The Class declaration into which the implicit
5557   /// move constructor will be added.
5558   ///
5559   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5560   /// declared.
5561   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5562 
5563   /// DefineImplicitMoveConstructor - Checks for feasibility of
5564   /// defining this constructor as the move constructor.
5565   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5566                                      CXXConstructorDecl *Constructor);
5567 
5568   /// Declare the implicit copy assignment operator for the given class.
5569   ///
5570   /// \param ClassDecl The class declaration into which the implicit
5571   /// copy assignment operator will be added.
5572   ///
5573   /// \returns The implicitly-declared copy assignment operator.
5574   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5575 
5576   /// Defines an implicitly-declared copy assignment operator.
5577   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5578                                     CXXMethodDecl *MethodDecl);
5579 
5580   /// Declare the implicit move assignment operator for the given class.
5581   ///
5582   /// \param ClassDecl The Class declaration into which the implicit
5583   /// move assignment operator will be added.
5584   ///
5585   /// \returns The implicitly-declared move assignment operator, or NULL if it
5586   /// wasn't declared.
5587   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5588 
5589   /// Defines an implicitly-declared move assignment operator.
5590   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5591                                     CXXMethodDecl *MethodDecl);
5592 
5593   /// Check a completed declaration of an implicit special member.
5594   void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5595 
5596   /// Determine whether the given function is an implicitly-deleted
5597   /// special member function.
5598   bool isImplicitlyDeleted(FunctionDecl *FD);
5599 
5600   /// Check whether 'this' shows up in the type of a static member
5601   /// function after the (naturally empty) cv-qualifier-seq would be.
5602   ///
5603   /// \returns true if an error occurred.
5604   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5605 
5606   /// Whether this' shows up in the exception specification of a static
5607   /// member function.
5608   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5609 
5610   /// Check whether 'this' shows up in the attributes of the given
5611   /// static member function.
5612   ///
5613   /// \returns true if an error occurred.
5614   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5615 
5616   bool CheckImmediateEscalatingFunctionDefinition(
5617       FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5618 
5619   void DiagnoseImmediateEscalatingReason(FunctionDecl *FD);
5620 
5621   /// Given a constructor and the set of arguments provided for the
5622   /// constructor, convert the arguments and add any required default arguments
5623   /// to form a proper call to this constructor.
5624   ///
5625   /// \returns true if an error occurred, false otherwise.
5626   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5627                                QualType DeclInitType, MultiExprArg ArgsPtr,
5628                                SourceLocation Loc,
5629                                SmallVectorImpl<Expr *> &ConvertedArgs,
5630                                bool AllowExplicit = false,
5631                                bool IsListInitialization = false);
5632 
5633   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5634   /// initializer for the declaration 'Dcl'.
5635   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5636   /// static data member of class X, names should be looked up in the scope of
5637   /// class X.
5638   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5639 
5640   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5641   /// initializer for the declaration 'Dcl'.
5642   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5643 
5644   /// Define the "body" of the conversion from a lambda object to a
5645   /// function pointer.
5646   ///
5647   /// This routine doesn't actually define a sensible body; rather, it fills
5648   /// in the initialization expression needed to copy the lambda object into
5649   /// the block, and IR generation actually generates the real body of the
5650   /// block pointer conversion.
5651   void
5652   DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc,
5653                                                   CXXConversionDecl *Conv);
5654 
5655   /// Define the "body" of the conversion from a lambda object to a
5656   /// block pointer.
5657   ///
5658   /// This routine doesn't actually define a sensible body; rather, it fills
5659   /// in the initialization expression needed to copy the lambda object into
5660   /// the block, and IR generation actually generates the real body of the
5661   /// block pointer conversion.
5662   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5663                                                     CXXConversionDecl *Conv);
5664 
5665   /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5666   /// linkage specification, including the language and (if present)
5667   /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5668   /// language string literal. LBraceLoc, if valid, provides the location of
5669   /// the '{' brace. Otherwise, this linkage specification does not
5670   /// have any braces.
5671   Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5672                                        Expr *LangStr, SourceLocation LBraceLoc);
5673 
5674   /// ActOnFinishLinkageSpecification - Complete the definition of
5675   /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5676   /// valid, it's the position of the closing '}' brace in a linkage
5677   /// specification that uses braces.
5678   Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec,
5679                                         SourceLocation RBraceLoc);
5680 
5681   //===--------------------------------------------------------------------===//
5682   // C++ Classes
5683   //
5684 
5685   /// Get the class that is directly named by the current context. This is the
5686   /// class for which an unqualified-id in this scope could name a constructor
5687   /// or destructor.
5688   ///
5689   /// If the scope specifier denotes a class, this will be that class.
5690   /// If the scope specifier is empty, this will be the class whose
5691   /// member-specification we are currently within. Otherwise, there
5692   /// is no such class.
5693   CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
5694 
5695   /// isCurrentClassName - Determine whether the identifier II is the
5696   /// name of the class type currently being defined. In the case of
5697   /// nested classes, this will only return true if II is the name of
5698   /// the innermost class.
5699   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5700                           const CXXScopeSpec *SS = nullptr);
5701 
5702   /// Determine whether the identifier II is a typo for the name of
5703   /// the class type currently being defined. If so, update it to the identifier
5704   /// that should have been used.
5705   bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5706 
5707   /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5708   bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
5709                             SourceLocation ColonLoc,
5710                             const ParsedAttributesView &Attrs);
5711 
5712   /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5713   /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5714   /// bitfield width if there is one, 'InitExpr' specifies the initializer if
5715   /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
5716   /// present (but parsing it has been deferred).
5717   NamedDecl *
5718   ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
5719                            MultiTemplateParamsArg TemplateParameterLists,
5720                            Expr *BitfieldWidth, const VirtSpecifiers &VS,
5721                            InClassInitStyle InitStyle);
5722 
5723   /// Enter a new C++ default initializer scope. After calling this, the
5724   /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
5725   /// parsing or instantiating the initializer failed.
5726   void ActOnStartCXXInClassMemberInitializer();
5727 
5728   /// This is invoked after parsing an in-class initializer for a
5729   /// non-static C++ class member, and after instantiating an in-class
5730   /// initializer in a class template. Such actions are deferred until the class
5731   /// is complete.
5732   void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5733                                               SourceLocation EqualLoc,
5734                                               ExprResult Init);
5735 
5736   /// Handle a C++ member initializer using parentheses syntax.
5737   MemInitResult
5738   ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
5739                       IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
5740                       const DeclSpec &DS, SourceLocation IdLoc,
5741                       SourceLocation LParenLoc, ArrayRef<Expr *> Args,
5742                       SourceLocation RParenLoc, SourceLocation EllipsisLoc);
5743 
5744   /// Handle a C++ member initializer using braced-init-list syntax.
5745   MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
5746                                     CXXScopeSpec &SS,
5747                                     IdentifierInfo *MemberOrBase,
5748                                     ParsedType TemplateTypeTy,
5749                                     const DeclSpec &DS, SourceLocation IdLoc,
5750                                     Expr *InitList, SourceLocation EllipsisLoc);
5751 
5752   /// Handle a C++ member initializer.
5753   MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
5754                                     CXXScopeSpec &SS,
5755                                     IdentifierInfo *MemberOrBase,
5756                                     ParsedType TemplateTypeTy,
5757                                     const DeclSpec &DS, SourceLocation IdLoc,
5758                                     Expr *Init, SourceLocation EllipsisLoc);
5759 
5760   MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init,
5761                                        SourceLocation IdLoc);
5762 
5763   MemInitResult BuildBaseInitializer(QualType BaseType,
5764                                      TypeSourceInfo *BaseTInfo, Expr *Init,
5765                                      CXXRecordDecl *ClassDecl,
5766                                      SourceLocation EllipsisLoc);
5767 
5768   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
5769                                            CXXRecordDecl *ClassDecl);
5770 
5771   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5772                                 CXXCtorInitializer *Initializer);
5773 
5774   bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5775                            ArrayRef<CXXCtorInitializer *> Initializers = {});
5776 
5777   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5778   /// mark all the non-trivial destructors of its members and bases as
5779   /// referenced.
5780   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5781                                               CXXRecordDecl *Record);
5782 
5783   /// Mark destructors of virtual bases of this class referenced. In the Itanium
5784   /// C++ ABI, this is done when emitting a destructor for any non-abstract
5785   /// class. In the Microsoft C++ ABI, this is done any time a class's
5786   /// destructor is referenced.
5787   void MarkVirtualBaseDestructorsReferenced(
5788       SourceLocation Location, CXXRecordDecl *ClassDecl,
5789       llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
5790           nullptr);
5791 
5792   /// Do semantic checks to allow the complete destructor variant to be emitted
5793   /// when the destructor is defined in another translation unit. In the Itanium
5794   /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
5795   /// can be emitted in separate TUs. To emit the complete variant, run a subset
5796   /// of the checks performed when emitting a regular destructor.
5797   void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
5798                                       CXXDestructorDecl *Dtor);
5799 
5800   /// The list of classes whose vtables have been used within
5801   /// this translation unit, and the source locations at which the
5802   /// first use occurred.
5803   typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
5804 
5805   /// The list of vtables that are required but have not yet been
5806   /// materialized.
5807   SmallVector<VTableUse, 16> VTableUses;
5808 
5809   /// The set of classes whose vtables have been used within
5810   /// this translation unit, and a bit that will be true if the vtable is
5811   /// required to be emitted (otherwise, it should be emitted only if needed
5812   /// by code generation).
5813   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5814 
5815   /// Load any externally-stored vtable uses.
5816   void LoadExternalVTableUses();
5817 
5818   /// Note that the vtable for the given class was used at the
5819   /// given location.
5820   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5821                       bool DefinitionRequired = false);
5822 
5823   /// Mark the exception specifications of all virtual member functions
5824   /// in the given class as needed.
5825   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5826                                              const CXXRecordDecl *RD);
5827 
5828   /// MarkVirtualMembersReferenced - Will mark all members of the given
5829   /// CXXRecordDecl referenced.
5830   void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
5831                                     bool ConstexprOnly = false);
5832 
5833   /// Define all of the vtables that have been used in this
5834   /// translation unit and reference any virtual members used by those
5835   /// vtables.
5836   ///
5837   /// \returns true if any work was done, false otherwise.
5838   bool DefineUsedVTables();
5839 
5840   /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5841   /// special functions, such as the default constructor, copy
5842   /// constructor, or destructor, to the given C++ class (C++
5843   /// [special]p1).  This routine can only be executed just before the
5844   /// definition of the class is complete.
5845   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5846 
5847   /// ActOnMemInitializers - Handle the member initializers for a constructor.
5848   void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
5849                             ArrayRef<CXXCtorInitializer *> MemInits,
5850                             bool AnyErrors);
5851 
5852   /// Check class-level dllimport/dllexport attribute. The caller must
5853   /// ensure that referenceDLLExportedClassMethods is called some point later
5854   /// when all outer classes of Class are complete.
5855   void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5856   void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
5857 
5858   void referenceDLLExportedClassMethods();
5859 
5860   /// Perform propagation of DLL attributes from a derived class to a
5861   /// templated base class for MS compatibility.
5862   void propagateDLLAttrToBaseClassTemplate(
5863       CXXRecordDecl *Class, Attr *ClassAttr,
5864       ClassTemplateSpecializationDecl *BaseTemplateSpec,
5865       SourceLocation BaseLoc);
5866 
5867   /// Perform semantic checks on a class definition that has been
5868   /// completing, introducing implicitly-declared members, checking for
5869   /// abstract types, etc.
5870   ///
5871   /// \param S The scope in which the class was parsed. Null if we didn't just
5872   ///        parse a class definition.
5873   /// \param Record The completed class.
5874   void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
5875 
5876   /// Check that the C++ class annoated with "trivial_abi" satisfies all the
5877   /// conditions that are needed for the attribute to have an effect.
5878   void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
5879 
5880   /// Check that VTable Pointer authentication is only being set on the first
5881   /// first instantiation of the vtable
5882   void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD);
5883 
5884   void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
5885                                          Decl *TagDecl, SourceLocation LBrac,
5886                                          SourceLocation RBrac,
5887                                          const ParsedAttributesView &AttrList);
5888 
5889   /// Perform any semantic analysis which needs to be delayed until all
5890   /// pending class member declarations have been parsed.
5891   void ActOnFinishCXXMemberDecls();
5892   void ActOnFinishCXXNonNestedClass();
5893 
5894   /// This is used to implement the constant expression evaluation part of the
5895   /// attribute enable_if extension. There is nothing in standard C++ which
5896   /// would require reentering parameters.
5897   void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5898   unsigned ActOnReenterTemplateScope(Decl *Template,
5899                                      llvm::function_ref<Scope *()> EnterScope);
5900   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5901 
5902   /// ActOnStartDelayedCXXMethodDeclaration - We have completed
5903   /// parsing a top-level (non-nested) C++ class, and we are now
5904   /// parsing those parts of the given Method declaration that could
5905   /// not be parsed earlier (C++ [class.mem]p2), such as default
5906   /// arguments. This action should enter the scope of the given
5907   /// Method declaration as if we had just parsed the qualified method
5908   /// name. However, it should not bring the parameters into scope;
5909   /// that will be performed by ActOnDelayedCXXMethodParameter.
5910   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5911   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5912   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5913 
5914   /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5915   /// processing the delayed method declaration for Method. The method
5916   /// declaration is now considered finished. There may be a separate
5917   /// ActOnStartOfFunctionDef action later (not necessarily
5918   /// immediately!) for this method, if it was also defined inside the
5919   /// class body.
5920   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5921   void ActOnFinishDelayedMemberInitializers(Decl *Record);
5922 
5923   enum class StringEvaluationContext { StaticAssert = 0, Asm = 1 };
5924 
5925   bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
5926                         StringEvaluationContext EvalContext,
5927                         bool ErrorOnInvalidMessage);
5928   bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
5929                         StringEvaluationContext EvalContext,
5930                         bool ErrorOnInvalidMessage);
5931 
5932   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5933                                      Expr *AssertExpr, Expr *AssertMessageExpr,
5934                                      SourceLocation RParenLoc);
5935   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5936                                      Expr *AssertExpr, Expr *AssertMessageExpr,
5937                                      SourceLocation RParenLoc, bool Failed);
5938 
5939   /// Try to print more useful information about a failed static_assert
5940   /// with expression \E
5941   void DiagnoseStaticAssertDetails(const Expr *E);
5942 
5943   /// If E represents a built-in type trait, or a known standard type trait,
5944   /// try to print more information about why the type type-trait failed.
5945   /// This assumes we already evaluated the expression to a false boolean value.
5946   void DiagnoseTypeTraitDetails(const Expr *E);
5947 
5948   /// Handle a friend type declaration.  This works in tandem with
5949   /// ActOnTag.
5950   ///
5951   /// Notes on friend class templates:
5952   ///
5953   /// We generally treat friend class declarations as if they were
5954   /// declaring a class.  So, for example, the elaborated type specifier
5955   /// in a friend declaration is required to obey the restrictions of a
5956   /// class-head (i.e. no typedefs in the scope chain), template
5957   /// parameters are required to match up with simple template-ids, &c.
5958   /// However, unlike when declaring a template specialization, it's
5959   /// okay to refer to a template specialization without an empty
5960   /// template parameter declaration, e.g.
5961   ///   friend class A<T>::B<unsigned>;
5962   /// We permit this as a special case; if there are any template
5963   /// parameters present at all, require proper matching, i.e.
5964   ///   template <> template \<class T> friend class A<int>::B;
5965   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5966                             MultiTemplateParamsArg TemplateParams,
5967                             SourceLocation EllipsisLoc);
5968   NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5969                                      MultiTemplateParamsArg TemplateParams);
5970 
5971   /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5972   /// the well-formedness of the constructor declarator @p D with type @p
5973   /// R. If there are any errors in the declarator, this routine will
5974   /// emit diagnostics and set the invalid bit to true.  In any case, the type
5975   /// will be updated to reflect a well-formed type for the constructor and
5976   /// returned.
5977   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5978                                       StorageClass &SC);
5979 
5980   /// CheckConstructor - Checks a fully-formed constructor for
5981   /// well-formedness, issuing any diagnostics required. Returns true if
5982   /// the constructor declarator is invalid.
5983   void CheckConstructor(CXXConstructorDecl *Constructor);
5984 
5985   /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5986   /// the well-formednes of the destructor declarator @p D with type @p
5987   /// R. If there are any errors in the declarator, this routine will
5988   /// emit diagnostics and set the declarator to invalid.  Even if this happens,
5989   /// will be updated to reflect a well-formed type for the destructor and
5990   /// returned.
5991   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5992                                      StorageClass &SC);
5993 
5994   /// CheckDestructor - Checks a fully-formed destructor definition for
5995   /// well-formedness, issuing any diagnostics required.  Returns true
5996   /// on error.
5997   bool CheckDestructor(CXXDestructorDecl *Destructor);
5998 
5999   /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6000   /// well-formednes of the conversion function declarator @p D with
6001   /// type @p R. If there are any errors in the declarator, this routine
6002   /// will emit diagnostics and return true. Otherwise, it will return
6003   /// false. Either way, the type @p R will be updated to reflect a
6004   /// well-formed type for the conversion operator.
6005   void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC);
6006 
6007   /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6008   /// the declaration of the given C++ conversion function. This routine
6009   /// is responsible for recording the conversion function in the C++
6010   /// class, if possible.
6011   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6012 
6013   /// Check the validity of a declarator that we parsed for a deduction-guide.
6014   /// These aren't actually declarators in the grammar, so we need to check that
6015   /// the user didn't specify any pieces that are not part of the
6016   /// deduction-guide grammar. Return true on invalid deduction-guide.
6017   bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6018                                      StorageClass &SC);
6019 
6020   void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6021 
6022   bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6023                                              CXXSpecialMemberKind CSM,
6024                                              SourceLocation DefaultLoc);
6025   void CheckDelayedMemberExceptionSpecs();
6026 
6027   /// Kinds of defaulted comparison operator functions.
6028   enum class DefaultedComparisonKind : unsigned char {
6029     /// This is not a defaultable comparison operator.
6030     None,
6031     /// This is an operator== that should be implemented as a series of
6032     /// subobject comparisons.
6033     Equal,
6034     /// This is an operator<=> that should be implemented as a series of
6035     /// subobject comparisons.
6036     ThreeWay,
6037     /// This is an operator!= that should be implemented as a rewrite in terms
6038     /// of a == comparison.
6039     NotEqual,
6040     /// This is an <, <=, >, or >= that should be implemented as a rewrite in
6041     /// terms of a <=> comparison.
6042     Relational,
6043   };
6044 
6045   bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6046                                           DefaultedComparisonKind DCK);
6047   void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6048                                          FunctionDecl *Spaceship);
6049   void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6050                                  DefaultedComparisonKind DCK);
6051 
6052   void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name,
6053                                          QualType R, bool IsLambda,
6054                                          DeclContext *DC = nullptr);
6055   void CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
6056                                          DeclarationName Name, QualType R);
6057   void CheckExplicitObjectLambda(Declarator &D);
6058 
6059   //===--------------------------------------------------------------------===//
6060   // C++ Derived Classes
6061   //
6062 
6063   /// Check the validity of a C++ base class specifier.
6064   ///
6065   /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6066   /// and returns NULL otherwise.
6067   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6068                                        SourceRange SpecifierRange, bool Virtual,
6069                                        AccessSpecifier Access,
6070                                        TypeSourceInfo *TInfo,
6071                                        SourceLocation EllipsisLoc);
6072 
6073   /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6074   /// one entry in the base class list of a class specifier, for
6075   /// example:
6076   ///    class foo : public bar, virtual private baz {
6077   /// 'public bar' and 'virtual private baz' are each base-specifiers.
6078   BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6079                                 const ParsedAttributesView &Attrs, bool Virtual,
6080                                 AccessSpecifier Access, ParsedType basetype,
6081                                 SourceLocation BaseLoc,
6082                                 SourceLocation EllipsisLoc);
6083 
6084   /// Performs the actual work of attaching the given base class
6085   /// specifiers to a C++ class.
6086   bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6087                             MutableArrayRef<CXXBaseSpecifier *> Bases);
6088 
6089   /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6090   /// class, after checking whether there are any duplicate base
6091   /// classes.
6092   void ActOnBaseSpecifiers(Decl *ClassDecl,
6093                            MutableArrayRef<CXXBaseSpecifier *> Bases);
6094 
6095   /// Determine whether the type \p Derived is a C++ class that is
6096   /// derived from the type \p Base.
6097   bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6098                      CXXRecordDecl *Base, CXXBasePaths &Paths);
6099   bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6100                      CXXRecordDecl *Base);
6101   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6102   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6103                      CXXBasePaths &Paths);
6104 
6105   // FIXME: I don't like this name.
6106   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6107 
6108   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6109                                     SourceLocation Loc, SourceRange Range,
6110                                     CXXCastPath *BasePath = nullptr,
6111                                     bool IgnoreAccess = false);
6112 
6113   /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6114   /// conversion (where Derived and Base are class types) is
6115   /// well-formed, meaning that the conversion is unambiguous (and
6116   /// that all of the base classes are accessible). Returns true
6117   /// and emits a diagnostic if the code is ill-formed, returns false
6118   /// otherwise. Loc is the location where this routine should point to
6119   /// if there is an error, and Range is the source range to highlight
6120   /// if there is an error.
6121   ///
6122   /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6123   /// diagnostic for the respective type of error will be suppressed, but the
6124   /// check for ill-formed code will still be performed.
6125   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6126                                     unsigned InaccessibleBaseID,
6127                                     unsigned AmbiguousBaseConvID,
6128                                     SourceLocation Loc, SourceRange Range,
6129                                     DeclarationName Name, CXXCastPath *BasePath,
6130                                     bool IgnoreAccess = false);
6131 
6132   /// Builds a string representing ambiguous paths from a
6133   /// specific derived class to different subobjects of the same base
6134   /// class.
6135   ///
6136   /// This function builds a string that can be used in error messages
6137   /// to show the different paths that one can take through the
6138   /// inheritance hierarchy to go from the derived class to different
6139   /// subobjects of a base class. The result looks something like this:
6140   /// @code
6141   /// struct D -> struct B -> struct A
6142   /// struct D -> struct C -> struct A
6143   /// @endcode
6144   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6145 
6146   bool CheckOverridingFunctionAttributes(CXXMethodDecl *New,
6147                                          const CXXMethodDecl *Old);
6148 
6149   /// CheckOverridingFunctionReturnType - Checks whether the return types are
6150   /// covariant, according to C++ [class.virtual]p5.
6151   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6152                                          const CXXMethodDecl *Old);
6153 
6154   // Check that the overriding method has no explicit object parameter.
6155   bool CheckExplicitObjectOverride(CXXMethodDecl *New,
6156                                    const CXXMethodDecl *Old);
6157 
6158   /// Mark the given method pure.
6159   ///
6160   /// \param Method the method to be marked pure.
6161   ///
6162   /// \param InitRange the source range that covers the "0" initializer.
6163   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6164 
6165   /// CheckOverrideControl - Check C++11 override control semantics.
6166   void CheckOverrideControl(NamedDecl *D);
6167 
6168   /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6169   /// not used in the declaration of an overriding method.
6170   void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
6171 
6172   /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6173   /// function overrides a virtual member function marked 'final', according to
6174   /// C++11 [class.virtual]p4.
6175   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6176                                               const CXXMethodDecl *Old);
6177 
6178   enum AbstractDiagSelID {
6179     AbstractNone = -1,
6180     AbstractReturnType,
6181     AbstractParamType,
6182     AbstractVariableType,
6183     AbstractFieldType,
6184     AbstractIvarType,
6185     AbstractSynthesizedIvarType,
6186     AbstractArrayType
6187   };
6188 
6189   struct TypeDiagnoser;
6190 
6191   bool isAbstractType(SourceLocation Loc, QualType T);
6192   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6193                               TypeDiagnoser &Diagnoser);
6194   template <typename... Ts>
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)6195   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6196                               const Ts &...Args) {
6197     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6198     return RequireNonAbstractType(Loc, T, Diagnoser);
6199   }
6200 
6201   void DiagnoseAbstractType(const CXXRecordDecl *RD);
6202 
6203   //===--------------------------------------------------------------------===//
6204   // C++ Overloaded Operators [C++ 13.5]
6205   //
6206 
6207   /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6208   /// of this overloaded operator is well-formed. If so, returns false;
6209   /// otherwise, emits appropriate diagnostics and returns true.
6210   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6211 
6212   /// CheckLiteralOperatorDeclaration - Check whether the declaration
6213   /// of this literal operator function is well-formed. If so, returns
6214   /// false; otherwise, emits appropriate diagnostics and returns true.
6215   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6216 
6217   /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6218   /// found in an explicit(bool) specifier.
6219   ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
6220 
6221   /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6222   /// Returns true if the explicit specifier is now resolved.
6223   bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
6224 
6225   /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6226   /// C++ if/switch/while/for statement.
6227   /// e.g: "if (int x = f()) {...}"
6228   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
6229 
6230   // Emitting members of dllexported classes is delayed until the class
6231   // (including field initializers) is fully parsed.
6232   SmallVector<CXXRecordDecl *, 4> DelayedDllExportClasses;
6233   SmallVector<CXXMethodDecl *, 4> DelayedDllExportMemberFunctions;
6234 
6235   /// Merge the exception specifications of two variable declarations.
6236   ///
6237   /// This is called when there's a redeclaration of a VarDecl. The function
6238   /// checks if the redeclaration might have an exception specification and
6239   /// validates compatibility and merges the specs if necessary.
6240   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
6241 
6242   /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6243   /// function, once we already know that they have the same
6244   /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6245   /// error, false otherwise.
6246   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
6247 
6248   /// Helpers for dealing with blocks and functions.
6249   void CheckCXXDefaultArguments(FunctionDecl *FD);
6250 
6251   /// CheckExtraCXXDefaultArguments - Check for any extra default
6252   /// arguments in the declarator, which is not a function declaration
6253   /// or definition and therefore is not permitted to have default
6254   /// arguments. This routine should be invoked for every declarator
6255   /// that is not a function declaration or definition.
6256   void CheckExtraCXXDefaultArguments(Declarator &D);
6257 
getSpecialMember(const CXXMethodDecl * MD)6258   CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD) {
6259     return getDefaultedFunctionKind(MD).asSpecialMember();
6260   }
6261 
6262   /// Perform semantic analysis for the variable declaration that
6263   /// occurs within a C++ catch clause, returning the newly-created
6264   /// variable.
6265   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
6266                                      SourceLocation StartLoc,
6267                                      SourceLocation IdLoc,
6268                                      const IdentifierInfo *Id);
6269 
6270   /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6271   /// handler.
6272   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
6273 
6274   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
6275 
6276   /// Handle a friend tag declaration where the scope specifier was
6277   /// templated.
6278   DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6279                                      unsigned TagSpec, SourceLocation TagLoc,
6280                                      CXXScopeSpec &SS, IdentifierInfo *Name,
6281                                      SourceLocation NameLoc,
6282                                      SourceLocation EllipsisLoc,
6283                                      const ParsedAttributesView &Attr,
6284                                      MultiTemplateParamsArg TempParamLists);
6285 
6286   MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
6287                                    SourceLocation DeclStart, Declarator &D,
6288                                    Expr *BitfieldWidth,
6289                                    InClassInitStyle InitStyle,
6290                                    AccessSpecifier AS,
6291                                    const ParsedAttr &MSPropertyAttr);
6292 
6293   /// Diagnose why the specified class does not have a trivial special member of
6294   /// the given kind.
6295   void DiagnoseNontrivial(const CXXRecordDecl *Record,
6296                           CXXSpecialMemberKind CSM);
6297 
6298   /// Determine whether a defaulted or deleted special member function is
6299   /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6300   /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6301   bool SpecialMemberIsTrivial(
6302       CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
6303       TrivialABIHandling TAH = TrivialABIHandling::IgnoreTrivialABI,
6304       bool Diagnose = false);
6305 
6306   /// For a defaulted function, the kind of defaulted function that it is.
6307   class DefaultedFunctionKind {
6308     LLVM_PREFERRED_TYPE(CXXSpecialMemberKind)
6309     unsigned SpecialMember : 8;
6310     unsigned Comparison : 8;
6311 
6312   public:
DefaultedFunctionKind()6313     DefaultedFunctionKind()
6314         : SpecialMember(llvm::to_underlying(CXXSpecialMemberKind::Invalid)),
6315           Comparison(llvm::to_underlying(DefaultedComparisonKind::None)) {}
DefaultedFunctionKind(CXXSpecialMemberKind CSM)6316     DefaultedFunctionKind(CXXSpecialMemberKind CSM)
6317         : SpecialMember(llvm::to_underlying(CSM)),
6318           Comparison(llvm::to_underlying(DefaultedComparisonKind::None)) {}
DefaultedFunctionKind(DefaultedComparisonKind Comp)6319     DefaultedFunctionKind(DefaultedComparisonKind Comp)
6320         : SpecialMember(llvm::to_underlying(CXXSpecialMemberKind::Invalid)),
6321           Comparison(llvm::to_underlying(Comp)) {}
6322 
isSpecialMember()6323     bool isSpecialMember() const {
6324       return static_cast<CXXSpecialMemberKind>(SpecialMember) !=
6325              CXXSpecialMemberKind::Invalid;
6326     }
isComparison()6327     bool isComparison() const {
6328       return static_cast<DefaultedComparisonKind>(Comparison) !=
6329              DefaultedComparisonKind::None;
6330     }
6331 
6332     explicit operator bool() const {
6333       return isSpecialMember() || isComparison();
6334     }
6335 
asSpecialMember()6336     CXXSpecialMemberKind asSpecialMember() const {
6337       return static_cast<CXXSpecialMemberKind>(SpecialMember);
6338     }
asComparison()6339     DefaultedComparisonKind asComparison() const {
6340       return static_cast<DefaultedComparisonKind>(Comparison);
6341     }
6342 
6343     /// Get the index of this function kind for use in diagnostics.
getDiagnosticIndex()6344     unsigned getDiagnosticIndex() const {
6345       static_assert(llvm::to_underlying(CXXSpecialMemberKind::Invalid) >
6346                         llvm::to_underlying(CXXSpecialMemberKind::Destructor),
6347                     "invalid should have highest index");
6348       static_assert((unsigned)DefaultedComparisonKind::None == 0,
6349                     "none should be equal to zero");
6350       return SpecialMember + Comparison;
6351     }
6352   };
6353 
6354   /// Determine the kind of defaulting that would be done for a given function.
6355   ///
6356   /// If the function is both a default constructor and a copy / move
6357   /// constructor (due to having a default argument for the first parameter),
6358   /// this picks CXXSpecialMemberKind::DefaultConstructor.
6359   ///
6360   /// FIXME: Check that case is properly handled by all callers.
6361   DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
6362 
6363   /// Handle a C++11 empty-declaration and attribute-declaration.
6364   Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
6365                               SourceLocation SemiLoc);
6366 
6367   enum class CheckConstexprKind {
6368     /// Diagnose issues that are non-constant or that are extensions.
6369     Diagnose,
6370     /// Identify whether this function satisfies the formal rules for constexpr
6371     /// functions in the current lanugage mode (with no extensions).
6372     CheckValid
6373   };
6374 
6375   // Check whether a function declaration satisfies the requirements of a
6376   // constexpr function definition or a constexpr constructor definition. If so,
6377   // return true. If not, produce appropriate diagnostics (unless asked not to
6378   // by Kind) and return false.
6379   //
6380   // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6381   bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
6382                                         CheckConstexprKind Kind);
6383 
6384   /// Diagnose methods which overload virtual methods in a base class
6385   /// without overriding any.
6386   void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
6387 
6388   /// Check if a method overloads virtual methods in a base class without
6389   /// overriding any.
6390   void
6391   FindHiddenVirtualMethods(CXXMethodDecl *MD,
6392                            SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6393   void
6394   NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6395                            SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6396 
6397   /// ActOnParamDefaultArgument - Check whether the default argument
6398   /// provided for a function parameter is well-formed. If so, attach it
6399   /// to the parameter declaration.
6400   void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6401                                  Expr *defarg);
6402 
6403   /// ActOnParamUnparsedDefaultArgument - We've seen a default
6404   /// argument for a function parameter, but we can't parse it yet
6405   /// because we're inside a class definition. Note that this default
6406   /// argument will be parsed later.
6407   void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
6408                                          SourceLocation ArgLoc);
6409 
6410   /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6411   /// the default argument for the parameter param failed.
6412   void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
6413                                       Expr *DefaultArg);
6414   ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6415                                          SourceLocation EqualLoc);
6416   void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6417                                SourceLocation EqualLoc);
6418 
6419   void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6420   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6421                       StringLiteral *Message = nullptr);
6422   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
6423 
6424   void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6425                            StringLiteral *DeletedMessage = nullptr);
6426   void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
6427   ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
6428   ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
6429 
6430   NamedDecl *
6431   ActOnDecompositionDeclarator(Scope *S, Declarator &D,
6432                                MultiTemplateParamsArg TemplateParamLists);
6433   void DiagPlaceholderVariableDefinition(SourceLocation Loc);
6434   bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
6435                                          RecordDecl *ClassDecl,
6436                                          const IdentifierInfo *Name);
6437 
6438   UnsignedOrNone GetDecompositionElementCount(QualType DecompType,
6439                                               SourceLocation Loc);
6440   void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
6441 
6442   /// Stack containing information needed when in C++2a an 'auto' is encountered
6443   /// in a function declaration parameter type specifier in order to invent a
6444   /// corresponding template parameter in the enclosing abbreviated function
6445   /// template. This information is also present in LambdaScopeInfo, stored in
6446   /// the FunctionScopes stack.
6447   SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
6448 
6449   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6450   std::unique_ptr<CXXFieldCollector> FieldCollector;
6451 
6452   typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType;
6453   /// Set containing all declared private fields that are not used.
6454   NamedDeclSetType UnusedPrivateFields;
6455 
6456   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 8> RecordDeclSetTy;
6457 
6458   /// PureVirtualClassDiagSet - a set of class declarations which we have
6459   /// emitted a list of pure virtual functions. Used to prevent emitting the
6460   /// same list more than once.
6461   std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6462 
6463   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
6464                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
6465       DelegatingCtorDeclsType;
6466 
6467   /// All the delegating constructors seen so far in the file, used for
6468   /// cycle detection at the end of the TU.
6469   DelegatingCtorDeclsType DelegatingCtorDecls;
6470 
6471   /// The C++ "std" namespace, where the standard library resides.
6472   LazyDeclPtr StdNamespace;
6473 
6474   /// The C++ "std::initializer_list" template, which is defined in
6475   /// \<initializer_list>.
6476   ClassTemplateDecl *StdInitializerList;
6477 
6478   /// The C++ "std::type_identity" template, which is defined in
6479   /// \<type_traits>.
6480   ClassTemplateDecl *StdTypeIdentity;
6481 
6482   // Contains the locations of the beginning of unparsed default
6483   // argument locations.
6484   llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6485 
6486   /// UndefinedInternals - all the used, undefined objects which require a
6487   /// definition in this translation unit.
6488   llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6489 
6490   typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6491       SpecialMemberDecl;
6492 
6493   /// The C++ special members which we are currently in the process of
6494   /// declaring. If this process recursively triggers the declaration of the
6495   /// same special member, we should act as if it is not yet declared.
6496   llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
6497 
6498   void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
6499 
6500   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6501 
6502   typedef ProcessingContextState ParsingClassState;
PushParsingClass()6503   ParsingClassState PushParsingClass() {
6504     ParsingClassDepth++;
6505     return DelayedDiagnostics.pushUndelayed();
6506   }
PopParsingClass(ParsingClassState state)6507   void PopParsingClass(ParsingClassState state) {
6508     ParsingClassDepth--;
6509     DelayedDiagnostics.popUndelayed(state);
6510   }
6511 
6512   ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
6513                                          CXXScopeSpec &SS,
6514                                          ParsedType TemplateTypeTy,
6515                                          IdentifierInfo *MemberOrBase);
6516 
6517 private:
6518   void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6519                                       QualType ResultTy,
6520                                       ArrayRef<QualType> Args);
6521   // Helper for ActOnFields to check for all function pointer members.
6522   bool EntirelyFunctionPointers(const RecordDecl *Record);
6523 
6524   // A cache representing if we've fully checked the various comparison category
6525   // types stored in ASTContext. The bit-index corresponds to the integer value
6526   // of a ComparisonCategoryType enumerator.
6527   llvm::SmallBitVector FullyCheckedComparisonCategories;
6528 
6529   /// Check if there is a field shadowing.
6530   void CheckShadowInheritedFields(const SourceLocation &Loc,
6531                                   DeclarationName FieldName,
6532                                   const CXXRecordDecl *RD,
6533                                   bool DeclIsField = true);
6534 
6535   ///@}
6536 
6537   //
6538   //
6539   // -------------------------------------------------------------------------
6540   //
6541   //
6542 
6543   /// \name C++ Exception Specifications
6544   /// Implementations are in SemaExceptionSpec.cpp
6545   ///@{
6546 
6547 public:
6548   /// All the overriding functions seen during a class definition
6549   /// that had their exception spec checks delayed, plus the overridden
6550   /// function.
6551   SmallVector<std::pair<const CXXMethodDecl *, const CXXMethodDecl *>, 2>
6552       DelayedOverridingExceptionSpecChecks;
6553 
6554   /// All the function redeclarations seen during a class definition that had
6555   /// their exception spec checks delayed, plus the prior declaration they
6556   /// should be checked against. Except during error recovery, the new decl
6557   /// should always be a friend declaration, as that's the only valid way to
6558   /// redeclare a special member before its class is complete.
6559   SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 2>
6560       DelayedEquivalentExceptionSpecChecks;
6561 
6562   /// Determine if we're in a case where we need to (incorrectly) eagerly
6563   /// parse an exception specification to work around a libstdc++ bug.
6564   bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6565 
6566   /// Check the given noexcept-specifier, convert its expression, and compute
6567   /// the appropriate ExceptionSpecificationType.
6568   ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6569                                ExceptionSpecificationType &EST);
6570 
6571   CanThrowResult canThrow(const Stmt *E);
6572   /// Determine whether the callee of a particular function call can throw.
6573   /// E, D and Loc are all optional.
6574   static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6575                                        SourceLocation Loc = SourceLocation());
6576   const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
6577                                                 const FunctionProtoType *FPT);
6578   void UpdateExceptionSpec(FunctionDecl *FD,
6579                            const FunctionProtoType::ExceptionSpecInfo &ESI);
6580 
6581   /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6582   /// exception specification. Incomplete types, or pointers to incomplete types
6583   /// other than void are not allowed.
6584   ///
6585   /// \param[in,out] T  The exception type. This will be decayed to a pointer
6586   /// type
6587   ///                   when the input is an array or a function type.
6588   bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
6589 
6590   /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6591   /// pointer to member to a function with an exception specification. This
6592   /// means that it is invalid to add another level of indirection.
6593   bool CheckDistantExceptionSpec(QualType T);
6594   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
6595 
6596   /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6597   /// exception specifications. Exception specifications are equivalent if
6598   /// they allow exactly the same set of exception types. It does not matter how
6599   /// that is achieved. See C++ [except.spec]p2.
6600   bool CheckEquivalentExceptionSpec(const FunctionProtoType *Old,
6601                                     SourceLocation OldLoc,
6602                                     const FunctionProtoType *New,
6603                                     SourceLocation NewLoc);
6604   bool CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
6605                                     const PartialDiagnostic &NoteID,
6606                                     const FunctionProtoType *Old,
6607                                     SourceLocation OldLoc,
6608                                     const FunctionProtoType *New,
6609                                     SourceLocation NewLoc);
6610   bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6611 
6612   /// CheckExceptionSpecSubset - Check whether the second function type's
6613   /// exception specification is a subset (or equivalent) of the first function
6614   /// type. This is used by override and pointer assignment checks.
6615   bool CheckExceptionSpecSubset(
6616       const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6617       const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6618       const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6619       SourceLocation SuperLoc, const FunctionProtoType *Subset,
6620       bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6621 
6622   /// CheckParamExceptionSpec - Check if the parameter and return types of the
6623   /// two functions have equivalent exception specs. This is part of the
6624   /// assignment and override compatibility check. We do not check the
6625   /// parameters of parameter function pointers recursively, as no sane
6626   /// programmer would even be able to write such a function type.
6627   bool CheckParamExceptionSpec(
6628       const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6629       const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6630       SourceLocation TargetLoc, const FunctionProtoType *Source,
6631       bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6632 
6633   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6634 
6635   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6636   /// spec is a subset of base spec.
6637   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6638                                             const CXXMethodDecl *Old);
6639 
6640   ///@}
6641 
6642   //
6643   //
6644   // -------------------------------------------------------------------------
6645   //
6646   //
6647 
6648   /// \name Expressions
6649   /// Implementations are in SemaExpr.cpp
6650   ///@{
6651 
6652 public:
6653   /// Describes how the expressions currently being parsed are
6654   /// evaluated at run-time, if at all.
6655   enum class ExpressionEvaluationContext {
6656     /// The current expression and its subexpressions occur within an
6657     /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6658     /// \c sizeof, where the type of the expression may be significant but
6659     /// no code will be generated to evaluate the value of the expression at
6660     /// run time.
6661     Unevaluated,
6662 
6663     /// The current expression occurs within a braced-init-list within
6664     /// an unevaluated operand. This is mostly like a regular unevaluated
6665     /// context, except that we still instantiate constexpr functions that are
6666     /// referenced here so that we can perform narrowing checks correctly.
6667     UnevaluatedList,
6668 
6669     /// The current expression occurs within a discarded statement.
6670     /// This behaves largely similarly to an unevaluated operand in preventing
6671     /// definitions from being required, but not in other ways.
6672     DiscardedStatement,
6673 
6674     /// The current expression occurs within an unevaluated
6675     /// operand that unconditionally permits abstract references to
6676     /// fields, such as a SIZE operator in MS-style inline assembly.
6677     UnevaluatedAbstract,
6678 
6679     /// The current context is "potentially evaluated" in C++11 terms,
6680     /// but the expression is evaluated at compile-time (like the values of
6681     /// cases in a switch statement).
6682     ConstantEvaluated,
6683 
6684     /// In addition of being constant evaluated, the current expression
6685     /// occurs in an immediate function context - either a consteval function
6686     /// or a consteval if statement.
6687     ImmediateFunctionContext,
6688 
6689     /// The current expression is potentially evaluated at run time,
6690     /// which means that code may be generated to evaluate the value of the
6691     /// expression at run time.
6692     PotentiallyEvaluated,
6693 
6694     /// The current expression is potentially evaluated, but any
6695     /// declarations referenced inside that expression are only used if
6696     /// in fact the current expression is used.
6697     ///
6698     /// This value is used when parsing default function arguments, for which
6699     /// we would like to provide diagnostics (e.g., passing non-POD arguments
6700     /// through varargs) but do not want to mark declarations as "referenced"
6701     /// until the default argument is used.
6702     PotentiallyEvaluatedIfUsed
6703   };
6704 
6705   /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6706   /// to a variable (constant) that may or may not be odr-used in this Expr, and
6707   /// we won't know until all lvalue-to-rvalue and discarded value conversions
6708   /// have been applied to all subexpressions of the enclosing full expression.
6709   /// This is cleared at the end of each full expression.
6710   using MaybeODRUseExprSet = llvm::SmallSetVector<Expr *, 4>;
6711   MaybeODRUseExprSet MaybeODRUseExprs;
6712 
6713   using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6714 
6715   /// Data structure used to record current or nested
6716   /// expression evaluation contexts.
6717   struct ExpressionEvaluationContextRecord {
6718     /// The expression evaluation context.
6719     ExpressionEvaluationContext Context;
6720 
6721     /// Whether the enclosing context needed a cleanup.
6722     CleanupInfo ParentCleanup;
6723 
6724     /// The number of active cleanup objects when we entered
6725     /// this expression evaluation context.
6726     unsigned NumCleanupObjects;
6727 
6728     MaybeODRUseExprSet SavedMaybeODRUseExprs;
6729 
6730     /// The lambdas that are present within this context, if it
6731     /// is indeed an unevaluated context.
6732     SmallVector<LambdaExpr *, 2> Lambdas;
6733 
6734     /// The declaration that provides context for lambda expressions
6735     /// and block literals if the normal declaration context does not
6736     /// suffice, e.g., in a default function argument.
6737     Decl *ManglingContextDecl;
6738 
6739     /// If we are processing a decltype type, a set of call expressions
6740     /// for which we have deferred checking the completeness of the return type.
6741     SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
6742 
6743     /// If we are processing a decltype type, a set of temporary binding
6744     /// expressions for which we have deferred checking the destructor.
6745     SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
6746 
6747     llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
6748 
6749     /// Expressions appearing as the LHS of a volatile assignment in this
6750     /// context. We produce a warning for these when popping the context if
6751     /// they are not discarded-value expressions nor unevaluated operands.
6752     SmallVector<Expr *, 2> VolatileAssignmentLHSs;
6753 
6754     /// Set of candidates for starting an immediate invocation.
6755     llvm::SmallVector<ImmediateInvocationCandidate, 4>
6756         ImmediateInvocationCandidates;
6757 
6758     /// Set of DeclRefExprs referencing a consteval function when used in a
6759     /// context not already known to be immediately invoked.
6760     llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
6761 
6762     /// P2718R0 - Lifetime extension in range-based for loops.
6763     /// MaterializeTemporaryExprs in for-range-init expressions which need to
6764     /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
6765     /// InLifetimeExtendingContext is true.
6766     SmallVector<MaterializeTemporaryExpr *, 8> ForRangeLifetimeExtendTemps;
6767 
6768     /// \brief Describes whether we are in an expression constext which we have
6769     /// to handle differently.
6770     enum ExpressionKind {
6771       EK_Decltype,
6772       EK_TemplateArgument,
6773       EK_AttrArgument,
6774       EK_VariableInit,
6775       EK_Other
6776     } ExprContext;
6777 
6778     // A context can be nested in both a discarded statement context and
6779     // an immediate function context, so they need to be tracked independently.
6780     bool InDiscardedStatement;
6781     bool InImmediateFunctionContext;
6782     bool InImmediateEscalatingFunctionContext;
6783 
6784     bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
6785 
6786     // We are in a constant context, but we also allow
6787     // non constant expressions, for example for array bounds (which may be
6788     // VLAs).
6789     bool InConditionallyConstantEvaluateContext = false;
6790 
6791     /// Whether we are currently in a context in which all temporaries must be
6792     /// lifetime-extended, even if they're not bound to a reference (for
6793     /// example, in a for-range initializer).
6794     bool InLifetimeExtendingContext = false;
6795 
6796     /// Whether evaluating an expression for a switch case label.
6797     bool IsCaseExpr = false;
6798 
6799     /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
6800     bool RebuildDefaultArgOrDefaultInit = false;
6801 
6802     // When evaluating immediate functions in the initializer of a default
6803     // argument or default member initializer, this is the declaration whose
6804     // default initializer is being evaluated and the location of the call
6805     // or constructor definition.
6806     struct InitializationContext {
InitializationContextExpressionEvaluationContextRecord::InitializationContext6807       InitializationContext(SourceLocation Loc, ValueDecl *Decl,
6808                             DeclContext *Context)
6809           : Loc(Loc), Decl(Decl), Context(Context) {
6810         assert(Decl && Context && "invalid initialization context");
6811       }
6812 
6813       SourceLocation Loc;
6814       ValueDecl *Decl = nullptr;
6815       DeclContext *Context = nullptr;
6816     };
6817     std::optional<InitializationContext> DelayedDefaultInitializationContext;
6818 
ExpressionEvaluationContextRecordExpressionEvaluationContextRecord6819     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
6820                                       unsigned NumCleanupObjects,
6821                                       CleanupInfo ParentCleanup,
6822                                       Decl *ManglingContextDecl,
6823                                       ExpressionKind ExprContext)
6824         : Context(Context), ParentCleanup(ParentCleanup),
6825           NumCleanupObjects(NumCleanupObjects),
6826           ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
6827           InDiscardedStatement(false), InImmediateFunctionContext(false),
6828           InImmediateEscalatingFunctionContext(false) {}
6829 
isUnevaluatedExpressionEvaluationContextRecord6830     bool isUnevaluated() const {
6831       return Context == ExpressionEvaluationContext::Unevaluated ||
6832              Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
6833              Context == ExpressionEvaluationContext::UnevaluatedList;
6834     }
6835 
isPotentiallyEvaluatedExpressionEvaluationContextRecord6836     bool isPotentiallyEvaluated() const {
6837       return Context == ExpressionEvaluationContext::PotentiallyEvaluated ||
6838              Context ==
6839                  ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed ||
6840              Context == ExpressionEvaluationContext::ConstantEvaluated;
6841     }
6842 
isConstantEvaluatedExpressionEvaluationContextRecord6843     bool isConstantEvaluated() const {
6844       return Context == ExpressionEvaluationContext::ConstantEvaluated ||
6845              Context == ExpressionEvaluationContext::ImmediateFunctionContext;
6846     }
6847 
isImmediateFunctionContextExpressionEvaluationContextRecord6848     bool isImmediateFunctionContext() const {
6849       return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
6850              (Context == ExpressionEvaluationContext::DiscardedStatement &&
6851               InImmediateFunctionContext) ||
6852              // C++23 [expr.const]p14:
6853              // An expression or conversion is in an immediate function
6854              // context if it is potentially evaluated and either:
6855              //   * its innermost enclosing non-block scope is a function
6856              //     parameter scope of an immediate function, or
6857              //   * its enclosing statement is enclosed by the compound-
6858              //     statement of a consteval if statement.
6859              (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
6860               InImmediateFunctionContext);
6861     }
6862 
isDiscardedStatementContextExpressionEvaluationContextRecord6863     bool isDiscardedStatementContext() const {
6864       return Context == ExpressionEvaluationContext::DiscardedStatement ||
6865              ((Context ==
6866                    ExpressionEvaluationContext::ImmediateFunctionContext ||
6867                isPotentiallyEvaluated()) &&
6868               InDiscardedStatement);
6869     }
6870   };
6871 
currentEvaluationContext()6872   const ExpressionEvaluationContextRecord &currentEvaluationContext() const {
6873     assert(!ExprEvalContexts.empty() &&
6874            "Must be in an expression evaluation context");
6875     return ExprEvalContexts.back();
6876   };
6877 
currentEvaluationContext()6878   ExpressionEvaluationContextRecord &currentEvaluationContext() {
6879     assert(!ExprEvalContexts.empty() &&
6880            "Must be in an expression evaluation context");
6881     return ExprEvalContexts.back();
6882   };
6883 
parentEvaluationContext()6884   ExpressionEvaluationContextRecord &parentEvaluationContext() {
6885     assert(ExprEvalContexts.size() >= 2 &&
6886            "Must be in an expression evaluation context");
6887     return ExprEvalContexts[ExprEvalContexts.size() - 2];
6888   };
6889 
parentEvaluationContext()6890   const ExpressionEvaluationContextRecord &parentEvaluationContext() const {
6891     return const_cast<Sema *>(this)->parentEvaluationContext();
6892   };
6893 
isAttrContext()6894   bool isAttrContext() const {
6895     return ExprEvalContexts.back().ExprContext ==
6896            ExpressionEvaluationContextRecord::ExpressionKind::EK_AttrArgument;
6897   }
6898 
6899   /// Increment when we find a reference; decrement when we find an ignored
6900   /// assignment.  Ultimately the value is 0 if every reference is an ignored
6901   /// assignment.
6902   llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
6903 
6904   /// Used to control the generation of ExprWithCleanups.
6905   CleanupInfo Cleanup;
6906 
6907   /// ExprCleanupObjects - This is the stack of objects requiring
6908   /// cleanup that are created by the current full expression.
6909   SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
6910 
6911   /// Determine whether the use of this declaration is valid, without
6912   /// emitting diagnostics.
6913   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
6914   // A version of DiagnoseUseOfDecl that should be used if overload resolution
6915   // has been used to find this declaration, which means we don't have to bother
6916   // checking the trailing requires clause.
DiagnoseUseOfOverloadedDecl(NamedDecl * D,SourceLocation Loc)6917   bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) {
6918     return DiagnoseUseOfDecl(
6919         D, Loc, /*UnknownObjCClass=*/nullptr, /*ObjCPropertyAccess=*/false,
6920         /*AvoidPartialAvailabilityChecks=*/false, /*ClassReceiver=*/nullptr,
6921         /*SkipTrailingRequiresClause=*/true);
6922   }
6923 
6924   /// Determine whether the use of this declaration is valid, and
6925   /// emit any corresponding diagnostics.
6926   ///
6927   /// This routine diagnoses various problems with referencing
6928   /// declarations that can occur when using a declaration. For example,
6929   /// it might warn if a deprecated or unavailable declaration is being
6930   /// used, or produce an error (and return true) if a C++0x deleted
6931   /// function is being used.
6932   ///
6933   /// \returns true if there was an error (this declaration cannot be
6934   /// referenced), false otherwise.
6935   bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
6936                          const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
6937                          bool ObjCPropertyAccess = false,
6938                          bool AvoidPartialAvailabilityChecks = false,
6939                          ObjCInterfaceDecl *ClassReciever = nullptr,
6940                          bool SkipTrailingRequiresClause = false);
6941 
6942   /// Emit a note explaining that this function is deleted.
6943   void NoteDeletedFunction(FunctionDecl *FD);
6944 
6945   /// DiagnoseSentinelCalls - This routine checks whether a call or
6946   /// message-send is to a declaration with the sentinel attribute, and
6947   /// if so, it checks that the requirements of the sentinel are
6948   /// satisfied.
6949   void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
6950                              ArrayRef<Expr *> Args);
6951 
6952   void PushExpressionEvaluationContext(
6953       ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
6954       ExpressionEvaluationContextRecord::ExpressionKind Type =
6955           ExpressionEvaluationContextRecord::EK_Other);
6956 
6957   void PushExpressionEvaluationContextForFunction(
6958       ExpressionEvaluationContext NewContext, FunctionDecl *FD);
6959 
6960   enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
6961   void PushExpressionEvaluationContext(
6962       ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
6963       ExpressionEvaluationContextRecord::ExpressionKind Type =
6964           ExpressionEvaluationContextRecord::EK_Other);
6965   void PopExpressionEvaluationContext();
6966 
6967   void DiscardCleanupsInEvaluationContext();
6968 
6969   ExprResult TransformToPotentiallyEvaluated(Expr *E);
6970   TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
6971   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
6972 
6973   /// Check whether E, which is either a discarded-value expression or an
6974   /// unevaluated operand, is a simple-assignment to a volatlie-qualified
6975   /// lvalue, and if so, remove it from the list of volatile-qualified
6976   /// assignments that we are going to warn are deprecated.
6977   void CheckUnusedVolatileAssignment(Expr *E);
6978 
6979   ExprResult ActOnConstantExpression(ExprResult Res);
6980 
6981   // Functions for marking a declaration referenced.  These functions also
6982   // contain the relevant logic for marking if a reference to a function or
6983   // variable is an odr-use (in the C++11 sense).  There are separate variants
6984   // for expressions referring to a decl; these exist because odr-use marking
6985   // needs to be delayed for some constant variables when we build one of the
6986   // named expressions.
6987   //
6988   // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
6989   // should usually be true. This only needs to be set to false if the lack of
6990   // odr-use cannot be determined from the current context (for instance,
6991   // because the name denotes a virtual function and was written without an
6992   // explicit nested-name-specifier).
6993   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
6994 
6995   /// Mark a function referenced, and check whether it is odr-used
6996   /// (C++ [basic.def.odr]p2, C99 6.9p3)
6997   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
6998                               bool MightBeOdrUse = true);
6999 
7000   /// Mark a variable referenced, and check whether it is odr-used
7001   /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
7002   /// used directly for normal expressions referring to VarDecl.
7003   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
7004 
7005   /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7006   ///
7007   /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7008   /// be handled with care if the DeclRefExpr is not newly-created.
7009   void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7010 
7011   /// Perform reference-marking and odr-use handling for a MemberExpr.
7012   void MarkMemberReferenced(MemberExpr *E);
7013 
7014   /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7015   void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
7016   void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc,
7017                                          unsigned CapturingScopeIndex);
7018 
7019   ExprResult CheckLValueToRValueConversionOperand(Expr *E);
7020   void CleanupVarDeclMarking();
7021 
7022   /// Try to capture the given variable.
7023   ///
7024   /// \param Var The variable to capture.
7025   ///
7026   /// \param Loc The location at which the capture occurs.
7027   ///
7028   /// \param Kind The kind of capture, which may be implicit (for either a
7029   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7030   ///
7031   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7032   /// an explicit lambda capture.
7033   ///
7034   /// \param BuildAndDiagnose Whether we are actually supposed to add the
7035   /// captures or diagnose errors. If false, this routine merely check whether
7036   /// the capture can occur without performing the capture itself or complaining
7037   /// if the variable cannot be captured.
7038   ///
7039   /// \param CaptureType Will be set to the type of the field used to capture
7040   /// this variable in the innermost block or lambda. Only valid when the
7041   /// variable can be captured.
7042   ///
7043   /// \param DeclRefType Will be set to the type of a reference to the capture
7044   /// from within the current scope. Only valid when the variable can be
7045   /// captured.
7046   ///
7047   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7048   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7049   /// This is useful when enclosing lambdas must speculatively capture
7050   /// variables that may or may not be used in certain specializations of
7051   /// a nested generic lambda.
7052   ///
7053   /// \returns true if an error occurred (i.e., the variable cannot be
7054   /// captured) and false if the capture succeeded.
7055   bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7056                           TryCaptureKind Kind, SourceLocation EllipsisLoc,
7057                           bool BuildAndDiagnose, QualType &CaptureType,
7058                           QualType &DeclRefType,
7059                           const unsigned *const FunctionScopeIndexToStopAt);
7060 
7061   /// Try to capture the given variable.
7062   bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7063                           TryCaptureKind Kind = TryCaptureKind::Implicit,
7064                           SourceLocation EllipsisLoc = SourceLocation());
7065 
7066   /// Checks if the variable must be captured.
7067   bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc);
7068 
7069   /// Given a variable, determine the type that a reference to that
7070   /// variable will have in the given scope.
7071   QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc);
7072 
7073   /// Mark all of the declarations referenced within a particular AST node as
7074   /// referenced. Used when template instantiation instantiates a non-dependent
7075   /// type -- entities referenced by the type are now referenced.
7076   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
7077 
7078   /// Mark any declarations that appear within this expression or any
7079   /// potentially-evaluated subexpressions as "referenced".
7080   ///
7081   /// \param SkipLocalVariables If true, don't mark local variables as
7082   /// 'referenced'.
7083   /// \param StopAt Subexpressions that we shouldn't recurse into.
7084   void MarkDeclarationsReferencedInExpr(Expr *E,
7085                                         bool SkipLocalVariables = false,
7086                                         ArrayRef<const Expr *> StopAt = {});
7087 
7088   /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7089   /// conversion.
7090   ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7091 
7092   /// Conditionally issue a diagnostic based on the statements's reachability
7093   /// analysis.
7094   ///
7095   /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7096   /// the function body is parsed, and then do a basic reachability analysis to
7097   /// determine if the statement is reachable. If it is unreachable, the
7098   /// diagnostic will not be emitted.
7099   bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7100                        const PartialDiagnostic &PD);
7101 
7102   /// Conditionally issue a diagnostic based on the current
7103   /// evaluation context.
7104   ///
7105   /// \param Statement If Statement is non-null, delay reporting the
7106   /// diagnostic until the function body is parsed, and then do a basic
7107   /// reachability analysis to determine if the statement is reachable.
7108   /// If it is unreachable, the diagnostic will not be emitted.
7109   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7110                            const PartialDiagnostic &PD);
7111   /// Similar, but diagnostic is only produced if all the specified statements
7112   /// are reachable.
7113   bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7114                            const PartialDiagnostic &PD);
7115 
7116   // Primary Expressions.
7117   SourceRange getExprRange(Expr *E) const;
7118 
7119   ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7120                                SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7121                                bool HasTrailingLParen, bool IsAddressOfOperand,
7122                                CorrectionCandidateCallback *CCC = nullptr,
7123                                bool IsInlineAsmIdentifier = false,
7124                                Token *KeywordReplacement = nullptr);
7125 
7126   /// Decomposes the given name into a DeclarationNameInfo, its location, and
7127   /// possibly a list of template arguments.
7128   ///
7129   /// If this produces template arguments, it is permitted to call
7130   /// DecomposeTemplateName.
7131   ///
7132   /// This actually loses a lot of source location information for
7133   /// non-standard name kinds; we should consider preserving that in
7134   /// some way.
7135   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7136                               TemplateArgumentListInfo &Buffer,
7137                               DeclarationNameInfo &NameInfo,
7138                               const TemplateArgumentListInfo *&TemplateArgs);
7139 
7140   /// Diagnose a lookup that found results in an enclosing class during error
7141   /// recovery. This usually indicates that the results were found in a
7142   /// dependent base class that could not be searched as part of a template
7143   /// definition. Always issues a diagnostic (though this may be only a warning
7144   /// in MS compatibility mode).
7145   ///
7146   /// Return \c true if the error is unrecoverable, or \c false if the caller
7147   /// should attempt to recover using these lookup results.
7148   bool DiagnoseDependentMemberLookup(const LookupResult &R);
7149 
7150   /// Diagnose an empty lookup.
7151   ///
7152   /// \return false if new lookup candidates were found
7153   bool
7154   DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7155                       CorrectionCandidateCallback &CCC,
7156                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7157                       ArrayRef<Expr *> Args = {},
7158                       DeclContext *LookupCtx = nullptr);
7159 
7160   /// If \p D cannot be odr-used in the current expression evaluation context,
7161   /// return a reason explaining why. Otherwise, return NOUR_None.
7162   NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
7163 
7164   DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7165                                 SourceLocation Loc,
7166                                 const CXXScopeSpec *SS = nullptr);
7167   DeclRefExpr *
7168   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7169                    const DeclarationNameInfo &NameInfo,
7170                    const CXXScopeSpec *SS = nullptr,
7171                    NamedDecl *FoundD = nullptr,
7172                    SourceLocation TemplateKWLoc = SourceLocation(),
7173                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
7174 
7175   /// BuildDeclRefExpr - Build an expression that references a
7176   /// declaration that does not require a closure capture.
7177   DeclRefExpr *
7178   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7179                    const DeclarationNameInfo &NameInfo,
7180                    NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7181                    SourceLocation TemplateKWLoc = SourceLocation(),
7182                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
7183 
7184   bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7185                                   bool HasTrailingLParen);
7186 
7187   /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7188   /// declaration name, generally during template instantiation.
7189   /// There's a large number of things which don't need to be done along
7190   /// this path.
7191   ExprResult BuildQualifiedDeclarationNameExpr(
7192       CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7193       bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7194 
7195   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7196                                       bool NeedsADL,
7197                                       bool AcceptInvalidDecl = false);
7198 
7199   /// Complete semantic analysis for a reference to the given declaration.
7200   ExprResult BuildDeclarationNameExpr(
7201       const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7202       NamedDecl *FoundD = nullptr,
7203       const TemplateArgumentListInfo *TemplateArgs = nullptr,
7204       bool AcceptInvalidDecl = false);
7205 
7206   // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7207   // where Tokens representing function local predefined macros (such as
7208   // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7209   std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7210 
7211   ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7212   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7213   ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7214 
7215   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7216 
7217   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7218   ExprResult ActOnCharacterConstant(const Token &Tok,
7219                                     Scope *UDLScope = nullptr);
7220   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7221   ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7222                                 MultiExprArg Val);
7223   ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7224                                        unsigned NumUserSpecifiedExprs,
7225                                        SourceLocation InitLoc,
7226                                        SourceLocation LParenLoc,
7227                                        SourceLocation RParenLoc);
7228 
7229   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7230   /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle
7231   /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7232   /// from multiple tokens.  However, the common case is that StringToks points
7233   /// to one string.
7234   ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7235                                 Scope *UDLScope = nullptr);
7236 
7237   ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7238 
7239   /// ControllingExprOrType is either an opaque pointer coming out of a
7240   /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7241   /// into two so we don't take a void *, but that's awkward because one of
7242   /// the operands is either a ParsedType or an Expr *, which doesn't lend
7243   /// itself to generic code very well.
7244   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7245                                        SourceLocation DefaultLoc,
7246                                        SourceLocation RParenLoc,
7247                                        bool PredicateIsExpr,
7248                                        void *ControllingExprOrType,
7249                                        ArrayRef<ParsedType> ArgTypes,
7250                                        ArrayRef<Expr *> ArgExprs);
7251   /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7252   /// it'd be better to split this interface into two so we don't take a
7253   /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7254   /// isn't a trivial change.
7255   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7256                                         SourceLocation DefaultLoc,
7257                                         SourceLocation RParenLoc,
7258                                         bool PredicateIsExpr,
7259                                         void *ControllingExprOrType,
7260                                         ArrayRef<TypeSourceInfo *> Types,
7261                                         ArrayRef<Expr *> Exprs);
7262 
7263   // Binary/Unary Operators.  'Tok' is the token for the operator.
7264   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7265                                   Expr *InputExpr, bool IsAfterAmp = false);
7266   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7267                           Expr *Input, bool IsAfterAmp = false);
7268 
7269   /// Unary Operators.  'Tok' is the token for the operator.
7270   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7271                           Expr *Input, bool IsAfterAmp = false);
7272 
7273   /// Determine whether the given expression is a qualified member
7274   /// access expression, of a form that could be turned into a pointer to member
7275   /// with the address-of operator.
7276   bool isQualifiedMemberAccess(Expr *E);
7277   bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7278                                              const Expr *Op,
7279                                              const CXXMethodDecl *MD);
7280 
7281   /// CheckAddressOfOperand - The operand of & must be either a function
7282   /// designator or an lvalue designating an object. If it is an lvalue, the
7283   /// object cannot be declared with storage class register or be a bit field.
7284   /// Note: The usual conversions are *not* applied to the operand of the &
7285   /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7286   /// In C++, the operand might be an overloaded function name, in which case
7287   /// we allow the '&' but retain the overloaded-function type.
7288   QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7289 
7290   /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7291   /// _Alignas(type-name) .
7292   /// [dcl.align] An alignment-specifier of the form
7293   /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7294   ///
7295   /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7296   /// _Alignas(_Alignof(type-name)).
7297   bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7298                                 SourceLocation OpLoc, SourceRange R);
7299   bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7300                                 SourceLocation OpLoc, SourceRange R);
7301 
7302   /// Build a sizeof or alignof expression given a type operand.
7303   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7304                                             SourceLocation OpLoc,
7305                                             UnaryExprOrTypeTrait ExprKind,
7306                                             SourceRange R);
7307 
7308   /// Build a sizeof or alignof expression given an expression
7309   /// operand.
7310   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7311                                             UnaryExprOrTypeTrait ExprKind);
7312 
7313   /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7314   /// expr and the same for @c alignof and @c __alignof
7315   /// Note that the ArgRange is invalid if isType is false.
7316   ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7317                                            UnaryExprOrTypeTrait ExprKind,
7318                                            bool IsType, void *TyOrEx,
7319                                            SourceRange ArgRange);
7320 
7321   /// Check for operands with placeholder types and complain if found.
7322   /// Returns ExprError() if there was an error and no recovery was possible.
7323   ExprResult CheckPlaceholderExpr(Expr *E);
7324   bool CheckVecStepExpr(Expr *E);
7325 
7326   /// Check the constraints on expression operands to unary type expression
7327   /// and type traits.
7328   ///
7329   /// Completes any types necessary and validates the constraints on the operand
7330   /// expression. The logic mostly mirrors the type-based overload, but may
7331   /// modify the expression as it completes the type for that expression through
7332   /// template instantiation, etc.
7333   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
7334 
7335   /// Check the constraints on operands to unary expression and type
7336   /// traits.
7337   ///
7338   /// This will complete any types necessary, and validate the various
7339   /// constraints on those operands.
7340   ///
7341   /// The UsualUnaryConversions() function is *not* called by this routine.
7342   /// C99 6.3.2.1p[2-4] all state:
7343   ///   Except when it is the operand of the sizeof operator ...
7344   ///
7345   /// C++ [expr.sizeof]p4
7346   ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7347   ///   standard conversions are not applied to the operand of sizeof.
7348   ///
7349   /// This policy is followed for all of the unary trait expressions.
7350   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7351                                         SourceRange ExprRange,
7352                                         UnaryExprOrTypeTrait ExprKind,
7353                                         StringRef KWName);
7354 
7355   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7356                                  tok::TokenKind Kind, Expr *Input);
7357 
7358   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7359                                      MultiExprArg ArgExprs,
7360                                      SourceLocation RLoc);
7361   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7362                                              Expr *Idx, SourceLocation RLoc);
7363 
7364   ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7365                                               Expr *ColumnIdx,
7366                                               SourceLocation RBLoc);
7367 
7368   /// ConvertArgumentsForCall - Converts the arguments specified in
7369   /// Args/NumArgs to the parameter types of the function FDecl with
7370   /// function prototype Proto. Call is the call expression itself, and
7371   /// Fn is the function expression. For a C++ member function, this
7372   /// routine does not attempt to convert the object argument. Returns
7373   /// true if the call is ill-formed.
7374   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7375                                const FunctionProtoType *Proto,
7376                                ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7377                                bool ExecConfig = false);
7378 
7379   /// CheckStaticArrayArgument - If the given argument corresponds to a static
7380   /// array parameter, check that it is non-null, and that if it is formed by
7381   /// array-to-pointer decay, the underlying array is sufficiently large.
7382   ///
7383   /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7384   /// the array type derivation, then for each call to the function, the value
7385   /// of the corresponding actual argument shall provide access to the first
7386   /// element of an array with at least as many elements as specified by the
7387   /// size expression.
7388   void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7389                                 const Expr *ArgExpr);
7390 
7391   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7392   /// This provides the location of the left/right parens and a list of comma
7393   /// locations.
7394   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7395                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
7396                            Expr *ExecConfig = nullptr);
7397 
7398   /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7399   /// This provides the location of the left/right parens and a list of comma
7400   /// locations.
7401   ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7402                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
7403                            Expr *ExecConfig = nullptr,
7404                            bool IsExecConfig = false,
7405                            bool AllowRecovery = false);
7406 
7407   /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7408   //  with the specified CallArgs
7409   Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7410                              MultiExprArg CallArgs);
7411 
7412   using ADLCallKind = CallExpr::ADLCallKind;
7413 
7414   /// BuildResolvedCallExpr - Build a call to a resolved expression,
7415   /// i.e. an expression not of \p OverloadTy.  The expression should
7416   /// unary-convert to an expression of function-pointer or
7417   /// block-pointer type.
7418   ///
7419   /// \param NDecl the declaration being called, if available
7420   ExprResult
7421   BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7422                         ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7423                         Expr *Config = nullptr, bool IsExecConfig = false,
7424                         ADLCallKind UsesADL = ADLCallKind::NotADL);
7425 
7426   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D,
7427                            ParsedType &Ty, SourceLocation RParenLoc,
7428                            Expr *CastExpr);
7429 
7430   /// Prepares for a scalar cast, performing all the necessary stages
7431   /// except the final cast and returning the kind required.
7432   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
7433 
7434   /// Build an altivec or OpenCL literal.
7435   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
7436                                 SourceLocation RParenLoc, Expr *E,
7437                                 TypeSourceInfo *TInfo);
7438 
7439   /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7440   /// the ParenListExpr into a sequence of comma binary operators.
7441   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
7442 
7443   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7444                                   SourceLocation RParenLoc, Expr *InitExpr);
7445 
7446   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
7447                                       TypeSourceInfo *TInfo,
7448                                       SourceLocation RParenLoc,
7449                                       Expr *LiteralExpr);
7450 
7451   ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7452                            SourceLocation RBraceLoc);
7453 
7454   ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7455                            SourceLocation RBraceLoc);
7456 
7457   /// Binary Operators.  'Tok' is the token for the operator.
7458   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind,
7459                         Expr *LHSExpr, Expr *RHSExpr);
7460   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7461                         Expr *LHSExpr, Expr *RHSExpr,
7462                         bool ForFoldExpression = false);
7463 
7464   /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7465   /// operator @p Opc at location @c TokLoc. This routine only supports
7466   /// built-in operations; ActOnBinOp handles overloaded operators.
7467   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
7468                                 Expr *LHSExpr, Expr *RHSExpr,
7469                                 bool ForFoldExpression = false);
7470   void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7471                    UnresolvedSetImpl &Functions);
7472 
7473   /// Look for instances where it is likely the comma operator is confused with
7474   /// another operator.  There is an explicit list of acceptable expressions for
7475   /// the left hand side of the comma operator, otherwise emit a warning.
7476   void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7477 
7478   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7479   /// in the case of a the GNU conditional expr extension.
7480   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
7481                                 SourceLocation ColonLoc, Expr *CondExpr,
7482                                 Expr *LHSExpr, Expr *RHSExpr);
7483 
7484   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7485   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
7486                             LabelDecl *TheDecl);
7487 
7488   void ActOnStartStmtExpr();
7489   ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7490                            SourceLocation RPLoc);
7491   ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
7492                            SourceLocation RPLoc, unsigned TemplateDepth);
7493   // Handle the final expression in a statement expression.
7494   ExprResult ActOnStmtExprResult(ExprResult E);
7495   void ActOnStmtExprError();
7496 
7497   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
7498   struct OffsetOfComponent {
7499     SourceLocation LocStart, LocEnd;
7500     bool isBrackets; // true if [expr], false if .ident
7501     union {
7502       IdentifierInfo *IdentInfo;
7503       Expr *E;
7504     } U;
7505   };
7506 
7507   /// __builtin_offsetof(type, a.b[123][456].c)
7508   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
7509                                   TypeSourceInfo *TInfo,
7510                                   ArrayRef<OffsetOfComponent> Components,
7511                                   SourceLocation RParenLoc);
7512   ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
7513                                   SourceLocation TypeLoc,
7514                                   ParsedType ParsedArgTy,
7515                                   ArrayRef<OffsetOfComponent> Components,
7516                                   SourceLocation RParenLoc);
7517 
7518   // __builtin_choose_expr(constExpr, expr1, expr2)
7519   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7520                              Expr *LHSExpr, Expr *RHSExpr,
7521                              SourceLocation RPLoc);
7522 
7523   // __builtin_va_arg(expr, type)
7524   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
7525                         SourceLocation RPLoc);
7526   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
7527                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
7528 
7529   // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7530   // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7531   ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind,
7532                                 SourceLocation BuiltinLoc,
7533                                 SourceLocation RPLoc);
7534 
7535   // #embed
7536   ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
7537                             StringLiteral *BinaryData, StringRef FileName);
7538 
7539   // Build a potentially resolved SourceLocExpr.
7540   ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
7541                                 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7542                                 DeclContext *ParentContext);
7543 
7544   // __null
7545   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
7546 
7547   bool CheckCaseExpression(Expr *E);
7548 
7549   //===------------------------- "Block" Extension ------------------------===//
7550 
7551   /// ActOnBlockStart - This callback is invoked when a block literal is
7552   /// started.
7553   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7554 
7555   /// ActOnBlockArguments - This callback allows processing of block arguments.
7556   /// If there are no arguments, this is still invoked.
7557   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7558                            Scope *CurScope);
7559 
7560   /// ActOnBlockError - If there is an error parsing a block, this callback
7561   /// is invoked to pop the information about the block from the action impl.
7562   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7563 
7564   /// ActOnBlockStmtExpr - This is called when the body of a block statement
7565   /// literal was successfully completed.  ^(int x){...}
7566   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
7567                                 Scope *CurScope);
7568 
7569   //===---------------------------- Clang Extensions ----------------------===//
7570 
7571   /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7572   /// provided arguments.
7573   ///
7574   /// __builtin_convertvector( value, dst type )
7575   ///
7576   ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7577                                     SourceLocation BuiltinLoc,
7578                                     SourceLocation RParenLoc);
7579 
7580   //===---------------------------- OpenCL Features -----------------------===//
7581 
7582   /// Parse a __builtin_astype expression.
7583   ///
7584   /// __builtin_astype( value, dst type )
7585   ///
7586   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7587                              SourceLocation BuiltinLoc,
7588                              SourceLocation RParenLoc);
7589 
7590   /// Create a new AsTypeExpr node (bitcast) from the arguments.
7591   ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
7592                              SourceLocation BuiltinLoc,
7593                              SourceLocation RParenLoc);
7594 
7595   /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7596   ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
7597                                 ArrayRef<Expr *> SubExprs,
7598                                 QualType T = QualType());
7599 
7600   /// Cast a base object to a member's actual type.
7601   ///
7602   /// There are two relevant checks:
7603   ///
7604   /// C++ [class.access.base]p7:
7605   ///
7606   ///   If a class member access operator [...] is used to access a non-static
7607   ///   data member or non-static member function, the reference is ill-formed
7608   ///   if the left operand [...] cannot be implicitly converted to a pointer to
7609   ///   the naming class of the right operand.
7610   ///
7611   /// C++ [expr.ref]p7:
7612   ///
7613   ///   If E2 is a non-static data member or a non-static member function, the
7614   ///   program is ill-formed if the class of which E2 is directly a member is
7615   ///   an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7616   ///
7617   /// Note that the latter check does not consider access; the access of the
7618   /// "real" base class is checked as appropriate when checking the access of
7619   /// the member name.
7620   ExprResult PerformObjectMemberConversion(Expr *From,
7621                                            NestedNameSpecifier *Qualifier,
7622                                            NamedDecl *FoundDecl,
7623                                            NamedDecl *Member);
7624 
7625   /// CheckCallReturnType - Checks that a call expression's return type is
7626   /// complete. Returns true on failure. The location passed in is the location
7627   /// that best represents the call.
7628   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7629                            CallExpr *CE, FunctionDecl *FD);
7630 
7631   /// Emit a warning for all pending noderef expressions that we recorded.
7632   void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
7633 
7634   ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
7635 
7636   /// Instantiate or parse a C++ default argument expression as necessary.
7637   /// Return true on error.
7638   bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7639                               ParmVarDecl *Param, Expr *Init = nullptr,
7640                               bool SkipImmediateInvocations = true);
7641 
7642   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7643   /// the default expr if needed.
7644   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7645                                     ParmVarDecl *Param, Expr *Init = nullptr);
7646 
7647   /// Wrap the expression in a ConstantExpr if it is a potential immediate
7648   /// invocation.
7649   ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
7650 
7651   void MarkExpressionAsImmediateEscalating(Expr *E);
7652 
7653   // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7654   bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7655 
7656   /// Abstract base class used for diagnosing integer constant
7657   /// expression violations.
7658   class VerifyICEDiagnoser {
7659   public:
7660     bool Suppress;
7661 
Suppress(Suppress)7662     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) {}
7663 
7664     virtual SemaDiagnosticBuilder
7665     diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7666     virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7667                                                  SourceLocation Loc) = 0;
7668     virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
~VerifyICEDiagnoser()7669     virtual ~VerifyICEDiagnoser() {}
7670   };
7671 
7672   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7673   /// and reports the appropriate diagnostics. Returns false on success.
7674   /// Can optionally return the value of the expression.
7675   ExprResult
7676   VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7677                                   VerifyICEDiagnoser &Diagnoser,
7678                                   AllowFoldKind CanFold = AllowFoldKind::No);
7679   ExprResult
7680   VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7681                                   unsigned DiagID,
7682                                   AllowFoldKind CanFold = AllowFoldKind::No);
7683   ExprResult
7684   VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7685                                   AllowFoldKind CanFold = AllowFoldKind::No);
7686   ExprResult
7687   VerifyIntegerConstantExpression(Expr *E,
7688                                   AllowFoldKind CanFold = AllowFoldKind::No) {
7689     return VerifyIntegerConstantExpression(E, nullptr, CanFold);
7690   }
7691 
7692   /// DiagnoseAssignmentAsCondition - Given that an expression is
7693   /// being used as a boolean condition, warn if it's an assignment.
7694   void DiagnoseAssignmentAsCondition(Expr *E);
7695 
7696   /// Redundant parentheses over an equality comparison can indicate
7697   /// that the user intended an assignment used as condition.
7698   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7699 
7700   class FullExprArg {
7701   public:
FullExprArg()7702     FullExprArg() : E(nullptr) {}
FullExprArg(Sema & actions)7703     FullExprArg(Sema &actions) : E(nullptr) {}
7704 
release()7705     ExprResult release() { return E; }
7706 
get()7707     Expr *get() const { return E; }
7708 
7709     Expr *operator->() { return E; }
7710 
7711   private:
7712     // FIXME: No need to make the entire Sema class a friend when it's just
7713     // Sema::MakeFullExpr that needs access to the constructor below.
7714     friend class Sema;
7715 
FullExprArg(Expr * expr)7716     explicit FullExprArg(Expr *expr) : E(expr) {}
7717 
7718     Expr *E;
7719   };
7720 
MakeFullExpr(Expr * Arg)7721   FullExprArg MakeFullExpr(Expr *Arg) {
7722     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
7723   }
MakeFullExpr(Expr * Arg,SourceLocation CC)7724   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
7725     return FullExprArg(
7726         ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
7727   }
MakeFullDiscardedValueExpr(Expr * Arg)7728   FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
7729     ExprResult FE =
7730         ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
7731                             /*DiscardedValue*/ true);
7732     return FullExprArg(FE.get());
7733   }
7734 
7735   class ConditionResult {
7736     Decl *ConditionVar;
7737     ExprResult Condition;
7738     bool Invalid;
7739     std::optional<bool> KnownValue;
7740 
7741     friend class Sema;
ConditionResult(Sema & S,Decl * ConditionVar,ExprResult Condition,bool IsConstexpr)7742     ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
7743                     bool IsConstexpr)
7744         : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
7745       if (IsConstexpr && Condition.get()) {
7746         if (std::optional<llvm::APSInt> Val =
7747                 Condition.get()->getIntegerConstantExpr(S.Context)) {
7748           KnownValue = !!(*Val);
7749         }
7750       }
7751     }
ConditionResult(bool Invalid)7752     explicit ConditionResult(bool Invalid)
7753         : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
7754           KnownValue(std::nullopt) {}
7755 
7756   public:
ConditionResult()7757     ConditionResult() : ConditionResult(false) {}
isInvalid()7758     bool isInvalid() const { return Invalid; }
get()7759     std::pair<VarDecl *, Expr *> get() const {
7760       return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
7761                             Condition.get());
7762     }
getKnownValue()7763     std::optional<bool> getKnownValue() const { return KnownValue; }
7764   };
ConditionError()7765   static ConditionResult ConditionError() { return ConditionResult(true); }
7766 
7767   /// CheckBooleanCondition - Diagnose problems involving the use of
7768   /// the given expression as a boolean condition (e.g. in an if
7769   /// statement).  Also performs the standard function and array
7770   /// decays, possibly changing the input variable.
7771   ///
7772   /// \param Loc - A location associated with the condition, e.g. the
7773   /// 'if' keyword.
7774   /// \return true iff there were any errors
7775   ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
7776                                    bool IsConstexpr = false);
7777 
7778   enum class ConditionKind {
7779     Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
7780     ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
7781     Switch       ///< An integral condition for a 'switch' statement.
7782   };
7783 
7784   ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
7785                                  ConditionKind CK, bool MissingOK = false);
7786 
7787   QualType CheckConditionalOperands( // C99 6.5.15
7788       ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
7789       ExprObjectKind &OK, SourceLocation QuestionLoc);
7790 
7791   /// Emit a specialized diagnostic when one expression is a null pointer
7792   /// constant and the other is not a pointer.  Returns true if a diagnostic is
7793   /// emitted.
7794   bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7795                                   SourceLocation QuestionLoc);
7796 
7797   /// type checking for vector binary operators.
7798   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7799                                SourceLocation Loc, bool IsCompAssign,
7800                                bool AllowBothBool, bool AllowBoolConversion,
7801                                bool AllowBoolOperation, bool ReportInvalid);
7802 
7803   /// Return a signed ext_vector_type that is of identical size and number of
7804   /// elements. For floating point vectors, return an integer type of identical
7805   /// size and number of elements. In the non ext_vector_type case, search from
7806   /// the largest type to the smallest type to avoid cases where long long ==
7807   /// long, where long gets picked over long long.
7808   QualType GetSignedVectorType(QualType V);
7809   QualType GetSignedSizelessVectorType(QualType V);
7810 
7811   /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7812   /// operates on extended vector types.  Instead of producing an IntTy result,
7813   /// like a scalar comparison, a vector comparison produces a vector of integer
7814   /// types.
7815   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7816                                       SourceLocation Loc,
7817                                       BinaryOperatorKind Opc);
7818   QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7819                                               SourceLocation Loc,
7820                                               BinaryOperatorKind Opc);
7821   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7822                                       SourceLocation Loc,
7823                                       BinaryOperatorKind Opc);
7824 
7825   // type checking for sizeless vector binary operators.
7826   QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
7827                                        SourceLocation Loc, bool IsCompAssign,
7828                                        ArithConvKind OperationKind);
7829 
7830   /// Type checking for matrix binary operators.
7831   QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
7832                                           SourceLocation Loc,
7833                                           bool IsCompAssign);
7834   QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
7835                                        SourceLocation Loc, bool IsCompAssign);
7836 
7837   /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
7838   /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
7839   /// VLST) allowed?
7840   ///
7841   /// This will also return false if the two given types do not make sense from
7842   /// the perspective of SVE bitcasts.
7843   bool isValidSveBitcast(QualType srcType, QualType destType);
7844 
7845   /// Are the two types matrix types and do they have the same dimensions i.e.
7846   /// do they have the same number of rows and the same number of columns?
7847   bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
7848 
7849   bool areVectorTypesSameSize(QualType srcType, QualType destType);
7850 
7851   /// Are the two types lax-compatible vector types?  That is, given
7852   /// that one of them is a vector, do they have equal storage sizes,
7853   /// where the storage size is the number of elements times the element
7854   /// size?
7855   ///
7856   /// This will also return false if either of the types is neither a
7857   /// vector nor a real type.
7858   bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
7859 
7860   /// Is this a legal conversion between two types, one of which is
7861   /// known to be a vector type?
7862   bool isLaxVectorConversion(QualType srcType, QualType destType);
7863 
7864   // This returns true if at least one of the types is an altivec vector.
7865   bool anyAltivecTypes(QualType srcType, QualType destType);
7866 
7867   // type checking C++ declaration initializers (C++ [dcl.init]).
7868 
7869   /// Check a cast of an unknown-any type.  We intentionally only
7870   /// trigger this for C-style casts.
7871   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
7872                                  Expr *CastExpr, CastKind &CastKind,
7873                                  ExprValueKind &VK, CXXCastPath &Path);
7874 
7875   /// Force an expression with unknown-type to an expression of the
7876   /// given type.
7877   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
7878 
7879   /// Type-check an expression that's being passed to an
7880   /// __unknown_anytype parameter.
7881   ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result,
7882                                 QualType &paramType);
7883 
7884   // CheckMatrixCast - Check type constraints for matrix casts.
7885   // We allow casting between matrixes of the same dimensions i.e. when they
7886   // have the same number of rows and column. Returns true if the cast is
7887   // invalid.
7888   bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7889                        CastKind &Kind);
7890 
7891   // CheckVectorCast - check type constraints for vectors.
7892   // Since vectors are an extension, there are no C standard reference for this.
7893   // We allow casting between vectors and integer datatypes of the same size.
7894   // returns true if the cast is invalid
7895   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7896                        CastKind &Kind);
7897 
7898   /// Prepare `SplattedExpr` for a vector splat operation, adding
7899   /// implicit casts if necessary.
7900   ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
7901 
7902   // CheckExtVectorCast - check type constraints for extended vectors.
7903   // Since vectors are an extension, there are no C standard reference for this.
7904   // We allow casting between vectors and integer datatypes of the same size,
7905   // or vectors and the element type of that vector.
7906   // returns the cast expr
7907   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
7908                                 CastKind &Kind);
7909 
PreferredConditionType(ConditionKind K)7910   QualType PreferredConditionType(ConditionKind K) const {
7911     return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
7912   }
7913 
7914   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
7915   // functions and arrays to their respective pointers (C99 6.3.2.1), and
7916   // promotes floating-piont types according to the language semantics.
7917   ExprResult UsualUnaryConversions(Expr *E);
7918 
7919   // UsualUnaryFPConversions - promotes floating-point types according to the
7920   // current language semantics.
7921   ExprResult UsualUnaryFPConversions(Expr *E);
7922 
7923   /// CallExprUnaryConversions - a special case of an unary conversion
7924   /// performed on a function designator of a call expression.
7925   ExprResult CallExprUnaryConversions(Expr *E);
7926 
7927   // DefaultFunctionArrayConversion - converts functions and arrays
7928   // to their respective pointers (C99 6.3.2.1).
7929   ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
7930 
7931   // DefaultFunctionArrayLvalueConversion - converts functions and
7932   // arrays to their respective pointers and performs the
7933   // lvalue-to-rvalue conversion.
7934   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
7935                                                   bool Diagnose = true);
7936 
7937   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
7938   // the operand. This function is a no-op if the operand has a function type
7939   // or an array type.
7940   ExprResult DefaultLvalueConversion(Expr *E);
7941 
7942   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
7943   // do not have a prototype. Integer promotions are performed on each
7944   // argument, and arguments that have type float are promoted to double.
7945   ExprResult DefaultArgumentPromotion(Expr *E);
7946 
7947   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
7948                                        const FunctionProtoType *Proto,
7949                                        Expr *Fn);
7950 
7951   /// Determine the degree of POD-ness for an expression.
7952   /// Incomplete types are considered POD, since this check can be performed
7953   /// when we're in an unevaluated context.
7954   VarArgKind isValidVarArgType(const QualType &Ty);
7955 
7956   /// Check to see if the given expression is a valid argument to a variadic
7957   /// function, issuing a diagnostic if not.
7958   void checkVariadicArgument(const Expr *E, VariadicCallType CT);
7959 
7960   /// GatherArgumentsForCall - Collector argument expressions for various
7961   /// form of call prototypes.
7962   bool GatherArgumentsForCall(
7963       SourceLocation CallLoc, FunctionDecl *FDecl,
7964       const FunctionProtoType *Proto, unsigned FirstParam,
7965       ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs,
7966       VariadicCallType CallType = VariadicCallType::DoesNotApply,
7967       bool AllowExplicit = false, bool IsListInitialization = false);
7968 
7969   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
7970   // will create a runtime trap if the resulting type is not a POD type.
7971   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
7972                                               FunctionDecl *FDecl);
7973 
7974   // Check that the usual arithmetic conversions can be performed on this pair
7975   // of expressions that might be of enumeration type.
7976   void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc,
7977                                       ArithConvKind ACK);
7978 
7979   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
7980   // operands and then handles various conversions that are common to binary
7981   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
7982   // routine returns the first non-arithmetic type found. The client is
7983   // responsible for emitting appropriate error diagnostics.
7984   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
7985                                       SourceLocation Loc, ArithConvKind ACK);
7986 
IsAssignConvertCompatible(AssignConvertType ConvTy)7987   bool IsAssignConvertCompatible(AssignConvertType ConvTy) {
7988     switch (ConvTy) {
7989     default:
7990       return false;
7991     case AssignConvertType::Compatible:
7992     case AssignConvertType::CompatiblePointerDiscardsQualifiers:
7993     case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
7994       return true;
7995     }
7996     llvm_unreachable("impossible");
7997   }
7998 
7999   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8000   /// assignment conversion type specified by ConvTy.  This returns true if the
8001   /// conversion was invalid or false if the conversion was accepted.
8002   bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc,
8003                                 QualType DstType, QualType SrcType,
8004                                 Expr *SrcExpr, AssignmentAction Action,
8005                                 bool *Complained = nullptr);
8006 
8007   /// CheckAssignmentConstraints - Perform type checking for assignment,
8008   /// argument passing, variable initialization, and function return values.
8009   /// C99 6.5.16.
8010   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8011                                                QualType LHSType,
8012                                                QualType RHSType);
8013 
8014   /// Check assignment constraints and optionally prepare for a conversion of
8015   /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8016   /// is true.
8017   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8018                                                ExprResult &RHS, CastKind &Kind,
8019                                                bool ConvertRHS = true);
8020 
8021   /// Check assignment constraints for an assignment of RHS to LHSType.
8022   ///
8023   /// \param LHSType The destination type for the assignment.
8024   /// \param RHS The source expression for the assignment.
8025   /// \param Diagnose If \c true, diagnostics may be produced when checking
8026   ///        for assignability. If a diagnostic is produced, \p RHS will be
8027   ///        set to ExprError(). Note that this function may still return
8028   ///        without producing a diagnostic, even for an invalid assignment.
8029   /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8030   ///        in an audited Core Foundation API and does not need to be checked
8031   ///        for ARC retain issues.
8032   /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8033   ///        conversions necessary to perform the assignment. If \c false,
8034   ///        \p Diagnose must also be \c false.
8035   AssignConvertType CheckSingleAssignmentConstraints(
8036       QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8037       bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8038 
8039   // If the lhs type is a transparent union, check whether we
8040   // can initialize the transparent union with the given expression.
8041   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8042                                                              ExprResult &RHS);
8043 
8044   /// the following "Check" methods will return a valid/converted QualType
8045   /// or a null QualType (indicating an error diagnostic was issued).
8046 
8047   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8048   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8049                            ExprResult &RHS);
8050 
8051   /// Diagnose cases where a scalar was implicitly converted to a vector and
8052   /// diagnose the underlying types. Otherwise, diagnose the error
8053   /// as invalid vector logical operands for non-C++ cases.
8054   QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8055                                         ExprResult &RHS);
8056 
8057   QualType CheckMultiplyDivideOperands( // C99 6.5.5
8058       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
8059       bool IsDivide);
8060   QualType CheckRemainderOperands( // C99 6.5.5
8061       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8062       bool IsCompAssign = false);
8063   QualType CheckAdditionOperands( // C99 6.5.6
8064       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8065       BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8066   QualType CheckSubtractionOperands( // C99 6.5.6
8067       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8068       QualType *CompLHSTy = nullptr);
8069   QualType CheckShiftOperands( // C99 6.5.7
8070       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8071       BinaryOperatorKind Opc, bool IsCompAssign = false);
8072   void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
8073   QualType CheckCompareOperands( // C99 6.5.8/9
8074       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8075       BinaryOperatorKind Opc);
8076   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8077       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8078       BinaryOperatorKind Opc);
8079   QualType CheckLogicalOperands( // C99 6.5.[13,14]
8080       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8081       BinaryOperatorKind Opc);
8082   // CheckAssignmentOperands is used for both simple and compound assignment.
8083   // For simple assignment, pass both expressions and a null converted type.
8084   // For compound assignment, pass both expressions and the converted type.
8085   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8086       Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8087       BinaryOperatorKind Opc);
8088 
8089   /// To be used for checking whether the arguments being passed to
8090   /// function exceeds the number of parameters expected for it.
8091   static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8092                                bool PartialOverloading = false) {
8093     // We check whether we're just after a comma in code-completion.
8094     if (NumArgs > 0 && PartialOverloading)
8095       return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8096     return NumArgs > NumParams;
8097   }
8098 
8099   /// Whether the AST is currently being rebuilt to correct immediate
8100   /// invocations. Immediate invocation candidates and references to consteval
8101   /// functions aren't tracked when this is set.
8102   bool RebuildingImmediateInvocation = false;
8103 
isAlwaysConstantEvaluatedContext()8104   bool isAlwaysConstantEvaluatedContext() const {
8105     const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8106     return (Ctx.isConstantEvaluated() || isConstantEvaluatedOverride) &&
8107            !Ctx.InConditionallyConstantEvaluateContext;
8108   }
8109 
8110   /// Determines whether we are currently in a context that
8111   /// is not evaluated as per C++ [expr] p5.
isUnevaluatedContext()8112   bool isUnevaluatedContext() const {
8113     return currentEvaluationContext().isUnevaluated();
8114   }
8115 
isImmediateFunctionContext()8116   bool isImmediateFunctionContext() const {
8117     return currentEvaluationContext().isImmediateFunctionContext();
8118   }
8119 
isInLifetimeExtendingContext()8120   bool isInLifetimeExtendingContext() const {
8121     return currentEvaluationContext().InLifetimeExtendingContext;
8122   }
8123 
needsRebuildOfDefaultArgOrInit()8124   bool needsRebuildOfDefaultArgOrInit() const {
8125     return currentEvaluationContext().RebuildDefaultArgOrDefaultInit;
8126   }
8127 
isCheckingDefaultArgumentOrInitializer()8128   bool isCheckingDefaultArgumentOrInitializer() const {
8129     const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8130     return (Ctx.Context ==
8131             ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) ||
8132            Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer;
8133   }
8134 
8135   std::optional<ExpressionEvaluationContextRecord::InitializationContext>
InnermostDeclarationWithDelayedImmediateInvocations()8136   InnermostDeclarationWithDelayedImmediateInvocations() const {
8137     assert(!ExprEvalContexts.empty() &&
8138            "Must be in an expression evaluation context");
8139     for (const auto &Ctx : llvm::reverse(ExprEvalContexts)) {
8140       if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8141           Ctx.DelayedDefaultInitializationContext)
8142         return Ctx.DelayedDefaultInitializationContext;
8143       if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8144           Ctx.isUnevaluated())
8145         break;
8146     }
8147     return std::nullopt;
8148   }
8149 
8150   std::optional<ExpressionEvaluationContextRecord::InitializationContext>
OutermostDeclarationWithDelayedImmediateInvocations()8151   OutermostDeclarationWithDelayedImmediateInvocations() const {
8152     assert(!ExprEvalContexts.empty() &&
8153            "Must be in an expression evaluation context");
8154     std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8155     for (auto &Ctx : llvm::reverse(ExprEvalContexts)) {
8156       if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8157           !Ctx.DelayedDefaultInitializationContext && Res)
8158         break;
8159       if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8160           Ctx.isUnevaluated())
8161         break;
8162       Res = Ctx.DelayedDefaultInitializationContext;
8163     }
8164     return Res;
8165   }
8166 
getDefaultedComparisonKind(const FunctionDecl * FD)8167   DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
8168     return getDefaultedFunctionKind(FD).asComparison();
8169   }
8170 
8171   /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8172   /// SelfAssigned when inside a CXXMethodDecl.
8173   const FieldDecl *
8174   getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
8175 
8176   void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
8177 
8178   template <typename... Ts>
RequireCompleteSizedType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)8179   bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
8180                                 const Ts &...Args) {
8181     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8182     return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8183   }
8184 
8185   template <typename... Ts>
RequireCompleteSizedExprType(Expr * E,unsigned DiagID,const Ts &...Args)8186   bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8187                                     const Ts &...Args) {
8188     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8189     return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
8190   }
8191 
8192   /// Abstract class used to diagnose incomplete types.
8193   struct TypeDiagnoser {
TypeDiagnoserTypeDiagnoser8194     TypeDiagnoser() {}
8195 
8196     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
~TypeDiagnoserTypeDiagnoser8197     virtual ~TypeDiagnoser() {}
8198   };
8199 
8200   template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8201   protected:
8202     unsigned DiagID;
8203     std::tuple<const Ts &...> Args;
8204 
8205     template <std::size_t... Is>
emit(const SemaDiagnosticBuilder & DB,std::index_sequence<Is...>)8206     void emit(const SemaDiagnosticBuilder &DB,
8207               std::index_sequence<Is...>) const {
8208       // Apply all tuple elements to the builder in order.
8209       bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8210       (void)Dummy;
8211     }
8212 
8213   public:
BoundTypeDiagnoser(unsigned DiagID,const Ts &...Args)8214     BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8215         : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8216       assert(DiagID != 0 && "no diagnostic for type diagnoser");
8217     }
8218 
diagnose(Sema & S,SourceLocation Loc,QualType T)8219     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8220       const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8221       emit(DB, std::index_sequence_for<Ts...>());
8222       DB << T;
8223     }
8224   };
8225 
8226   /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8227   /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8228   /// For example, a diagnostic with no other parameters would generally have
8229   /// the form "...%select{incomplete|sizeless}0 type %1...".
8230   template <typename... Ts>
8231   class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
8232   public:
SizelessTypeDiagnoser(unsigned DiagID,const Ts &...Args)8233     SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8234         : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8235 
diagnose(Sema & S,SourceLocation Loc,QualType T)8236     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8237       const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8238       this->emit(DB, std::index_sequence_for<Ts...>());
8239       DB << T->isSizelessType() << T;
8240     }
8241   };
8242 
8243   /// Check an argument list for placeholders that we won't try to
8244   /// handle later.
8245   bool CheckArgsForPlaceholders(MultiExprArg args);
8246 
8247   /// The C++ "std::source_location::__impl" struct, defined in
8248   /// \<source_location>.
8249   RecordDecl *StdSourceLocationImplDecl;
8250 
8251   /// A stack of expression evaluation contexts.
8252   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
8253 
8254   // Set of failed immediate invocations to avoid double diagnosing.
8255   llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
8256 
8257   /// List of SourceLocations where 'self' is implicitly retained inside a
8258   /// block.
8259   llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
8260       ImplicitlyRetainedSelfLocs;
8261 
8262   /// Do an explicit extend of the given block pointer if we're in ARC.
8263   void maybeExtendBlockObject(ExprResult &E);
8264 
8265   std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8266   SourceLocation LocationOfExcessPrecisionNotSatisfied;
8267   void DiagnosePrecisionLossInComplexDivision();
8268 
8269 private:
8270   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8271 
8272   /// Methods for marking which expressions involve dereferencing a pointer
8273   /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8274   /// they are parsed, meaning that a noderef pointer may not be accessed. For
8275   /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8276   /// `*p`, but need to check that `address of` is called on it. This requires
8277   /// keeping a container of all pending expressions and checking if the address
8278   /// of them are eventually taken.
8279   void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8280   void CheckAddressOfNoDeref(const Expr *E);
8281 
8282   ///@}
8283 
8284   //
8285   //
8286   // -------------------------------------------------------------------------
8287   //
8288   //
8289 
8290   /// \name C++ Expressions
8291   /// Implementations are in SemaExprCXX.cpp
8292   ///@{
8293 
8294 public:
8295   /// The C++ "std::bad_alloc" class, which is defined by the C++
8296   /// standard library.
8297   LazyDeclPtr StdBadAlloc;
8298 
8299   /// The C++ "std::align_val_t" enum class, which is defined by the C++
8300   /// standard library.
8301   LazyDeclPtr StdAlignValT;
8302 
8303   /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
8304   RecordDecl *CXXTypeInfoDecl;
8305 
8306   /// A flag to remember whether the implicit forms of operator new and delete
8307   /// have been declared.
8308   bool GlobalNewDeleteDeclared;
8309 
8310   /// Delete-expressions to be analyzed at the end of translation unit
8311   ///
8312   /// This list contains class members, and locations of delete-expressions
8313   /// that could not be proven as to whether they mismatch with new-expression
8314   /// used in initializer of the field.
8315   llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8316 
8317   /// Handle the result of the special case name lookup for inheriting
8318   /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8319   /// constructor names in member using declarations, even if 'X' is not the
8320   /// name of the corresponding type.
8321   ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
8322                                           SourceLocation NameLoc,
8323                                           const IdentifierInfo &Name);
8324 
8325   ParsedType getConstructorName(const IdentifierInfo &II,
8326                                 SourceLocation NameLoc, Scope *S,
8327                                 CXXScopeSpec &SS, bool EnteringContext);
8328   ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc,
8329                                Scope *S, CXXScopeSpec &SS,
8330                                ParsedType ObjectType, bool EnteringContext);
8331 
8332   ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
8333                                           ParsedType ObjectType);
8334 
8335   /// Build a C++ typeid expression with a type operand.
8336   ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8337                             TypeSourceInfo *Operand, SourceLocation RParenLoc);
8338 
8339   /// Build a C++ typeid expression with an expression operand.
8340   ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8341                             Expr *Operand, SourceLocation RParenLoc);
8342 
8343   /// ActOnCXXTypeid - Parse typeid( something ).
8344   ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
8345                             bool isType, void *TyOrExpr,
8346                             SourceLocation RParenLoc);
8347 
8348   /// Build a Microsoft __uuidof expression with a type operand.
8349   ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8350                             TypeSourceInfo *Operand, SourceLocation RParenLoc);
8351 
8352   /// Build a Microsoft __uuidof expression with an expression operand.
8353   ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8354                             Expr *Operand, SourceLocation RParenLoc);
8355 
8356   /// ActOnCXXUuidof - Parse __uuidof( something ).
8357   ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
8358                             bool isType, void *TyOrExpr,
8359                             SourceLocation RParenLoc);
8360 
8361   //// ActOnCXXThis -  Parse 'this' pointer.
8362   ExprResult ActOnCXXThis(SourceLocation Loc);
8363 
8364   /// Check whether the type of 'this' is valid in the current context.
8365   bool CheckCXXThisType(SourceLocation Loc, QualType Type);
8366 
8367   /// Build a CXXThisExpr and mark it referenced in the current context.
8368   Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8369   void MarkThisReferenced(CXXThisExpr *This);
8370 
8371   /// Try to retrieve the type of the 'this' pointer.
8372   ///
8373   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8374   QualType getCurrentThisType();
8375 
8376   /// When non-NULL, the C++ 'this' expression is allowed despite the
8377   /// current context not being a non-static member function. In such cases,
8378   /// this provides the type used for 'this'.
8379   QualType CXXThisTypeOverride;
8380 
8381   /// RAII object used to temporarily allow the C++ 'this' expression
8382   /// to be used, with the given qualifiers on the current class type.
8383   class CXXThisScopeRAII {
8384     Sema &S;
8385     QualType OldCXXThisTypeOverride;
8386     bool Enabled;
8387 
8388   public:
8389     /// Introduce a new scope where 'this' may be allowed (when enabled),
8390     /// using the given declaration (which is either a class template or a
8391     /// class) along with the given qualifiers.
8392     /// along with the qualifiers placed on '*this'.
8393     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8394                      bool Enabled = true);
8395 
8396     ~CXXThisScopeRAII();
8397   };
8398 
8399   /// Make sure the value of 'this' is actually available in the current
8400   /// context, if it is a potentially evaluated context.
8401   ///
8402   /// \param Loc The location at which the capture of 'this' occurs.
8403   ///
8404   /// \param Explicit Whether 'this' is explicitly captured in a lambda
8405   /// capture list.
8406   ///
8407   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8408   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8409   /// This is useful when enclosing lambdas must speculatively capture
8410   /// 'this' that may or may not be used in certain specializations of
8411   /// a nested generic lambda (depending on whether the name resolves to
8412   /// a non-static member function or a static function).
8413   /// \return returns 'true' if failed, 'false' if success.
8414   bool CheckCXXThisCapture(
8415       SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8416       const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8417       bool ByCopy = false);
8418 
8419   /// Determine whether the given type is the type of *this that is used
8420   /// outside of the body of a member function for a type that is currently
8421   /// being defined.
8422   bool isThisOutsideMemberFunctionBody(QualType BaseType);
8423 
8424   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8425   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
8426 
8427   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8428   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
8429 
8430   //// ActOnCXXThrow -  Parse throw expressions.
8431   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
8432   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
8433                            bool IsThrownVarInScope);
8434 
8435   /// CheckCXXThrowOperand - Validate the operand of a throw.
8436   bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8437 
8438   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8439   /// Can be interpreted either as function-style casting ("int(x)")
8440   /// or class type construction ("ClassType(x,y,z)")
8441   /// or creation of a value-initialized type ("int()").
8442   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
8443                                        SourceLocation LParenOrBraceLoc,
8444                                        MultiExprArg Exprs,
8445                                        SourceLocation RParenOrBraceLoc,
8446                                        bool ListInitialization);
8447 
8448   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
8449                                        SourceLocation LParenLoc,
8450                                        MultiExprArg Exprs,
8451                                        SourceLocation RParenLoc,
8452                                        bool ListInitialization);
8453 
8454   /// Parsed a C++ 'new' expression (C++ 5.3.4).
8455   ///
8456   /// E.g.:
8457   /// @code new (memory) int[size][4] @endcode
8458   /// or
8459   /// @code ::new Foo(23, "hello") @endcode
8460   ///
8461   /// \param StartLoc The first location of the expression.
8462   /// \param UseGlobal True if 'new' was prefixed with '::'.
8463   /// \param PlacementLParen Opening paren of the placement arguments.
8464   /// \param PlacementArgs Placement new arguments.
8465   /// \param PlacementRParen Closing paren of the placement arguments.
8466   /// \param TypeIdParens If the type is in parens, the source range.
8467   /// \param D The type to be allocated, as well as array dimensions.
8468   /// \param Initializer The initializing expression or initializer-list, or
8469   ///   null if there is none.
8470   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8471                          SourceLocation PlacementLParen,
8472                          MultiExprArg PlacementArgs,
8473                          SourceLocation PlacementRParen,
8474                          SourceRange TypeIdParens, Declarator &D,
8475                          Expr *Initializer);
8476   ExprResult
8477   BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8478               MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8479               SourceRange TypeIdParens, QualType AllocType,
8480               TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8481               SourceRange DirectInitRange, Expr *Initializer);
8482 
8483   /// Determine whether \p FD is an aligned allocation or deallocation
8484   /// function that is unavailable.
8485   bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
8486 
8487   /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8488   /// function that is unavailable.
8489   void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
8490                                             SourceLocation Loc);
8491 
8492   /// Checks that a type is suitable as the allocated type
8493   /// in a new-expression.
8494   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8495                           SourceRange R);
8496 
8497   /// Finds the overloads of operator new and delete that are appropriate
8498   /// for the allocation.
8499   bool FindAllocationFunctions(
8500       SourceLocation StartLoc, SourceRange Range,
8501       AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope,
8502       QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP,
8503       MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew,
8504       FunctionDecl *&OperatorDelete, bool Diagnose = true);
8505 
8506   /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8507   /// delete. These are:
8508   /// @code
8509   ///   // C++03:
8510   ///   void* operator new(std::size_t) throw(std::bad_alloc);
8511   ///   void* operator new[](std::size_t) throw(std::bad_alloc);
8512   ///   void operator delete(void *) throw();
8513   ///   void operator delete[](void *) throw();
8514   ///   // C++11:
8515   ///   void* operator new(std::size_t);
8516   ///   void* operator new[](std::size_t);
8517   ///   void operator delete(void *) noexcept;
8518   ///   void operator delete[](void *) noexcept;
8519   ///   // C++1y:
8520   ///   void* operator new(std::size_t);
8521   ///   void* operator new[](std::size_t);
8522   ///   void operator delete(void *) noexcept;
8523   ///   void operator delete[](void *) noexcept;
8524   ///   void operator delete(void *, std::size_t) noexcept;
8525   ///   void operator delete[](void *, std::size_t) noexcept;
8526   /// @endcode
8527   /// Note that the placement and nothrow forms of new are *not* implicitly
8528   /// declared. Their use requires including \<new\>.
8529   void DeclareGlobalNewDelete();
8530   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
8531                                        ArrayRef<QualType> Params);
8532 
8533   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
8534                                 DeclarationName Name, FunctionDecl *&Operator,
8535                                 ImplicitDeallocationParameters,
8536                                 bool Diagnose = true);
8537   FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
8538                                               ImplicitDeallocationParameters,
8539                                               DeclarationName Name);
8540   FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
8541                                                       CXXRecordDecl *RD,
8542                                                       bool Diagnose = true);
8543 
8544   /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8545   /// @code ::delete ptr; @endcode
8546   /// or
8547   /// @code delete [] ptr; @endcode
8548   ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8549                             bool ArrayForm, Expr *Operand);
8550   void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
8551                             bool IsDelete, bool CallCanBeVirtual,
8552                             bool WarnOnNonAbstractTypes,
8553                             SourceLocation DtorLoc);
8554 
8555   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
8556                                Expr *Operand, SourceLocation RParen);
8557   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8558                                   SourceLocation RParen);
8559 
8560   ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base,
8561                                           SourceLocation OpLoc,
8562                                           tok::TokenKind OpKind,
8563                                           ParsedType &ObjectType,
8564                                           bool &MayBePseudoDestructor);
8565 
8566   ExprResult BuildPseudoDestructorExpr(
8567       Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8568       const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8569       SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8570 
8571   ExprResult ActOnPseudoDestructorExpr(
8572       Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8573       CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8574       SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8575 
8576   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
8577                                        SourceLocation OpLoc,
8578                                        tok::TokenKind OpKind,
8579                                        SourceLocation TildeLoc,
8580                                        const DeclSpec &DS);
8581 
8582   /// MaybeCreateExprWithCleanups - If the current full-expression
8583   /// requires any cleanups, surround it with a ExprWithCleanups node.
8584   /// Otherwise, just returns the passed-in expression.
8585   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
8586   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
8587   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
8588 
ActOnFinishFullExpr(Expr * Expr,bool DiscardedValue)8589   ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8590     return ActOnFinishFullExpr(
8591         Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8592   }
8593   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
8594                                  bool DiscardedValue, bool IsConstexpr = false,
8595                                  bool IsTemplateArgument = false);
8596   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
8597 
8598   /// Process the expression contained within a decltype. For such expressions,
8599   /// certain semantic checks on temporaries are delayed until this point, and
8600   /// are omitted for the 'topmost' call in the decltype expression. If the
8601   /// topmost call bound a temporary, strip that temporary off the expression.
8602   ExprResult ActOnDecltypeExpression(Expr *E);
8603 
8604   bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8605                               bool IsUDSuffix);
8606 
8607   bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
8608 
8609   ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8610                                          SourceLocation StmtLoc,
8611                                          ConditionKind CK);
8612 
8613   /// Check the use of the given variable as a C++ condition in an if,
8614   /// while, do-while, or switch statement.
8615   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
8616                                     SourceLocation StmtLoc, ConditionKind CK);
8617 
8618   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8619   ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8620 
8621   /// Helper function to determine whether this is the (deprecated) C++
8622   /// conversion from a string literal to a pointer to non-const char or
8623   /// non-const wchar_t (for narrow and wide string literals,
8624   /// respectively).
8625   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8626 
8627   /// PerformImplicitConversion - Perform an implicit conversion of the
8628   /// expression From to the type ToType using the pre-computed implicit
8629   /// conversion sequence ICS. Returns the converted
8630   /// expression. Action is the kind of conversion we're performing,
8631   /// used in the error message.
8632   ExprResult PerformImplicitConversion(
8633       Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8634       AssignmentAction Action,
8635       CheckedConversionKind CCK = CheckedConversionKind::Implicit);
8636 
8637   /// PerformImplicitConversion - Perform an implicit conversion of the
8638   /// expression From to the type ToType by following the standard
8639   /// conversion sequence SCS. Returns the converted
8640   /// expression. Flavor is the context in which we're performing this
8641   /// conversion, for use in error messages.
8642   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8643                                        const StandardConversionSequence &SCS,
8644                                        AssignmentAction Action,
8645                                        CheckedConversionKind CCK);
8646 
8647   bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8648 
8649   /// Parsed one of the type trait support pseudo-functions.
8650   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8651                             ArrayRef<ParsedType> Args,
8652                             SourceLocation RParenLoc);
8653   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8654                             ArrayRef<TypeSourceInfo *> Args,
8655                             SourceLocation RParenLoc);
8656 
8657   /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8658   /// pseudo-functions.
8659   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8660                                  ParsedType LhsTy, Expr *DimExpr,
8661                                  SourceLocation RParen);
8662 
8663   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8664                                  TypeSourceInfo *TSInfo, Expr *DimExpr,
8665                                  SourceLocation RParen);
8666 
8667   /// ActOnExpressionTrait - Parsed one of the unary type trait support
8668   /// pseudo-functions.
8669   ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8670                                   Expr *Queried, SourceLocation RParen);
8671 
8672   ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8673                                   Expr *Queried, SourceLocation RParen);
8674 
8675   QualType CheckPointerToMemberOperands( // C++ 5.5
8676       ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc,
8677       bool isIndirect);
8678   QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
8679                                        ExprResult &RHS,
8680                                        SourceLocation QuestionLoc);
8681 
8682   QualType CheckSizelessVectorConditionalTypes(ExprResult &Cond,
8683                                                ExprResult &LHS, ExprResult &RHS,
8684                                                SourceLocation QuestionLoc);
8685 
8686   //// Determines if a type is trivially relocatable
8687   /// according to the C++26 rules.
8688   // FIXME: This is in Sema because it requires
8689   // overload resolution, can we move to ASTContext?
8690   bool IsCXXTriviallyRelocatableType(QualType T);
8691   bool IsCXXTriviallyRelocatableType(const CXXRecordDecl &RD);
8692 
8693   //// Determines if a type is replaceable
8694   /// according to the C++26 rules.
8695   // FIXME: This is in Sema because it requires
8696   // overload resolution, can we move to ASTContext?
8697   bool IsCXXReplaceableType(QualType T);
8698 
8699   /// Check the operands of ?: under C++ semantics.
8700   ///
8701   /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8702   /// extension. In this case, LHS == Cond. (But they're not aliases.)
8703   ///
8704   /// This function also implements GCC's vector extension and the
8705   /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8706   /// permit the use of a?b:c where the type of a is that of a integer vector
8707   /// with the same number of elements and size as the vectors of b and c. If
8708   /// one of either b or c is a scalar it is implicitly converted to match the
8709   /// type of the vector. Otherwise the expression is ill-formed. If both b and
8710   /// c are scalars, then b and c are checked and converted to the type of a if
8711   /// possible.
8712   ///
8713   /// The expressions are evaluated differently for GCC's and OpenCL's
8714   /// extensions. For the GCC extension, the ?: operator is evaluated as
8715   ///   (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8716   /// For the OpenCL extensions, the ?: operator is evaluated as
8717   ///   (most-significant-bit-set(a[0])  ? b[0] : c[0], .. ,
8718   ///    most-significant-bit-set(a[n]) ? b[n] : c[n]).
8719   QualType CXXCheckConditionalOperands( // C++ 5.16
8720       ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8721       ExprObjectKind &OK, SourceLocation questionLoc);
8722 
8723   /// Find a merged pointer type and convert the two expressions to it.
8724   ///
8725   /// This finds the composite pointer type for \p E1 and \p E2 according to
8726   /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8727   /// it.  It does not emit diagnostics (FIXME: that's not true if \p
8728   /// ConvertArgs is \c true).
8729   ///
8730   /// \param Loc The location of the operator requiring these two expressions to
8731   /// be converted to the composite pointer type.
8732   ///
8733   /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
8734   /// type.
8735   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8736                                     bool ConvertArgs = true);
8737   QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1,
8738                                     ExprResult &E2, bool ConvertArgs = true) {
8739     Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8740     QualType Composite =
8741         FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
8742     E1 = E1Tmp;
8743     E2 = E2Tmp;
8744     return Composite;
8745   }
8746 
8747   /// MaybeBindToTemporary - If the passed in expression has a record type with
8748   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
8749   /// it simply returns the passed in expression.
8750   ExprResult MaybeBindToTemporary(Expr *E);
8751 
8752   /// IgnoredValueConversions - Given that an expression's result is
8753   /// syntactically ignored, perform any conversions that are
8754   /// required.
8755   ExprResult IgnoredValueConversions(Expr *E);
8756 
8757   ExprResult CheckUnevaluatedOperand(Expr *E);
8758 
8759   IfExistsResult
8760   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
8761                                const DeclarationNameInfo &TargetNameInfo);
8762 
8763   IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S,
8764                                               SourceLocation KeywordLoc,
8765                                               bool IsIfExists, CXXScopeSpec &SS,
8766                                               UnqualifiedId &Name);
8767 
8768   RequiresExprBodyDecl *
8769   ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8770                          ArrayRef<ParmVarDecl *> LocalParameters,
8771                          Scope *BodyScope);
8772   void ActOnFinishRequiresExpr();
8773   concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8774   concepts::Requirement *ActOnTypeRequirement(SourceLocation TypenameKWLoc,
8775                                               CXXScopeSpec &SS,
8776                                               SourceLocation NameLoc,
8777                                               const IdentifierInfo *TypeName,
8778                                               TemplateIdAnnotation *TemplateId);
8779   concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8780                                                   SourceLocation NoexceptLoc);
8781   concepts::Requirement *ActOnCompoundRequirement(
8782       Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8783       TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8784   concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8785   concepts::ExprRequirement *BuildExprRequirement(
8786       Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8787       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8788   concepts::ExprRequirement *BuildExprRequirement(
8789       concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8790       bool IsSatisfied, SourceLocation NoexceptLoc,
8791       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8792   concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8793   concepts::TypeRequirement *BuildTypeRequirement(
8794       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8795   concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8796   concepts::NestedRequirement *
8797   BuildNestedRequirement(StringRef InvalidConstraintEntity,
8798                          const ASTConstraintSatisfaction &Satisfaction);
8799   ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8800                                RequiresExprBodyDecl *Body,
8801                                SourceLocation LParenLoc,
8802                                ArrayRef<ParmVarDecl *> LocalParameters,
8803                                SourceLocation RParenLoc,
8804                                ArrayRef<concepts::Requirement *> Requirements,
8805                                SourceLocation ClosingBraceLoc);
8806 
8807 private:
8808   ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
8809                                                 bool IsDelete);
8810 
8811   void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8812   void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8813                                  bool DeleteWasArrayForm);
8814 
8815   ///@}
8816 
8817   //
8818   //
8819   // -------------------------------------------------------------------------
8820   //
8821   //
8822 
8823   /// \name Member Access Expressions
8824   /// Implementations are in SemaExprMember.cpp
8825   ///@{
8826 
8827 public:
8828   /// Check whether an expression might be an implicit class member access.
8829   bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R,
8830                                        bool IsAddressOfOperand);
8831 
8832   /// Builds an expression which might be an implicit member expression.
8833   ExprResult BuildPossibleImplicitMemberExpr(
8834       const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
8835       const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
8836 
8837   /// Builds an implicit member access expression.  The current context
8838   /// is known to be an instance method, and the given unqualified lookup
8839   /// set is known to contain only instance members, at least one of which
8840   /// is from an appropriate type.
8841   ExprResult
8842   BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8843                           LookupResult &R,
8844                           const TemplateArgumentListInfo *TemplateArgs,
8845                           bool IsDefiniteInstance, const Scope *S);
8846 
8847   ExprResult ActOnDependentMemberExpr(
8848       Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
8849       const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8850       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
8851       const TemplateArgumentListInfo *TemplateArgs);
8852 
8853   /// The main callback when the parser finds something like
8854   ///   expression . [nested-name-specifier] identifier
8855   ///   expression -> [nested-name-specifier] identifier
8856   /// where 'identifier' encompasses a fairly broad spectrum of
8857   /// possibilities, including destructor and operator references.
8858   ///
8859   /// \param OpKind either tok::arrow or tok::period
8860   /// \param ObjCImpDecl the current Objective-C \@implementation
8861   ///   decl; this is an ugly hack around the fact that Objective-C
8862   ///   \@implementations aren't properly put in the context chain
8863   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
8864                                    tok::TokenKind OpKind, CXXScopeSpec &SS,
8865                                    SourceLocation TemplateKWLoc,
8866                                    UnqualifiedId &Member, Decl *ObjCImpDecl);
8867 
8868   MemberExpr *
8869   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
8870                   NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
8871                   ValueDecl *Member, DeclAccessPair FoundDecl,
8872                   bool HadMultipleCandidates,
8873                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
8874                   ExprValueKind VK, ExprObjectKind OK,
8875                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
8876 
8877   // Check whether the declarations we found through a nested-name
8878   // specifier in a member expression are actually members of the base
8879   // type.  The restriction here is:
8880   //
8881   //   C++ [expr.ref]p2:
8882   //     ... In these cases, the id-expression shall name a
8883   //     member of the class or of one of its base classes.
8884   //
8885   // So it's perfectly legitimate for the nested-name specifier to name
8886   // an unrelated class, and for us to find an overload set including
8887   // decls from classes which are not superclasses, as long as the decl
8888   // we actually pick through overload resolution is from a superclass.
8889   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
8890                                      const CXXScopeSpec &SS,
8891                                      const LookupResult &R);
8892 
8893   // This struct is for use by ActOnMemberAccess to allow
8894   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
8895   // changing the access operator from a '.' to a '->' (to see if that is the
8896   // change needed to fix an error about an unknown member, e.g. when the class
8897   // defines a custom operator->).
8898   struct ActOnMemberAccessExtraArgs {
8899     Scope *S;
8900     UnqualifiedId &Id;
8901     Decl *ObjCImpDecl;
8902   };
8903 
8904   ExprResult BuildMemberReferenceExpr(
8905       Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
8906       CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8907       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
8908       const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
8909       ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
8910 
8911   ExprResult
8912   BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
8913                            bool IsArrow, const CXXScopeSpec &SS,
8914                            SourceLocation TemplateKWLoc,
8915                            NamedDecl *FirstQualifierInScope, LookupResult &R,
8916                            const TemplateArgumentListInfo *TemplateArgs,
8917                            const Scope *S, bool SuppressQualifierCheck = false,
8918                            ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
8919 
8920   ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
8921                                      SourceLocation OpLoc,
8922                                      const CXXScopeSpec &SS, FieldDecl *Field,
8923                                      DeclAccessPair FoundDecl,
8924                                      const DeclarationNameInfo &MemberNameInfo);
8925 
8926   /// Perform conversions on the LHS of a member access expression.
8927   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
8928 
8929   ExprResult BuildAnonymousStructUnionMemberReference(
8930       const CXXScopeSpec &SS, SourceLocation nameLoc,
8931       IndirectFieldDecl *indirectField,
8932       DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
8933       Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
8934 
8935 private:
8936   void CheckMemberAccessOfNoDeref(const MemberExpr *E);
8937 
8938   ///@}
8939 
8940   //
8941   //
8942   // -------------------------------------------------------------------------
8943   //
8944   //
8945 
8946   /// \name Initializers
8947   /// Implementations are in SemaInit.cpp
8948   ///@{
8949 
8950 public:
8951   /// Stack of types that correspond to the parameter entities that are
8952   /// currently being copy-initialized. Can be empty.
8953   llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
8954 
8955   llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
8956       AggregateDeductionCandidates;
8957 
8958   bool IsStringInit(Expr *Init, const ArrayType *AT);
8959 
8960   /// Determine whether we can perform aggregate initialization for the purposes
8961   /// of overload resolution.
8962   bool CanPerformAggregateInitializationForOverloadResolution(
8963       const InitializedEntity &Entity, InitListExpr *From);
8964 
8965   ExprResult ActOnDesignatedInitializer(Designation &Desig,
8966                                         SourceLocation EqualOrColonLoc,
8967                                         bool GNUSyntax, ExprResult Init);
8968 
8969   /// Check that the lifetime of the initializer (and its subobjects) is
8970   /// sufficient for initializing the entity, and perform lifetime extension
8971   /// (when permitted) if not.
8972   void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
8973 
8974   MaterializeTemporaryExpr *
8975   CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
8976                                  bool BoundToLvalueReference);
8977 
8978   /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
8979   /// it as an xvalue. In C++98, the result will still be a prvalue, because
8980   /// we don't have xvalues there.
8981   ExprResult TemporaryMaterializationConversion(Expr *E);
8982 
8983   ExprResult PerformQualificationConversion(
8984       Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
8985       CheckedConversionKind CCK = CheckedConversionKind::Implicit);
8986 
8987   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
8988                                     ExprResult Init);
8989   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
8990                                        SourceLocation EqualLoc, ExprResult Init,
8991                                        bool TopLevelOfInitList = false,
8992                                        bool AllowExplicit = false);
8993 
8994   QualType DeduceTemplateSpecializationFromInitializer(
8995       TypeSourceInfo *TInfo, const InitializedEntity &Entity,
8996       const InitializationKind &Kind, MultiExprArg Init);
8997 
8998   ///@}
8999 
9000   //
9001   //
9002   // -------------------------------------------------------------------------
9003   //
9004   //
9005 
9006   /// \name C++ Lambda Expressions
9007   /// Implementations are in SemaLambda.cpp
9008   ///@{
9009 
9010 public:
9011   /// Create a new lambda closure type.
9012   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
9013                                          TypeSourceInfo *Info,
9014                                          unsigned LambdaDependencyKind,
9015                                          LambdaCaptureDefault CaptureDefault);
9016 
9017   /// Number lambda for linkage purposes if necessary.
9018   void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method,
9019                              std::optional<CXXRecordDecl::LambdaNumbering>
9020                                  NumberingOverride = std::nullopt);
9021 
9022   /// Endow the lambda scope info with the relevant properties.
9023   void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9024                         SourceRange IntroducerRange,
9025                         LambdaCaptureDefault CaptureDefault,
9026                         SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9027                         bool Mutable);
9028 
9029   CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange,
9030                                           CXXRecordDecl *Class);
9031 
9032   void AddTemplateParametersToLambdaCallOperator(
9033       CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9034       TemplateParameterList *TemplateParams);
9035 
9036   void
9037   CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc,
9038                              SourceLocation CallOperatorLoc,
9039                              const AssociatedConstraint &TrailingRequiresClause,
9040                              TypeSourceInfo *MethodTyInfo,
9041                              ConstexprSpecKind ConstexprKind, StorageClass SC,
9042                              ArrayRef<ParmVarDecl *> Params,
9043                              bool HasExplicitResultType);
9044 
9045   /// Returns true if the explicit object parameter was invalid.
9046   bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method,
9047                                                       SourceLocation CallLoc);
9048 
9049   /// Perform initialization analysis of the init-capture and perform
9050   /// any implicit conversions such as an lvalue-to-rvalue conversion if
9051   /// not being used to initialize a reference.
actOnLambdaInitCaptureInitialization(SourceLocation Loc,bool ByRef,SourceLocation EllipsisLoc,IdentifierInfo * Id,LambdaCaptureInitKind InitKind,Expr * & Init)9052   ParsedType actOnLambdaInitCaptureInitialization(
9053       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9054       IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9055     return ParsedType::make(buildLambdaInitCaptureInitialization(
9056         Loc, ByRef, EllipsisLoc, std::nullopt, Id,
9057         InitKind != LambdaCaptureInitKind::CopyInit, Init));
9058   }
9059   QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
9060                                                 SourceLocation EllipsisLoc,
9061                                                 UnsignedOrNone NumExpansions,
9062                                                 IdentifierInfo *Id,
9063                                                 bool DirectInit, Expr *&Init);
9064 
9065   /// Create a dummy variable within the declcontext of the lambda's
9066   ///  call operator, for name lookup purposes for a lambda init capture.
9067   ///
9068   ///  CodeGen handles emission of lambda captures, ignoring these dummy
9069   ///  variables appropriately.
9070   VarDecl *createLambdaInitCaptureVarDecl(
9071       SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9072       IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9073 
9074   /// Add an init-capture to a lambda scope.
9075   void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9076 
9077   /// Note that we have finished the explicit captures for the
9078   /// given lambda.
9079   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
9080 
9081   /// Deduce a block or lambda's return type based on the return
9082   /// statements present in the body.
9083   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
9084 
9085   /// Once the Lambdas capture are known, we can start to create the closure,
9086   /// call operator method, and keep track of the captures.
9087   /// We do the capture lookup here, but they are not actually captured until
9088   /// after we know what the qualifiers of the call operator are.
9089   void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
9090                                             Scope *CurContext);
9091 
9092   /// This is called after parsing the explicit template parameter list
9093   /// on a lambda (if it exists) in C++2a.
9094   void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
9095                                                 SourceLocation LAngleLoc,
9096                                                 ArrayRef<NamedDecl *> TParams,
9097                                                 SourceLocation RAngleLoc,
9098                                                 ExprResult RequiresClause);
9099 
9100   void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
9101                                     SourceLocation MutableLoc);
9102 
9103   void ActOnLambdaClosureParameters(
9104       Scope *LambdaScope,
9105       MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo);
9106 
9107   /// ActOnStartOfLambdaDefinition - This is called just before we start
9108   /// parsing the body of a lambda; it analyzes the explicit captures and
9109   /// arguments, and sets up various data-structures for the body of the
9110   /// lambda.
9111   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
9112                                     Declarator &ParamInfo, const DeclSpec &DS);
9113 
9114   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9115   /// is invoked to pop the information about the lambda.
9116   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9117                         bool IsInstantiation = false);
9118 
9119   /// ActOnLambdaExpr - This is called when the body of a lambda expression
9120   /// was successfully completed.
9121   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body);
9122 
9123   /// Does copying/destroying the captured variable have side effects?
9124   bool CaptureHasSideEffects(const sema::Capture &From);
9125 
9126   /// Diagnose if an explicit lambda capture is unused. Returns true if a
9127   /// diagnostic is emitted.
9128   bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9129                                    SourceRange FixItRange,
9130                                    const sema::Capture &From);
9131 
9132   /// Build a FieldDecl suitable to hold the given capture.
9133   FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
9134 
9135   /// Initialize the given capture with a suitable expression.
9136   ExprResult BuildCaptureInit(const sema::Capture &Capture,
9137                               SourceLocation ImplicitCaptureLoc,
9138                               bool IsOpenMPMapping = false);
9139 
9140   /// Complete a lambda-expression having processed and attached the
9141   /// lambda body.
9142   ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
9143                              sema::LambdaScopeInfo *LSI);
9144 
9145   /// Get the return type to use for a lambda's conversion function(s) to
9146   /// function pointer type, given the type of the call operator.
9147   QualType
9148   getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
9149                                         CallingConv CC);
9150 
9151   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
9152                                            SourceLocation ConvLocation,
9153                                            CXXConversionDecl *Conv, Expr *Src);
9154 
9155   class LambdaScopeForCallOperatorInstantiationRAII
9156       : private FunctionScopeRAII {
9157   public:
9158     LambdaScopeForCallOperatorInstantiationRAII(
9159         Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9160         LocalInstantiationScope &Scope,
9161         bool ShouldAddDeclsFromParentScope = true);
9162   };
9163 
9164   /// Compute the mangling number context for a lambda expression or
9165   /// block literal. Also return the extra mangling decl if any.
9166   ///
9167   /// \param DC - The DeclContext containing the lambda expression or
9168   /// block literal.
9169   std::tuple<MangleNumberingContext *, Decl *>
9170   getCurrentMangleNumberContext(const DeclContext *DC);
9171 
9172   ///@}
9173 
9174   //
9175   //
9176   // -------------------------------------------------------------------------
9177   //
9178   //
9179 
9180   /// \name Name Lookup
9181   ///
9182   /// These routines provide name lookup that is used during semantic
9183   /// analysis to resolve the various kinds of names (identifiers,
9184   /// overloaded operator names, constructor names, etc.) into zero or
9185   /// more declarations within a particular scope. The major entry
9186   /// points are LookupName, which performs unqualified name lookup,
9187   /// and LookupQualifiedName, which performs qualified name lookup.
9188   ///
9189   /// All name lookup is performed based on some specific criteria,
9190   /// which specify what names will be visible to name lookup and how
9191   /// far name lookup should work. These criteria are important both
9192   /// for capturing language semantics (certain lookups will ignore
9193   /// certain names, for example) and for performance, since name
9194   /// lookup is often a bottleneck in the compilation of C++. Name
9195   /// lookup criteria is specified via the LookupCriteria enumeration.
9196   ///
9197   /// The results of name lookup can vary based on the kind of name
9198   /// lookup performed, the current language, and the translation
9199   /// unit. In C, for example, name lookup will either return nothing
9200   /// (no entity found) or a single declaration. In C++, name lookup
9201   /// can additionally refer to a set of overloaded functions or
9202   /// result in an ambiguity. All of the possible results of name
9203   /// lookup are captured by the LookupResult class, which provides
9204   /// the ability to distinguish among them.
9205   ///
9206   /// Implementations are in SemaLookup.cpp
9207   ///@{
9208 
9209 public:
9210   /// Tracks whether we are in a context where typo correction is
9211   /// disabled.
9212   bool DisableTypoCorrection;
9213 
9214   /// The number of typos corrected by CorrectTypo.
9215   unsigned TyposCorrected;
9216 
9217   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9218   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9219 
9220   /// A cache containing identifiers for which typo correction failed and
9221   /// their locations, so that repeated attempts to correct an identifier in a
9222   /// given location are ignored if typo correction already failed for it.
9223   IdentifierSourceLocations TypoCorrectionFailures;
9224 
9225   /// SpecialMemberOverloadResult - The overloading result for a special member
9226   /// function.
9227   ///
9228   /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9229   /// integer are used to determine whether overload resolution succeeded.
9230   class SpecialMemberOverloadResult {
9231   public:
9232     enum Kind { NoMemberOrDeleted, Ambiguous, Success };
9233 
9234   private:
9235     llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9236 
9237   public:
SpecialMemberOverloadResult()9238     SpecialMemberOverloadResult() {}
SpecialMemberOverloadResult(CXXMethodDecl * MD)9239     SpecialMemberOverloadResult(CXXMethodDecl *MD)
9240         : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9241 
getMethod()9242     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
setMethod(CXXMethodDecl * MD)9243     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9244 
getKind()9245     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
setKind(Kind K)9246     void setKind(Kind K) { Pair.setInt(K); }
9247   };
9248 
9249   class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode,
9250                                            public SpecialMemberOverloadResult {
9251   public:
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID & ID)9252     SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
9253         : FastFoldingSetNode(ID) {}
9254   };
9255 
9256   /// A cache of special member function overload resolution results
9257   /// for C++ records.
9258   llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
9259 
9260   enum class AcceptableKind { Visible, Reachable };
9261 
9262   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9263   // TODO: make this is a typesafe union.
9264   typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
9265   typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
9266 
9267   /// Describes the kind of name lookup to perform.
9268   enum LookupNameKind {
9269     /// Ordinary name lookup, which finds ordinary names (functions,
9270     /// variables, typedefs, etc.) in C and most kinds of names
9271     /// (functions, variables, members, types, etc.) in C++.
9272     LookupOrdinaryName = 0,
9273     /// Tag name lookup, which finds the names of enums, classes,
9274     /// structs, and unions.
9275     LookupTagName,
9276     /// Label name lookup.
9277     LookupLabel,
9278     /// Member name lookup, which finds the names of
9279     /// class/struct/union members.
9280     LookupMemberName,
9281     /// Look up of an operator name (e.g., operator+) for use with
9282     /// operator overloading. This lookup is similar to ordinary name
9283     /// lookup, but will ignore any declarations that are class members.
9284     LookupOperatorName,
9285     /// Look up a name following ~ in a destructor name. This is an ordinary
9286     /// lookup, but prefers tags to typedefs.
9287     LookupDestructorName,
9288     /// Look up of a name that precedes the '::' scope resolution
9289     /// operator in C++. This lookup completely ignores operator, object,
9290     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9291     LookupNestedNameSpecifierName,
9292     /// Look up a namespace name within a C++ using directive or
9293     /// namespace alias definition, ignoring non-namespace names (C++
9294     /// [basic.lookup.udir]p1).
9295     LookupNamespaceName,
9296     /// Look up all declarations in a scope with the given name,
9297     /// including resolved using declarations.  This is appropriate
9298     /// for checking redeclarations for a using declaration.
9299     LookupUsingDeclName,
9300     /// Look up an ordinary name that is going to be redeclared as a
9301     /// name with linkage. This lookup ignores any declarations that
9302     /// are outside of the current scope unless they have linkage. See
9303     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9304     LookupRedeclarationWithLinkage,
9305     /// Look up a friend of a local class. This lookup does not look
9306     /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9307     LookupLocalFriendName,
9308     /// Look up the name of an Objective-C protocol.
9309     LookupObjCProtocolName,
9310     /// Look up implicit 'self' parameter of an objective-c method.
9311     LookupObjCImplicitSelfParam,
9312     /// Look up the name of an OpenMP user-defined reduction operation.
9313     LookupOMPReductionName,
9314     /// Look up the name of an OpenMP user-defined mapper.
9315     LookupOMPMapperName,
9316     /// Look up any declaration with any name.
9317     LookupAnyName
9318   };
9319 
9320   /// The possible outcomes of name lookup for a literal operator.
9321   enum LiteralOperatorLookupResult {
9322     /// The lookup resulted in an error.
9323     LOLR_Error,
9324     /// The lookup found no match but no diagnostic was issued.
9325     LOLR_ErrorNoDiagnostic,
9326     /// The lookup found a single 'cooked' literal operator, which
9327     /// expects a normal literal to be built and passed to it.
9328     LOLR_Cooked,
9329     /// The lookup found a single 'raw' literal operator, which expects
9330     /// a string literal containing the spelling of the literal token.
9331     LOLR_Raw,
9332     /// The lookup found an overload set of literal operator templates,
9333     /// which expect the characters of the spelling of the literal token to be
9334     /// passed as a non-type template argument pack.
9335     LOLR_Template,
9336     /// The lookup found an overload set of literal operator templates,
9337     /// which expect the character type and characters of the spelling of the
9338     /// string literal token to be passed as template arguments.
9339     LOLR_StringTemplatePack,
9340   };
9341 
9342   SpecialMemberOverloadResult
9343   LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg,
9344                       bool VolatileArg, bool RValueThis, bool ConstThis,
9345                       bool VolatileThis);
9346 
9347   RedeclarationKind forRedeclarationInCurContext() const;
9348 
9349   /// Look up a name, looking for a single declaration.  Return
9350   /// null if the results were absent, ambiguous, or overloaded.
9351   ///
9352   /// It is preferable to use the elaborated form and explicitly handle
9353   /// ambiguity and overloaded.
9354   NamedDecl *LookupSingleName(
9355       Scope *S, DeclarationName Name, SourceLocation Loc,
9356       LookupNameKind NameKind,
9357       RedeclarationKind Redecl = RedeclarationKind::NotForRedeclaration);
9358 
9359   /// Lookup a builtin function, when name lookup would otherwise
9360   /// fail.
9361   bool LookupBuiltin(LookupResult &R);
9362   void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9363 
9364   /// Perform unqualified name lookup starting from a given
9365   /// scope.
9366   ///
9367   /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9368   /// used to find names within the current scope. For example, 'x' in
9369   /// @code
9370   /// int x;
9371   /// int f() {
9372   ///   return x; // unqualified name look finds 'x' in the global scope
9373   /// }
9374   /// @endcode
9375   ///
9376   /// Different lookup criteria can find different names. For example, a
9377   /// particular scope can have both a struct and a function of the same
9378   /// name, and each can be found by certain lookup criteria. For more
9379   /// information about lookup criteria, see the documentation for the
9380   /// class LookupCriteria.
9381   ///
9382   /// @param S        The scope from which unqualified name lookup will
9383   /// begin. If the lookup criteria permits, name lookup may also search
9384   /// in the parent scopes.
9385   ///
9386   /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9387   /// look up and the lookup kind), and is updated with the results of lookup
9388   /// including zero or more declarations and possibly additional information
9389   /// used to diagnose ambiguities.
9390   ///
9391   /// @returns \c true if lookup succeeded and false otherwise.
9392   bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9393                   bool ForceNoCPlusPlus = false);
9394 
9395   /// Perform qualified name lookup into a given context.
9396   ///
9397   /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9398   /// names when the context of those names is explicit specified, e.g.,
9399   /// "std::vector" or "x->member", or as part of unqualified name lookup.
9400   ///
9401   /// Different lookup criteria can find different names. For example, a
9402   /// particular scope can have both a struct and a function of the same
9403   /// name, and each can be found by certain lookup criteria. For more
9404   /// information about lookup criteria, see the documentation for the
9405   /// class LookupCriteria.
9406   ///
9407   /// \param R captures both the lookup criteria and any lookup results found.
9408   ///
9409   /// \param LookupCtx The context in which qualified name lookup will
9410   /// search. If the lookup criteria permits, name lookup may also search
9411   /// in the parent contexts or (for C++ classes) base classes.
9412   ///
9413   /// \param InUnqualifiedLookup true if this is qualified name lookup that
9414   /// occurs as part of unqualified name lookup.
9415   ///
9416   /// \returns true if lookup succeeded, false if it failed.
9417   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9418                            bool InUnqualifiedLookup = false);
9419 
9420   /// Performs qualified name lookup or special type of lookup for
9421   /// "__super::" scope specifier.
9422   ///
9423   /// This routine is a convenience overload meant to be called from contexts
9424   /// that need to perform a qualified name lookup with an optional C++ scope
9425   /// specifier that might require special kind of lookup.
9426   ///
9427   /// \param R captures both the lookup criteria and any lookup results found.
9428   ///
9429   /// \param LookupCtx The context in which qualified name lookup will
9430   /// search.
9431   ///
9432   /// \param SS An optional C++ scope-specifier.
9433   ///
9434   /// \returns true if lookup succeeded, false if it failed.
9435   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9436                            CXXScopeSpec &SS);
9437 
9438   /// Performs name lookup for a name that was parsed in the
9439   /// source code, and may contain a C++ scope specifier.
9440   ///
9441   /// This routine is a convenience routine meant to be called from
9442   /// contexts that receive a name and an optional C++ scope specifier
9443   /// (e.g., "N::M::x"). It will then perform either qualified or
9444   /// unqualified name lookup (with LookupQualifiedName or LookupName,
9445   /// respectively) on the given name and return those results. It will
9446   /// perform a special type of lookup for "__super::" scope specifier.
9447   ///
9448   /// @param S        The scope from which unqualified name lookup will
9449   /// begin.
9450   ///
9451   /// @param SS       An optional C++ scope-specifier, e.g., "::N::M".
9452   ///
9453   /// @param EnteringContext Indicates whether we are going to enter the
9454   /// context of the scope-specifier SS (if present).
9455   ///
9456   /// @returns True if any decls were found (but possibly ambiguous)
9457   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
9458                         QualType ObjectType, bool AllowBuiltinCreation = false,
9459                         bool EnteringContext = false);
9460 
9461   /// Perform qualified name lookup into all base classes of the given
9462   /// class.
9463   ///
9464   /// \param R captures both the lookup criteria and any lookup results found.
9465   ///
9466   /// \param Class The context in which qualified name lookup will
9467   /// search. Name lookup will search in all base classes merging the results.
9468   ///
9469   /// @returns True if any decls were found (but possibly ambiguous)
9470   bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
9471 
9472   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
9473                                     UnresolvedSetImpl &Functions);
9474 
9475   /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9476   /// If GnuLabelLoc is a valid source location, then this is a definition
9477   /// of an __label__ label name, otherwise it is a normal label definition
9478   /// or use.
9479   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
9480                                  SourceLocation GnuLabelLoc = SourceLocation());
9481 
9482   /// Look up the constructors for the given class.
9483   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
9484 
9485   /// Look up the default constructor for the given class.
9486   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
9487 
9488   /// Look up the copying constructor for the given class.
9489   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
9490                                                unsigned Quals);
9491 
9492   /// Look up the copying assignment operator for the given class.
9493   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
9494                                          bool RValueThis, unsigned ThisQuals);
9495 
9496   /// Look up the moving constructor for the given class.
9497   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
9498                                               unsigned Quals);
9499 
9500   /// Look up the moving assignment operator for the given class.
9501   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
9502                                         bool RValueThis, unsigned ThisQuals);
9503 
9504   /// Look for the destructor of the given class.
9505   ///
9506   /// During semantic analysis, this routine should be used in lieu of
9507   /// CXXRecordDecl::getDestructor().
9508   ///
9509   /// \returns The destructor for this class.
9510   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
9511 
9512   /// Force the declaration of any implicitly-declared members of this
9513   /// class.
9514   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
9515 
9516   /// Make a merged definition of an existing hidden definition \p ND
9517   /// visible at the specified location.
9518   void makeMergedDefinitionVisible(NamedDecl *ND);
9519 
9520   /// Check ODR hashes for C/ObjC when merging types from modules.
9521   /// Differently from C++, actually parse the body and reject in case
9522   /// of a mismatch.
9523   template <typename T,
9524             typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
ActOnDuplicateODRHashDefinition(T * Duplicate,T * Previous)9525   bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
9526     if (Duplicate->getODRHash() != Previous->getODRHash())
9527       return false;
9528 
9529     // Make the previous decl visible.
9530     makeMergedDefinitionVisible(Previous);
9531     return true;
9532   }
9533 
9534   /// Get the set of additional modules that should be checked during
9535   /// name lookup. A module and its imports become visible when instanting a
9536   /// template defined within it.
9537   llvm::DenseSet<Module *> &getLookupModules();
9538 
9539   bool hasVisibleMergedDefinition(const NamedDecl *Def);
9540   bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
9541 
9542   /// Determine if the template parameter \p D has a visible default argument.
9543   bool
9544   hasVisibleDefaultArgument(const NamedDecl *D,
9545                             llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9546   /// Determine if the template parameter \p D has a reachable default argument.
9547   bool hasReachableDefaultArgument(
9548       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9549   /// Determine if the template parameter \p D has a reachable default argument.
9550   bool hasAcceptableDefaultArgument(const NamedDecl *D,
9551                                     llvm::SmallVectorImpl<Module *> *Modules,
9552                                     Sema::AcceptableKind Kind);
9553 
9554   /// Determine if there is a visible declaration of \p D that is an explicit
9555   /// specialization declaration for a specialization of a template. (For a
9556   /// member specialization, use hasVisibleMemberSpecialization.)
9557   bool hasVisibleExplicitSpecialization(
9558       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9559   /// Determine if there is a reachable declaration of \p D that is an explicit
9560   /// specialization declaration for a specialization of a template. (For a
9561   /// member specialization, use hasReachableMemberSpecialization.)
9562   bool hasReachableExplicitSpecialization(
9563       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9564 
9565   /// Determine if there is a visible declaration of \p D that is a member
9566   /// specialization declaration (as opposed to an instantiated declaration).
9567   bool hasVisibleMemberSpecialization(
9568       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9569   /// Determine if there is a reachable declaration of \p D that is a member
9570   /// specialization declaration (as opposed to an instantiated declaration).
9571   bool hasReachableMemberSpecialization(
9572       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9573 
9574   bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9575 
9576   /// Determine whether any declaration of an entity is visible.
9577   bool
9578   hasVisibleDeclaration(const NamedDecl *D,
9579                         llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9580     return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9581   }
9582 
9583   bool hasVisibleDeclarationSlow(const NamedDecl *D,
9584                                  llvm::SmallVectorImpl<Module *> *Modules);
9585   /// Determine whether any declaration of an entity is reachable.
9586   bool
9587   hasReachableDeclaration(const NamedDecl *D,
9588                           llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9589     return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9590   }
9591   bool hasReachableDeclarationSlow(
9592       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9593 
9594   void diagnoseTypo(const TypoCorrection &Correction,
9595                     const PartialDiagnostic &TypoDiag,
9596                     bool ErrorRecovery = true);
9597 
9598   /// Diagnose a successfully-corrected typo. Separated from the correction
9599   /// itself to allow external validation of the result, etc.
9600   ///
9601   /// \param Correction The result of performing typo correction.
9602   /// \param TypoDiag The diagnostic to produce. This will have the corrected
9603   ///        string added to it (and usually also a fixit).
9604   /// \param PrevNote A note to use when indicating the location of the entity
9605   ///        to which we are correcting. Will have the correction string added
9606   ///        to it.
9607   /// \param ErrorRecovery If \c true (the default), the caller is going to
9608   ///        recover from the typo as if the corrected string had been typed.
9609   ///        In this case, \c PDiag must be an error, and we will attach a fixit
9610   ///        to it.
9611   void diagnoseTypo(const TypoCorrection &Correction,
9612                     const PartialDiagnostic &TypoDiag,
9613                     const PartialDiagnostic &PrevNote,
9614                     bool ErrorRecovery = true);
9615 
9616   /// Find the associated classes and namespaces for
9617   /// argument-dependent lookup for a call with the given set of
9618   /// arguments.
9619   ///
9620   /// This routine computes the sets of associated classes and associated
9621   /// namespaces searched by argument-dependent lookup
9622   /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9623   void FindAssociatedClassesAndNamespaces(
9624       SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9625       AssociatedNamespaceSet &AssociatedNamespaces,
9626       AssociatedClassSet &AssociatedClasses);
9627 
9628   /// Produce a diagnostic describing the ambiguity that resulted
9629   /// from name lookup.
9630   ///
9631   /// \param Result The result of the ambiguous lookup to be diagnosed.
9632   void DiagnoseAmbiguousLookup(LookupResult &Result);
9633 
9634   /// LookupLiteralOperator - Determine which literal operator should be used
9635   /// for a user-defined literal, per C++11 [lex.ext].
9636   ///
9637   /// Normal overload resolution is not used to select which literal operator to
9638   /// call for a user-defined literal. Look up the provided literal operator
9639   /// name, and filter the results to the appropriate set for the given argument
9640   /// types.
9641   LiteralOperatorLookupResult
9642   LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
9643                         bool AllowRaw, bool AllowTemplate,
9644                         bool AllowStringTemplate, bool DiagnoseMissing,
9645                         StringLiteral *StringLit = nullptr);
9646 
9647   void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
9648                                ArrayRef<Expr *> Args, ADLResult &Functions);
9649 
9650   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9651                           VisibleDeclConsumer &Consumer,
9652                           bool IncludeGlobalScope = true,
9653                           bool LoadExternal = true);
9654   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9655                           VisibleDeclConsumer &Consumer,
9656                           bool IncludeGlobalScope = true,
9657                           bool IncludeDependentBases = false,
9658                           bool LoadExternal = true);
9659 
9660   /// Try to "correct" a typo in the source code by finding
9661   /// visible declarations whose names are similar to the name that was
9662   /// present in the source code.
9663   ///
9664   /// \param TypoName the \c DeclarationNameInfo structure that contains
9665   /// the name that was present in the source code along with its location.
9666   ///
9667   /// \param LookupKind the name-lookup criteria used to search for the name.
9668   ///
9669   /// \param S the scope in which name lookup occurs.
9670   ///
9671   /// \param SS the nested-name-specifier that precedes the name we're
9672   /// looking for, if present.
9673   ///
9674   /// \param CCC A CorrectionCandidateCallback object that provides further
9675   /// validation of typo correction candidates. It also provides flags for
9676   /// determining the set of keywords permitted.
9677   ///
9678   /// \param MemberContext if non-NULL, the context in which to look for
9679   /// a member access expression.
9680   ///
9681   /// \param EnteringContext whether we're entering the context described by
9682   /// the nested-name-specifier SS.
9683   ///
9684   /// \param OPT when non-NULL, the search for visible declarations will
9685   /// also walk the protocols in the qualified interfaces of \p OPT.
9686   ///
9687   /// \returns a \c TypoCorrection containing the corrected name if the typo
9688   /// along with information such as the \c NamedDecl where the corrected name
9689   /// was declared, and any additional \c NestedNameSpecifier needed to access
9690   /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9691   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
9692                              Sema::LookupNameKind LookupKind, Scope *S,
9693                              CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9694                              CorrectTypoKind Mode,
9695                              DeclContext *MemberContext = nullptr,
9696                              bool EnteringContext = false,
9697                              const ObjCObjectPointerType *OPT = nullptr,
9698                              bool RecordFailure = true);
9699 
9700   /// Kinds of missing import. Note, the values of these enumerators correspond
9701   /// to %select values in diagnostics.
9702   enum class MissingImportKind {
9703     Declaration,
9704     Definition,
9705     DefaultArgument,
9706     ExplicitSpecialization,
9707     PartialSpecialization
9708   };
9709 
9710   /// Diagnose that the specified declaration needs to be visible but
9711   /// isn't, and suggest a module import that would resolve the problem.
9712   void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9713                              MissingImportKind MIK, bool Recover = true);
9714   void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9715                              SourceLocation DeclLoc, ArrayRef<Module *> Modules,
9716                              MissingImportKind MIK, bool Recover);
9717 
9718   /// Called on #pragma clang __debug dump II
9719   void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9720 
9721   /// Called on #pragma clang __debug dump E
9722   void ActOnPragmaDump(Expr *E);
9723 
9724 private:
9725   // The set of known/encountered (unique, canonicalized) NamespaceDecls.
9726   //
9727   // The boolean value will be true to indicate that the namespace was loaded
9728   // from an AST/PCH file, or false otherwise.
9729   llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
9730 
9731   /// Whether we have already loaded known namespaces from an extenal
9732   /// source.
9733   bool LoadedExternalKnownNamespaces;
9734 
9735   bool CppLookupName(LookupResult &R, Scope *S);
9736 
9737   /// Determine if we could use all the declarations in the module.
9738   bool isUsableModule(const Module *M);
9739 
9740   /// Helper for CorrectTypo used to create and populate a new
9741   /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
9742   /// skipped entirely.
9743   std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
9744       const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
9745       Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9746       DeclContext *MemberContext, bool EnteringContext,
9747       const ObjCObjectPointerType *OPT, bool ErrorRecovery);
9748 
9749   /// Cache for module units which is usable for current module.
9750   llvm::DenseSet<const Module *> UsableModuleUnitsCache;
9751 
9752   /// Record the typo correction failure and return an empty correction.
9753   TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
9754                                   bool RecordFailure = true) {
9755     if (RecordFailure)
9756       TypoCorrectionFailures[Typo].insert(TypoLoc);
9757     return TypoCorrection();
9758   }
9759 
9760   bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
9761 
9762   /// Determine whether two declarations should be linked together, given that
9763   /// the old declaration might not be visible and the new declaration might
9764   /// not have external linkage.
shouldLinkPossiblyHiddenDecl(const NamedDecl * Old,const NamedDecl * New)9765   bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
9766                                     const NamedDecl *New) {
9767     if (isVisible(Old))
9768       return true;
9769     // See comment in below overload for why it's safe to compute the linkage
9770     // of the new declaration here.
9771     if (New->isExternallyDeclarable()) {
9772       assert(Old->isExternallyDeclarable() &&
9773              "should not have found a non-externally-declarable previous decl");
9774       return true;
9775     }
9776     return false;
9777   }
9778   bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
9779 
9780   ///@}
9781 
9782   //
9783   //
9784   // -------------------------------------------------------------------------
9785   //
9786   //
9787 
9788   /// \name Modules
9789   /// Implementations are in SemaModule.cpp
9790   ///@{
9791 
9792 public:
9793   /// Get the module unit whose scope we are currently within.
getCurrentModule()9794   Module *getCurrentModule() const {
9795     return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
9796   }
9797 
9798   /// Is the module scope we are an implementation unit?
currentModuleIsImplementation()9799   bool currentModuleIsImplementation() const {
9800     return ModuleScopes.empty()
9801                ? false
9802                : ModuleScopes.back().Module->isModuleImplementation();
9803   }
9804 
9805   // When loading a non-modular PCH files, this is used to restore module
9806   // visibility.
makeModuleVisible(Module * Mod,SourceLocation ImportLoc)9807   void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
9808     VisibleModules.setVisible(Mod, ImportLoc);
9809   }
9810 
9811   enum class ModuleDeclKind {
9812     Interface,               ///< 'export module X;'
9813     Implementation,          ///< 'module X;'
9814     PartitionInterface,      ///< 'export module X:Y;'
9815     PartitionImplementation, ///< 'module X:Y;'
9816   };
9817 
9818   /// An enumeration to represent the transition of states in parsing module
9819   /// fragments and imports.  If we are not parsing a C++20 TU, or we find
9820   /// an error in state transition, the state is set to NotACXX20Module.
9821   enum class ModuleImportState {
9822     FirstDecl,      ///< Parsing the first decl in a TU.
9823     GlobalFragment, ///< after 'module;' but before 'module X;'
9824     ImportAllowed,  ///< after 'module X;' but before any non-import decl.
9825     ImportFinished, ///< after any non-import decl.
9826     PrivateFragmentImportAllowed,  ///< after 'module :private;' but before any
9827                                    ///< non-import decl.
9828     PrivateFragmentImportFinished, ///< after 'module :private;' but a
9829                                    ///< non-import decl has already been seen.
9830     NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
9831   };
9832 
9833   /// The parser has processed a module-declaration that begins the definition
9834   /// of a module interface or implementation.
9835   DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
9836                                  SourceLocation ModuleLoc, ModuleDeclKind MDK,
9837                                  ModuleIdPath Path, ModuleIdPath Partition,
9838                                  ModuleImportState &ImportState,
9839                                  bool SeenNoTrivialPPDirective);
9840 
9841   /// The parser has processed a global-module-fragment declaration that begins
9842   /// the definition of the global module fragment of the current module unit.
9843   /// \param ModuleLoc The location of the 'module' keyword.
9844   DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
9845 
9846   /// The parser has processed a private-module-fragment declaration that begins
9847   /// the definition of the private module fragment of the current module unit.
9848   /// \param ModuleLoc The location of the 'module' keyword.
9849   /// \param PrivateLoc The location of the 'private' keyword.
9850   DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
9851                                                 SourceLocation PrivateLoc);
9852 
9853   /// The parser has processed a module import declaration.
9854   ///
9855   /// \param StartLoc The location of the first token in the declaration. This
9856   ///        could be the location of an '@', 'export', or 'import'.
9857   /// \param ExportLoc The location of the 'export' keyword, if any.
9858   /// \param ImportLoc The location of the 'import' keyword.
9859   /// \param Path The module toplevel name as an access path.
9860   /// \param IsPartition If the name is for a partition.
9861   DeclResult ActOnModuleImport(SourceLocation StartLoc,
9862                                SourceLocation ExportLoc,
9863                                SourceLocation ImportLoc, ModuleIdPath Path,
9864                                bool IsPartition = false);
9865   DeclResult ActOnModuleImport(SourceLocation StartLoc,
9866                                SourceLocation ExportLoc,
9867                                SourceLocation ImportLoc, Module *M,
9868                                ModuleIdPath Path = {});
9869 
9870   /// The parser has processed a module import translated from a
9871   /// #include or similar preprocessing directive.
9872   void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
9873   void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
9874 
9875   /// The parsed has entered a submodule.
9876   void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
9877   /// The parser has left a submodule.
9878   void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
9879 
9880   /// Create an implicit import of the given module at the given
9881   /// source location, for error recovery, if possible.
9882   ///
9883   /// This routine is typically used when an entity found by name lookup
9884   /// is actually hidden within a module that we know about but the user
9885   /// has forgotten to import.
9886   void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
9887                                                   Module *Mod);
9888 
9889   /// We have parsed the start of an export declaration, including the '{'
9890   /// (if present).
9891   Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
9892                              SourceLocation LBraceLoc);
9893 
9894   /// Complete the definition of an export declaration.
9895   Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
9896                               SourceLocation RBraceLoc);
9897 
9898 private:
9899   /// The parser has begun a translation unit to be compiled as a C++20
9900   /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
9901   void HandleStartOfHeaderUnit();
9902 
9903   struct ModuleScope {
9904     SourceLocation BeginLoc;
9905     clang::Module *Module = nullptr;
9906     VisibleModuleSet OuterVisibleModules;
9907   };
9908   /// The modules we're currently parsing.
9909   llvm::SmallVector<ModuleScope, 16> ModuleScopes;
9910 
9911   /// For an interface unit, this is the implicitly imported interface unit.
9912   clang::Module *ThePrimaryInterface = nullptr;
9913 
9914   /// The explicit global module fragment of the current translation unit.
9915   /// The explicit Global Module Fragment, as specified in C++
9916   /// [module.global.frag].
9917   clang::Module *TheGlobalModuleFragment = nullptr;
9918 
9919   /// The implicit global module fragments of the current translation unit.
9920   ///
9921   /// The contents in the implicit global module fragment can't be discarded.
9922   clang::Module *TheImplicitGlobalModuleFragment = nullptr;
9923 
9924   /// Namespace definitions that we will export when they finish.
9925   llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
9926 
9927   /// In a C++ standard module, inline declarations require a definition to be
9928   /// present at the end of a definition domain.  This set holds the decls to
9929   /// be checked at the end of the TU.
9930   llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
9931 
9932   /// Helper function to judge if we are in module purview.
9933   /// Return false if we are not in a module.
9934   bool isCurrentModulePurview() const;
9935 
9936   /// Enter the scope of the explicit global module fragment.
9937   Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
9938   /// Leave the scope of the explicit global module fragment.
9939   void PopGlobalModuleFragment();
9940 
9941   /// Enter the scope of an implicit global module fragment.
9942   Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
9943   /// Leave the scope of an implicit global module fragment.
9944   void PopImplicitGlobalModuleFragment();
9945 
9946   VisibleModuleSet VisibleModules;
9947 
9948   ///@}
9949 
9950   //
9951   //
9952   // -------------------------------------------------------------------------
9953   //
9954   //
9955 
9956   /// \name C++ Overloading
9957   /// Implementations are in SemaOverload.cpp
9958   ///@{
9959 
9960 public:
9961   /// Whether deferrable diagnostics should be deferred.
9962   bool DeferDiags = false;
9963 
9964   /// RAII class to control scope of DeferDiags.
9965   class DeferDiagsRAII {
9966     Sema &S;
9967     bool SavedDeferDiags = false;
9968 
9969   public:
DeferDiagsRAII(Sema & S,bool DeferDiags)9970     DeferDiagsRAII(Sema &S, bool DeferDiags)
9971         : S(S), SavedDeferDiags(S.DeferDiags) {
9972       S.DeferDiags = DeferDiags;
9973     }
~DeferDiagsRAII()9974     ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
9975   };
9976 
9977   /// Flag indicating if Sema is building a recovery call expression.
9978   ///
9979   /// This flag is used to avoid building recovery call expressions
9980   /// if Sema is already doing so, which would cause infinite recursions.
9981   bool IsBuildingRecoveryCallExpr;
9982 
9983   /// Determine whether the given New declaration is an overload of the
9984   /// declarations in Old. This routine returns OverloadKind::Match or
9985   /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
9986   /// New has the same signature as some function in Old (C++ 1.3.10) or if the
9987   /// Old declarations aren't functions (or function templates) at all. When it
9988   /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
9989   /// will point to the decl that New cannot be overloaded with. This decl may
9990   /// be a UsingShadowDecl on top of the underlying declaration.
9991   ///
9992   /// Example: Given the following input:
9993   ///
9994   ///   void f(int, float); // #1
9995   ///   void f(int, int); // #2
9996   ///   int f(int, int); // #3
9997   ///
9998   /// When we process #1, there is no previous declaration of "f", so IsOverload
9999   /// will not be used.
10000   ///
10001   /// When we process #2, Old contains only the FunctionDecl for #1. By
10002   /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10003   /// they have different signatures), so this routine returns
10004   /// OverloadKind::Overload; MatchedDecl is unchanged.
10005   ///
10006   /// When we process #3, Old is an overload set containing #1 and #2. We
10007   /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10008   /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10009   /// types of functions are not part of the signature), IsOverload returns
10010   /// OverloadKind::Match and MatchedDecl will be set to point to the
10011   /// FunctionDecl for #2.
10012   ///
10013   /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10014   /// class by a using declaration. The rules for whether to hide shadow
10015   /// declarations ignore some properties which otherwise figure into a function
10016   /// template's signature.
10017   OverloadKind CheckOverload(Scope *S, FunctionDecl *New,
10018                              const LookupResult &OldDecls, NamedDecl *&OldDecl,
10019                              bool UseMemberUsingDeclRules);
10020   bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
10021                   bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10022 
10023   // Checks whether MD constitutes an override the base class method BaseMD.
10024   // When checking for overrides, the object object members are ignored.
10025   bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10026                   bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10027 
10028   enum class AllowedExplicit {
10029     /// Allow no explicit functions to be used.
10030     None,
10031     /// Allow explicit conversion functions but not explicit constructors.
10032     Conversions,
10033     /// Allow both explicit conversion functions and explicit constructors.
10034     All
10035   };
10036 
10037   ImplicitConversionSequence TryImplicitConversion(
10038       Expr *From, QualType ToType, bool SuppressUserConversions,
10039       AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10040       bool AllowObjCWritebackConversion);
10041 
10042   /// PerformImplicitConversion - Perform an implicit conversion of the
10043   /// expression From to the type ToType. Returns the
10044   /// converted expression. Flavor is the kind of conversion we're
10045   /// performing, used in the error message. If @p AllowExplicit,
10046   /// explicit user-defined conversions are permitted.
10047   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10048                                        AssignmentAction Action,
10049                                        bool AllowExplicit = false);
10050 
10051   /// IsIntegralPromotion - Determines whether the conversion from the
10052   /// expression From (whose potentially-adjusted type is FromType) to
10053   /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10054   /// sets PromotedType to the promoted type.
10055   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10056 
10057   /// IsFloatingPointPromotion - Determines whether the conversion from
10058   /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10059   /// returns true and sets PromotedType to the promoted type.
10060   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10061 
10062   /// Determine if a conversion is a complex promotion.
10063   ///
10064   /// A complex promotion is defined as a complex -> complex conversion
10065   /// where the conversion between the underlying real types is a
10066   /// floating-point or integral promotion.
10067   bool IsComplexPromotion(QualType FromType, QualType ToType);
10068 
10069   /// IsPointerConversion - Determines whether the conversion of the
10070   /// expression From, which has the (possibly adjusted) type FromType,
10071   /// can be converted to the type ToType via a pointer conversion (C++
10072   /// 4.10). If so, returns true and places the converted type (that
10073   /// might differ from ToType in its cv-qualifiers at some level) into
10074   /// ConvertedType.
10075   ///
10076   /// This routine also supports conversions to and from block pointers
10077   /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10078   /// pointers to interfaces. FIXME: Once we've determined the
10079   /// appropriate overloading rules for Objective-C, we may want to
10080   /// split the Objective-C checks into a different routine; however,
10081   /// GCC seems to consider all of these conversions to be pointer
10082   /// conversions, so for now they live here. IncompatibleObjC will be
10083   /// set if the conversion is an allowed Objective-C conversion that
10084   /// should result in a warning.
10085   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10086                            bool InOverloadResolution, QualType &ConvertedType,
10087                            bool &IncompatibleObjC);
10088 
10089   /// isObjCPointerConversion - Determines whether this is an
10090   /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10091   /// with the same arguments and return values.
10092   bool isObjCPointerConversion(QualType FromType, QualType ToType,
10093                                QualType &ConvertedType, bool &IncompatibleObjC);
10094   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10095                                 QualType &ConvertedType);
10096 
10097   /// FunctionParamTypesAreEqual - This routine checks two function proto types
10098   /// for equality of their parameter types. Caller has already checked that
10099   /// they have same number of parameters.  If the parameters are different,
10100   /// ArgPos will have the parameter index of the first different parameter.
10101   /// If `Reversed` is true, the parameters of `NewType` will be compared in
10102   /// reverse order. That's useful if one of the functions is being used as a
10103   /// C++20 synthesized operator overload with a reversed parameter order.
10104   bool FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
10105                                   ArrayRef<QualType> New,
10106                                   unsigned *ArgPos = nullptr,
10107                                   bool Reversed = false);
10108 
10109   bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
10110                                   const FunctionProtoType *NewType,
10111                                   unsigned *ArgPos = nullptr,
10112                                   bool Reversed = false);
10113 
10114   bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10115                                            const FunctionDecl *NewFunction,
10116                                            unsigned *ArgPos = nullptr,
10117                                            bool Reversed = false);
10118 
10119   /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10120   /// function types.  Catches different number of parameter, mismatch in
10121   /// parameter types, and different return types.
10122   void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType,
10123                                   QualType ToType);
10124 
10125   /// CheckPointerConversion - Check the pointer conversion from the
10126   /// expression From to the type ToType. This routine checks for
10127   /// ambiguous or inaccessible derived-to-base pointer
10128   /// conversions for which IsPointerConversion has already returned
10129   /// true. It returns true and produces a diagnostic if there was an
10130   /// error, or returns false otherwise.
10131   bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10132                               CXXCastPath &BasePath, bool IgnoreBaseAccess,
10133                               bool Diagnose = true);
10134 
10135   /// IsMemberPointerConversion - Determines whether the conversion of the
10136   /// expression From, which has the (possibly adjusted) type FromType, can be
10137   /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10138   /// If so, returns true and places the converted type (that might differ from
10139   /// ToType in its cv-qualifiers at some level) into ConvertedType.
10140   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10141                                  bool InOverloadResolution,
10142                                  QualType &ConvertedType);
10143 
10144   enum class MemberPointerConversionResult {
10145     Success,
10146     DifferentPointee,
10147     NotDerived,
10148     Ambiguous,
10149     Virtual,
10150     Inaccessible
10151   };
10152   enum class MemberPointerConversionDirection : bool { Downcast, Upcast };
10153   /// CheckMemberPointerConversion - Check the member pointer conversion from
10154   /// the expression From to the type ToType. This routine checks for ambiguous
10155   /// or virtual or inaccessible base-to-derived member pointer conversions for
10156   /// which IsMemberPointerConversion has already returned true. It produces a
10157   // diagnostic if there was an error.
10158   MemberPointerConversionResult CheckMemberPointerConversion(
10159       QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10160       CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10161       bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10162 
10163   /// IsQualificationConversion - Determines whether the conversion from
10164   /// an rvalue of type FromType to ToType is a qualification conversion
10165   /// (C++ 4.4).
10166   ///
10167   /// \param ObjCLifetimeConversion Output parameter that will be set to
10168   /// indicate when the qualification conversion involves a change in the
10169   /// Objective-C object lifetime.
10170   bool IsQualificationConversion(QualType FromType, QualType ToType,
10171                                  bool CStyle, bool &ObjCLifetimeConversion);
10172 
10173   /// Determine whether the conversion from FromType to ToType is a valid
10174   /// conversion that strips "noexcept" or "noreturn" or "cfi_unchecked_callee"
10175   /// off the nested function type. This also checks if "cfi_unchecked_callee"
10176   /// was added to the function type. If "cfi_unchecked_callee" is added and
10177   /// `AddingCFIUncheckedCallee` is provided, it will be set to true. The same
10178   /// thing applies for `DiscardingCFIUncheckedCallee` if the attribute is
10179   /// discarded.
10180   bool IsFunctionConversion(QualType FromType, QualType ToType,
10181                             bool *DiscardingCFIUncheckedCallee = nullptr,
10182                             bool *AddingCFIUncheckedCallee = nullptr) const;
10183 
10184   /// Same as `IsFunctionConversion`, but if this would return true, it sets
10185   /// `ResultTy` to `ToType`.
10186   bool TryFunctionConversion(QualType FromType, QualType ToType,
10187                              QualType &ResultTy) const;
10188 
10189   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
10190   void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
10191                                     DeclarationName Name,
10192                                     OverloadCandidateSet &CandidateSet,
10193                                     FunctionDecl *Fn, MultiExprArg Args,
10194                                     bool IsMember = false);
10195 
10196   ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
10197                                               FunctionDecl *Fun);
10198   ExprResult PerformImplicitObjectArgumentInitialization(
10199       Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
10200       CXXMethodDecl *Method);
10201 
10202   /// PerformContextuallyConvertToBool - Perform a contextual conversion
10203   /// of the expression From to bool (C++0x [conv]p3).
10204   ExprResult PerformContextuallyConvertToBool(Expr *From);
10205 
10206   /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10207   /// conversion of the expression From to an Objective-C pointer type.
10208   /// Returns a valid but null ExprResult if no conversion sequence exists.
10209   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
10210 
10211   ExprResult BuildConvertedConstantExpression(Expr *From, QualType T,
10212                                               CCEKind CCE,
10213                                               NamedDecl *Dest = nullptr);
10214 
10215   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10216                                               llvm::APSInt &Value, CCEKind CCE);
10217   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10218                                               APValue &Value, CCEKind CCE,
10219                                               NamedDecl *Dest = nullptr);
10220 
10221   /// EvaluateConvertedConstantExpression - Evaluate an Expression
10222   /// That is a converted constant expression
10223   /// (which was built with BuildConvertedConstantExpression)
10224   ExprResult
10225   EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
10226                                       CCEKind CCE, bool RequireInt,
10227                                       const APValue &PreNarrowingValue);
10228 
10229   /// Abstract base class used to perform a contextual implicit
10230   /// conversion from an expression to any type passing a filter.
10231   class ContextualImplicitConverter {
10232   public:
10233     bool Suppress;
10234     bool SuppressConversion;
10235 
10236     ContextualImplicitConverter(bool Suppress = false,
10237                                 bool SuppressConversion = false)
Suppress(Suppress)10238         : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
10239 
10240     /// Determine whether the specified type is a valid destination type
10241     /// for this conversion.
10242     virtual bool match(QualType T) = 0;
10243 
10244     /// Emits a diagnostic complaining that the expression does not have
10245     /// integral or enumeration type.
10246     virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10247                                                   QualType T) = 0;
10248 
10249     /// Emits a diagnostic when the expression has incomplete class type.
10250     virtual SemaDiagnosticBuilder
10251     diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
10252 
10253     /// Emits a diagnostic when the only matching conversion function
10254     /// is explicit.
10255     virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S,
10256                                                        SourceLocation Loc,
10257                                                        QualType T,
10258                                                        QualType ConvTy) = 0;
10259 
10260     /// Emits a note for the explicit conversion function.
10261     virtual SemaDiagnosticBuilder
10262     noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10263 
10264     /// Emits a diagnostic when there are multiple possible conversion
10265     /// functions.
10266     virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10267                                                     QualType T) = 0;
10268 
10269     /// Emits a note for one of the candidate conversions.
10270     virtual SemaDiagnosticBuilder
10271     noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10272 
10273     /// Emits a diagnostic when we picked a conversion function
10274     /// (for cases when we are not allowed to pick a conversion function).
10275     virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S,
10276                                                      SourceLocation Loc,
10277                                                      QualType T,
10278                                                      QualType ConvTy) = 0;
10279 
~ContextualImplicitConverter()10280     virtual ~ContextualImplicitConverter() {}
10281   };
10282 
10283   class ICEConvertDiagnoser : public ContextualImplicitConverter {
10284     bool AllowScopedEnumerations;
10285 
10286   public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,bool Suppress,bool SuppressConversion)10287     ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10288                         bool SuppressConversion)
10289         : ContextualImplicitConverter(Suppress, SuppressConversion),
10290           AllowScopedEnumerations(AllowScopedEnumerations) {}
10291 
10292     /// Match an integral or (possibly scoped) enumeration type.
10293     bool match(QualType T) override;
10294 
diagnoseNoMatch(Sema & S,SourceLocation Loc,QualType T)10295     SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10296                                           QualType T) override {
10297       return diagnoseNotInt(S, Loc, T);
10298     }
10299 
10300     /// Emits a diagnostic complaining that the expression does not have
10301     /// integral or enumeration type.
10302     virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10303                                                  QualType T) = 0;
10304   };
10305 
10306   /// Perform a contextual implicit conversion.
10307   ExprResult
10308   PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE,
10309                                       ContextualImplicitConverter &Converter);
10310 
10311   /// ReferenceCompareResult - Expresses the result of comparing two
10312   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10313   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10314   enum ReferenceCompareResult {
10315     /// Ref_Incompatible - The two types are incompatible, so direct
10316     /// reference binding is not possible.
10317     Ref_Incompatible = 0,
10318     /// Ref_Related - The two types are reference-related, which means
10319     /// that their unqualified forms (T1 and T2) are either the same
10320     /// or T1 is a base class of T2.
10321     Ref_Related,
10322     /// Ref_Compatible - The two types are reference-compatible.
10323     Ref_Compatible
10324   };
10325 
10326   // Fake up a scoped enumeration that still contextually converts to bool.
10327   struct ReferenceConversionsScope {
10328     /// The conversions that would be performed on an lvalue of type T2 when
10329     /// binding a reference of type T1 to it, as determined when evaluating
10330     /// whether T1 is reference-compatible with T2.
10331     enum ReferenceConversions {
10332       Qualification = 0x1,
10333       NestedQualification = 0x2,
10334       Function = 0x4,
10335       DerivedToBase = 0x8,
10336       ObjC = 0x10,
10337       ObjCLifetime = 0x20,
10338 
10339       LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
10340     };
10341   };
10342   using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
10343 
10344   /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10345   /// determine whether they are reference-compatible,
10346   /// reference-related, or incompatible, for use in C++ initialization by
10347   /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10348   /// type, and the first type (T1) is the pointee type of the reference
10349   /// type being initialized.
10350   ReferenceCompareResult
10351   CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
10352                                ReferenceConversions *Conv = nullptr);
10353 
10354   /// AddOverloadCandidate - Adds the given function to the set of
10355   /// candidate functions, using the given function call arguments.  If
10356   /// @p SuppressUserConversions, then don't allow user-defined
10357   /// conversions via constructors or conversion operators.
10358   ///
10359   /// \param PartialOverloading true if we are performing "partial" overloading
10360   /// based on an incomplete set of function arguments. This feature is used by
10361   /// code completion.
10362   void AddOverloadCandidate(
10363       FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
10364       OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10365       bool PartialOverloading = false, bool AllowExplicit = true,
10366       bool AllowExplicitConversion = false,
10367       ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10368       ConversionSequenceList EarlyConversions = {},
10369       OverloadCandidateParamOrder PO = {},
10370       bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10371 
10372   /// Add all of the function declarations in the given function set to
10373   /// the overload candidate set.
10374   void AddFunctionCandidates(
10375       const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10376       OverloadCandidateSet &CandidateSet,
10377       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10378       bool SuppressUserConversions = false, bool PartialOverloading = false,
10379       bool FirstArgumentIsBase = false);
10380 
10381   /// AddMethodCandidate - Adds a named decl (which is some kind of
10382   /// method) as a method candidate to the given overload set.
10383   void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10384                           Expr::Classification ObjectClassification,
10385                           ArrayRef<Expr *> Args,
10386                           OverloadCandidateSet &CandidateSet,
10387                           bool SuppressUserConversion = false,
10388                           OverloadCandidateParamOrder PO = {});
10389 
10390   /// AddMethodCandidate - Adds the given C++ member function to the set
10391   /// of candidate functions, using the given function call arguments
10392   /// and the object argument (@c Object). For example, in a call
10393   /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10394   /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10395   /// allow user-defined conversions via constructors or conversion
10396   /// operators.
10397   void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10398                           CXXRecordDecl *ActingContext, QualType ObjectType,
10399                           Expr::Classification ObjectClassification,
10400                           ArrayRef<Expr *> Args,
10401                           OverloadCandidateSet &CandidateSet,
10402                           bool SuppressUserConversions = false,
10403                           bool PartialOverloading = false,
10404                           ConversionSequenceList EarlyConversions = {},
10405                           OverloadCandidateParamOrder PO = {},
10406                           bool StrictPackMatch = false);
10407 
10408   /// Add a C++ member function template as a candidate to the candidate
10409   /// set, using template argument deduction to produce an appropriate member
10410   /// function template specialization.
10411   void AddMethodTemplateCandidate(
10412       FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10413       CXXRecordDecl *ActingContext,
10414       TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10415       Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10416       OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10417       bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10418 
10419   /// Add a C++ function template specialization as a candidate
10420   /// in the candidate set, using template argument deduction to produce
10421   /// an appropriate function template specialization.
10422   void AddTemplateOverloadCandidate(
10423       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10424       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10425       OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10426       bool PartialOverloading = false, bool AllowExplicit = true,
10427       ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10428       OverloadCandidateParamOrder PO = {},
10429       bool AggregateCandidateDeduction = false);
10430 
10431   struct CheckNonDependentConversionsFlag {
10432     /// Do not consider any user-defined conversions when constructing the
10433     /// initializing sequence.
10434     bool SuppressUserConversions;
10435 
10436     /// Before constructing the initializing sequence, we check whether the
10437     /// parameter type and argument type contain any user defined conversions.
10438     /// If so, do not initialize them. This effectively bypasses some undesired
10439     /// instantiation before checking constaints, which might otherwise result
10440     /// in non-SFINAE errors e.g. recursive constraints.
10441     bool OnlyInitializeNonUserDefinedConversions;
10442 
CheckNonDependentConversionsFlagCheckNonDependentConversionsFlag10443     CheckNonDependentConversionsFlag(
10444         bool SuppressUserConversions,
10445         bool OnlyInitializeNonUserDefinedConversions)
10446         : SuppressUserConversions(SuppressUserConversions),
10447           OnlyInitializeNonUserDefinedConversions(
10448               OnlyInitializeNonUserDefinedConversions) {}
10449   };
10450 
10451   /// Check that implicit conversion sequences can be formed for each argument
10452   /// whose corresponding parameter has a non-dependent type, per DR1391's
10453   /// [temp.deduct.call]p10.
10454   bool CheckNonDependentConversions(
10455       FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
10456       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10457       ConversionSequenceList &Conversions,
10458       CheckNonDependentConversionsFlag UserConversionFlag,
10459       CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10460       Expr::Classification ObjectClassification = {},
10461       OverloadCandidateParamOrder PO = {});
10462 
10463   /// AddConversionCandidate - Add a C++ conversion function as a
10464   /// candidate in the candidate set (C++ [over.match.conv],
10465   /// C++ [over.match.copy]). From is the expression we're converting from,
10466   /// and ToType is the type that we're eventually trying to convert to
10467   /// (which may or may not be the same type as the type that the
10468   /// conversion function produces).
10469   void AddConversionCandidate(
10470       CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10471       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10472       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10473       bool AllowExplicit, bool AllowResultConversion = true,
10474       bool StrictPackMatch = false);
10475 
10476   /// Adds a conversion function template specialization
10477   /// candidate to the overload set, using template argument deduction
10478   /// to deduce the template arguments of the conversion function
10479   /// template from the type that we are converting to (C++
10480   /// [temp.deduct.conv]).
10481   void AddTemplateConversionCandidate(
10482       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10483       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10484       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10485       bool AllowExplicit, bool AllowResultConversion = true);
10486 
10487   /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10488   /// converts the given @c Object to a function pointer via the
10489   /// conversion function @c Conversion, and then attempts to call it
10490   /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10491   /// the type of function that we'll eventually be calling.
10492   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10493                              DeclAccessPair FoundDecl,
10494                              CXXRecordDecl *ActingContext,
10495                              const FunctionProtoType *Proto, Expr *Object,
10496                              ArrayRef<Expr *> Args,
10497                              OverloadCandidateSet &CandidateSet);
10498 
10499   /// Add all of the non-member operator function declarations in the given
10500   /// function set to the overload candidate set.
10501   void AddNonMemberOperatorCandidates(
10502       const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10503       OverloadCandidateSet &CandidateSet,
10504       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10505 
10506   /// Add overload candidates for overloaded operators that are
10507   /// member functions.
10508   ///
10509   /// Add the overloaded operator candidates that are member functions
10510   /// for the operator Op that was used in an operator expression such
10511   /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10512   /// CandidateSet will store the added overload candidates. (C++
10513   /// [over.match.oper]).
10514   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
10515                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
10516                                    OverloadCandidateSet &CandidateSet,
10517                                    OverloadCandidateParamOrder PO = {});
10518 
10519   /// AddBuiltinCandidate - Add a candidate for a built-in
10520   /// operator. ResultTy and ParamTys are the result and parameter types
10521   /// of the built-in candidate, respectively. Args and NumArgs are the
10522   /// arguments being passed to the candidate. IsAssignmentOperator
10523   /// should be true when this built-in candidate is an assignment
10524   /// operator. NumContextualBoolArguments is the number of arguments
10525   /// (at the beginning of the argument list) that will be contextually
10526   /// converted to bool.
10527   void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10528                            OverloadCandidateSet &CandidateSet,
10529                            bool IsAssignmentOperator = false,
10530                            unsigned NumContextualBoolArguments = 0);
10531 
10532   /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10533   /// operator overloads to the candidate set (C++ [over.built]), based
10534   /// on the operator @p Op and the arguments given. For example, if the
10535   /// operator is a binary '+', this routine might add "int
10536   /// operator+(int, int)" to cover integer addition.
10537   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10538                                     SourceLocation OpLoc, ArrayRef<Expr *> Args,
10539                                     OverloadCandidateSet &CandidateSet);
10540 
10541   /// Add function candidates found via argument-dependent lookup
10542   /// to the set of overloading candidates.
10543   ///
10544   /// This routine performs argument-dependent name lookup based on the
10545   /// given function name (which may also be an operator name) and adds
10546   /// all of the overload candidates found by ADL to the overload
10547   /// candidate set (C++ [basic.lookup.argdep]).
10548   void AddArgumentDependentLookupCandidates(
10549       DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10550       TemplateArgumentListInfo *ExplicitTemplateArgs,
10551       OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10552 
10553   /// Check the enable_if expressions on the given function. Returns the first
10554   /// failing attribute, or NULL if they were all successful.
10555   EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10556                               ArrayRef<Expr *> Args,
10557                               bool MissingImplicitThis = false);
10558 
10559   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10560   /// non-ArgDependent DiagnoseIfAttrs.
10561   ///
10562   /// Argument-dependent diagnose_if attributes should be checked each time a
10563   /// function is used as a direct callee of a function call.
10564   ///
10565   /// Returns true if any errors were emitted.
10566   bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10567                                            const Expr *ThisArg,
10568                                            ArrayRef<const Expr *> Args,
10569                                            SourceLocation Loc);
10570 
10571   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10572   /// ArgDependent DiagnoseIfAttrs.
10573   ///
10574   /// Argument-independent diagnose_if attributes should be checked on every use
10575   /// of a function.
10576   ///
10577   /// Returns true if any errors were emitted.
10578   bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10579                                              SourceLocation Loc);
10580 
10581   /// Determine if \p A and \p B are equivalent internal linkage declarations
10582   /// from different modules, and thus an ambiguity error can be downgraded to
10583   /// an extension warning.
10584   bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10585                                               const NamedDecl *B);
10586   void diagnoseEquivalentInternalLinkageDeclarations(
10587       SourceLocation Loc, const NamedDecl *D,
10588       ArrayRef<const NamedDecl *> Equiv);
10589 
10590   // Emit as a 'note' the specific overload candidate
10591   void NoteOverloadCandidate(
10592       const NamedDecl *Found, const FunctionDecl *Fn,
10593       OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
10594       QualType DestType = QualType(), bool TakingAddress = false);
10595 
10596   // Emit as a series of 'note's all template and non-templates identified by
10597   // the expression Expr
10598   void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10599                                  bool TakingAddress = false);
10600 
10601   /// Returns whether the given function's address can be taken or not,
10602   /// optionally emitting a diagnostic if the address can't be taken.
10603   ///
10604   /// Returns false if taking the address of the function is illegal.
10605   bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10606                                          bool Complain = false,
10607                                          SourceLocation Loc = SourceLocation());
10608 
10609   // [PossiblyAFunctionType]  -->   [Return]
10610   // NonFunctionType --> NonFunctionType
10611   // R (A) --> R(A)
10612   // R (*)(A) --> R (A)
10613   // R (&)(A) --> R (A)
10614   // R (S::*)(A) --> R (A)
10615   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10616 
10617   /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10618   /// an overloaded function (C++ [over.over]), where @p From is an
10619   /// expression with overloaded function type and @p ToType is the type
10620   /// we're trying to resolve to. For example:
10621   ///
10622   /// @code
10623   /// int f(double);
10624   /// int f(int);
10625   ///
10626   /// int (*pfd)(double) = f; // selects f(double)
10627   /// @endcode
10628   ///
10629   /// This routine returns the resulting FunctionDecl if it could be
10630   /// resolved, and NULL otherwise. When @p Complain is true, this
10631   /// routine will emit diagnostics if there is an error.
10632   FunctionDecl *
10633   ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10634                                      bool Complain, DeclAccessPair &Found,
10635                                      bool *pHadMultipleCandidates = nullptr);
10636 
10637   /// Given an expression that refers to an overloaded function, try to
10638   /// resolve that function to a single function that can have its address
10639   /// taken. This will modify `Pair` iff it returns non-null.
10640   ///
10641   /// This routine can only succeed if from all of the candidates in the
10642   /// overload set for SrcExpr that can have their addresses taken, there is one
10643   /// candidate that is more constrained than the rest.
10644   FunctionDecl *
10645   resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10646 
10647   /// Given an overloaded function, tries to turn it into a non-overloaded
10648   /// function reference using resolveAddressOfSingleOverloadCandidate. This
10649   /// will perform access checks, diagnose the use of the resultant decl, and,
10650   /// if requested, potentially perform a function-to-pointer decay.
10651   ///
10652   /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10653   /// Otherwise, returns true. This may emit diagnostics and return true.
10654   bool resolveAndFixAddressOfSingleOverloadCandidate(
10655       ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10656 
10657   /// Given an expression that refers to an overloaded function, try to
10658   /// resolve that overloaded function expression down to a single function.
10659   ///
10660   /// This routine can only resolve template-ids that refer to a single function
10661   /// template, where that template-id refers to a single template whose
10662   /// template arguments are either provided by the template-id or have
10663   /// defaults, as described in C++0x [temp.arg.explicit]p3.
10664   ///
10665   /// If no template-ids are found, no diagnostics are emitted and NULL is
10666   /// returned.
10667   FunctionDecl *ResolveSingleFunctionTemplateSpecialization(
10668       OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10669       TemplateSpecCandidateSet *FailedTSC = nullptr,
10670       bool ForTypeDeduction = false);
10671 
10672   // Resolve and fix an overloaded expression that can be resolved
10673   // because it identifies a single function template specialization.
10674   //
10675   // Last three arguments should only be supplied if Complain = true
10676   //
10677   // Return true if it was logically possible to so resolve the
10678   // expression, regardless of whether or not it succeeded.  Always
10679   // returns true if 'complain' is set.
10680   bool ResolveAndFixSingleFunctionTemplateSpecialization(
10681       ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10682       bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10683       QualType DestTypeForComplaining = QualType(),
10684       unsigned DiagIDForComplaining = 0);
10685 
10686   /// Add the overload candidates named by callee and/or found by argument
10687   /// dependent lookup to the given overload set.
10688   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10689                                    ArrayRef<Expr *> Args,
10690                                    OverloadCandidateSet &CandidateSet,
10691                                    bool PartialOverloading = false);
10692 
10693   /// Add the call candidates from the given set of lookup results to the given
10694   /// overload set. Non-function lookup results are ignored.
10695   void AddOverloadedCallCandidates(
10696       LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
10697       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
10698 
10699   // An enum used to represent the different possible results of building a
10700   // range-based for loop.
10701   enum ForRangeStatus {
10702     FRS_Success,
10703     FRS_NoViableFunction,
10704     FRS_DiagnosticIssued
10705   };
10706 
10707   /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
10708   /// given LookupResult is non-empty, it is assumed to describe a member which
10709   /// will be invoked. Otherwise, the function will be found via argument
10710   /// dependent lookup.
10711   /// CallExpr is set to a valid expression and FRS_Success returned on success,
10712   /// otherwise CallExpr is set to ExprError() and some non-success value
10713   /// is returned.
10714   ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
10715                                            SourceLocation RangeLoc,
10716                                            const DeclarationNameInfo &NameInfo,
10717                                            LookupResult &MemberLookup,
10718                                            OverloadCandidateSet *CandidateSet,
10719                                            Expr *Range, ExprResult *CallExpr);
10720 
10721   /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10722   /// (which eventually refers to the declaration Func) and the call
10723   /// arguments Args/NumArgs, attempt to resolve the function call down
10724   /// to a specific function. If overload resolution succeeds, returns
10725   /// the call expression produced by overload resolution.
10726   /// Otherwise, emits diagnostics and returns ExprError.
10727   ExprResult BuildOverloadedCallExpr(
10728       Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
10729       MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
10730       bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
10731 
10732   /// Constructs and populates an OverloadedCandidateSet from
10733   /// the given function.
10734   /// \returns true when an the ExprResult output parameter has been set.
10735   bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
10736                               MultiExprArg Args, SourceLocation RParenLoc,
10737                               OverloadCandidateSet *CandidateSet,
10738                               ExprResult *Result);
10739 
10740   ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
10741                                         NestedNameSpecifierLoc NNSLoc,
10742                                         DeclarationNameInfo DNI,
10743                                         const UnresolvedSetImpl &Fns,
10744                                         bool PerformADL = true);
10745 
10746   /// Create a unary operation that may resolve to an overloaded
10747   /// operator.
10748   ///
10749   /// \param OpLoc The location of the operator itself (e.g., '*').
10750   ///
10751   /// \param Opc The UnaryOperatorKind that describes this operator.
10752   ///
10753   /// \param Fns The set of non-member functions that will be
10754   /// considered by overload resolution. The caller needs to build this
10755   /// set based on the context using, e.g.,
10756   /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10757   /// set should not contain any member functions; those will be added
10758   /// by CreateOverloadedUnaryOp().
10759   ///
10760   /// \param Input The input argument.
10761   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
10762                                      UnaryOperatorKind Opc,
10763                                      const UnresolvedSetImpl &Fns, Expr *input,
10764                                      bool RequiresADL = true);
10765 
10766   /// Perform lookup for an overloaded binary operator.
10767   void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
10768                              OverloadedOperatorKind Op,
10769                              const UnresolvedSetImpl &Fns,
10770                              ArrayRef<Expr *> Args, bool RequiresADL = true);
10771 
10772   /// Create a binary operation that may resolve to an overloaded
10773   /// operator.
10774   ///
10775   /// \param OpLoc The location of the operator itself (e.g., '+').
10776   ///
10777   /// \param Opc The BinaryOperatorKind that describes this operator.
10778   ///
10779   /// \param Fns The set of non-member functions that will be
10780   /// considered by overload resolution. The caller needs to build this
10781   /// set based on the context using, e.g.,
10782   /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10783   /// set should not contain any member functions; those will be added
10784   /// by CreateOverloadedBinOp().
10785   ///
10786   /// \param LHS Left-hand argument.
10787   /// \param RHS Right-hand argument.
10788   /// \param PerformADL Whether to consider operator candidates found by ADL.
10789   /// \param AllowRewrittenCandidates Whether to consider candidates found by
10790   ///        C++20 operator rewrites.
10791   /// \param DefaultedFn If we are synthesizing a defaulted operator function,
10792   ///        the function in question. Such a function is never a candidate in
10793   ///        our overload resolution. This also enables synthesizing a three-way
10794   ///        comparison from < and == as described in C++20 [class.spaceship]p1.
10795   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
10796                                    const UnresolvedSetImpl &Fns, Expr *LHS,
10797                                    Expr *RHS, bool RequiresADL = true,
10798                                    bool AllowRewrittenCandidates = true,
10799                                    FunctionDecl *DefaultedFn = nullptr);
10800   ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
10801                                                 const UnresolvedSetImpl &Fns,
10802                                                 Expr *LHS, Expr *RHS,
10803                                                 FunctionDecl *DefaultedFn);
10804 
10805   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10806                                                 SourceLocation RLoc, Expr *Base,
10807                                                 MultiExprArg Args);
10808 
10809   /// BuildCallToMemberFunction - Build a call to a member
10810   /// function. MemExpr is the expression that refers to the member
10811   /// function (and includes the object parameter), Args/NumArgs are the
10812   /// arguments to the function call (not including the object
10813   /// parameter). The caller needs to validate that the member
10814   /// expression refers to a non-static member function or an overloaded
10815   /// member function.
10816   ExprResult BuildCallToMemberFunction(
10817       Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
10818       SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
10819       bool IsExecConfig = false, bool AllowRecovery = false);
10820 
10821   /// BuildCallToObjectOfClassType - Build a call to an object of class
10822   /// type (C++ [over.call.object]), which can end up invoking an
10823   /// overloaded function call operator (@c operator()) or performing a
10824   /// user-defined conversion on the object argument.
10825   ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object,
10826                                           SourceLocation LParenLoc,
10827                                           MultiExprArg Args,
10828                                           SourceLocation RParenLoc);
10829 
10830   /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
10831   ///  (if one exists), where @c Base is an expression of class type and
10832   /// @c Member is the name of the member we're trying to find.
10833   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
10834                                       SourceLocation OpLoc,
10835                                       bool *NoArrowOperatorFound = nullptr);
10836 
10837   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
10838                                     CXXConversionDecl *Method,
10839                                     bool HadMultipleCandidates);
10840 
10841   /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
10842   /// to a literal operator described by the provided lookup results.
10843   ExprResult BuildLiteralOperatorCall(
10844       LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args,
10845       SourceLocation LitEndLoc,
10846       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10847 
10848   /// FixOverloadedFunctionReference - E is an expression that refers to
10849   /// a C++ overloaded function (possibly with some parentheses and
10850   /// perhaps a '&' around it). We have resolved the overloaded function
10851   /// to the function declaration Fn, so patch up the expression E to
10852   /// refer (possibly indirectly) to Fn. Returns the new expr.
10853   ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl,
10854                                             FunctionDecl *Fn);
10855   ExprResult FixOverloadedFunctionReference(ExprResult,
10856                                             DeclAccessPair FoundDecl,
10857                                             FunctionDecl *Fn);
10858 
10859   /// - Returns a selector which best matches given argument list or
10860   /// nullptr if none could be found
10861   ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
10862                                    bool IsInstance,
10863                                    SmallVectorImpl<ObjCMethodDecl *> &Methods);
10864 
10865   ///@}
10866 
10867   //
10868   //
10869   // -------------------------------------------------------------------------
10870   //
10871   //
10872 
10873   /// \name Statements
10874   /// Implementations are in SemaStmt.cpp
10875   ///@{
10876 
10877 public:
10878   /// Stack of active SEH __finally scopes.  Can be empty.
10879   SmallVector<Scope *, 2> CurrentSEHFinally;
10880 
10881   StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
10882   StmtResult ActOnExprStmtError();
10883 
10884   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
10885                            bool HasLeadingEmptyMacro = false);
10886 
10887   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc,
10888                            SourceLocation EndLoc);
10889   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
10890 
10891   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
10892   /// whose result is unused, warn.
10893   void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
10894 
10895   void ActOnStartOfCompoundStmt(bool IsStmtExpr);
10896   void ActOnAfterCompoundStatementLeadingPragmas();
10897   void ActOnFinishOfCompoundStmt();
10898   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
10899                                ArrayRef<Stmt *> Elts, bool isStmtExpr);
10900 
10901   sema::CompoundScopeInfo &getCurCompoundScope() const;
10902 
10903   ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
10904   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
10905                            SourceLocation DotDotDotLoc, ExprResult RHS,
10906                            SourceLocation ColonLoc);
10907 
10908   /// ActOnCaseStmtBody - This installs a statement as the body of a case.
10909   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
10910 
10911   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
10912                               SourceLocation ColonLoc, Stmt *SubStmt,
10913                               Scope *CurScope);
10914   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
10915                             SourceLocation ColonLoc, Stmt *SubStmt);
10916 
10917   StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
10918                                  ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
10919   StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
10920                                  Stmt *SubStmt);
10921 
10922   /// Check whether the given statement can have musttail applied to it,
10923   /// issuing a diagnostic and returning false if not. In the success case,
10924   /// the statement is rewritten to remove implicit nodes from the return
10925   /// value.
10926   bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
10927 
10928   StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
10929                          SourceLocation LParenLoc, Stmt *InitStmt,
10930                          ConditionResult Cond, SourceLocation RParenLoc,
10931                          Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
10932   StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
10933                          SourceLocation LParenLoc, Stmt *InitStmt,
10934                          ConditionResult Cond, SourceLocation RParenLoc,
10935                          Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
10936 
10937   ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
10938 
10939   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
10940                                     SourceLocation LParenLoc, Stmt *InitStmt,
10941                                     ConditionResult Cond,
10942                                     SourceLocation RParenLoc);
10943   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
10944                                    Stmt *Body);
10945 
10946   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
10947   /// integer not in the range of enum values.
10948   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
10949                               Expr *SrcExpr);
10950 
10951   StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
10952                             ConditionResult Cond, SourceLocation RParenLoc,
10953                             Stmt *Body);
10954   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
10955                          SourceLocation WhileLoc, SourceLocation CondLParen,
10956                          Expr *Cond, SourceLocation CondRParen);
10957 
10958   StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
10959                           Stmt *First, ConditionResult Second,
10960                           FullExprArg Third, SourceLocation RParenLoc,
10961                           Stmt *Body);
10962 
10963   /// In an Objective C collection iteration statement:
10964   ///   for (x in y)
10965   /// x can be an arbitrary l-value expression.  Bind it up as a
10966   /// full-expression.
10967   StmtResult ActOnForEachLValueExpr(Expr *E);
10968 
10969   enum BuildForRangeKind {
10970     /// Initial building of a for-range statement.
10971     BFRK_Build,
10972     /// Instantiation or recovery rebuild of a for-range statement. Don't
10973     /// attempt any typo-correction.
10974     BFRK_Rebuild,
10975     /// Determining whether a for-range statement could be built. Avoid any
10976     /// unnecessary or irreversible actions.
10977     BFRK_Check
10978   };
10979 
10980   /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
10981   ///
10982   /// C++11 [stmt.ranged]:
10983   ///   A range-based for statement is equivalent to
10984   ///
10985   ///   {
10986   ///     auto && __range = range-init;
10987   ///     for ( auto __begin = begin-expr,
10988   ///           __end = end-expr;
10989   ///           __begin != __end;
10990   ///           ++__begin ) {
10991   ///       for-range-declaration = *__begin;
10992   ///       statement
10993   ///     }
10994   ///   }
10995   ///
10996   /// The body of the loop is not available yet, since it cannot be analysed
10997   /// until we have determined the type of the for-range-declaration.
10998   StmtResult ActOnCXXForRangeStmt(
10999       Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11000       Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11001       SourceLocation RParenLoc, BuildForRangeKind Kind,
11002       ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11003 
11004   /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11005   StmtResult BuildCXXForRangeStmt(
11006       SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11007       SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11008       Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11009       BuildForRangeKind Kind,
11010       ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11011 
11012   /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11013   /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11014   /// body cannot be performed until after the type of the range variable is
11015   /// determined.
11016   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11017 
11018   StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11019                            LabelDecl *TheDecl);
11020   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11021                                    SourceLocation StarLoc, Expr *DestExp);
11022   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
11023   StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
11024 
11025   struct NamedReturnInfo {
11026     const VarDecl *Candidate;
11027 
11028     enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
11029     Status S;
11030 
isMoveEligibleNamedReturnInfo11031     bool isMoveEligible() const { return S != None; };
isCopyElidableNamedReturnInfo11032     bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
11033   };
11034   enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
11035 
11036   /// Determine whether the given expression might be move-eligible or
11037   /// copy-elidable in either a (co_)return statement or throw expression,
11038   /// without considering function return type, if applicable.
11039   ///
11040   /// \param E The expression being returned from the function or block,
11041   /// being thrown, or being co_returned from a coroutine. This expression
11042   /// might be modified by the implementation.
11043   ///
11044   /// \param Mode Overrides detection of current language mode
11045   /// and uses the rules for C++23.
11046   ///
11047   /// \returns An aggregate which contains the Candidate and isMoveEligible
11048   /// and isCopyElidable methods. If Candidate is non-null, it means
11049   /// isMoveEligible() would be true under the most permissive language
11050   /// standard.
11051   NamedReturnInfo getNamedReturnInfo(
11052       Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
11053 
11054   /// Determine whether the given NRVO candidate variable is move-eligible or
11055   /// copy-elidable, without considering function return type.
11056   ///
11057   /// \param VD The NRVO candidate variable.
11058   ///
11059   /// \returns An aggregate which contains the Candidate and isMoveEligible
11060   /// and isCopyElidable methods. If Candidate is non-null, it means
11061   /// isMoveEligible() would be true under the most permissive language
11062   /// standard.
11063   NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11064 
11065   /// Updates given NamedReturnInfo's move-eligible and
11066   /// copy-elidable statuses, considering the function
11067   /// return type criteria as applicable to return statements.
11068   ///
11069   /// \param Info The NamedReturnInfo object to update.
11070   ///
11071   /// \param ReturnType This is the return type of the function.
11072   /// \returns The copy elision candidate, in case the initial return expression
11073   /// was copy elidable, or nullptr otherwise.
11074   const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11075                                          QualType ReturnType);
11076 
11077   /// Perform the initialization of a potentially-movable value, which
11078   /// is the result of return value.
11079   ///
11080   /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11081   /// treat returned lvalues as rvalues in certain cases (to prefer move
11082   /// construction), then falls back to treating them as lvalues if that failed.
11083   ExprResult
11084   PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
11085                                   const NamedReturnInfo &NRInfo, Expr *Value,
11086                                   bool SupressSimplerImplicitMoves = false);
11087 
11088   TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
11089 
11090   /// Deduce the return type for a function from a returned expression, per
11091   /// C++1y [dcl.spec.auto]p6.
11092   bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
11093                                         SourceLocation ReturnLoc, Expr *RetExpr,
11094                                         const AutoType *AT);
11095 
11096   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11097                              Scope *CurScope);
11098   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11099                              bool AllowRecovery = false);
11100 
11101   /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11102   /// for capturing scopes.
11103   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11104                                      NamedReturnInfo &NRInfo,
11105                                      bool SupressSimplerImplicitMoves);
11106 
11107   /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11108   /// and creates a proper catch handler from them.
11109   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
11110                                 Stmt *HandlerBlock);
11111 
11112   /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11113   /// handlers and creates a try statement from them.
11114   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
11115                               ArrayRef<Stmt *> Handlers);
11116 
11117   void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11118 
11119   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11120                               SourceLocation TryLoc, Stmt *TryBlock,
11121                               Stmt *Handler);
11122   StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
11123                                  Stmt *Block);
11124   void ActOnStartSEHFinallyBlock();
11125   void ActOnAbortSEHFinallyBlock();
11126   StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
11127   StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
11128 
11129   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
11130                                         bool IsIfExists,
11131                                         NestedNameSpecifierLoc QualifierLoc,
11132                                         DeclarationNameInfo NameInfo,
11133                                         Stmt *Nested);
11134   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
11135                                         bool IsIfExists, CXXScopeSpec &SS,
11136                                         UnqualifiedId &Name, Stmt *Nested);
11137 
11138   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11139                                 CapturedRegionKind Kind, unsigned NumParams);
11140   typedef std::pair<StringRef, QualType> CapturedParamNameType;
11141   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11142                                 CapturedRegionKind Kind,
11143                                 ArrayRef<CapturedParamNameType> Params,
11144                                 unsigned OpenMPCaptureLevel = 0);
11145   StmtResult ActOnCapturedRegionEnd(Stmt *S);
11146   void ActOnCapturedRegionError();
11147   RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
11148                                            SourceLocation Loc,
11149                                            unsigned NumParams);
11150 
11151 private:
11152   /// Check whether the given statement can have musttail applied to it,
11153   /// issuing a diagnostic and returning false if not.
11154   bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11155 
11156   /// Check if the given expression contains 'break' or 'continue'
11157   /// statement that produces control flow different from GCC.
11158   void CheckBreakContinueBinding(Expr *E);
11159 
11160   ///@}
11161 
11162   //
11163   //
11164   // -------------------------------------------------------------------------
11165   //
11166   //
11167 
11168   /// \name `inline asm` Statement
11169   /// Implementations are in SemaStmtAsm.cpp
11170   ///@{
11171 
11172 public:
11173   ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel);
11174   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11175                              bool IsVolatile, unsigned NumOutputs,
11176                              unsigned NumInputs, IdentifierInfo **Names,
11177                              MultiExprArg Constraints, MultiExprArg Exprs,
11178                              Expr *AsmString, MultiExprArg Clobbers,
11179                              unsigned NumLabels, SourceLocation RParenLoc);
11180 
11181   void FillInlineAsmIdentifierInfo(Expr *Res,
11182                                    llvm::InlineAsmIdentifierInfo &Info);
11183   ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
11184                                        SourceLocation TemplateKWLoc,
11185                                        UnqualifiedId &Id,
11186                                        bool IsUnevaluatedContext);
11187   bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11188                             SourceLocation AsmLoc);
11189   ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
11190                                          SourceLocation AsmLoc);
11191   StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
11192                             ArrayRef<Token> AsmToks, StringRef AsmString,
11193                             unsigned NumOutputs, unsigned NumInputs,
11194                             ArrayRef<StringRef> Constraints,
11195                             ArrayRef<StringRef> Clobbers,
11196                             ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11197   LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11198                                    SourceLocation Location, bool AlwaysCreate);
11199 
11200   ///@}
11201 
11202   //
11203   //
11204   // -------------------------------------------------------------------------
11205   //
11206   //
11207 
11208   /// \name Statement Attribute Handling
11209   /// Implementations are in SemaStmtAttr.cpp
11210   ///@{
11211 
11212 public:
11213   bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11214                          const AttributeCommonInfo &A);
11215   bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11216                              const AttributeCommonInfo &A);
11217 
11218   CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11219   bool CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs);
11220 
11221   /// Process the attributes before creating an attributed statement. Returns
11222   /// the semantic attributes that have been processed.
11223   void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11224                              SmallVectorImpl<const Attr *> &OutAttrs);
11225 
11226   ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A,
11227                                 SourceRange Range);
11228   ExprResult BuildCXXAssumeExpr(Expr *Assumption,
11229                                 const IdentifierInfo *AttrName,
11230                                 SourceRange Range);
11231 
11232   ///@}
11233 
11234   //
11235   //
11236   // -------------------------------------------------------------------------
11237   //
11238   //
11239 
11240   /// \name C++ Templates
11241   /// Implementations are in SemaTemplate.cpp
11242   ///@{
11243 
11244 public:
11245   // Saves the current floating-point pragma stack and clear it in this Sema.
11246   class FpPragmaStackSaveRAII {
11247   public:
FpPragmaStackSaveRAII(Sema & S)11248     FpPragmaStackSaveRAII(Sema &S)
11249         : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11250       S.FpPragmaStack.Stack.clear();
11251     }
~FpPragmaStackSaveRAII()11252     ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11253 
11254   private:
11255     Sema &S;
11256     PragmaStack<FPOptionsOverride> SavedStack;
11257   };
11258 
resetFPOptions(FPOptions FPO)11259   void resetFPOptions(FPOptions FPO) {
11260     CurFPFeatures = FPO;
11261     FpPragmaStack.CurrentValue = FPO.getChangesFrom(FPOptions(LangOpts));
11262   }
11263 
getInventedParameterInfos()11264   ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
11265     return llvm::ArrayRef(InventedParameterInfos.begin() +
11266                               InventedParameterInfosStart,
11267                           InventedParameterInfos.end());
11268   }
11269 
11270   /// The number of SFINAE diagnostics that have been trapped.
11271   unsigned NumSFINAEErrors;
11272 
getFunctionScopes()11273   ArrayRef<sema::FunctionScopeInfo *> getFunctionScopes() const {
11274     return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
11275                           FunctionScopes.end());
11276   }
11277 
11278   typedef llvm::MapVector<const FunctionDecl *,
11279                           std::unique_ptr<LateParsedTemplate>>
11280       LateParsedTemplateMapT;
11281   LateParsedTemplateMapT LateParsedTemplateMap;
11282 
11283   /// Determine the number of levels of enclosing template parameters. This is
11284   /// only usable while parsing. Note that this does not include dependent
11285   /// contexts in which no template parameters have yet been declared, such as
11286   /// in a terse function template or generic lambda before the first 'auto' is
11287   /// encountered.
11288   unsigned getTemplateDepth(Scope *S) const;
11289 
11290   void FilterAcceptableTemplateNames(LookupResult &R,
11291                                      bool AllowFunctionTemplates = true,
11292                                      bool AllowDependent = true);
11293   bool hasAnyAcceptableTemplateNames(LookupResult &R,
11294                                      bool AllowFunctionTemplates = true,
11295                                      bool AllowDependent = true,
11296                                      bool AllowNonTemplateFunctions = false);
11297   /// Try to interpret the lookup result D as a template-name.
11298   ///
11299   /// \param D A declaration found by name lookup.
11300   /// \param AllowFunctionTemplates Whether function templates should be
11301   ///        considered valid results.
11302   /// \param AllowDependent Whether unresolved using declarations (that might
11303   ///        name templates) should be considered valid results.
11304   static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
11305                                           bool AllowFunctionTemplates = true,
11306                                           bool AllowDependent = true);
11307 
11308   enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
11309   /// Whether and why a template name is required in this lookup.
11310   class RequiredTemplateKind {
11311   public:
11312     /// Template name is required if TemplateKWLoc is valid.
11313     RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
TemplateKW(TemplateKWLoc)11314         : TemplateKW(TemplateKWLoc) {}
11315     /// Template name is unconditionally required.
RequiredTemplateKind(TemplateNameIsRequiredTag)11316     RequiredTemplateKind(TemplateNameIsRequiredTag) {}
11317 
getTemplateKeywordLoc()11318     SourceLocation getTemplateKeywordLoc() const {
11319       return TemplateKW.value_or(SourceLocation());
11320     }
hasTemplateKeyword()11321     bool hasTemplateKeyword() const {
11322       return getTemplateKeywordLoc().isValid();
11323     }
isRequired()11324     bool isRequired() const { return TemplateKW != SourceLocation(); }
11325     explicit operator bool() const { return isRequired(); }
11326 
11327   private:
11328     std::optional<SourceLocation> TemplateKW;
11329   };
11330 
11331   enum class AssumedTemplateKind {
11332     /// This is not assumed to be a template name.
11333     None,
11334     /// This is assumed to be a template name because lookup found nothing.
11335     FoundNothing,
11336     /// This is assumed to be a template name because lookup found one or more
11337     /// functions (but no function templates).
11338     FoundFunctions,
11339   };
11340 
11341   bool
11342   LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
11343                      QualType ObjectType, bool EnteringContext,
11344                      RequiredTemplateKind RequiredTemplate = SourceLocation(),
11345                      AssumedTemplateKind *ATK = nullptr,
11346                      bool AllowTypoCorrection = true);
11347 
11348   TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS,
11349                                   bool hasTemplateKeyword,
11350                                   const UnqualifiedId &Name,
11351                                   ParsedType ObjectType, bool EnteringContext,
11352                                   TemplateTy &Template,
11353                                   bool &MemberOfUnknownSpecialization,
11354                                   bool Disambiguation = false);
11355 
11356   /// Try to resolve an undeclared template name as a type template.
11357   ///
11358   /// Sets II to the identifier corresponding to the template name, and updates
11359   /// Name to a corresponding (typo-corrected) type template name and TNK to
11360   /// the corresponding kind, if possible.
11361   void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
11362                                        TemplateNameKind &TNK,
11363                                        SourceLocation NameLoc,
11364                                        IdentifierInfo *&II);
11365 
11366   bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
11367                                         SourceLocation NameLoc,
11368                                         bool Diagnose = true);
11369 
11370   /// Determine whether a particular identifier might be the name in a C++1z
11371   /// deduction-guide declaration.
11372   bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11373                             SourceLocation NameLoc, CXXScopeSpec &SS,
11374                             ParsedTemplateTy *Template = nullptr);
11375 
11376   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
11377                                    SourceLocation IILoc, Scope *S,
11378                                    const CXXScopeSpec *SS,
11379                                    TemplateTy &SuggestedTemplate,
11380                                    TemplateNameKind &SuggestedKind);
11381 
11382   /// Determine whether we would be unable to instantiate this template (because
11383   /// it either has no definition, or is in the process of being instantiated).
11384   bool DiagnoseUninstantiableTemplate(
11385       SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11386       bool InstantiatedFromMember, const NamedDecl *Pattern,
11387       const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11388       bool Complain = true, bool *Unreachable = nullptr);
11389 
11390   /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11391   /// that the template parameter 'PrevDecl' is being shadowed by a new
11392   /// declaration at location Loc. Returns true to indicate that this is
11393   /// an error, and false otherwise.
11394   ///
11395   /// \param Loc The location of the declaration that shadows a template
11396   ///            parameter.
11397   ///
11398   /// \param PrevDecl The template parameter that the declaration shadows.
11399   ///
11400   /// \param SupportedForCompatibility Whether to issue the diagnostic as
11401   ///        a warning for compatibility with older versions of clang.
11402   ///        Ignored when MSVC compatibility is enabled.
11403   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
11404                                        bool SupportedForCompatibility = false);
11405 
11406   /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11407   /// the parameter D to reference the templated declaration and return a
11408   /// pointer to the template declaration. Otherwise, do nothing to D and return
11409   /// null.
11410   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
11411 
11412   /// ActOnTypeParameter - Called when a C++ template type parameter
11413   /// (e.g., "typename T") has been parsed. Typename specifies whether
11414   /// the keyword "typename" was used to declare the type parameter
11415   /// (otherwise, "class" was used), and KeyLoc is the location of the
11416   /// "class" or "typename" keyword. ParamName is the name of the
11417   /// parameter (NULL indicates an unnamed template parameter) and
11418   /// ParamNameLoc is the location of the parameter name (if any).
11419   /// If the type parameter has a default argument, it will be added
11420   /// later via ActOnTypeParameterDefault.
11421   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
11422                                 SourceLocation EllipsisLoc,
11423                                 SourceLocation KeyLoc,
11424                                 IdentifierInfo *ParamName,
11425                                 SourceLocation ParamNameLoc, unsigned Depth,
11426                                 unsigned Position, SourceLocation EqualLoc,
11427                                 ParsedType DefaultArg, bool HasTypeConstraint);
11428 
11429   bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint);
11430 
11431   bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11432                            TemplateIdAnnotation *TypeConstraint,
11433                            TemplateTypeParmDecl *ConstrainedParameter,
11434                            SourceLocation EllipsisLoc);
11435   bool BuildTypeConstraint(const CXXScopeSpec &SS,
11436                            TemplateIdAnnotation *TypeConstraint,
11437                            TemplateTypeParmDecl *ConstrainedParameter,
11438                            SourceLocation EllipsisLoc,
11439                            bool AllowUnexpandedPack);
11440 
11441   /// Attach a type-constraint to a template parameter.
11442   /// \returns true if an error occurred. This can happen if the
11443   /// immediately-declared constraint could not be formed (e.g. incorrect number
11444   /// of arguments for the named concept).
11445   bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
11446                             DeclarationNameInfo NameInfo,
11447                             ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
11448                             const TemplateArgumentListInfo *TemplateArgs,
11449                             TemplateTypeParmDecl *ConstrainedParameter,
11450                             SourceLocation EllipsisLoc);
11451 
11452   bool AttachTypeConstraint(AutoTypeLoc TL,
11453                             NonTypeTemplateParmDecl *NewConstrainedParm,
11454                             NonTypeTemplateParmDecl *OrigConstrainedParm,
11455                             SourceLocation EllipsisLoc);
11456 
11457   /// Require the given type to be a structural type, and diagnose if it is not.
11458   ///
11459   /// \return \c true if an error was produced.
11460   bool RequireStructuralType(QualType T, SourceLocation Loc);
11461 
11462   /// Check that the type of a non-type template parameter is
11463   /// well-formed.
11464   ///
11465   /// \returns the (possibly-promoted) parameter type if valid;
11466   /// otherwise, produces a diagnostic and returns a NULL type.
11467   QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
11468                                              SourceLocation Loc);
11469   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
11470 
11471   NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
11472                                            unsigned Depth, unsigned Position,
11473                                            SourceLocation EqualLoc,
11474                                            Expr *DefaultArg);
11475 
11476   /// ActOnTemplateTemplateParameter - Called when a C++ template template
11477   /// parameter (e.g. T in template <template \<typename> class T> class array)
11478   /// has been parsed. S is the current scope.
11479   NamedDecl *ActOnTemplateTemplateParameter(
11480       Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
11481       bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11482       SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11483       SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11484 
11485   /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11486   /// constrained by RequiresClause, that contains the template parameters in
11487   /// Params.
11488   TemplateParameterList *ActOnTemplateParameterList(
11489       unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11490       SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11491       SourceLocation RAngleLoc, Expr *RequiresClause);
11492 
11493   /// The context in which we are checking a template parameter list.
11494   enum TemplateParamListContext {
11495     // For this context, Class, Variable, TypeAlias, and non-pack Template
11496     // Template Parameters are treated uniformly.
11497     TPC_Other,
11498 
11499     TPC_FunctionTemplate,
11500     TPC_ClassTemplateMember,
11501     TPC_FriendClassTemplate,
11502     TPC_FriendFunctionTemplate,
11503     TPC_FriendFunctionTemplateDefinition,
11504     TPC_TemplateTemplateParameterPack,
11505   };
11506 
11507   /// Checks the validity of a template parameter list, possibly
11508   /// considering the template parameter list from a previous
11509   /// declaration.
11510   ///
11511   /// If an "old" template parameter list is provided, it must be
11512   /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11513   /// template parameter list.
11514   ///
11515   /// \param NewParams Template parameter list for a new template
11516   /// declaration. This template parameter list will be updated with any
11517   /// default arguments that are carried through from the previous
11518   /// template parameter list.
11519   ///
11520   /// \param OldParams If provided, template parameter list from a
11521   /// previous declaration of the same template. Default template
11522   /// arguments will be merged from the old template parameter list to
11523   /// the new template parameter list.
11524   ///
11525   /// \param TPC Describes the context in which we are checking the given
11526   /// template parameter list.
11527   ///
11528   /// \param SkipBody If we might have already made a prior merged definition
11529   /// of this template visible, the corresponding body-skipping information.
11530   /// Default argument redefinition is not an error when skipping such a body,
11531   /// because (under the ODR) we can assume the default arguments are the same
11532   /// as the prior merged definition.
11533   ///
11534   /// \returns true if an error occurred, false otherwise.
11535   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
11536                                   TemplateParameterList *OldParams,
11537                                   TemplateParamListContext TPC,
11538                                   SkipBodyInfo *SkipBody = nullptr);
11539 
11540   /// Match the given template parameter lists to the given scope
11541   /// specifier, returning the template parameter list that applies to the
11542   /// name.
11543   ///
11544   /// \param DeclStartLoc the start of the declaration that has a scope
11545   /// specifier or a template parameter list.
11546   ///
11547   /// \param DeclLoc The location of the declaration itself.
11548   ///
11549   /// \param SS the scope specifier that will be matched to the given template
11550   /// parameter lists. This scope specifier precedes a qualified name that is
11551   /// being declared.
11552   ///
11553   /// \param TemplateId The template-id following the scope specifier, if there
11554   /// is one. Used to check for a missing 'template<>'.
11555   ///
11556   /// \param ParamLists the template parameter lists, from the outermost to the
11557   /// innermost template parameter lists.
11558   ///
11559   /// \param IsFriend Whether to apply the slightly different rules for
11560   /// matching template parameters to scope specifiers in friend
11561   /// declarations.
11562   ///
11563   /// \param IsMemberSpecialization will be set true if the scope specifier
11564   /// denotes a fully-specialized type, and therefore this is a declaration of
11565   /// a member specialization.
11566   ///
11567   /// \returns the template parameter list, if any, that corresponds to the
11568   /// name that is preceded by the scope specifier @p SS. This template
11569   /// parameter list may have template parameters (if we're declaring a
11570   /// template) or may have no template parameters (if we're declaring a
11571   /// template specialization), or may be NULL (if what we're declaring isn't
11572   /// itself a template).
11573   TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
11574       SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11575       const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11576       ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11577       bool &IsMemberSpecialization, bool &Invalid,
11578       bool SuppressDiagnostic = false);
11579 
11580   /// Returns the template parameter list with all default template argument
11581   /// information.
11582   TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD);
11583 
11584   DeclResult CheckClassTemplate(
11585       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11586       CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11587       const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11588       AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11589       SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11590       TemplateParameterList **OuterTemplateParamLists,
11591       SkipBodyInfo *SkipBody = nullptr);
11592 
11593   /// Translates template arguments as provided by the parser
11594   /// into template arguments used by semantic analysis.
11595   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
11596                                   TemplateArgumentListInfo &Out);
11597 
11598   /// Convert a parsed type into a parsed template argument. This is mostly
11599   /// trivial, except that we may have parsed a C++17 deduced class template
11600   /// specialization type, in which case we should form a template template
11601   /// argument instead of a type template argument.
11602   ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
11603 
11604   void NoteAllFoundTemplates(TemplateName Name);
11605 
11606   QualType CheckTemplateIdType(TemplateName Template,
11607                                SourceLocation TemplateLoc,
11608                                TemplateArgumentListInfo &TemplateArgs);
11609 
11610   TypeResult
11611   ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11612                       TemplateTy Template, const IdentifierInfo *TemplateII,
11613                       SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11614                       ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11615                       bool IsCtorOrDtorName = false, bool IsClassName = false,
11616                       ImplicitTypenameContext AllowImplicitTypename =
11617                           ImplicitTypenameContext::No);
11618 
11619   /// Parsed an elaborated-type-specifier that refers to a template-id,
11620   /// such as \c class T::template apply<U>.
11621   TypeResult ActOnTagTemplateIdType(
11622       TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11623       CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11624       SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11625       ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11626 
11627   DeclResult ActOnVarTemplateSpecialization(
11628       Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous,
11629       SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11630       StorageClass SC, bool IsPartialSpecialization);
11631 
11632   /// Get the specialization of the given variable template corresponding to
11633   /// the specified argument list, or a null-but-valid result if the arguments
11634   /// are dependent.
11635   DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
11636                                 SourceLocation TemplateLoc,
11637                                 SourceLocation TemplateNameLoc,
11638                                 const TemplateArgumentListInfo &TemplateArgs);
11639 
11640   /// Form a reference to the specialization of the given variable template
11641   /// corresponding to the specified argument list, or a null-but-valid result
11642   /// if the arguments are dependent.
11643   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
11644                                 const DeclarationNameInfo &NameInfo,
11645                                 VarTemplateDecl *Template, NamedDecl *FoundD,
11646                                 SourceLocation TemplateLoc,
11647                                 const TemplateArgumentListInfo *TemplateArgs);
11648 
11649   ExprResult
11650   CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11651                          const DeclarationNameInfo &ConceptNameInfo,
11652                          NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
11653                          const TemplateArgumentListInfo *TemplateArgs);
11654 
11655   void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
11656   void diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
11657                                         bool TemplateKeyword, TemplateDecl *TD,
11658                                         SourceLocation Loc);
11659 
11660   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
11661                                  SourceLocation TemplateKWLoc, LookupResult &R,
11662                                  bool RequiresADL,
11663                                  const TemplateArgumentListInfo *TemplateArgs);
11664 
11665   // We actually only call this from template instantiation.
11666   ExprResult
11667   BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11668                                const DeclarationNameInfo &NameInfo,
11669                                const TemplateArgumentListInfo *TemplateArgs,
11670                                bool IsAddressOfOperand);
11671 
11672   /// Form a template name from a name that is syntactically required to name a
11673   /// template, either due to use of the 'template' keyword or because a name in
11674   /// this syntactic context is assumed to name a template (C++
11675   /// [temp.names]p2-4).
11676   ///
11677   /// This action forms a template name given the name of the template and its
11678   /// optional scope specifier. This is used when the 'template' keyword is used
11679   /// or when the parsing context unambiguously treats a following '<' as
11680   /// introducing a template argument list. Note that this may produce a
11681   /// non-dependent template name if we can perform the lookup now and identify
11682   /// the named template.
11683   ///
11684   /// For example, given "x.MetaFun::template apply", the scope specifier
11685   /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
11686   /// of the "template" keyword, and "apply" is the \p Name.
11687   TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS,
11688                                      SourceLocation TemplateKWLoc,
11689                                      const UnqualifiedId &Name,
11690                                      ParsedType ObjectType,
11691                                      bool EnteringContext, TemplateTy &Template,
11692                                      bool AllowInjectedClassName = false);
11693 
11694   DeclResult ActOnClassTemplateSpecialization(
11695       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11696       SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
11697       TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
11698       MultiTemplateParamsArg TemplateParameterLists,
11699       SkipBodyInfo *SkipBody = nullptr);
11700 
11701   /// Check the non-type template arguments of a class template
11702   /// partial specialization according to C++ [temp.class.spec]p9.
11703   ///
11704   /// \param TemplateNameLoc the location of the template name.
11705   /// \param PrimaryTemplate the template parameters of the primary class
11706   ///        template.
11707   /// \param NumExplicit the number of explicitly-specified template arguments.
11708   /// \param TemplateArgs the template arguments of the class template
11709   ///        partial specialization.
11710   ///
11711   /// \returns \c true if there was an error, \c false otherwise.
11712   bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
11713                                               TemplateDecl *PrimaryTemplate,
11714                                               unsigned NumExplicitArgs,
11715                                               ArrayRef<TemplateArgument> Args);
11716   void CheckTemplatePartialSpecialization(
11717       ClassTemplatePartialSpecializationDecl *Partial);
11718   void CheckTemplatePartialSpecialization(
11719       VarTemplatePartialSpecializationDecl *Partial);
11720 
11721   Decl *ActOnTemplateDeclarator(Scope *S,
11722                                 MultiTemplateParamsArg TemplateParameterLists,
11723                                 Declarator &D);
11724 
11725   /// Diagnose cases where we have an explicit template specialization
11726   /// before/after an explicit template instantiation, producing diagnostics
11727   /// for those cases where they are required and determining whether the
11728   /// new specialization/instantiation will have any effect.
11729   ///
11730   /// \param NewLoc the location of the new explicit specialization or
11731   /// instantiation.
11732   ///
11733   /// \param NewTSK the kind of the new explicit specialization or
11734   /// instantiation.
11735   ///
11736   /// \param PrevDecl the previous declaration of the entity.
11737   ///
11738   /// \param PrevTSK the kind of the old explicit specialization or
11739   /// instantiatin.
11740   ///
11741   /// \param PrevPointOfInstantiation if valid, indicates where the previous
11742   /// declaration was instantiated (either implicitly or explicitly).
11743   ///
11744   /// \param HasNoEffect will be set to true to indicate that the new
11745   /// specialization or instantiation has no effect and should be ignored.
11746   ///
11747   /// \returns true if there was an error that should prevent the introduction
11748   /// of the new declaration into the AST, false otherwise.
11749   bool CheckSpecializationInstantiationRedecl(
11750       SourceLocation NewLoc,
11751       TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
11752       NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
11753       SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
11754 
11755   /// Perform semantic analysis for the given dependent function
11756   /// template specialization.
11757   ///
11758   /// The only possible way to get a dependent function template specialization
11759   /// is with a friend declaration, like so:
11760   ///
11761   /// \code
11762   ///   template \<class T> void foo(T);
11763   ///   template \<class T> class A {
11764   ///     friend void foo<>(T);
11765   ///   };
11766   /// \endcode
11767   ///
11768   /// There really isn't any useful analysis we can do here, so we
11769   /// just store the information.
11770   bool CheckDependentFunctionTemplateSpecialization(
11771       FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
11772       LookupResult &Previous);
11773 
11774   /// Perform semantic analysis for the given function template
11775   /// specialization.
11776   ///
11777   /// This routine performs all of the semantic analysis required for an
11778   /// explicit function template specialization. On successful completion,
11779   /// the function declaration \p FD will become a function template
11780   /// specialization.
11781   ///
11782   /// \param FD the function declaration, which will be updated to become a
11783   /// function template specialization.
11784   ///
11785   /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
11786   /// if any. Note that this may be valid info even when 0 arguments are
11787   /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
11788   /// as it anyway contains info on the angle brackets locations.
11789   ///
11790   /// \param Previous the set of declarations that may be specialized by
11791   /// this function specialization.
11792   ///
11793   /// \param QualifiedFriend whether this is a lookup for a qualified friend
11794   /// declaration with no explicit template argument list that might be
11795   /// befriending a function template specialization.
11796   bool CheckFunctionTemplateSpecialization(
11797       FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
11798       LookupResult &Previous, bool QualifiedFriend = false);
11799 
11800   /// Perform semantic analysis for the given non-template member
11801   /// specialization.
11802   ///
11803   /// This routine performs all of the semantic analysis required for an
11804   /// explicit member function specialization. On successful completion,
11805   /// the function declaration \p FD will become a member function
11806   /// specialization.
11807   ///
11808   /// \param Member the member declaration, which will be updated to become a
11809   /// specialization.
11810   ///
11811   /// \param Previous the set of declarations, one of which may be specialized
11812   /// by this function specialization;  the set will be modified to contain the
11813   /// redeclared member.
11814   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
11815   void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
11816 
11817   // Explicit instantiation of a class template specialization
11818   DeclResult ActOnExplicitInstantiation(
11819       Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
11820       unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
11821       TemplateTy Template, SourceLocation TemplateNameLoc,
11822       SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
11823       SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
11824 
11825   // Explicit instantiation of a member class of a class template.
11826   DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
11827                                         SourceLocation TemplateLoc,
11828                                         unsigned TagSpec, SourceLocation KWLoc,
11829                                         CXXScopeSpec &SS, IdentifierInfo *Name,
11830                                         SourceLocation NameLoc,
11831                                         const ParsedAttributesView &Attr);
11832 
11833   DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
11834                                         SourceLocation TemplateLoc,
11835                                         Declarator &D);
11836 
11837   /// If the given template parameter has a default template
11838   /// argument, substitute into that default template argument and
11839   /// return the corresponding template argument.
11840   TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(
11841       TemplateDecl *Template, SourceLocation TemplateLoc,
11842       SourceLocation RAngleLoc, Decl *Param,
11843       ArrayRef<TemplateArgument> SugaredConverted,
11844       ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
11845 
11846   /// Returns the top most location responsible for the definition of \p N.
11847   /// If \p N is a a template specialization, this is the location
11848   /// of the top of the instantiation stack.
11849   /// Otherwise, the location of \p N is returned.
11850   SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const;
11851 
11852   /// Specifies the context in which a particular template
11853   /// argument is being checked.
11854   enum CheckTemplateArgumentKind {
11855     /// The template argument was specified in the code or was
11856     /// instantiated with some deduced template arguments.
11857     CTAK_Specified,
11858 
11859     /// The template argument was deduced via template argument
11860     /// deduction.
11861     CTAK_Deduced,
11862 
11863     /// The template argument was deduced from an array bound
11864     /// via template argument deduction.
11865     CTAK_DeducedFromArrayBound
11866   };
11867 
11868   struct CheckTemplateArgumentInfo {
11869     explicit CheckTemplateArgumentInfo(bool PartialOrdering = false,
11870                                        bool MatchingTTP = false)
PartialOrderingCheckTemplateArgumentInfo11871         : PartialOrdering(PartialOrdering), MatchingTTP(MatchingTTP) {}
11872     CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &) = delete;
11873     CheckTemplateArgumentInfo &
11874     operator=(const CheckTemplateArgumentInfo &) = delete;
11875 
11876     /// The checked, converted argument will be added to the
11877     /// end of these vectors.
11878     SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
11879 
11880     /// The check is being performed in the context of partial ordering.
11881     bool PartialOrdering;
11882 
11883     /// If true, assume these template arguments are
11884     /// the injected template arguments for a template template parameter.
11885     /// This will relax the requirement that all its possible uses are valid:
11886     /// TTP checking is loose, and assumes that invalid uses will be diagnosed
11887     /// during instantiation.
11888     bool MatchingTTP;
11889 
11890     /// Is set to true when, in the context of TTP matching, a pack parameter
11891     /// matches non-pack arguments.
11892     bool StrictPackMatch = false;
11893   };
11894 
11895   /// Check that the given template argument corresponds to the given
11896   /// template parameter.
11897   ///
11898   /// \param Param The template parameter against which the argument will be
11899   /// checked.
11900   ///
11901   /// \param Arg The template argument, which may be updated due to conversions.
11902   ///
11903   /// \param Template The template in which the template argument resides.
11904   ///
11905   /// \param TemplateLoc The location of the template name for the template
11906   /// whose argument list we're matching.
11907   ///
11908   /// \param RAngleLoc The location of the right angle bracket ('>') that closes
11909   /// the template argument list.
11910   ///
11911   /// \param ArgumentPackIndex The index into the argument pack where this
11912   /// argument will be placed. Only valid if the parameter is a parameter pack.
11913   ///
11914   /// \param CTAK Describes how we arrived at this particular template argument:
11915   /// explicitly written, deduced, etc.
11916   ///
11917   /// \returns true on error, false otherwise.
11918   bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
11919                              NamedDecl *Template, SourceLocation TemplateLoc,
11920                              SourceLocation RAngleLoc,
11921                              unsigned ArgumentPackIndex,
11922                              CheckTemplateArgumentInfo &CTAI,
11923                              CheckTemplateArgumentKind CTAK);
11924 
11925   /// Check that the given template arguments can be provided to
11926   /// the given template, converting the arguments along the way.
11927   ///
11928   /// \param Template The template to which the template arguments are being
11929   /// provided.
11930   ///
11931   /// \param TemplateLoc The location of the template name in the source.
11932   ///
11933   /// \param TemplateArgs The list of template arguments. If the template is
11934   /// a template template parameter, this function may extend the set of
11935   /// template arguments to also include substituted, defaulted template
11936   /// arguments.
11937   ///
11938   /// \param PartialTemplateArgs True if the list of template arguments is
11939   /// intentionally partial, e.g., because we're checking just the initial
11940   /// set of template arguments.
11941   ///
11942   /// \param Converted Will receive the converted, canonicalized template
11943   /// arguments.
11944   ///
11945   /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
11946   /// contain the converted forms of the template arguments as written.
11947   /// Otherwise, \p TemplateArgs will not be modified.
11948   ///
11949   /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
11950   /// receive true if the cause for the error is the associated constraints of
11951   /// the template not being satisfied by the template arguments.
11952   ///
11953   /// \param DefaultArgs any default arguments from template specialization
11954   /// deduction.
11955   ///
11956   /// \returns true if an error occurred, false otherwise.
11957   bool CheckTemplateArgumentList(TemplateDecl *Template,
11958                                  SourceLocation TemplateLoc,
11959                                  TemplateArgumentListInfo &TemplateArgs,
11960                                  const DefaultArguments &DefaultArgs,
11961                                  bool PartialTemplateArgs,
11962                                  CheckTemplateArgumentInfo &CTAI,
11963                                  bool UpdateArgsWithConversions = true,
11964                                  bool *ConstraintsNotSatisfied = nullptr);
11965 
11966   bool CheckTemplateTypeArgument(
11967       TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
11968       SmallVectorImpl<TemplateArgument> &SugaredConverted,
11969       SmallVectorImpl<TemplateArgument> &CanonicalConverted);
11970 
11971   /// Check a template argument against its corresponding
11972   /// template type parameter.
11973   ///
11974   /// This routine implements the semantics of C++ [temp.arg.type]. It
11975   /// returns true if an error occurred, and false otherwise.
11976   bool CheckTemplateArgument(TypeSourceInfo *Arg);
11977 
11978   /// Check a template argument against its corresponding
11979   /// non-type template parameter.
11980   ///
11981   /// This routine implements the semantics of C++ [temp.arg.nontype].
11982   /// If an error occurred, it returns ExprError(); otherwise, it
11983   /// returns the converted template argument. \p ParamType is the
11984   /// type of the non-type template parameter after it has been instantiated.
11985   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
11986                                    QualType InstantiatedParamType, Expr *Arg,
11987                                    TemplateArgument &SugaredConverted,
11988                                    TemplateArgument &CanonicalConverted,
11989                                    bool StrictCheck,
11990                                    CheckTemplateArgumentKind CTAK);
11991 
11992   /// Check a template argument against its corresponding
11993   /// template template parameter.
11994   ///
11995   /// This routine implements the semantics of C++ [temp.arg.template].
11996   /// It returns true if an error occurred, and false otherwise.
11997   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
11998                                      TemplateParameterList *Params,
11999                                      TemplateArgumentLoc &Arg,
12000                                      bool PartialOrdering,
12001                                      bool *StrictPackMatch);
12002 
12003   void NoteTemplateLocation(const NamedDecl &Decl,
12004                             std::optional<SourceRange> ParamRange = {});
12005   void NoteTemplateParameterLocation(const NamedDecl &Decl);
12006 
12007   /// Given a non-type template argument that refers to a
12008   /// declaration and the type of its corresponding non-type template
12009   /// parameter, produce an expression that properly refers to that
12010   /// declaration.
12011   /// FIXME: This is used in some contexts where the resulting expression
12012   /// doesn't need to live too long. It would be useful if this function
12013   /// could return a temporary expression.
12014   ExprResult BuildExpressionFromDeclTemplateArgument(
12015       const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
12016       NamedDecl *TemplateParam = nullptr);
12017   ExprResult
12018   BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
12019                                              SourceLocation Loc);
12020 
12021   /// Enumeration describing how template parameter lists are compared
12022   /// for equality.
12023   enum TemplateParameterListEqualKind {
12024     /// We are matching the template parameter lists of two templates
12025     /// that might be redeclarations.
12026     ///
12027     /// \code
12028     /// template<typename T> struct X;
12029     /// template<typename T> struct X;
12030     /// \endcode
12031     TPL_TemplateMatch,
12032 
12033     /// We are matching the template parameter lists of two template
12034     /// template parameters as part of matching the template parameter lists
12035     /// of two templates that might be redeclarations.
12036     ///
12037     /// \code
12038     /// template<template<int I> class TT> struct X;
12039     /// template<template<int Value> class Other> struct X;
12040     /// \endcode
12041     TPL_TemplateTemplateParmMatch,
12042 
12043     /// We are determining whether the template-parameters are equivalent
12044     /// according to C++ [temp.over.link]/6. This comparison does not consider
12045     /// constraints.
12046     ///
12047     /// \code
12048     /// template<C1 T> void f(T);
12049     /// template<C2 T> void f(T);
12050     /// \endcode
12051     TPL_TemplateParamsEquivalent,
12052   };
12053 
12054   // A struct to represent the 'new' declaration, which is either itself just
12055   // the named decl, or the important information we need about it in order to
12056   // do constraint comparisons.
12057   class TemplateCompareNewDeclInfo {
12058     const NamedDecl *ND = nullptr;
12059     const DeclContext *DC = nullptr;
12060     const DeclContext *LexicalDC = nullptr;
12061     SourceLocation Loc;
12062 
12063   public:
TemplateCompareNewDeclInfo(const NamedDecl * ND)12064     TemplateCompareNewDeclInfo(const NamedDecl *ND) : ND(ND) {}
TemplateCompareNewDeclInfo(const DeclContext * DeclCtx,const DeclContext * LexicalDeclCtx,SourceLocation Loc)12065     TemplateCompareNewDeclInfo(const DeclContext *DeclCtx,
12066                                const DeclContext *LexicalDeclCtx,
12067                                SourceLocation Loc)
12068 
12069         : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12070       assert(DC && LexicalDC &&
12071              "Constructor only for cases where we have the information to put "
12072              "in here");
12073     }
12074 
12075     // If this was constructed with no information, we cannot do substitution
12076     // for constraint comparison, so make sure we can check that.
isInvalid()12077     bool isInvalid() const { return !ND && !DC; }
12078 
getDecl()12079     const NamedDecl *getDecl() const { return ND; }
12080 
ContainsDecl(const NamedDecl * ND)12081     bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12082 
getLexicalDeclContext()12083     const DeclContext *getLexicalDeclContext() const {
12084       return ND ? ND->getLexicalDeclContext() : LexicalDC;
12085     }
12086 
getDeclContext()12087     const DeclContext *getDeclContext() const {
12088       return ND ? ND->getDeclContext() : DC;
12089     }
12090 
getLocation()12091     SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12092   };
12093 
12094   /// Determine whether the given template parameter lists are
12095   /// equivalent.
12096   ///
12097   /// \param New  The new template parameter list, typically written in the
12098   /// source code as part of a new template declaration.
12099   ///
12100   /// \param Old  The old template parameter list, typically found via
12101   /// name lookup of the template declared with this template parameter
12102   /// list.
12103   ///
12104   /// \param Complain  If true, this routine will produce a diagnostic if
12105   /// the template parameter lists are not equivalent.
12106   ///
12107   /// \param Kind describes how we are to match the template parameter lists.
12108   ///
12109   /// \param TemplateArgLoc If this source location is valid, then we
12110   /// are actually checking the template parameter list of a template
12111   /// argument (New) against the template parameter list of its
12112   /// corresponding template template parameter (Old). We produce
12113   /// slightly different diagnostics in this scenario.
12114   ///
12115   /// \returns True if the template parameter lists are equal, false
12116   /// otherwise.
12117   bool TemplateParameterListsAreEqual(
12118       const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12119       const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12120       TemplateParameterListEqualKind Kind,
12121       SourceLocation TemplateArgLoc = SourceLocation());
12122 
12123   bool TemplateParameterListsAreEqual(
12124       TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12125       TemplateParameterListEqualKind Kind,
12126       SourceLocation TemplateArgLoc = SourceLocation()) {
12127     return TemplateParameterListsAreEqual(nullptr, New, nullptr, Old, Complain,
12128                                           Kind, TemplateArgLoc);
12129   }
12130 
12131   /// Check whether a template can be declared within this scope.
12132   ///
12133   /// If the template declaration is valid in this scope, returns
12134   /// false. Otherwise, issues a diagnostic and returns true.
12135   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12136 
12137   /// Called when the parser has parsed a C++ typename
12138   /// specifier, e.g., "typename T::type".
12139   ///
12140   /// \param S The scope in which this typename type occurs.
12141   /// \param TypenameLoc the location of the 'typename' keyword
12142   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12143   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12144   /// \param IdLoc the location of the identifier.
12145   /// \param IsImplicitTypename context where T::type refers to a type.
12146   TypeResult ActOnTypenameType(
12147       Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12148       const IdentifierInfo &II, SourceLocation IdLoc,
12149       ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No);
12150 
12151   /// Called when the parser has parsed a C++ typename
12152   /// specifier that ends in a template-id, e.g.,
12153   /// "typename MetaFun::template apply<T1, T2>".
12154   ///
12155   /// \param S The scope in which this typename type occurs.
12156   /// \param TypenameLoc the location of the 'typename' keyword
12157   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12158   /// \param TemplateLoc the location of the 'template' keyword, if any.
12159   /// \param TemplateName The template name.
12160   /// \param TemplateII The identifier used to name the template.
12161   /// \param TemplateIILoc The location of the template name.
12162   /// \param LAngleLoc The location of the opening angle bracket  ('<').
12163   /// \param TemplateArgs The template arguments.
12164   /// \param RAngleLoc The location of the closing angle bracket  ('>').
12165   TypeResult
12166   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12167                     const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12168                     TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12169                     SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12170                     ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12171 
12172   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12173                              SourceLocation KeywordLoc,
12174                              NestedNameSpecifierLoc QualifierLoc,
12175                              const IdentifierInfo &II, SourceLocation IILoc,
12176                              TypeSourceInfo **TSI, bool DeducedTSTContext);
12177 
12178   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12179                              SourceLocation KeywordLoc,
12180                              NestedNameSpecifierLoc QualifierLoc,
12181                              const IdentifierInfo &II, SourceLocation IILoc,
12182                              bool DeducedTSTContext = true);
12183 
12184   /// Rebuilds a type within the context of the current instantiation.
12185   ///
12186   /// The type \p T is part of the type of an out-of-line member definition of
12187   /// a class template (or class template partial specialization) that was
12188   /// parsed and constructed before we entered the scope of the class template
12189   /// (or partial specialization thereof). This routine will rebuild that type
12190   /// now that we have entered the declarator's scope, which may produce
12191   /// different canonical types, e.g.,
12192   ///
12193   /// \code
12194   /// template<typename T>
12195   /// struct X {
12196   ///   typedef T* pointer;
12197   ///   pointer data();
12198   /// };
12199   ///
12200   /// template<typename T>
12201   /// typename X<T>::pointer X<T>::data() { ... }
12202   /// \endcode
12203   ///
12204   /// Here, the type "typename X<T>::pointer" will be created as a
12205   /// DependentNameType, since we do not know that we can look into X<T> when we
12206   /// parsed the type. This function will rebuild the type, performing the
12207   /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12208   /// canonical type is the same as the canonical type of T*, allowing the
12209   /// return types of the out-of-line definition and the declaration to match.
12210   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
12211                                                     SourceLocation Loc,
12212                                                     DeclarationName Name);
12213   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
12214 
12215   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
12216 
12217   /// Rebuild the template parameters now that we know we're in a current
12218   /// instantiation.
12219   bool
12220   RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params);
12221 
12222   /// Produces a formatted string that describes the binding of
12223   /// template parameters to template arguments.
12224   std::string
12225   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12226                                   const TemplateArgumentList &Args);
12227 
12228   std::string
12229   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12230                                   const TemplateArgument *Args,
12231                                   unsigned NumArgs);
12232 
12233   void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
12234                                           SourceLocation Less,
12235                                           SourceLocation Greater);
12236 
12237   /// ActOnDependentIdExpression - Handle a dependent id-expression that
12238   /// was just parsed.  This is only possible with an explicit scope
12239   /// specifier naming a dependent type.
12240   ExprResult ActOnDependentIdExpression(
12241       const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12242       const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12243       const TemplateArgumentListInfo *TemplateArgs);
12244 
12245   ExprResult
12246   BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
12247                             SourceLocation TemplateKWLoc,
12248                             const DeclarationNameInfo &NameInfo,
12249                             const TemplateArgumentListInfo *TemplateArgs);
12250 
12251   // Calculates whether the expression Constraint depends on an enclosing
12252   // template, for the purposes of [temp.friend] p9.
12253   // TemplateDepth is the 'depth' of the friend function, which is used to
12254   // compare whether a declaration reference is referring to a containing
12255   // template, or just the current friend function. A 'lower' TemplateDepth in
12256   // the AST refers to a 'containing' template. As the constraint is
12257   // uninstantiated, this is relative to the 'top' of the TU.
12258   bool
12259   ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
12260                                                  unsigned TemplateDepth,
12261                                                  const Expr *Constraint);
12262 
12263   /// Find the failed Boolean condition within a given Boolean
12264   /// constant expression, and describe it with a string.
12265   std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12266 
12267   void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
12268 
12269   ConceptDecl *ActOnStartConceptDefinition(
12270       Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12271       const IdentifierInfo *Name, SourceLocation NameLoc);
12272 
12273   ConceptDecl *ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
12274                                             Expr *ConstraintExpr,
12275                                             const ParsedAttributesView &Attrs);
12276 
12277   void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
12278                                 bool &AddToScope);
12279   bool CheckConceptUseInDefinition(ConceptDecl *Concept, SourceLocation Loc);
12280 
12281   TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12282                                const CXXScopeSpec &SS,
12283                                const IdentifierInfo *Name,
12284                                SourceLocation TagLoc, SourceLocation NameLoc);
12285 
12286   void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
12287                                 CachedTokens &Toks);
12288   void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
12289   bool IsInsideALocalClassWithinATemplateFunction();
12290 
12291   /// We've found a use of a templated declaration that would trigger an
12292   /// implicit instantiation. Check that any relevant explicit specializations
12293   /// and partial specializations are visible/reachable, and diagnose if not.
12294   void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
12295   void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
12296 
12297   ///@}
12298 
12299   //
12300   //
12301   // -------------------------------------------------------------------------
12302   //
12303   //
12304 
12305   /// \name C++ Template Argument Deduction
12306   /// Implementations are in SemaTemplateDeduction.cpp
12307   ///@{
12308 
12309 public:
12310   /// When true, access checking violations are treated as SFINAE
12311   /// failures rather than hard errors.
12312   bool AccessCheckingSFINAE;
12313 
12314   /// RAII class used to determine whether SFINAE has
12315   /// trapped any errors that occur during template argument
12316   /// deduction.
12317   class SFINAETrap {
12318     Sema &SemaRef;
12319     unsigned PrevSFINAEErrors;
12320     bool PrevInNonInstantiationSFINAEContext;
12321     bool PrevAccessCheckingSFINAE;
12322     bool PrevLastDiagnosticIgnored;
12323 
12324   public:
12325     /// \param ForValidityCheck If true, discard all diagnostics (from the
12326     /// immediate context) instead of adding them to the currently active
12327     /// \ref TemplateDeductionInfo (as returned by \ref isSFINAEContext).
12328     explicit SFINAETrap(Sema &SemaRef, bool ForValidityCheck = false)
SemaRef(SemaRef)12329         : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
12330           PrevInNonInstantiationSFINAEContext(
12331               SemaRef.InNonInstantiationSFINAEContext),
12332           PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
12333           PrevLastDiagnosticIgnored(
12334               SemaRef.getDiagnostics().isLastDiagnosticIgnored()) {
12335       if (ForValidityCheck || !SemaRef.isSFINAEContext())
12336         SemaRef.InNonInstantiationSFINAEContext = true;
12337       SemaRef.AccessCheckingSFINAE = ForValidityCheck;
12338     }
12339 
~SFINAETrap()12340     ~SFINAETrap() {
12341       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
12342       SemaRef.InNonInstantiationSFINAEContext =
12343           PrevInNonInstantiationSFINAEContext;
12344       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
12345       SemaRef.getDiagnostics().setLastDiagnosticIgnored(
12346           PrevLastDiagnosticIgnored);
12347     }
12348 
12349     /// Determine whether any SFINAE errors have been trapped.
hasErrorOccurred()12350     bool hasErrorOccurred() const {
12351       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
12352     }
12353   };
12354 
12355   /// RAII class used to indicate that we are performing provisional
12356   /// semantic analysis to determine the validity of a construct, so
12357   /// typo-correction and diagnostics in the immediate context (not within
12358   /// implicitly-instantiated templates) should be suppressed.
12359   class TentativeAnalysisScope {
12360     Sema &SemaRef;
12361     // FIXME: Using a SFINAETrap for this is a hack.
12362     SFINAETrap Trap;
12363     bool PrevDisableTypoCorrection;
12364 
12365   public:
TentativeAnalysisScope(Sema & SemaRef)12366     explicit TentativeAnalysisScope(Sema &SemaRef)
12367         : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12368           PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12369       SemaRef.DisableTypoCorrection = true;
12370     }
~TentativeAnalysisScope()12371     ~TentativeAnalysisScope() {
12372       SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12373     }
12374   };
12375 
12376   /// For each declaration that involved template argument deduction, the
12377   /// set of diagnostics that were suppressed during that template argument
12378   /// deduction.
12379   ///
12380   /// FIXME: Serialize this structure to the AST file.
12381   typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12382       SuppressedDiagnosticsMap;
12383   SuppressedDiagnosticsMap SuppressedDiagnostics;
12384 
12385   /// Compare types for equality with respect to possibly compatible
12386   /// function types (noreturn adjustment, implicit calling conventions). If any
12387   /// of parameter and argument is not a function, just perform type comparison.
12388   ///
12389   /// \param P the template parameter type.
12390   ///
12391   /// \param A the argument type.
12392   bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
12393 
12394   /// Allocate a TemplateArgumentLoc where all locations have
12395   /// been initialized to the given location.
12396   ///
12397   /// \param Arg The template argument we are producing template argument
12398   /// location information for.
12399   ///
12400   /// \param NTTPType For a declaration template argument, the type of
12401   /// the non-type template parameter that corresponds to this template
12402   /// argument. Can be null if no type sugar is available to add to the
12403   /// type from the template argument.
12404   ///
12405   /// \param Loc The source location to use for the resulting template
12406   /// argument.
12407   TemplateArgumentLoc
12408   getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType,
12409                                 SourceLocation Loc,
12410                                 NamedDecl *TemplateParam = nullptr);
12411 
12412   /// Get a template argument mapping the given template parameter to itself,
12413   /// e.g. for X in \c template<int X>, this would return an expression template
12414   /// argument referencing X.
12415   TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
12416                                                      SourceLocation Location);
12417 
12418   /// Adjust the type \p ArgFunctionType to match the calling convention,
12419   /// noreturn, and optionally the exception specification of \p FunctionType.
12420   /// Deduction often wants to ignore these properties when matching function
12421   /// types.
12422   QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
12423                                bool AdjustExceptionSpec = false);
12424 
12425   TemplateDeductionResult
12426   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
12427                           ArrayRef<TemplateArgument> TemplateArgs,
12428                           sema::TemplateDeductionInfo &Info);
12429 
12430   TemplateDeductionResult
12431   DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
12432                           ArrayRef<TemplateArgument> TemplateArgs,
12433                           sema::TemplateDeductionInfo &Info);
12434 
12435   /// Deduce the template arguments of the given template from \p FromType.
12436   /// Used to implement the IsDeducible constraint for alias CTAD per C++
12437   /// [over.match.class.deduct]p4.
12438   ///
12439   /// It only supports class or type alias templates.
12440   TemplateDeductionResult
12441   DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType,
12442                                   sema::TemplateDeductionInfo &Info);
12443 
12444   TemplateDeductionResult DeduceTemplateArguments(
12445       TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps,
12446       ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info,
12447       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12448       bool NumberOfArgumentsMustMatch);
12449 
12450   /// Substitute the explicitly-provided template arguments into the
12451   /// given function template according to C++ [temp.arg.explicit].
12452   ///
12453   /// \param FunctionTemplate the function template into which the explicit
12454   /// template arguments will be substituted.
12455   ///
12456   /// \param ExplicitTemplateArgs the explicitly-specified template
12457   /// arguments.
12458   ///
12459   /// \param Deduced the deduced template arguments, which will be populated
12460   /// with the converted and checked explicit template arguments.
12461   ///
12462   /// \param ParamTypes will be populated with the instantiated function
12463   /// parameters.
12464   ///
12465   /// \param FunctionType if non-NULL, the result type of the function template
12466   /// will also be instantiated and the pointed-to value will be updated with
12467   /// the instantiated function type.
12468   ///
12469   /// \param Info if substitution fails for any reason, this object will be
12470   /// populated with more information about the failure.
12471   ///
12472   /// \returns TemplateDeductionResult::Success if substitution was successful,
12473   /// or some failure condition.
12474   TemplateDeductionResult SubstituteExplicitTemplateArguments(
12475       FunctionTemplateDecl *FunctionTemplate,
12476       TemplateArgumentListInfo &ExplicitTemplateArgs,
12477       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12478       SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
12479       sema::TemplateDeductionInfo &Info);
12480 
12481   /// brief A function argument from which we performed template argument
12482   // deduction for a call.
12483   struct OriginalCallArg {
OriginalCallArgOriginalCallArg12484     OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
12485                     unsigned ArgIdx, QualType OriginalArgType)
12486         : OriginalParamType(OriginalParamType),
12487           DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
12488           OriginalArgType(OriginalArgType) {}
12489 
12490     QualType OriginalParamType;
12491     bool DecomposedParam;
12492     unsigned ArgIdx;
12493     QualType OriginalArgType;
12494   };
12495 
12496   /// Finish template argument deduction for a function template,
12497   /// checking the deduced template arguments for completeness and forming
12498   /// the function template specialization.
12499   ///
12500   /// \param OriginalCallArgs If non-NULL, the original call arguments against
12501   /// which the deduced argument types should be compared.
12502   /// \param CheckNonDependent Callback before substituting into the declaration
12503   /// with the deduced template arguments.
12504   /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12505   /// some breakages introduced by CWG2369, where non-user-defined conversions
12506   /// are checked first before the constraints.
12507   TemplateDeductionResult FinishTemplateArgumentDeduction(
12508       FunctionTemplateDecl *FunctionTemplate,
12509       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12510       unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12511       sema::TemplateDeductionInfo &Info,
12512       SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12513       bool PartialOverloading, bool PartialOrdering,
12514       bool ForOverloadSetAddressResolution,
12515       llvm::function_ref<bool(bool)> CheckNonDependent =
12516           [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12517             return false;
12518           });
12519 
12520   /// Perform template argument deduction from a function call
12521   /// (C++ [temp.deduct.call]).
12522   ///
12523   /// \param FunctionTemplate the function template for which we are performing
12524   /// template argument deduction.
12525   ///
12526   /// \param ExplicitTemplateArgs the explicit template arguments provided
12527   /// for this call.
12528   ///
12529   /// \param Args the function call arguments
12530   ///
12531   /// \param Specialization if template argument deduction was successful,
12532   /// this will be set to the function template specialization produced by
12533   /// template argument deduction.
12534   ///
12535   /// \param Info the argument will be updated to provide additional information
12536   /// about template argument deduction.
12537   ///
12538   /// \param CheckNonDependent A callback to invoke to check conversions for
12539   /// non-dependent parameters, between deduction and substitution, per DR1391.
12540   /// If this returns true, substitution will be skipped and we return
12541   /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12542   /// passed the parameter types (after substituting explicit template
12543   /// arguments).
12544   ///
12545   /// \returns the result of template argument deduction.
12546   TemplateDeductionResult DeduceTemplateArguments(
12547       FunctionTemplateDecl *FunctionTemplate,
12548       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12549       FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12550       bool PartialOverloading, bool AggregateDeductionCandidate,
12551       bool PartialOrdering, QualType ObjectType,
12552       Expr::Classification ObjectClassification,
12553       bool ForOverloadSetAddressResolution,
12554       llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12555 
12556   /// Deduce template arguments when taking the address of a function
12557   /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12558   /// a template.
12559   ///
12560   /// \param FunctionTemplate the function template for which we are performing
12561   /// template argument deduction.
12562   ///
12563   /// \param ExplicitTemplateArgs the explicitly-specified template
12564   /// arguments.
12565   ///
12566   /// \param ArgFunctionType the function type that will be used as the
12567   /// "argument" type (A) when performing template argument deduction from the
12568   /// function template's function type. This type may be NULL, if there is no
12569   /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
12570   ///
12571   /// \param Specialization if template argument deduction was successful,
12572   /// this will be set to the function template specialization produced by
12573   /// template argument deduction.
12574   ///
12575   /// \param Info the argument will be updated to provide additional information
12576   /// about template argument deduction.
12577   ///
12578   /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12579   /// the address of a function template per [temp.deduct.funcaddr] and
12580   /// [over.over]. If \c false, we are looking up a function template
12581   /// specialization based on its signature, per [temp.deduct.decl].
12582   ///
12583   /// \returns the result of template argument deduction.
12584   TemplateDeductionResult DeduceTemplateArguments(
12585       FunctionTemplateDecl *FunctionTemplate,
12586       TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
12587       FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12588       bool IsAddressOfFunction = false);
12589 
12590   /// Deduce template arguments for a templated conversion
12591   /// function (C++ [temp.deduct.conv]) and, if successful, produce a
12592   /// conversion function template specialization.
12593   TemplateDeductionResult DeduceTemplateArguments(
12594       FunctionTemplateDecl *FunctionTemplate, QualType ObjectType,
12595       Expr::Classification ObjectClassification, QualType ToType,
12596       CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info);
12597 
12598   /// Deduce template arguments for a function template when there is
12599   /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
12600   ///
12601   /// \param FunctionTemplate the function template for which we are performing
12602   /// template argument deduction.
12603   ///
12604   /// \param ExplicitTemplateArgs the explicitly-specified template
12605   /// arguments.
12606   ///
12607   /// \param Specialization if template argument deduction was successful,
12608   /// this will be set to the function template specialization produced by
12609   /// template argument deduction.
12610   ///
12611   /// \param Info the argument will be updated to provide additional information
12612   /// about template argument deduction.
12613   ///
12614   /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12615   /// the address of a function template in a context where we do not have a
12616   /// target type, per [over.over]. If \c false, we are looking up a function
12617   /// template specialization based on its signature, which only happens when
12618   /// deducing a function parameter type from an argument that is a template-id
12619   /// naming a function template specialization.
12620   ///
12621   /// \returns the result of template argument deduction.
12622   TemplateDeductionResult
12623   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
12624                           TemplateArgumentListInfo *ExplicitTemplateArgs,
12625                           FunctionDecl *&Specialization,
12626                           sema::TemplateDeductionInfo &Info,
12627                           bool IsAddressOfFunction = false);
12628 
12629   /// Substitute Replacement for \p auto in \p TypeWithAuto
12630   QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
12631   /// Substitute Replacement for auto in TypeWithAuto
12632   TypeSourceInfo *SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12633                                           QualType Replacement);
12634 
12635   // Substitute auto in TypeWithAuto for a Dependent auto type
12636   QualType SubstAutoTypeDependent(QualType TypeWithAuto);
12637 
12638   // Substitute auto in TypeWithAuto for a Dependent auto type
12639   TypeSourceInfo *
12640   SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
12641 
12642   /// Completely replace the \c auto in \p TypeWithAuto by
12643   /// \p Replacement. This does not retain any \c auto type sugar.
12644   QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
12645   TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12646                                             QualType Replacement);
12647 
12648   /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
12649   ///
12650   /// Note that this is done even if the initializer is dependent. (This is
12651   /// necessary to support partial ordering of templates using 'auto'.)
12652   /// A dependent type will be produced when deducing from a dependent type.
12653   ///
12654   /// \param Type the type pattern using the auto type-specifier.
12655   /// \param Init the initializer for the variable whose type is to be deduced.
12656   /// \param Result if type deduction was successful, this will be set to the
12657   ///        deduced type.
12658   /// \param Info the argument will be updated to provide additional information
12659   ///        about template argument deduction.
12660   /// \param DependentDeduction Set if we should permit deduction in
12661   ///        dependent cases. This is necessary for template partial ordering
12662   ///        with 'auto' template parameters. The template parameter depth to be
12663   ///        used should be specified in the 'Info' parameter.
12664   /// \param IgnoreConstraints Set if we should not fail if the deduced type
12665   ///                          does not satisfy the type-constraint in the auto
12666   ///                          type.
12667   TemplateDeductionResult
12668   DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result,
12669                  sema::TemplateDeductionInfo &Info,
12670                  bool DependentDeduction = false,
12671                  bool IgnoreConstraints = false,
12672                  TemplateSpecCandidateSet *FailedTSC = nullptr);
12673   void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
12674   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
12675                         bool Diagnose = true);
12676 
12677   bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD,
12678                                                 SourceLocation Loc);
12679 
12680   /// Returns the more specialized class template partial specialization
12681   /// according to the rules of partial ordering of class template partial
12682   /// specializations (C++ [temp.class.order]).
12683   ///
12684   /// \param PS1 the first class template partial specialization
12685   ///
12686   /// \param PS2 the second class template partial specialization
12687   ///
12688   /// \returns the more specialized class template partial specialization. If
12689   /// neither partial specialization is more specialized, returns NULL.
12690   ClassTemplatePartialSpecializationDecl *
12691   getMoreSpecializedPartialSpecialization(
12692       ClassTemplatePartialSpecializationDecl *PS1,
12693       ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
12694 
12695   bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
12696                                     sema::TemplateDeductionInfo &Info);
12697 
12698   VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
12699       VarTemplatePartialSpecializationDecl *PS1,
12700       VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
12701 
12702   bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
12703                                     sema::TemplateDeductionInfo &Info);
12704 
12705   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
12706       TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
12707       const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
12708       bool PartialOrdering, bool *StrictPackMatch);
12709 
12710   /// Mark which template parameters are used in a given expression.
12711   ///
12712   /// \param E the expression from which template parameters will be deduced.
12713   ///
12714   /// \param Used a bit vector whose elements will be set to \c true
12715   /// to indicate when the corresponding template parameter will be
12716   /// deduced.
12717   void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
12718                                   unsigned Depth, llvm::SmallBitVector &Used);
12719 
12720   /// Mark which template parameters can be deduced from a given
12721   /// template argument list.
12722   ///
12723   /// \param TemplateArgs the template argument list from which template
12724   /// parameters will be deduced.
12725   ///
12726   /// \param Used a bit vector whose elements will be set to \c true
12727   /// to indicate when the corresponding template parameter will be
12728   /// deduced.
12729   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
12730                                   bool OnlyDeduced, unsigned Depth,
12731                                   llvm::SmallBitVector &Used);
12732 
12733   void MarkUsedTemplateParameters(ArrayRef<TemplateArgument> TemplateArgs,
12734                                   unsigned Depth, llvm::SmallBitVector &Used);
12735 
12736   void
MarkDeducedTemplateParameters(const FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)12737   MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate,
12738                                 llvm::SmallBitVector &Deduced) {
12739     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
12740   }
12741 
12742   /// Marks all of the template parameters that will be deduced by a
12743   /// call to the given function template.
12744   static void
12745   MarkDeducedTemplateParameters(ASTContext &Ctx,
12746                                 const FunctionTemplateDecl *FunctionTemplate,
12747                                 llvm::SmallBitVector &Deduced);
12748 
12749   /// Returns the more specialized function template according
12750   /// to the rules of function template partial ordering (C++
12751   /// [temp.func.order]).
12752   ///
12753   /// \param FT1 the first function template
12754   ///
12755   /// \param FT2 the second function template
12756   ///
12757   /// \param TPOC the context in which we are performing partial ordering of
12758   /// function templates.
12759   ///
12760   /// \param NumCallArguments1 The number of arguments in the call to FT1, used
12761   /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
12762   /// when calling a member function.
12763   ///
12764   /// \param RawObj1Ty The type of the object parameter of FT1 if a member
12765   /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
12766   /// template from a member function
12767   ///
12768   /// \param RawObj2Ty The type of the object parameter of FT2 if a member
12769   /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
12770   /// template from a member function
12771   ///
12772   /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
12773   /// candidate with a reversed parameter order. In this case, the corresponding
12774   /// P/A pairs between FT1 and FT2 are reversed.
12775   ///
12776   /// \returns the more specialized function template. If neither
12777   /// template is more specialized, returns NULL.
12778   FunctionTemplateDecl *getMoreSpecializedTemplate(
12779       FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
12780       TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
12781       QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
12782       bool PartialOverloading = false);
12783 
12784   /// Retrieve the most specialized of the given function template
12785   /// specializations.
12786   ///
12787   /// \param SpecBegin the start iterator of the function template
12788   /// specializations that we will be comparing.
12789   ///
12790   /// \param SpecEnd the end iterator of the function template
12791   /// specializations, paired with \p SpecBegin.
12792   ///
12793   /// \param Loc the location where the ambiguity or no-specializations
12794   /// diagnostic should occur.
12795   ///
12796   /// \param NoneDiag partial diagnostic used to diagnose cases where there are
12797   /// no matching candidates.
12798   ///
12799   /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
12800   /// occurs.
12801   ///
12802   /// \param CandidateDiag partial diagnostic used for each function template
12803   /// specialization that is a candidate in the ambiguous ordering. One
12804   /// parameter in this diagnostic should be unbound, which will correspond to
12805   /// the string describing the template arguments for the function template
12806   /// specialization.
12807   ///
12808   /// \returns the most specialized function template specialization, if
12809   /// found. Otherwise, returns SpecEnd.
12810   UnresolvedSetIterator
12811   getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
12812                      TemplateSpecCandidateSet &FailedCandidates,
12813                      SourceLocation Loc, const PartialDiagnostic &NoneDiag,
12814                      const PartialDiagnostic &AmbigDiag,
12815                      const PartialDiagnostic &CandidateDiag,
12816                      bool Complain = true, QualType TargetType = QualType());
12817 
12818   /// Returns the more constrained function according to the rules of
12819   /// partial ordering by constraints (C++ [temp.constr.order]).
12820   ///
12821   /// \param FD1 the first function
12822   ///
12823   /// \param FD2 the second function
12824   ///
12825   /// \returns the more constrained function. If neither function is
12826   /// more constrained, returns NULL.
12827   FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
12828                                            FunctionDecl *FD2);
12829 
12830   ///@}
12831 
12832   //
12833   //
12834   // -------------------------------------------------------------------------
12835   //
12836   //
12837 
12838   /// \name C++ Template Deduction Guide
12839   /// Implementations are in SemaTemplateDeductionGuide.cpp
12840   ///@{
12841 
12842   /// Declare implicit deduction guides for a class template if we've
12843   /// not already done so.
12844   void DeclareImplicitDeductionGuides(TemplateDecl *Template,
12845                                       SourceLocation Loc);
12846 
12847   FunctionTemplateDecl *DeclareAggregateDeductionGuideFromInitList(
12848       TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
12849       SourceLocation Loc);
12850 
12851   ///@}
12852 
12853   //
12854   //
12855   // -------------------------------------------------------------------------
12856   //
12857   //
12858 
12859   /// \name C++ Template Instantiation
12860   /// Implementations are in SemaTemplateInstantiate.cpp
12861   ///@{
12862 
12863 public:
12864   /// A helper class for building up ExtParameterInfos.
12865   class ExtParameterInfoBuilder {
12866     SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
12867     bool HasInteresting = false;
12868 
12869   public:
12870     /// Set the ExtParameterInfo for the parameter at the given index,
12871     ///
set(unsigned index,FunctionProtoType::ExtParameterInfo info)12872     void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
12873       assert(Infos.size() <= index);
12874       Infos.resize(index);
12875       Infos.push_back(info);
12876 
12877       if (!HasInteresting)
12878         HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
12879     }
12880 
12881     /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
12882     /// ExtParameterInfo array we've built up.
12883     const FunctionProtoType::ExtParameterInfo *
getPointerOrNull(unsigned numParams)12884     getPointerOrNull(unsigned numParams) {
12885       if (!HasInteresting)
12886         return nullptr;
12887       Infos.resize(numParams);
12888       return Infos.data();
12889     }
12890   };
12891 
12892   /// The current instantiation scope used to store local
12893   /// variables.
12894   LocalInstantiationScope *CurrentInstantiationScope;
12895 
12896   typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
12897       UnparsedDefaultArgInstantiationsMap;
12898 
12899   /// A mapping from parameters with unparsed default arguments to the
12900   /// set of instantiations of each parameter.
12901   ///
12902   /// This mapping is a temporary data structure used when parsing
12903   /// nested class templates or nested classes of class templates,
12904   /// where we might end up instantiating an inner class before the
12905   /// default arguments of its methods have been parsed.
12906   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
12907 
12908   /// A context in which code is being synthesized (where a source location
12909   /// alone is not sufficient to identify the context). This covers template
12910   /// instantiation and various forms of implicitly-generated functions.
12911   struct CodeSynthesisContext {
12912     /// The kind of template instantiation we are performing
12913     enum SynthesisKind {
12914       /// We are instantiating a template declaration. The entity is
12915       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
12916       TemplateInstantiation,
12917 
12918       /// We are instantiating a default argument for a template
12919       /// parameter. The Entity is the template parameter whose argument is
12920       /// being instantiated, the Template is the template, and the
12921       /// TemplateArgs/NumTemplateArguments provide the template arguments as
12922       /// specified.
12923       DefaultTemplateArgumentInstantiation,
12924 
12925       /// We are instantiating a default argument for a function.
12926       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
12927       /// provides the template arguments as specified.
12928       DefaultFunctionArgumentInstantiation,
12929 
12930       /// We are substituting explicit template arguments provided for
12931       /// a function template. The entity is a FunctionTemplateDecl.
12932       ExplicitTemplateArgumentSubstitution,
12933 
12934       /// We are substituting template argument determined as part of
12935       /// template argument deduction for either a class template
12936       /// partial specialization or a function template. The
12937       /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
12938       /// a TemplateDecl.
12939       DeducedTemplateArgumentSubstitution,
12940 
12941       /// We are substituting into a lambda expression.
12942       LambdaExpressionSubstitution,
12943 
12944       /// We are substituting prior template arguments into a new
12945       /// template parameter. The template parameter itself is either a
12946       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
12947       PriorTemplateArgumentSubstitution,
12948 
12949       /// We are checking the validity of a default template argument that
12950       /// has been used when naming a template-id.
12951       DefaultTemplateArgumentChecking,
12952 
12953       /// We are computing the exception specification for a defaulted special
12954       /// member function.
12955       ExceptionSpecEvaluation,
12956 
12957       /// We are instantiating the exception specification for a function
12958       /// template which was deferred until it was needed.
12959       ExceptionSpecInstantiation,
12960 
12961       /// We are instantiating a requirement of a requires expression.
12962       RequirementInstantiation,
12963 
12964       /// We are checking the satisfaction of a nested requirement of a requires
12965       /// expression.
12966       NestedRequirementConstraintsCheck,
12967 
12968       /// We are declaring an implicit special member function.
12969       DeclaringSpecialMember,
12970 
12971       /// We are declaring an implicit 'operator==' for a defaulted
12972       /// 'operator<=>'.
12973       DeclaringImplicitEqualityComparison,
12974 
12975       /// We are defining a synthesized function (such as a defaulted special
12976       /// member).
12977       DefiningSynthesizedFunction,
12978 
12979       // We are checking the constraints associated with a constrained entity or
12980       // the constraint expression of a concept. This includes the checks that
12981       // atomic constraints have the type 'bool' and that they can be constant
12982       // evaluated.
12983       ConstraintsCheck,
12984 
12985       // We are substituting template arguments into a constraint expression.
12986       ConstraintSubstitution,
12987 
12988       // We are normalizing a constraint expression.
12989       ConstraintNormalization,
12990 
12991       // Instantiating a Requires Expression parameter clause.
12992       RequirementParameterInstantiation,
12993 
12994       // We are substituting into the parameter mapping of an atomic constraint
12995       // during normalization.
12996       ParameterMappingSubstitution,
12997 
12998       /// We are rewriting a comparison operator in terms of an operator<=>.
12999       RewritingOperatorAsSpaceship,
13000 
13001       /// We are initializing a structured binding.
13002       InitializingStructuredBinding,
13003 
13004       /// We are marking a class as __dllexport.
13005       MarkingClassDllexported,
13006 
13007       /// We are building an implied call from __builtin_dump_struct. The
13008       /// arguments are in CallArgs.
13009       BuildingBuiltinDumpStructCall,
13010 
13011       /// Added for Template instantiation observation.
13012       /// Memoization means we are _not_ instantiating a template because
13013       /// it is already instantiated (but we entered a context where we
13014       /// would have had to if it was not already instantiated).
13015       Memoization,
13016 
13017       /// We are building deduction guides for a class.
13018       BuildingDeductionGuides,
13019 
13020       /// We are instantiating a type alias template declaration.
13021       TypeAliasTemplateInstantiation,
13022 
13023       /// We are performing partial ordering for template template parameters.
13024       PartialOrderingTTP,
13025     } Kind;
13026 
13027     /// Was the enclosing context a non-instantiation SFINAE context?
13028     bool SavedInNonInstantiationSFINAEContext;
13029 
13030     /// Whether we're substituting into constraints.
13031     bool InConstraintSubstitution;
13032 
13033     /// The point of instantiation or synthesis within the source code.
13034     SourceLocation PointOfInstantiation;
13035 
13036     /// The entity that is being synthesized.
13037     Decl *Entity;
13038 
13039     /// The template (or partial specialization) in which we are
13040     /// performing the instantiation, for substitutions of prior template
13041     /// arguments.
13042     NamedDecl *Template;
13043 
13044     union {
13045       /// The list of template arguments we are substituting, if they
13046       /// are not part of the entity.
13047       const TemplateArgument *TemplateArgs;
13048 
13049       /// The list of argument expressions in a synthesized call.
13050       const Expr *const *CallArgs;
13051     };
13052 
13053     // FIXME: Wrap this union around more members, or perhaps store the
13054     // kind-specific members in the RAII object owning the context.
13055     union {
13056       /// The number of template arguments in TemplateArgs.
13057       unsigned NumTemplateArgs;
13058 
13059       /// The number of expressions in CallArgs.
13060       unsigned NumCallArgs;
13061 
13062       /// The special member being declared or defined.
13063       CXXSpecialMemberKind SpecialMember;
13064     };
13065 
template_argumentsCodeSynthesisContext13066     ArrayRef<TemplateArgument> template_arguments() const {
13067       assert(Kind != DeclaringSpecialMember);
13068       return {TemplateArgs, NumTemplateArgs};
13069     }
13070 
13071     /// The template deduction info object associated with the
13072     /// substitution or checking of explicit or deduced template arguments.
13073     sema::TemplateDeductionInfo *DeductionInfo;
13074 
13075     /// The source range that covers the construct that cause
13076     /// the instantiation, e.g., the template-id that causes a class
13077     /// template instantiation.
13078     SourceRange InstantiationRange;
13079 
CodeSynthesisContextCodeSynthesisContext13080     CodeSynthesisContext()
13081         : Kind(TemplateInstantiation),
13082           SavedInNonInstantiationSFINAEContext(false),
13083           InConstraintSubstitution(false), Entity(nullptr), Template(nullptr),
13084           TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
13085 
13086     /// Determines whether this template is an actual instantiation
13087     /// that should be counted toward the maximum instantiation depth.
13088     bool isInstantiationRecord() const;
13089   };
13090 
13091   /// A stack object to be created when performing template
13092   /// instantiation.
13093   ///
13094   /// Construction of an object of type \c InstantiatingTemplate
13095   /// pushes the current instantiation onto the stack of active
13096   /// instantiations. If the size of this stack exceeds the maximum
13097   /// number of recursive template instantiations, construction
13098   /// produces an error and evaluates true.
13099   ///
13100   /// Destruction of this object will pop the named instantiation off
13101   /// the stack.
13102   struct InstantiatingTemplate {
13103     /// Note that we are instantiating a class template,
13104     /// function template, variable template, alias template,
13105     /// or a member thereof.
13106     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13107                           Decl *Entity,
13108                           SourceRange InstantiationRange = SourceRange());
13109 
13110     struct ExceptionSpecification {};
13111     /// Note that we are instantiating an exception specification
13112     /// of a function template.
13113     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13114                           FunctionDecl *Entity, ExceptionSpecification,
13115                           SourceRange InstantiationRange = SourceRange());
13116 
13117     /// Note that we are instantiating a type alias template declaration.
13118     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13119                           TypeAliasTemplateDecl *Entity,
13120                           ArrayRef<TemplateArgument> TemplateArgs,
13121                           SourceRange InstantiationRange = SourceRange());
13122 
13123     /// Note that we are instantiating a default argument in a
13124     /// template-id.
13125     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13126                           TemplateParameter Param, TemplateDecl *Template,
13127                           ArrayRef<TemplateArgument> TemplateArgs,
13128                           SourceRange InstantiationRange = SourceRange());
13129 
13130     /// Note that we are substituting either explicitly-specified or
13131     /// deduced template arguments during function template argument deduction.
13132     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13133                           FunctionTemplateDecl *FunctionTemplate,
13134                           ArrayRef<TemplateArgument> TemplateArgs,
13135                           CodeSynthesisContext::SynthesisKind Kind,
13136                           sema::TemplateDeductionInfo &DeductionInfo,
13137                           SourceRange InstantiationRange = SourceRange());
13138 
13139     /// Note that we are instantiating as part of template
13140     /// argument deduction for a class template declaration.
13141     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13142                           TemplateDecl *Template,
13143                           ArrayRef<TemplateArgument> TemplateArgs,
13144                           sema::TemplateDeductionInfo &DeductionInfo,
13145                           SourceRange InstantiationRange = SourceRange());
13146 
13147     /// Note that we are instantiating as part of template
13148     /// argument deduction for a class template partial
13149     /// specialization.
13150     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13151                           ClassTemplatePartialSpecializationDecl *PartialSpec,
13152                           ArrayRef<TemplateArgument> TemplateArgs,
13153                           sema::TemplateDeductionInfo &DeductionInfo,
13154                           SourceRange InstantiationRange = SourceRange());
13155 
13156     /// Note that we are instantiating as part of template
13157     /// argument deduction for a variable template partial
13158     /// specialization.
13159     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13160                           VarTemplatePartialSpecializationDecl *PartialSpec,
13161                           ArrayRef<TemplateArgument> TemplateArgs,
13162                           sema::TemplateDeductionInfo &DeductionInfo,
13163                           SourceRange InstantiationRange = SourceRange());
13164 
13165     /// Note that we are instantiating a default argument for a function
13166     /// parameter.
13167     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13168                           ParmVarDecl *Param,
13169                           ArrayRef<TemplateArgument> TemplateArgs,
13170                           SourceRange InstantiationRange = SourceRange());
13171 
13172     /// Note that we are substituting prior template arguments into a
13173     /// non-type parameter.
13174     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13175                           NamedDecl *Template, NonTypeTemplateParmDecl *Param,
13176                           ArrayRef<TemplateArgument> TemplateArgs,
13177                           SourceRange InstantiationRange);
13178 
13179     /// Note that we are substituting prior template arguments into a
13180     /// template template parameter.
13181     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13182                           NamedDecl *Template, TemplateTemplateParmDecl *Param,
13183                           ArrayRef<TemplateArgument> TemplateArgs,
13184                           SourceRange InstantiationRange);
13185 
13186     /// Note that we are checking the default template argument
13187     /// against the template parameter for a given template-id.
13188     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13189                           TemplateDecl *Template, NamedDecl *Param,
13190                           ArrayRef<TemplateArgument> TemplateArgs,
13191                           SourceRange InstantiationRange);
13192 
13193     struct ConstraintsCheck {};
13194     /// \brief Note that we are checking the constraints associated with some
13195     /// constrained entity (a concept declaration or a template with associated
13196     /// constraints).
13197     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13198                           ConstraintsCheck, NamedDecl *Template,
13199                           ArrayRef<TemplateArgument> TemplateArgs,
13200                           SourceRange InstantiationRange);
13201 
13202     struct ConstraintSubstitution {};
13203     /// \brief Note that we are checking a constraint expression associated
13204     /// with a template declaration or as part of the satisfaction check of a
13205     /// concept.
13206     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13207                           ConstraintSubstitution, NamedDecl *Template,
13208                           sema::TemplateDeductionInfo &DeductionInfo,
13209                           SourceRange InstantiationRange);
13210 
13211     struct ConstraintNormalization {};
13212     /// \brief Note that we are normalizing a constraint expression.
13213     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13214                           ConstraintNormalization, NamedDecl *Template,
13215                           SourceRange InstantiationRange);
13216 
13217     struct ParameterMappingSubstitution {};
13218     /// \brief Note that we are subtituting into the parameter mapping of an
13219     /// atomic constraint during constraint normalization.
13220     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13221                           ParameterMappingSubstitution, NamedDecl *Template,
13222                           SourceRange InstantiationRange);
13223 
13224     /// \brief Note that we are substituting template arguments into a part of
13225     /// a requirement of a requires expression.
13226     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13227                           concepts::Requirement *Req,
13228                           sema::TemplateDeductionInfo &DeductionInfo,
13229                           SourceRange InstantiationRange = SourceRange());
13230 
13231     /// \brief Note that we are checking the satisfaction of the constraint
13232     /// expression inside of a nested requirement.
13233     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13234                           concepts::NestedRequirement *Req, ConstraintsCheck,
13235                           SourceRange InstantiationRange = SourceRange());
13236 
13237     /// \brief Note that we are checking a requires clause.
13238     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13239                           const RequiresExpr *E,
13240                           sema::TemplateDeductionInfo &DeductionInfo,
13241                           SourceRange InstantiationRange);
13242 
13243     struct BuildingDeductionGuidesTag {};
13244     /// \brief Note that we are building deduction guides.
13245     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13246                           TemplateDecl *Entity, BuildingDeductionGuidesTag,
13247                           SourceRange InstantiationRange = SourceRange());
13248 
13249     struct PartialOrderingTTP {};
13250     /// \brief Note that we are partial ordering template template parameters.
13251     InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13252                           PartialOrderingTTP, TemplateDecl *PArg,
13253                           SourceRange InstantiationRange = SourceRange());
13254 
13255     /// Note that we have finished instantiating this template.
13256     void Clear();
13257 
~InstantiatingTemplateInstantiatingTemplate13258     ~InstantiatingTemplate() { Clear(); }
13259 
13260     /// Determines whether we have exceeded the maximum
13261     /// recursive template instantiations.
isInvalidInstantiatingTemplate13262     bool isInvalid() const { return Invalid; }
13263 
13264     /// Determine whether we are already instantiating this
13265     /// specialization in some surrounding active instantiation.
isAlreadyInstantiatingInstantiatingTemplate13266     bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
13267 
13268   private:
13269     Sema &SemaRef;
13270     bool Invalid;
13271     bool AlreadyInstantiating;
13272     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
13273                                  SourceRange InstantiationRange);
13274 
13275     InstantiatingTemplate(Sema &SemaRef,
13276                           CodeSynthesisContext::SynthesisKind Kind,
13277                           SourceLocation PointOfInstantiation,
13278                           SourceRange InstantiationRange, Decl *Entity,
13279                           NamedDecl *Template = nullptr,
13280                           ArrayRef<TemplateArgument> TemplateArgs = {},
13281                           sema::TemplateDeductionInfo *DeductionInfo = nullptr);
13282 
13283     InstantiatingTemplate(const InstantiatingTemplate &) = delete;
13284 
13285     InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13286   };
13287 
13288   bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13289                              const MultiLevelTemplateArgumentList &TemplateArgs,
13290                              TemplateArgumentLoc &Output,
13291                              SourceLocation Loc = {},
13292                              const DeclarationName &Entity = {});
13293   bool
13294   SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13295                          const MultiLevelTemplateArgumentList &TemplateArgs,
13296                          TemplateArgumentListInfo &Outputs);
13297 
13298   /// Retrieve the template argument list(s) that should be used to
13299   /// instantiate the definition of the given declaration.
13300   ///
13301   /// \param ND the declaration for which we are computing template
13302   /// instantiation arguments.
13303   ///
13304   /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13305   ///  the decl context where it will be created.  In this case, the `Innermost`
13306   ///  should likely be provided.  If ND is non-null, this is ignored.
13307   ///
13308   /// \param Innermost if non-NULL, specifies a template argument list for the
13309   /// template declaration passed as ND.
13310   ///
13311   /// \param RelativeToPrimary true if we should get the template
13312   /// arguments relative to the primary template, even when we're
13313   /// dealing with a specialization. This is only relevant for function
13314   /// template specializations.
13315   ///
13316   /// \param Pattern If non-NULL, indicates the pattern from which we will be
13317   /// instantiating the definition of the given declaration, \p ND. This is
13318   /// used to determine the proper set of template instantiation arguments for
13319   /// friend function template specializations.
13320   ///
13321   /// \param ForConstraintInstantiation when collecting arguments,
13322   /// ForConstraintInstantiation indicates we should continue looking when
13323   /// encountering a lambda generic call operator, and continue looking for
13324   /// arguments on an enclosing class template.
13325   ///
13326   /// \param SkipForSpecialization when specified, any template specializations
13327   /// in a traversal would be ignored.
13328   ///
13329   /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13330   /// when encountering a specialized member function template, rather than
13331   /// returning immediately.
13332   MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13333       const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13334       std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13335       bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13336       bool ForConstraintInstantiation = false,
13337       bool SkipForSpecialization = false,
13338       bool ForDefaultArgumentSubstitution = false);
13339 
13340   /// RAII object to handle the state changes required to synthesize
13341   /// a function body.
13342   class SynthesizedFunctionScope {
13343     Sema &S;
13344     Sema::ContextRAII SavedContext;
13345     bool PushedCodeSynthesisContext = false;
13346 
13347   public:
SynthesizedFunctionScope(Sema & S,DeclContext * DC)13348     SynthesizedFunctionScope(Sema &S, DeclContext *DC)
13349         : S(S), SavedContext(S, DC) {
13350       auto *FD = dyn_cast<FunctionDecl>(DC);
13351       S.PushFunctionScope();
13352       S.PushExpressionEvaluationContextForFunction(
13353           ExpressionEvaluationContext::PotentiallyEvaluated, FD);
13354       if (FD)
13355         FD->setWillHaveBody(true);
13356       else
13357         assert(isa<ObjCMethodDecl>(DC));
13358     }
13359 
addContextNote(SourceLocation UseLoc)13360     void addContextNote(SourceLocation UseLoc) {
13361       assert(!PushedCodeSynthesisContext);
13362 
13363       Sema::CodeSynthesisContext Ctx;
13364       Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
13365       Ctx.PointOfInstantiation = UseLoc;
13366       Ctx.Entity = cast<Decl>(S.CurContext);
13367       S.pushCodeSynthesisContext(Ctx);
13368 
13369       PushedCodeSynthesisContext = true;
13370     }
13371 
~SynthesizedFunctionScope()13372     ~SynthesizedFunctionScope() {
13373       if (PushedCodeSynthesisContext)
13374         S.popCodeSynthesisContext();
13375       if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
13376         FD->setWillHaveBody(false);
13377         S.CheckImmediateEscalatingFunctionDefinition(FD, S.getCurFunction());
13378       }
13379       S.PopExpressionEvaluationContext();
13380       S.PopFunctionScopeInfo();
13381     }
13382   };
13383 
13384   /// List of active code synthesis contexts.
13385   ///
13386   /// This vector is treated as a stack. As synthesis of one entity requires
13387   /// synthesis of another, additional contexts are pushed onto the stack.
13388   SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
13389 
13390   /// Specializations whose definitions are currently being instantiated.
13391   llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
13392 
13393   /// Non-dependent types used in templates that have already been instantiated
13394   /// by some template instantiation.
13395   llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13396 
13397   /// Extra modules inspected when performing a lookup during a template
13398   /// instantiation. Computed lazily.
13399   SmallVector<Module *, 16> CodeSynthesisContextLookupModules;
13400 
13401   /// Cache of additional modules that should be used for name lookup
13402   /// within the current template instantiation. Computed lazily; use
13403   /// getLookupModules() to get a complete set.
13404   llvm::DenseSet<Module *> LookupModulesCache;
13405 
13406   /// Map from the most recent declaration of a namespace to the most
13407   /// recent visible declaration of that namespace.
13408   llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13409 
13410   /// Whether we are in a SFINAE context that is not associated with
13411   /// template instantiation.
13412   ///
13413   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
13414   /// of a template instantiation or template argument deduction.
13415   bool InNonInstantiationSFINAEContext;
13416 
13417   /// The number of \p CodeSynthesisContexts that are not template
13418   /// instantiations and, therefore, should not be counted as part of the
13419   /// instantiation depth.
13420   ///
13421   /// When the instantiation depth reaches the user-configurable limit
13422   /// \p LangOptions::InstantiationDepth we will abort instantiation.
13423   // FIXME: Should we have a similar limit for other forms of synthesis?
13424   unsigned NonInstantiationEntries;
13425 
13426   /// The depth of the context stack at the point when the most recent
13427   /// error or warning was produced.
13428   ///
13429   /// This value is used to suppress printing of redundant context stacks
13430   /// when there are multiple errors or warnings in the same instantiation.
13431   // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13432   unsigned LastEmittedCodeSynthesisContextDepth = 0;
13433 
13434   /// The template instantiation callbacks to trace or track
13435   /// instantiations (objects can be chained).
13436   ///
13437   /// This callbacks is used to print, trace or track template
13438   /// instantiations as they are being constructed.
13439   std::vector<std::unique_ptr<TemplateInstantiationCallback>>
13440       TemplateInstCallbacks;
13441 
13442   /// The current index into pack expansion arguments that will be
13443   /// used for substitution of parameter packs.
13444   ///
13445   /// The pack expansion index will be none to indicate that parameter packs
13446   /// should be instantiated as themselves. Otherwise, the index specifies
13447   /// which argument within the parameter pack will be used for substitution.
13448   UnsignedOrNone ArgPackSubstIndex;
13449 
13450   /// RAII object used to change the argument pack substitution index
13451   /// within a \c Sema object.
13452   ///
13453   /// See \c ArgPackSubstIndex for more information.
13454   class ArgPackSubstIndexRAII {
13455     Sema &Self;
13456     UnsignedOrNone OldSubstIndex;
13457 
13458   public:
ArgPackSubstIndexRAII(Sema & Self,UnsignedOrNone NewSubstIndex)13459     ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
13460         : Self(Self),
13461           OldSubstIndex(std::exchange(Self.ArgPackSubstIndex, NewSubstIndex)) {}
13462 
~ArgPackSubstIndexRAII()13463     ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13464   };
13465 
13466   friend class ArgumentPackSubstitutionRAII;
13467 
13468   void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
13469   void popCodeSynthesisContext();
13470 
PrintContextStack(InstantiationContextDiagFuncRef DiagFunc)13471   void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc) {
13472     if (!CodeSynthesisContexts.empty() &&
13473         CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
13474       PrintInstantiationStack(DiagFunc);
13475       LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
13476     }
13477     if (PragmaAttributeCurrentTargetDecl)
13478       PrintPragmaAttributeInstantiationPoint(DiagFunc);
13479   }
PrintContextStack()13480   void PrintContextStack() { PrintContextStack(getDefaultDiagFunc()); }
13481   /// Prints the current instantiation stack through a series of
13482   /// notes.
13483   void PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc);
PrintInstantiationStack()13484   void PrintInstantiationStack() {
13485     PrintInstantiationStack(getDefaultDiagFunc());
13486   }
13487 
13488   /// Determines whether we are currently in a context where
13489   /// template argument substitution failures are not considered
13490   /// errors.
13491   ///
13492   /// \returns An empty \c Optional if we're not in a SFINAE context.
13493   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
13494   /// template-deduction context object, which can be used to capture
13495   /// diagnostics that will be suppressed.
13496   std::optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
13497 
13498   /// Perform substitution on the type T with a given set of template
13499   /// arguments.
13500   ///
13501   /// This routine substitutes the given template arguments into the
13502   /// type T and produces the instantiated type.
13503   ///
13504   /// \param T the type into which the template arguments will be
13505   /// substituted. If this type is not dependent, it will be returned
13506   /// immediately.
13507   ///
13508   /// \param Args the template arguments that will be
13509   /// substituted for the top-level template parameters within T.
13510   ///
13511   /// \param Loc the location in the source code where this substitution
13512   /// is being performed. It will typically be the location of the
13513   /// declarator (if we're instantiating the type of some declaration)
13514   /// or the location of the type in the source code (if, e.g., we're
13515   /// instantiating the type of a cast expression).
13516   ///
13517   /// \param Entity the name of the entity associated with a declaration
13518   /// being instantiated (if any). May be empty to indicate that there
13519   /// is no such entity (if, e.g., this is a type that occurs as part of
13520   /// a cast expression) or that the entity has no name (e.g., an
13521   /// unnamed function parameter).
13522   ///
13523   /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
13524   /// acceptable as the top level type of the result.
13525   ///
13526   /// \param IsIncompleteSubstitution If provided, the pointee will be set
13527   /// whenever substitution would perform a replacement with a null or
13528   /// non-existent template argument.
13529   ///
13530   /// \returns If the instantiation succeeds, the instantiated
13531   /// type. Otherwise, produces diagnostics and returns a NULL type.
13532   TypeSourceInfo *SubstType(TypeSourceInfo *T,
13533                             const MultiLevelTemplateArgumentList &TemplateArgs,
13534                             SourceLocation Loc, DeclarationName Entity,
13535                             bool AllowDeducedTST = false);
13536 
13537   QualType SubstType(QualType T,
13538                      const MultiLevelTemplateArgumentList &TemplateArgs,
13539                      SourceLocation Loc, DeclarationName Entity,
13540                      bool *IsIncompleteSubstitution = nullptr);
13541 
13542   TypeSourceInfo *SubstType(TypeLoc TL,
13543                             const MultiLevelTemplateArgumentList &TemplateArgs,
13544                             SourceLocation Loc, DeclarationName Entity);
13545 
13546   /// A form of SubstType intended specifically for instantiating the
13547   /// type of a FunctionDecl.  Its purpose is solely to force the
13548   /// instantiation of default-argument expressions and to avoid
13549   /// instantiating an exception-specification.
13550   TypeSourceInfo *SubstFunctionDeclType(
13551       TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
13552       SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
13553       Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
13554   void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
13555                           const MultiLevelTemplateArgumentList &Args);
13556   bool SubstExceptionSpec(SourceLocation Loc,
13557                           FunctionProtoType::ExceptionSpecInfo &ESI,
13558                           SmallVectorImpl<QualType> &ExceptionStorage,
13559                           const MultiLevelTemplateArgumentList &Args);
13560   ParmVarDecl *
13561   SubstParmVarDecl(ParmVarDecl *D,
13562                    const MultiLevelTemplateArgumentList &TemplateArgs,
13563                    int indexAdjustment, UnsignedOrNone NumExpansions,
13564                    bool ExpectParameterPack, bool EvaluateConstraints = true);
13565 
13566   /// Substitute the given template arguments into the given set of
13567   /// parameters, producing the set of parameter types that would be generated
13568   /// from such a substitution.
13569   bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
13570                       const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
13571                       const MultiLevelTemplateArgumentList &TemplateArgs,
13572                       SmallVectorImpl<QualType> &ParamTypes,
13573                       SmallVectorImpl<ParmVarDecl *> *OutParams,
13574                       ExtParameterInfoBuilder &ParamInfos);
13575 
13576   /// Substitute the given template arguments into the default argument.
13577   bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param,
13578                             const MultiLevelTemplateArgumentList &TemplateArgs,
13579                             bool ForCallExpr = false);
13580   ExprResult SubstExpr(Expr *E,
13581                        const MultiLevelTemplateArgumentList &TemplateArgs);
13582   /// Substitute an expression as if it is a address-of-operand, which makes it
13583   /// act like a CXXIdExpression rather than an attempt to call.
13584   ExprResult SubstCXXIdExpr(Expr *E,
13585                             const MultiLevelTemplateArgumentList &TemplateArgs);
13586 
13587   // A RAII type used by the TemplateDeclInstantiator and TemplateInstantiator
13588   // to disable constraint evaluation, then restore the state.
13589   template <typename InstTy> struct ConstraintEvalRAII {
13590     InstTy &TI;
13591     bool OldValue;
13592 
ConstraintEvalRAIIConstraintEvalRAII13593     ConstraintEvalRAII(InstTy &TI)
13594         : TI(TI), OldValue(TI.getEvaluateConstraints()) {
13595       TI.setEvaluateConstraints(false);
13596     }
~ConstraintEvalRAIIConstraintEvalRAII13597     ~ConstraintEvalRAII() { TI.setEvaluateConstraints(OldValue); }
13598   };
13599 
13600   // Must be used instead of SubstExpr at 'constraint checking' time.
13601   ExprResult
13602   SubstConstraintExpr(Expr *E,
13603                       const MultiLevelTemplateArgumentList &TemplateArgs);
13604   // Unlike the above, this does not evaluate constraints.
13605   ExprResult SubstConstraintExprWithoutSatisfaction(
13606       Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
13607 
13608   /// Substitute the given template arguments into a list of
13609   /// expressions, expanding pack expansions if required.
13610   ///
13611   /// \param Exprs The list of expressions to substitute into.
13612   ///
13613   /// \param IsCall Whether this is some form of call, in which case
13614   /// default arguments will be dropped.
13615   ///
13616   /// \param TemplateArgs The set of template arguments to substitute.
13617   ///
13618   /// \param Outputs Will receive all of the substituted arguments.
13619   ///
13620   /// \returns true if an error occurred, false otherwise.
13621   bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
13622                   const MultiLevelTemplateArgumentList &TemplateArgs,
13623                   SmallVectorImpl<Expr *> &Outputs);
13624 
13625   StmtResult SubstStmt(Stmt *S,
13626                        const MultiLevelTemplateArgumentList &TemplateArgs);
13627 
13628   ExprResult
13629   SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs,
13630                    bool CXXDirectInit);
13631 
13632   /// Perform substitution on the base class specifiers of the
13633   /// given class template specialization.
13634   ///
13635   /// Produces a diagnostic and returns true on error, returns false and
13636   /// attaches the instantiated base classes to the class template
13637   /// specialization if successful.
13638   bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13639                            const MultiLevelTemplateArgumentList &TemplateArgs);
13640 
13641   /// Instantiate the definition of a class from a given pattern.
13642   ///
13643   /// \param PointOfInstantiation The point of instantiation within the
13644   /// source code.
13645   ///
13646   /// \param Instantiation is the declaration whose definition is being
13647   /// instantiated. This will be either a class template specialization
13648   /// or a member class of a class template specialization.
13649   ///
13650   /// \param Pattern is the pattern from which the instantiation
13651   /// occurs. This will be either the declaration of a class template or
13652   /// the declaration of a member class of a class template.
13653   ///
13654   /// \param TemplateArgs The template arguments to be substituted into
13655   /// the pattern.
13656   ///
13657   /// \param TSK the kind of implicit or explicit instantiation to perform.
13658   ///
13659   /// \param Complain whether to complain if the class cannot be instantiated
13660   /// due to the lack of a definition.
13661   ///
13662   /// \returns true if an error occurred, false otherwise.
13663   bool InstantiateClass(SourceLocation PointOfInstantiation,
13664                         CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13665                         const MultiLevelTemplateArgumentList &TemplateArgs,
13666                         TemplateSpecializationKind TSK, bool Complain = true);
13667 
13668   /// Instantiate the definition of an enum from a given pattern.
13669   ///
13670   /// \param PointOfInstantiation The point of instantiation within the
13671   ///        source code.
13672   /// \param Instantiation is the declaration whose definition is being
13673   ///        instantiated. This will be a member enumeration of a class
13674   ///        temploid specialization, or a local enumeration within a
13675   ///        function temploid specialization.
13676   /// \param Pattern The templated declaration from which the instantiation
13677   ///        occurs.
13678   /// \param TemplateArgs The template arguments to be substituted into
13679   ///        the pattern.
13680   /// \param TSK The kind of implicit or explicit instantiation to perform.
13681   ///
13682   /// \return \c true if an error occurred, \c false otherwise.
13683   bool InstantiateEnum(SourceLocation PointOfInstantiation,
13684                        EnumDecl *Instantiation, EnumDecl *Pattern,
13685                        const MultiLevelTemplateArgumentList &TemplateArgs,
13686                        TemplateSpecializationKind TSK);
13687 
13688   /// Instantiate the definition of a field from the given pattern.
13689   ///
13690   /// \param PointOfInstantiation The point of instantiation within the
13691   ///        source code.
13692   /// \param Instantiation is the declaration whose definition is being
13693   ///        instantiated. This will be a class of a class temploid
13694   ///        specialization, or a local enumeration within a function temploid
13695   ///        specialization.
13696   /// \param Pattern The templated declaration from which the instantiation
13697   ///        occurs.
13698   /// \param TemplateArgs The template arguments to be substituted into
13699   ///        the pattern.
13700   ///
13701   /// \return \c true if an error occurred, \c false otherwise.
13702   bool InstantiateInClassInitializer(
13703       SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
13704       FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
13705 
13706   bool usesPartialOrExplicitSpecialization(
13707       SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
13708 
13709   bool InstantiateClassTemplateSpecialization(
13710       SourceLocation PointOfInstantiation,
13711       ClassTemplateSpecializationDecl *ClassTemplateSpec,
13712       TemplateSpecializationKind TSK, bool Complain,
13713       bool PrimaryStrictPackMatch);
13714 
13715   /// Instantiates the definitions of all of the member
13716   /// of the given class, which is an instantiation of a class template
13717   /// or a member class of a template.
13718   void
13719   InstantiateClassMembers(SourceLocation PointOfInstantiation,
13720                           CXXRecordDecl *Instantiation,
13721                           const MultiLevelTemplateArgumentList &TemplateArgs,
13722                           TemplateSpecializationKind TSK);
13723 
13724   /// Instantiate the definitions of all of the members of the
13725   /// given class template specialization, which was named as part of an
13726   /// explicit instantiation.
13727   void InstantiateClassTemplateSpecializationMembers(
13728       SourceLocation PointOfInstantiation,
13729       ClassTemplateSpecializationDecl *ClassTemplateSpec,
13730       TemplateSpecializationKind TSK);
13731 
13732   NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(
13733       NestedNameSpecifierLoc NNS,
13734       const MultiLevelTemplateArgumentList &TemplateArgs);
13735 
13736   /// Do template substitution on declaration name info.
13737   DeclarationNameInfo
13738   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
13739                            const MultiLevelTemplateArgumentList &TemplateArgs);
13740   TemplateName
13741   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
13742                     SourceLocation Loc,
13743                     const MultiLevelTemplateArgumentList &TemplateArgs);
13744 
13745   bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
13746                            const MultiLevelTemplateArgumentList &TemplateArgs,
13747                            bool EvaluateConstraint);
13748 
13749   /// Determine whether we are currently performing template instantiation.
inTemplateInstantiation()13750   bool inTemplateInstantiation() const {
13751     return CodeSynthesisContexts.size() > NonInstantiationEntries;
13752   }
13753 
13754   /// Determine whether we are currently performing constraint substitution.
inConstraintSubstitution()13755   bool inConstraintSubstitution() const {
13756     return !CodeSynthesisContexts.empty() &&
13757            CodeSynthesisContexts.back().InConstraintSubstitution;
13758   }
13759 
13760   using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
13761 
13762   /// \brief create a Requirement::SubstitutionDiagnostic with only a
13763   /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
13764   concepts::Requirement::SubstitutionDiagnostic *
13765   createSubstDiagAt(SourceLocation Location, EntityPrinter Printer);
13766 
13767   ///@}
13768 
13769   //
13770   //
13771   // -------------------------------------------------------------------------
13772   //
13773   //
13774 
13775   /// \name C++ Template Declaration Instantiation
13776   /// Implementations are in SemaTemplateInstantiateDecl.cpp
13777   ///@{
13778 
13779 public:
13780   /// An entity for which implicit template instantiation is required.
13781   ///
13782   /// The source location associated with the declaration is the first place in
13783   /// the source code where the declaration was "used". It is not necessarily
13784   /// the point of instantiation (which will be either before or after the
13785   /// namespace-scope declaration that triggered this implicit instantiation),
13786   /// However, it is the location that diagnostics should generally refer to,
13787   /// because users will need to know what code triggered the instantiation.
13788   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
13789 
13790   /// The queue of implicit template instantiations that are required
13791   /// but have not yet been performed.
13792   std::deque<PendingImplicitInstantiation> PendingInstantiations;
13793 
13794   /// Queue of implicit template instantiations that cannot be performed
13795   /// eagerly.
13796   SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
13797 
13798   SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses;
13799   SmallVector<std::deque<PendingImplicitInstantiation>, 8>
13800       SavedPendingInstantiations;
13801 
13802   /// The queue of implicit template instantiations that are required
13803   /// and must be performed within the current local scope.
13804   ///
13805   /// This queue is only used for member functions of local classes in
13806   /// templates, which must be instantiated in the same scope as their
13807   /// enclosing function, so that they can reference function-local
13808   /// types, static variables, enumerators, etc.
13809   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
13810 
13811   class LocalEagerInstantiationScope {
13812   public:
LocalEagerInstantiationScope(Sema & S,bool AtEndOfTU)13813     LocalEagerInstantiationScope(Sema &S, bool AtEndOfTU)
13814         : S(S), AtEndOfTU(AtEndOfTU) {
13815       SavedPendingLocalImplicitInstantiations.swap(
13816           S.PendingLocalImplicitInstantiations);
13817     }
13818 
perform()13819     void perform() {
13820       S.PerformPendingInstantiations(/*LocalOnly=*/true,
13821                                      /*AtEndOfTU=*/AtEndOfTU);
13822     }
13823 
~LocalEagerInstantiationScope()13824     ~LocalEagerInstantiationScope() {
13825       assert(S.PendingLocalImplicitInstantiations.empty() &&
13826              "there shouldn't be any pending local implicit instantiations");
13827       SavedPendingLocalImplicitInstantiations.swap(
13828           S.PendingLocalImplicitInstantiations);
13829     }
13830 
13831   private:
13832     Sema &S;
13833     bool AtEndOfTU;
13834     std::deque<PendingImplicitInstantiation>
13835         SavedPendingLocalImplicitInstantiations;
13836   };
13837 
13838   /// Records and restores the CurFPFeatures state on entry/exit of compound
13839   /// statements.
13840   class FPFeaturesStateRAII {
13841   public:
13842     FPFeaturesStateRAII(Sema &S);
13843     ~FPFeaturesStateRAII();
getOverrides()13844     FPOptionsOverride getOverrides() { return OldOverrides; }
13845 
13846   private:
13847     Sema &S;
13848     FPOptions OldFPFeaturesState;
13849     FPOptionsOverride OldOverrides;
13850     LangOptions::FPEvalMethodKind OldEvalMethod;
13851     SourceLocation OldFPPragmaLocation;
13852   };
13853 
13854   class GlobalEagerInstantiationScope {
13855   public:
GlobalEagerInstantiationScope(Sema & S,bool Enabled,bool AtEndOfTU)13856     GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
13857         : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
13858       if (!Enabled)
13859         return;
13860 
13861       S.SavedPendingInstantiations.emplace_back();
13862       S.SavedPendingInstantiations.back().swap(S.PendingInstantiations);
13863 
13864       S.SavedVTableUses.emplace_back();
13865       S.SavedVTableUses.back().swap(S.VTableUses);
13866     }
13867 
perform()13868     void perform() {
13869       if (Enabled) {
13870         S.DefineUsedVTables();
13871         S.PerformPendingInstantiations(/*LocalOnly=*/false,
13872                                        /*AtEndOfTU=*/AtEndOfTU);
13873       }
13874     }
13875 
~GlobalEagerInstantiationScope()13876     ~GlobalEagerInstantiationScope() {
13877       if (!Enabled)
13878         return;
13879 
13880       // Restore the set of pending vtables.
13881       assert(S.VTableUses.empty() &&
13882              "VTableUses should be empty before it is discarded.");
13883       S.VTableUses.swap(S.SavedVTableUses.back());
13884       S.SavedVTableUses.pop_back();
13885 
13886       // Restore the set of pending implicit instantiations.
13887       if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
13888           AtEndOfTU) {
13889         assert(S.PendingInstantiations.empty() &&
13890                "PendingInstantiations should be empty before it is discarded.");
13891         S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
13892         S.SavedPendingInstantiations.pop_back();
13893       } else {
13894         // Template instantiations in the PCH may be delayed until the TU.
13895         S.PendingInstantiations.swap(S.SavedPendingInstantiations.back());
13896         S.PendingInstantiations.insert(
13897             S.PendingInstantiations.end(),
13898             S.SavedPendingInstantiations.back().begin(),
13899             S.SavedPendingInstantiations.back().end());
13900         S.SavedPendingInstantiations.pop_back();
13901       }
13902     }
13903 
13904   private:
13905     Sema &S;
13906     bool Enabled;
13907     bool AtEndOfTU;
13908   };
13909 
13910   ExplicitSpecifier instantiateExplicitSpecifier(
13911       const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
13912 
13913   struct LateInstantiatedAttribute {
13914     const Attr *TmplAttr;
13915     LocalInstantiationScope *Scope;
13916     Decl *NewDecl;
13917 
LateInstantiatedAttributeLateInstantiatedAttribute13918     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
13919                               Decl *D)
13920         : TmplAttr(A), Scope(S), NewDecl(D) {}
13921   };
13922   typedef SmallVector<LateInstantiatedAttribute, 1> LateInstantiatedAttrVec;
13923 
13924   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
13925                         const Decl *Pattern, Decl *Inst,
13926                         LateInstantiatedAttrVec *LateAttrs = nullptr,
13927                         LocalInstantiationScope *OuterMostScope = nullptr);
13928 
13929   /// Update instantiation attributes after template was late parsed.
13930   ///
13931   /// Some attributes are evaluated based on the body of template. If it is
13932   /// late parsed, such attributes cannot be evaluated when declaration is
13933   /// instantiated. This function is used to update instantiation attributes
13934   /// when template definition is ready.
13935   void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
13936 
13937   void
13938   InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
13939                           const Decl *Pattern, Decl *Inst,
13940                           LateInstantiatedAttrVec *LateAttrs = nullptr,
13941                           LocalInstantiationScope *OuterMostScope = nullptr);
13942 
13943   /// In the MS ABI, we need to instantiate default arguments of dllexported
13944   /// default constructors along with the constructor definition. This allows IR
13945   /// gen to emit a constructor closure which calls the default constructor with
13946   /// its default arguments.
13947   void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
13948 
13949   bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
13950                                   ParmVarDecl *Param);
13951   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
13952                                 FunctionDecl *Function);
13953 
13954   /// Instantiate (or find existing instantiation of) a function template with a
13955   /// given set of template arguments.
13956   ///
13957   /// Usually this should not be used, and template argument deduction should be
13958   /// used in its place.
13959   FunctionDecl *InstantiateFunctionDeclaration(
13960       FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
13961       SourceLocation Loc,
13962       CodeSynthesisContext::SynthesisKind CSC =
13963           CodeSynthesisContext::ExplicitTemplateArgumentSubstitution);
13964 
13965   /// Instantiate the definition of the given function from its
13966   /// template.
13967   ///
13968   /// \param PointOfInstantiation the point at which the instantiation was
13969   /// required. Note that this is not precisely a "point of instantiation"
13970   /// for the function, but it's close.
13971   ///
13972   /// \param Function the already-instantiated declaration of a
13973   /// function template specialization or member function of a class template
13974   /// specialization.
13975   ///
13976   /// \param Recursive if true, recursively instantiates any functions that
13977   /// are required by this instantiation.
13978   ///
13979   /// \param DefinitionRequired if true, then we are performing an explicit
13980   /// instantiation where the body of the function is required. Complain if
13981   /// there is no such body.
13982   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
13983                                      FunctionDecl *Function,
13984                                      bool Recursive = false,
13985                                      bool DefinitionRequired = false,
13986                                      bool AtEndOfTU = false);
13987   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
13988       VarTemplateDecl *VarTemplate, VarDecl *FromVar,
13989       const TemplateArgumentList *PartialSpecArgs,
13990       const TemplateArgumentListInfo &TemplateArgsInfo,
13991       SmallVectorImpl<TemplateArgument> &Converted,
13992       SourceLocation PointOfInstantiation,
13993       LateInstantiatedAttrVec *LateAttrs = nullptr,
13994       LocalInstantiationScope *StartingScope = nullptr);
13995 
13996   /// Instantiates a variable template specialization by completing it
13997   /// with appropriate type information and initializer.
13998   VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
13999       VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14000       const MultiLevelTemplateArgumentList &TemplateArgs);
14001 
14002   /// BuildVariableInstantiation - Used after a new variable has been created.
14003   /// Sets basic variable data and decides whether to postpone the
14004   /// variable instantiation.
14005   void
14006   BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
14007                              const MultiLevelTemplateArgumentList &TemplateArgs,
14008                              LateInstantiatedAttrVec *LateAttrs,
14009                              DeclContext *Owner,
14010                              LocalInstantiationScope *StartingScope,
14011                              bool InstantiatingVarTemplate = false,
14012                              VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14013 
14014   /// Instantiate the initializer of a variable.
14015   void InstantiateVariableInitializer(
14016       VarDecl *Var, VarDecl *OldVar,
14017       const MultiLevelTemplateArgumentList &TemplateArgs);
14018 
14019   /// Instantiate the definition of the given variable from its
14020   /// template.
14021   ///
14022   /// \param PointOfInstantiation the point at which the instantiation was
14023   /// required. Note that this is not precisely a "point of instantiation"
14024   /// for the variable, but it's close.
14025   ///
14026   /// \param Var the already-instantiated declaration of a templated variable.
14027   ///
14028   /// \param Recursive if true, recursively instantiates any functions that
14029   /// are required by this instantiation.
14030   ///
14031   /// \param DefinitionRequired if true, then we are performing an explicit
14032   /// instantiation where a definition of the variable is required. Complain
14033   /// if there is no such definition.
14034   void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14035                                      VarDecl *Var, bool Recursive = false,
14036                                      bool DefinitionRequired = false,
14037                                      bool AtEndOfTU = false);
14038 
14039   void InstantiateMemInitializers(
14040       CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl,
14041       const MultiLevelTemplateArgumentList &TemplateArgs);
14042 
14043   /// Find the instantiation of the given declaration within the
14044   /// current instantiation.
14045   ///
14046   /// This routine is intended to be used when \p D is a declaration
14047   /// referenced from within a template, that needs to mapped into the
14048   /// corresponding declaration within an instantiation. For example,
14049   /// given:
14050   ///
14051   /// \code
14052   /// template<typename T>
14053   /// struct X {
14054   ///   enum Kind {
14055   ///     KnownValue = sizeof(T)
14056   ///   };
14057   ///
14058   ///   bool getKind() const { return KnownValue; }
14059   /// };
14060   ///
14061   /// template struct X<int>;
14062   /// \endcode
14063   ///
14064   /// In the instantiation of X<int>::getKind(), we need to map the \p
14065   /// EnumConstantDecl for \p KnownValue (which refers to
14066   /// X<T>::<Kind>::KnownValue) to its instantiation
14067   /// (X<int>::<Kind>::KnownValue).
14068   /// \p FindInstantiatedDecl performs this mapping from within the
14069   /// instantiation of X<int>.
14070   NamedDecl *
14071   FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
14072                        const MultiLevelTemplateArgumentList &TemplateArgs,
14073                        bool FindingInstantiatedContext = false);
14074 
14075   /// Finds the instantiation of the given declaration context
14076   /// within the current instantiation.
14077   ///
14078   /// \returns NULL if there was an error
14079   DeclContext *
14080   FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
14081                           const MultiLevelTemplateArgumentList &TemplateArgs);
14082 
14083   Decl *SubstDecl(Decl *D, DeclContext *Owner,
14084                   const MultiLevelTemplateArgumentList &TemplateArgs);
14085 
14086   /// Substitute the name and return type of a defaulted 'operator<=>' to form
14087   /// an implicit 'operator=='.
14088   FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
14089                                            FunctionDecl *Spaceship);
14090 
14091   /// Performs template instantiation for all implicit template
14092   /// instantiations we have seen until this point.
14093   void PerformPendingInstantiations(bool LocalOnly = false,
14094                                     bool AtEndOfTU = true);
14095 
14096   TemplateParameterList *
14097   SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
14098                       const MultiLevelTemplateArgumentList &TemplateArgs,
14099                       bool EvaluateConstraints = true);
14100 
14101   void PerformDependentDiagnostics(
14102       const DeclContext *Pattern,
14103       const MultiLevelTemplateArgumentList &TemplateArgs);
14104 
14105 private:
14106   /// Introduce the instantiated local variables into the local
14107   /// instantiation scope.
14108   void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14109                                        const FunctionDecl *PatternDecl,
14110                                        LocalInstantiationScope &Scope);
14111   /// Introduce the instantiated function parameters into the local
14112   /// instantiation scope, and set the parameter names to those used
14113   /// in the template.
14114   bool addInstantiatedParametersToScope(
14115       FunctionDecl *Function, const FunctionDecl *PatternDecl,
14116       LocalInstantiationScope &Scope,
14117       const MultiLevelTemplateArgumentList &TemplateArgs);
14118 
14119   /// Introduce the instantiated captures of the lambda into the local
14120   /// instantiation scope.
14121   bool addInstantiatedCapturesToScope(
14122       FunctionDecl *Function, const FunctionDecl *PatternDecl,
14123       LocalInstantiationScope &Scope,
14124       const MultiLevelTemplateArgumentList &TemplateArgs);
14125 
14126   int ParsingClassDepth = 0;
14127 
14128   class SavePendingParsedClassStateRAII {
14129   public:
SavePendingParsedClassStateRAII(Sema & S)14130     SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14131 
~SavePendingParsedClassStateRAII()14132     ~SavePendingParsedClassStateRAII() {
14133       assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14134              "there shouldn't be any pending delayed exception spec checks");
14135       assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14136              "there shouldn't be any pending delayed exception spec checks");
14137       swapSavedState();
14138     }
14139 
14140   private:
14141     Sema &S;
14142     decltype(DelayedOverridingExceptionSpecChecks)
14143         SavedOverridingExceptionSpecChecks;
14144     decltype(DelayedEquivalentExceptionSpecChecks)
14145         SavedEquivalentExceptionSpecChecks;
14146 
swapSavedState()14147     void swapSavedState() {
14148       SavedOverridingExceptionSpecChecks.swap(
14149           S.DelayedOverridingExceptionSpecChecks);
14150       SavedEquivalentExceptionSpecChecks.swap(
14151           S.DelayedEquivalentExceptionSpecChecks);
14152     }
14153   };
14154 
14155   ///@}
14156 
14157   //
14158   //
14159   // -------------------------------------------------------------------------
14160   //
14161   //
14162 
14163   /// \name C++ Variadic Templates
14164   /// Implementations are in SemaTemplateVariadic.cpp
14165   ///@{
14166 
14167 public:
14168   /// Determine whether an unexpanded parameter pack might be permitted in this
14169   /// location. Useful for error recovery.
14170   bool isUnexpandedParameterPackPermitted();
14171 
14172   /// The context in which an unexpanded parameter pack is
14173   /// being diagnosed.
14174   ///
14175   /// Note that the values of this enumeration line up with the first
14176   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14177   enum UnexpandedParameterPackContext {
14178     /// An arbitrary expression.
14179     UPPC_Expression = 0,
14180 
14181     /// The base type of a class type.
14182     UPPC_BaseType,
14183 
14184     /// The type of an arbitrary declaration.
14185     UPPC_DeclarationType,
14186 
14187     /// The type of a data member.
14188     UPPC_DataMemberType,
14189 
14190     /// The size of a bit-field.
14191     UPPC_BitFieldWidth,
14192 
14193     /// The expression in a static assertion.
14194     UPPC_StaticAssertExpression,
14195 
14196     /// The fixed underlying type of an enumeration.
14197     UPPC_FixedUnderlyingType,
14198 
14199     /// The enumerator value.
14200     UPPC_EnumeratorValue,
14201 
14202     /// A using declaration.
14203     UPPC_UsingDeclaration,
14204 
14205     /// A friend declaration.
14206     UPPC_FriendDeclaration,
14207 
14208     /// A declaration qualifier.
14209     UPPC_DeclarationQualifier,
14210 
14211     /// An initializer.
14212     UPPC_Initializer,
14213 
14214     /// A default argument.
14215     UPPC_DefaultArgument,
14216 
14217     /// The type of a non-type template parameter.
14218     UPPC_NonTypeTemplateParameterType,
14219 
14220     /// The type of an exception.
14221     UPPC_ExceptionType,
14222 
14223     /// Explicit specialization.
14224     UPPC_ExplicitSpecialization,
14225 
14226     /// Partial specialization.
14227     UPPC_PartialSpecialization,
14228 
14229     /// Microsoft __if_exists.
14230     UPPC_IfExists,
14231 
14232     /// Microsoft __if_not_exists.
14233     UPPC_IfNotExists,
14234 
14235     /// Lambda expression.
14236     UPPC_Lambda,
14237 
14238     /// Block expression.
14239     UPPC_Block,
14240 
14241     /// A type constraint.
14242     UPPC_TypeConstraint,
14243 
14244     // A requirement in a requires-expression.
14245     UPPC_Requirement,
14246 
14247     // A requires-clause.
14248     UPPC_RequiresClause,
14249   };
14250 
14251   /// Diagnose unexpanded parameter packs.
14252   ///
14253   /// \param Loc The location at which we should emit the diagnostic.
14254   ///
14255   /// \param UPPC The context in which we are diagnosing unexpanded
14256   /// parameter packs.
14257   ///
14258   /// \param Unexpanded the set of unexpanded parameter packs.
14259   ///
14260   /// \returns true if an error occurred, false otherwise.
14261   bool DiagnoseUnexpandedParameterPacks(
14262       SourceLocation Loc, UnexpandedParameterPackContext UPPC,
14263       ArrayRef<UnexpandedParameterPack> Unexpanded);
14264 
14265   /// If the given type contains an unexpanded parameter pack,
14266   /// diagnose the error.
14267   ///
14268   /// \param Loc The source location where a diagnostc should be emitted.
14269   ///
14270   /// \param T The type that is being checked for unexpanded parameter
14271   /// packs.
14272   ///
14273   /// \returns true if an error occurred, false otherwise.
14274   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
14275                                        UnexpandedParameterPackContext UPPC);
14276 
14277   /// If the given expression contains an unexpanded parameter
14278   /// pack, diagnose the error.
14279   ///
14280   /// \param E The expression that is being checked for unexpanded
14281   /// parameter packs.
14282   ///
14283   /// \returns true if an error occurred, false otherwise.
14284   bool DiagnoseUnexpandedParameterPack(
14285       Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression);
14286 
14287   /// If the given requirees-expression contains an unexpanded reference to one
14288   /// of its own parameter packs, diagnose the error.
14289   ///
14290   /// \param RE The requiress-expression that is being checked for unexpanded
14291   /// parameter packs.
14292   ///
14293   /// \returns true if an error occurred, false otherwise.
14294   bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
14295 
14296   /// If the given nested-name-specifier contains an unexpanded
14297   /// parameter pack, diagnose the error.
14298   ///
14299   /// \param SS The nested-name-specifier that is being checked for
14300   /// unexpanded parameter packs.
14301   ///
14302   /// \returns true if an error occurred, false otherwise.
14303   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
14304                                        UnexpandedParameterPackContext UPPC);
14305 
14306   /// If the given name contains an unexpanded parameter pack,
14307   /// diagnose the error.
14308   ///
14309   /// \param NameInfo The name (with source location information) that
14310   /// is being checked for unexpanded parameter packs.
14311   ///
14312   /// \returns true if an error occurred, false otherwise.
14313   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
14314                                        UnexpandedParameterPackContext UPPC);
14315 
14316   /// If the given template name contains an unexpanded parameter pack,
14317   /// diagnose the error.
14318   ///
14319   /// \param Loc The location of the template name.
14320   ///
14321   /// \param Template The template name that is being checked for unexpanded
14322   /// parameter packs.
14323   ///
14324   /// \returns true if an error occurred, false otherwise.
14325   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
14326                                        TemplateName Template,
14327                                        UnexpandedParameterPackContext UPPC);
14328 
14329   /// If the given template argument contains an unexpanded parameter
14330   /// pack, diagnose the error.
14331   ///
14332   /// \param Arg The template argument that is being checked for unexpanded
14333   /// parameter packs.
14334   ///
14335   /// \returns true if an error occurred, false otherwise.
14336   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
14337                                        UnexpandedParameterPackContext UPPC);
14338 
14339   /// Collect the set of unexpanded parameter packs within the given
14340   /// template argument.
14341   ///
14342   /// \param Arg The template argument that will be traversed to find
14343   /// unexpanded parameter packs.
14344   void collectUnexpandedParameterPacks(
14345       TemplateArgument Arg,
14346       SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14347 
14348   /// Collect the set of unexpanded parameter packs within the given
14349   /// template argument.
14350   ///
14351   /// \param Arg The template argument that will be traversed to find
14352   /// unexpanded parameter packs.
14353   void collectUnexpandedParameterPacks(
14354       TemplateArgumentLoc Arg,
14355       SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14356 
14357   /// Collect the set of unexpanded parameter packs within the given
14358   /// type.
14359   ///
14360   /// \param T The type that will be traversed to find
14361   /// unexpanded parameter packs.
14362   void collectUnexpandedParameterPacks(
14363       QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14364 
14365   /// Collect the set of unexpanded parameter packs within the given
14366   /// type.
14367   ///
14368   /// \param TL The type that will be traversed to find
14369   /// unexpanded parameter packs.
14370   void collectUnexpandedParameterPacks(
14371       TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14372 
14373   /// Collect the set of unexpanded parameter packs within the given
14374   /// nested-name-specifier.
14375   ///
14376   /// \param NNS The nested-name-specifier that will be traversed to find
14377   /// unexpanded parameter packs.
14378   void collectUnexpandedParameterPacks(
14379       NestedNameSpecifierLoc NNS,
14380       SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14381 
14382   /// Collect the set of unexpanded parameter packs within the given
14383   /// name.
14384   ///
14385   /// \param NameInfo The name that will be traversed to find
14386   /// unexpanded parameter packs.
14387   void collectUnexpandedParameterPacks(
14388       const DeclarationNameInfo &NameInfo,
14389       SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14390 
14391   /// Collect the set of unexpanded parameter packs within the given
14392   /// expression.
14393   static void collectUnexpandedParameterPacks(
14394       Expr *E, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14395 
14396   /// Invoked when parsing a template argument followed by an
14397   /// ellipsis, which creates a pack expansion.
14398   ///
14399   /// \param Arg The template argument preceding the ellipsis, which
14400   /// may already be invalid.
14401   ///
14402   /// \param EllipsisLoc The location of the ellipsis.
14403   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
14404                                             SourceLocation EllipsisLoc);
14405 
14406   /// Invoked when parsing a type followed by an ellipsis, which
14407   /// creates a pack expansion.
14408   ///
14409   /// \param Type The type preceding the ellipsis, which will become
14410   /// the pattern of the pack expansion.
14411   ///
14412   /// \param EllipsisLoc The location of the ellipsis.
14413   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
14414 
14415   /// Construct a pack expansion type from the pattern of the pack
14416   /// expansion.
14417   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
14418                                      SourceLocation EllipsisLoc,
14419                                      UnsignedOrNone NumExpansions);
14420 
14421   /// Construct a pack expansion type from the pattern of the pack
14422   /// expansion.
14423   QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14424                               SourceLocation EllipsisLoc,
14425                               UnsignedOrNone NumExpansions);
14426 
14427   /// Invoked when parsing an expression followed by an ellipsis, which
14428   /// creates a pack expansion.
14429   ///
14430   /// \param Pattern The expression preceding the ellipsis, which will become
14431   /// the pattern of the pack expansion.
14432   ///
14433   /// \param EllipsisLoc The location of the ellipsis.
14434   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14435 
14436   /// Invoked when parsing an expression followed by an ellipsis, which
14437   /// creates a pack expansion.
14438   ///
14439   /// \param Pattern The expression preceding the ellipsis, which will become
14440   /// the pattern of the pack expansion.
14441   ///
14442   /// \param EllipsisLoc The location of the ellipsis.
14443   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14444                                 UnsignedOrNone NumExpansions);
14445 
14446   /// Determine whether we could expand a pack expansion with the
14447   /// given set of parameter packs into separate arguments by repeatedly
14448   /// transforming the pattern.
14449   ///
14450   /// \param EllipsisLoc The location of the ellipsis that identifies the
14451   /// pack expansion.
14452   ///
14453   /// \param PatternRange The source range that covers the entire pattern of
14454   /// the pack expansion.
14455   ///
14456   /// \param Unexpanded The set of unexpanded parameter packs within the
14457   /// pattern.
14458   ///
14459   /// \param ShouldExpand Will be set to \c true if the transformer should
14460   /// expand the corresponding pack expansions into separate arguments. When
14461   /// set, \c NumExpansions must also be set.
14462   ///
14463   /// \param RetainExpansion Whether the caller should add an unexpanded
14464   /// pack expansion after all of the expanded arguments. This is used
14465   /// when extending explicitly-specified template argument packs per
14466   /// C++0x [temp.arg.explicit]p9.
14467   ///
14468   /// \param NumExpansions The number of separate arguments that will be in
14469   /// the expanded form of the corresponding pack expansion. This is both an
14470   /// input and an output parameter, which can be set by the caller if the
14471   /// number of expansions is known a priori (e.g., due to a prior substitution)
14472   /// and will be set by the callee when the number of expansions is known.
14473   /// The callee must set this value when \c ShouldExpand is \c true; it may
14474   /// set this value in other cases.
14475   ///
14476   /// \returns true if an error occurred (e.g., because the parameter packs
14477   /// are to be instantiated with arguments of different lengths), false
14478   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
14479   /// must be set.
14480   bool CheckParameterPacksForExpansion(
14481       SourceLocation EllipsisLoc, SourceRange PatternRange,
14482       ArrayRef<UnexpandedParameterPack> Unexpanded,
14483       const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
14484       bool &RetainExpansion, UnsignedOrNone &NumExpansions);
14485 
14486   /// Determine the number of arguments in the given pack expansion
14487   /// type.
14488   ///
14489   /// This routine assumes that the number of arguments in the expansion is
14490   /// consistent across all of the unexpanded parameter packs in its pattern.
14491   ///
14492   /// Returns an empty Optional if the type can't be expanded.
14493   UnsignedOrNone getNumArgumentsInExpansion(
14494       QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
14495 
14496   UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(
14497       llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
14498       const MultiLevelTemplateArgumentList &TemplateArgs);
14499 
14500   /// Determine whether the given declarator contains any unexpanded
14501   /// parameter packs.
14502   ///
14503   /// This routine is used by the parser to disambiguate function declarators
14504   /// with an ellipsis prior to the ')', e.g.,
14505   ///
14506   /// \code
14507   ///   void f(T...);
14508   /// \endcode
14509   ///
14510   /// To determine whether we have an (unnamed) function parameter pack or
14511   /// a variadic function.
14512   ///
14513   /// \returns true if the declarator contains any unexpanded parameter packs,
14514   /// false otherwise.
14515   bool containsUnexpandedParameterPacks(Declarator &D);
14516 
14517   /// Returns the pattern of the pack expansion for a template argument.
14518   ///
14519   /// \param OrigLoc The template argument to expand.
14520   ///
14521   /// \param Ellipsis Will be set to the location of the ellipsis.
14522   ///
14523   /// \param NumExpansions Will be set to the number of expansions that will
14524   /// be generated from this pack expansion, if known a priori.
14525   TemplateArgumentLoc
14526   getTemplateArgumentPackExpansionPattern(TemplateArgumentLoc OrigLoc,
14527                                           SourceLocation &Ellipsis,
14528                                           UnsignedOrNone &NumExpansions) const;
14529 
14530   /// Given a template argument that contains an unexpanded parameter pack, but
14531   /// which has already been substituted, attempt to determine the number of
14532   /// elements that will be produced once this argument is fully-expanded.
14533   ///
14534   /// This is intended for use when transforming 'sizeof...(Arg)' in order to
14535   /// avoid actually expanding the pack where possible.
14536   UnsignedOrNone getFullyPackExpandedSize(TemplateArgument Arg);
14537 
14538   /// Called when an expression computing the size of a parameter pack
14539   /// is parsed.
14540   ///
14541   /// \code
14542   /// template<typename ...Types> struct count {
14543   ///   static const unsigned value = sizeof...(Types);
14544   /// };
14545   /// \endcode
14546   ///
14547   //
14548   /// \param OpLoc The location of the "sizeof" keyword.
14549   /// \param Name The name of the parameter pack whose size will be determined.
14550   /// \param NameLoc The source location of the name of the parameter pack.
14551   /// \param RParenLoc The location of the closing parentheses.
14552   ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc,
14553                                           IdentifierInfo &Name,
14554                                           SourceLocation NameLoc,
14555                                           SourceLocation RParenLoc);
14556 
14557   ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
14558                                    SourceLocation EllipsisLoc,
14559                                    SourceLocation LSquareLoc, Expr *IndexExpr,
14560                                    SourceLocation RSquareLoc);
14561 
14562   ExprResult BuildPackIndexingExpr(Expr *PackExpression,
14563                                    SourceLocation EllipsisLoc, Expr *IndexExpr,
14564                                    SourceLocation RSquareLoc,
14565                                    ArrayRef<Expr *> ExpandedExprs = {},
14566                                    bool FullySubstituted = false);
14567 
14568   /// Handle a C++1z fold-expression: ( expr op ... op expr ).
14569   ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
14570                               tok::TokenKind Operator,
14571                               SourceLocation EllipsisLoc, Expr *RHS,
14572                               SourceLocation RParenLoc);
14573   ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
14574                               SourceLocation LParenLoc, Expr *LHS,
14575                               BinaryOperatorKind Operator,
14576                               SourceLocation EllipsisLoc, Expr *RHS,
14577                               SourceLocation RParenLoc,
14578                               UnsignedOrNone NumExpansions);
14579   ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
14580                                    BinaryOperatorKind Operator);
14581 
14582   ///@}
14583 
14584   //
14585   //
14586   // -------------------------------------------------------------------------
14587   //
14588   //
14589 
14590   /// \name Constraints and Concepts
14591   /// Implementations are in SemaConcept.cpp
14592   ///@{
14593 
14594 public:
PushSatisfactionStackEntry(const NamedDecl * D,const llvm::FoldingSetNodeID & ID)14595   void PushSatisfactionStackEntry(const NamedDecl *D,
14596                                   const llvm::FoldingSetNodeID &ID) {
14597     const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
14598     SatisfactionStack.emplace_back(Can, ID);
14599   }
14600 
PopSatisfactionStackEntry()14601   void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
14602 
SatisfactionStackContains(const NamedDecl * D,const llvm::FoldingSetNodeID & ID)14603   bool SatisfactionStackContains(const NamedDecl *D,
14604                                  const llvm::FoldingSetNodeID &ID) const {
14605     const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl());
14606     return llvm::is_contained(SatisfactionStack,
14607                               SatisfactionStackEntryTy{Can, ID});
14608   }
14609 
14610   using SatisfactionStackEntryTy =
14611       std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
14612 
14613   // Resets the current SatisfactionStack for cases where we are instantiating
14614   // constraints as a 'side effect' of normal instantiation in a way that is not
14615   // indicative of recursive definition.
14616   class SatisfactionStackResetRAII {
14617     llvm::SmallVector<SatisfactionStackEntryTy, 10> BackupSatisfactionStack;
14618     Sema &SemaRef;
14619 
14620   public:
SatisfactionStackResetRAII(Sema & S)14621     SatisfactionStackResetRAII(Sema &S) : SemaRef(S) {
14622       SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
14623     }
14624 
~SatisfactionStackResetRAII()14625     ~SatisfactionStackResetRAII() {
14626       SemaRef.SwapSatisfactionStack(BackupSatisfactionStack);
14627     }
14628   };
14629 
SwapSatisfactionStack(llvm::SmallVectorImpl<SatisfactionStackEntryTy> & NewSS)14630   void SwapSatisfactionStack(
14631       llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) {
14632     SatisfactionStack.swap(NewSS);
14633   }
14634 
14635   /// Check whether the given expression is a valid constraint expression.
14636   /// A diagnostic is emitted if it is not, false is returned, and
14637   /// PossibleNonPrimary will be set to true if the failure might be due to a
14638   /// non-primary expression being used as an atomic constraint.
14639   bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
14640                                  bool *PossibleNonPrimary = nullptr,
14641                                  bool IsTrailingRequiresClause = false);
14642 
14643   /// \brief Check whether the given list of constraint expressions are
14644   /// satisfied (as if in a 'conjunction') given template arguments.
14645   /// \param Template the template-like entity that triggered the constraints
14646   /// check (either a concept or a constrained entity).
14647   /// \param ConstraintExprs a list of constraint expressions, treated as if
14648   /// they were 'AND'ed together.
14649   /// \param TemplateArgLists the list of template arguments to substitute into
14650   /// the constraint expression.
14651   /// \param TemplateIDRange The source range of the template id that
14652   /// caused the constraints check.
14653   /// \param Satisfaction if true is returned, will contain details of the
14654   /// satisfaction, with enough information to diagnose an unsatisfied
14655   /// expression.
14656   /// \returns true if an error occurred and satisfaction could not be checked,
14657   /// false otherwise.
CheckConstraintSatisfaction(const NamedDecl * Template,ArrayRef<AssociatedConstraint> AssociatedConstraints,const MultiLevelTemplateArgumentList & TemplateArgLists,SourceRange TemplateIDRange,ConstraintSatisfaction & Satisfaction)14658   bool CheckConstraintSatisfaction(
14659       const NamedDecl *Template,
14660       ArrayRef<AssociatedConstraint> AssociatedConstraints,
14661       const MultiLevelTemplateArgumentList &TemplateArgLists,
14662       SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction) {
14663     llvm::SmallVector<Expr *, 4> Converted;
14664     return CheckConstraintSatisfaction(Template, AssociatedConstraints,
14665                                        Converted, TemplateArgLists,
14666                                        TemplateIDRange, Satisfaction);
14667   }
14668 
14669   /// \brief Check whether the given list of constraint expressions are
14670   /// satisfied (as if in a 'conjunction') given template arguments.
14671   /// Additionally, takes an empty list of Expressions which is populated with
14672   /// the instantiated versions of the ConstraintExprs.
14673   /// \param Template the template-like entity that triggered the constraints
14674   /// check (either a concept or a constrained entity).
14675   /// \param ConstraintExprs a list of constraint expressions, treated as if
14676   /// they were 'AND'ed together.
14677   /// \param ConvertedConstraints a out parameter that will get populated with
14678   /// the instantiated version of the ConstraintExprs if we successfully checked
14679   /// satisfaction.
14680   /// \param TemplateArgList the multi-level list of template arguments to
14681   /// substitute into the constraint expression. This should be relative to the
14682   /// top-level (hence multi-level), since we need to instantiate fully at the
14683   /// time of checking.
14684   /// \param TemplateIDRange The source range of the template id that
14685   /// caused the constraints check.
14686   /// \param Satisfaction if true is returned, will contain details of the
14687   /// satisfaction, with enough information to diagnose an unsatisfied
14688   /// expression.
14689   /// \returns true if an error occurred and satisfaction could not be checked,
14690   /// false otherwise.
14691   bool CheckConstraintSatisfaction(
14692       const NamedDecl *Template,
14693       ArrayRef<AssociatedConstraint> AssociatedConstraints,
14694       llvm::SmallVectorImpl<Expr *> &ConvertedConstraints,
14695       const MultiLevelTemplateArgumentList &TemplateArgList,
14696       SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
14697 
14698   /// \brief Check whether the given non-dependent constraint expression is
14699   /// satisfied. Returns false and updates Satisfaction with the satisfaction
14700   /// verdict if successful, emits a diagnostic and returns true if an error
14701   /// occurred and satisfaction could not be determined.
14702   ///
14703   /// \returns true if an error occurred, false otherwise.
14704   bool
14705   CheckConstraintSatisfaction(const ConceptSpecializationExpr *ConstraintExpr,
14706                               ConstraintSatisfaction &Satisfaction);
14707 
14708   /// Check whether the given function decl's trailing requires clause is
14709   /// satisfied, if any. Returns false and updates Satisfaction with the
14710   /// satisfaction verdict if successful, emits a diagnostic and returns true if
14711   /// an error occurred and satisfaction could not be determined.
14712   ///
14713   /// \returns true if an error occurred, false otherwise.
14714   bool CheckFunctionConstraints(const FunctionDecl *FD,
14715                                 ConstraintSatisfaction &Satisfaction,
14716                                 SourceLocation UsageLoc = SourceLocation(),
14717                                 bool ForOverloadResolution = false);
14718 
14719   // Calculates whether two constraint expressions are equal irrespective of a
14720   // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
14721   // 'New', which are the "source" of the constraint, since this is necessary
14722   // for figuring out the relative 'depth' of the constraint. The depth of the
14723   // 'primary template' and the 'instantiated from' templates aren't necessarily
14724   // the same, such as a case when one is a 'friend' defined in a class.
14725   bool AreConstraintExpressionsEqual(const NamedDecl *Old,
14726                                      const Expr *OldConstr,
14727                                      const TemplateCompareNewDeclInfo &New,
14728                                      const Expr *NewConstr);
14729 
14730   // Calculates whether the friend function depends on an enclosing template for
14731   // the purposes of [temp.friend] p9.
14732   bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
14733 
14734   /// \brief Ensure that the given template arguments satisfy the constraints
14735   /// associated with the given template, emitting a diagnostic if they do not.
14736   ///
14737   /// \param Template The template to which the template arguments are being
14738   /// provided.
14739   ///
14740   /// \param TemplateArgs The converted, canonicalized template arguments.
14741   ///
14742   /// \param TemplateIDRange The source range of the template id that
14743   /// caused the constraints check.
14744   ///
14745   /// \returns true if the constrains are not satisfied or could not be checked
14746   /// for satisfaction, false if the constraints are satisfied.
14747   bool EnsureTemplateArgumentListConstraints(
14748       TemplateDecl *Template,
14749       const MultiLevelTemplateArgumentList &TemplateArgs,
14750       SourceRange TemplateIDRange);
14751 
14752   bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
14753                                         FunctionDecl *Decl,
14754                                         ArrayRef<TemplateArgument> TemplateArgs,
14755                                         ConstraintSatisfaction &Satisfaction);
14756 
14757   /// \brief Emit diagnostics explaining why a constraint expression was deemed
14758   /// unsatisfied.
14759   /// \param First whether this is the first time an unsatisfied constraint is
14760   /// diagnosed for this error.
14761   void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
14762                                      bool First = true);
14763 
14764   /// \brief Emit diagnostics explaining why a constraint expression was deemed
14765   /// unsatisfied.
14766   void
14767   DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
14768                                 bool First = true);
14769 
14770   const NormalizedConstraint *getNormalizedAssociatedConstraints(
14771       const NamedDecl *ConstrainedDecl,
14772       ArrayRef<AssociatedConstraint> AssociatedConstraints);
14773 
14774   /// \brief Check whether the given declaration's associated constraints are
14775   /// at least as constrained than another declaration's according to the
14776   /// partial ordering of constraints.
14777   ///
14778   /// \param Result If no error occurred, receives the result of true if D1 is
14779   /// at least constrained than D2, and false otherwise.
14780   ///
14781   /// \returns true if an error occurred, false otherwise.
14782   bool IsAtLeastAsConstrained(const NamedDecl *D1,
14783                               MutableArrayRef<AssociatedConstraint> AC1,
14784                               const NamedDecl *D2,
14785                               MutableArrayRef<AssociatedConstraint> AC2,
14786                               bool &Result);
14787 
14788   /// If D1 was not at least as constrained as D2, but would've been if a pair
14789   /// of atomic constraints involved had been declared in a concept and not
14790   /// repeated in two separate places in code.
14791   /// \returns true if such a diagnostic was emitted, false otherwise.
14792   bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(
14793       const NamedDecl *D1, ArrayRef<AssociatedConstraint> AC1,
14794       const NamedDecl *D2, ArrayRef<AssociatedConstraint> AC2);
14795 
14796 private:
14797   /// Caches pairs of template-like decls whose associated constraints were
14798   /// checked for subsumption and whether or not the first's constraints did in
14799   /// fact subsume the second's.
14800   llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
14801       SubsumptionCache;
14802   /// Caches the normalized associated constraints of declarations (concepts or
14803   /// constrained declarations). If an error occurred while normalizing the
14804   /// associated constraints of the template or concept, nullptr will be cached
14805   /// here.
14806   llvm::DenseMap<const NamedDecl *, NormalizedConstraint *> NormalizationCache;
14807 
14808   llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
14809       SatisfactionCache;
14810 
14811   // The current stack of constraint satisfactions, so we can exit-early.
14812   llvm::SmallVector<SatisfactionStackEntryTy, 10> SatisfactionStack;
14813 
14814   /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
14815   /// LocalInstantiationScope of the current non-lambda function. For lambdas,
14816   /// use LambdaScopeForCallOperatorInstantiationRAII.
14817   bool
14818   SetupConstraintScope(FunctionDecl *FD,
14819                        std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
14820                        const MultiLevelTemplateArgumentList &MLTAL,
14821                        LocalInstantiationScope &Scope);
14822 
14823   /// Used during constraint checking, sets up the constraint template argument
14824   /// lists, and calls SetupConstraintScope to set up the
14825   /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
14826   std::optional<MultiLevelTemplateArgumentList>
14827   SetupConstraintCheckingTemplateArgumentsAndScope(
14828       FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
14829       LocalInstantiationScope &Scope);
14830 
14831   ///@}
14832 
14833   //
14834   //
14835   // -------------------------------------------------------------------------
14836   //
14837   //
14838 
14839   /// \name Types
14840   /// Implementations are in SemaType.cpp
14841   ///@{
14842 
14843 public:
14844   /// A mapping that describes the nullability we've seen in each header file.
14845   FileNullabilityMap NullabilityMap;
14846 
getPrintable(int I)14847   static int getPrintable(int I) { return I; }
getPrintable(unsigned I)14848   static unsigned getPrintable(unsigned I) { return I; }
getPrintable(bool B)14849   static bool getPrintable(bool B) { return B; }
getPrintable(const char * S)14850   static const char *getPrintable(const char *S) { return S; }
getPrintable(StringRef S)14851   static StringRef getPrintable(StringRef S) { return S; }
getPrintable(const std::string & S)14852   static const std::string &getPrintable(const std::string &S) { return S; }
getPrintable(const IdentifierInfo * II)14853   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
14854     return II;
14855   }
getPrintable(DeclarationName N)14856   static DeclarationName getPrintable(DeclarationName N) { return N; }
getPrintable(QualType T)14857   static QualType getPrintable(QualType T) { return T; }
getPrintable(SourceRange R)14858   static SourceRange getPrintable(SourceRange R) { return R; }
getPrintable(SourceLocation L)14859   static SourceRange getPrintable(SourceLocation L) { return L; }
getPrintable(const Expr * E)14860   static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
getPrintable(TypeLoc TL)14861   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange(); }
14862 
14863   enum class CompleteTypeKind {
14864     /// Apply the normal rules for complete types.  In particular,
14865     /// treat all sizeless types as incomplete.
14866     Normal,
14867 
14868     /// Relax the normal rules for complete types so that they include
14869     /// sizeless built-in types.
14870     AcceptSizeless,
14871 
14872     // FIXME: Eventually we should flip the default to Normal and opt in
14873     // to AcceptSizeless rather than opt out of it.
14874     Default = AcceptSizeless
14875   };
14876 
14877   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
14878                               const DeclSpec *DS = nullptr);
14879   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
14880                               const DeclSpec *DS = nullptr);
14881 
14882   /// Build a pointer type.
14883   ///
14884   /// \param T The type to which we'll be building a pointer.
14885   ///
14886   /// \param Loc The location of the entity whose type involves this
14887   /// pointer type or, if there is no such entity, the location of the
14888   /// type that will have pointer type.
14889   ///
14890   /// \param Entity The name of the entity that involves the pointer
14891   /// type, if known.
14892   ///
14893   /// \returns A suitable pointer type, if there are no
14894   /// errors. Otherwise, returns a NULL type.
14895   QualType BuildPointerType(QualType T, SourceLocation Loc,
14896                             DeclarationName Entity);
14897 
14898   /// Build a reference type.
14899   ///
14900   /// \param T The type to which we'll be building a reference.
14901   ///
14902   /// \param Loc The location of the entity whose type involves this
14903   /// reference type or, if there is no such entity, the location of the
14904   /// type that will have reference type.
14905   ///
14906   /// \param Entity The name of the entity that involves the reference
14907   /// type, if known.
14908   ///
14909   /// \returns A suitable reference type, if there are no
14910   /// errors. Otherwise, returns a NULL type.
14911   QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc,
14912                               DeclarationName Entity);
14913 
14914   /// Build an array type.
14915   ///
14916   /// \param T The type of each element in the array.
14917   ///
14918   /// \param ASM C99 array size modifier (e.g., '*', 'static').
14919   ///
14920   /// \param ArraySize Expression describing the size of the array.
14921   ///
14922   /// \param Brackets The range from the opening '[' to the closing ']'.
14923   ///
14924   /// \param Entity The name of the entity that involves the array
14925   /// type, if known.
14926   ///
14927   /// \returns A suitable array type, if there are no errors. Otherwise,
14928   /// returns a NULL type.
14929   QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize,
14930                           unsigned Quals, SourceRange Brackets,
14931                           DeclarationName Entity);
14932   QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
14933 
14934   /// Build an ext-vector type.
14935   ///
14936   /// Run the required checks for the extended vector type.
14937   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
14938                               SourceLocation AttrLoc);
14939   QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
14940                            SourceLocation AttrLoc);
14941 
14942   QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy,
14943                                                   Expr *CountExpr,
14944                                                   bool CountInBytes,
14945                                                   bool OrNull);
14946 
14947   /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
14948   /// expression is uninstantiated. If instantiated it will apply the
14949   /// appropriate address space to the type. This function allows dependent
14950   /// template variables to be used in conjunction with the address_space
14951   /// attribute
14952   QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
14953                                  SourceLocation AttrLoc);
14954 
14955   /// Same as above, but constructs the AddressSpace index if not provided.
14956   QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
14957                                  SourceLocation AttrLoc);
14958 
14959   bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
14960 
14961   bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
14962 
14963   /// Build a function type.
14964   ///
14965   /// This routine checks the function type according to C++ rules and
14966   /// under the assumption that the result type and parameter types have
14967   /// just been instantiated from a template. It therefore duplicates
14968   /// some of the behavior of GetTypeForDeclarator, but in a much
14969   /// simpler form that is only suitable for this narrow use case.
14970   ///
14971   /// \param T The return type of the function.
14972   ///
14973   /// \param ParamTypes The parameter types of the function. This array
14974   /// will be modified to account for adjustments to the types of the
14975   /// function parameters.
14976   ///
14977   /// \param Loc The location of the entity whose type involves this
14978   /// function type or, if there is no such entity, the location of the
14979   /// type that will have function type.
14980   ///
14981   /// \param Entity The name of the entity that involves the function
14982   /// type, if known.
14983   ///
14984   /// \param EPI Extra information about the function type. Usually this will
14985   /// be taken from an existing function with the same prototype.
14986   ///
14987   /// \returns A suitable function type, if there are no errors. The
14988   /// unqualified type will always be a FunctionProtoType.
14989   /// Otherwise, returns a NULL type.
14990   QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes,
14991                              SourceLocation Loc, DeclarationName Entity,
14992                              const FunctionProtoType::ExtProtoInfo &EPI);
14993 
14994   /// Build a member pointer type \c T Class::*.
14995   ///
14996   /// \param T the type to which the member pointer refers.
14997   /// \param Class the class type into which the member pointer points.
14998   /// \param Loc the location where this type begins
14999   /// \param Entity the name of the entity that will have this member pointer
15000   /// type
15001   ///
15002   /// \returns a member pointer type, if successful, or a NULL type if there was
15003   /// an error.
15004   QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS,
15005                                   CXXRecordDecl *Cls, SourceLocation Loc,
15006                                   DeclarationName Entity);
15007 
15008   /// Build a block pointer type.
15009   ///
15010   /// \param T The type to which we'll be building a block pointer.
15011   ///
15012   /// \param Loc The source location, used for diagnostics.
15013   ///
15014   /// \param Entity The name of the entity that involves the block pointer
15015   /// type, if known.
15016   ///
15017   /// \returns A suitable block pointer type, if there are no
15018   /// errors. Otherwise, returns a NULL type.
15019   QualType BuildBlockPointerType(QualType T, SourceLocation Loc,
15020                                  DeclarationName Entity);
15021 
15022   /// Build a paren type including \p T.
15023   QualType BuildParenType(QualType T);
15024   QualType BuildAtomicType(QualType T, SourceLocation Loc);
15025 
15026   /// Build a Read-only Pipe type.
15027   ///
15028   /// \param T The type to which we'll be building a Pipe.
15029   ///
15030   /// \param Loc We do not use it for now.
15031   ///
15032   /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15033   /// a NULL type.
15034   QualType BuildReadPipeType(QualType T, SourceLocation Loc);
15035 
15036   /// Build a Write-only Pipe type.
15037   ///
15038   /// \param T The type to which we'll be building a Pipe.
15039   ///
15040   /// \param Loc We do not use it for now.
15041   ///
15042   /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15043   /// a NULL type.
15044   QualType BuildWritePipeType(QualType T, SourceLocation Loc);
15045 
15046   /// Build a bit-precise integer type.
15047   ///
15048   /// \param IsUnsigned Boolean representing the signedness of the type.
15049   ///
15050   /// \param BitWidth Size of this int type in bits, or an expression
15051   /// representing that.
15052   ///
15053   /// \param Loc Location of the keyword.
15054   QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15055 
15056   /// GetTypeForDeclarator - Convert the type for the specified
15057   /// declarator to Type instances.
15058   ///
15059   /// The result of this call will never be null, but the associated
15060   /// type may be a null type if there's an unrecoverable error.
15061   TypeSourceInfo *GetTypeForDeclarator(Declarator &D);
15062   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
15063 
15064   /// Package the given type and TSI into a ParsedType.
15065   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
15066   static QualType GetTypeFromParser(ParsedType Ty,
15067                                     TypeSourceInfo **TInfo = nullptr);
15068 
15069   TypeResult ActOnTypeName(Declarator &D);
15070 
15071   // Check whether the size of array element of type \p EltTy is a multiple of
15072   // its alignment and return false if it isn't.
15073   bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
15074 
15075   void
15076   diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15077                             SourceLocation FallbackLoc,
15078                             SourceLocation ConstQualLoc = SourceLocation(),
15079                             SourceLocation VolatileQualLoc = SourceLocation(),
15080                             SourceLocation RestrictQualLoc = SourceLocation(),
15081                             SourceLocation AtomicQualLoc = SourceLocation(),
15082                             SourceLocation UnalignedQualLoc = SourceLocation());
15083 
15084   /// Retrieve the keyword associated
15085   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
15086 
15087   /// Adjust the calling convention of a method to be the ABI default if it
15088   /// wasn't specified explicitly.  This handles method types formed from
15089   /// function type typedefs and typename template arguments.
15090   void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15091                               bool IsCtorOrDtor, SourceLocation Loc);
15092 
15093   // Check if there is an explicit attribute, but only look through parens.
15094   // The intent is to look for an attribute on the current declarator, but not
15095   // one that came from a typedef.
15096   bool hasExplicitCallingConv(QualType T);
15097 
15098   /// Check whether a nullability type specifier can be added to the given
15099   /// type through some means not written in source (e.g. API notes).
15100   ///
15101   /// \param Type The type to which the nullability specifier will be
15102   /// added. On success, this type will be updated appropriately.
15103   ///
15104   /// \param Nullability The nullability specifier to add.
15105   ///
15106   /// \param DiagLoc The location to use for diagnostics.
15107   ///
15108   /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15109   /// array type (e.g., because it will decay to a pointer).
15110   ///
15111   /// \param OverrideExisting Whether to override an existing, locally-specified
15112   /// nullability specifier rather than complaining about the conflict.
15113   ///
15114   /// \returns true if nullability cannot be applied, false otherwise.
15115   bool CheckImplicitNullabilityTypeSpecifier(QualType &Type,
15116                                              NullabilityKind Nullability,
15117                                              SourceLocation DiagLoc,
15118                                              bool AllowArrayTypes,
15119                                              bool OverrideExisting);
15120 
15121   /// Get the type of expression E, triggering instantiation to complete the
15122   /// type if necessary -- that is, if the expression refers to a templated
15123   /// static data member of incomplete array type.
15124   ///
15125   /// May still return an incomplete type if instantiation was not possible or
15126   /// if the type is incomplete for a different reason. Use
15127   /// RequireCompleteExprType instead if a diagnostic is expected for an
15128   /// incomplete expression type.
15129   QualType getCompletedType(Expr *E);
15130 
15131   void completeExprArrayBound(Expr *E);
15132 
15133   /// Ensure that the type of the given expression is complete.
15134   ///
15135   /// This routine checks whether the expression \p E has a complete type. If
15136   /// the expression refers to an instantiable construct, that instantiation is
15137   /// performed as needed to complete its type. Furthermore
15138   /// Sema::RequireCompleteType is called for the expression's type (or in the
15139   /// case of a reference type, the referred-to type).
15140   ///
15141   /// \param E The expression whose type is required to be complete.
15142   /// \param Kind Selects which completeness rules should be applied.
15143   /// \param Diagnoser The object that will emit a diagnostic if the type is
15144   /// incomplete.
15145   ///
15146   /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15147   /// otherwise.
15148   bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
15149                                TypeDiagnoser &Diagnoser);
15150   bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15151 
15152   template <typename... Ts>
RequireCompleteExprType(Expr * E,unsigned DiagID,const Ts &...Args)15153   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15154     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15155     return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
15156   }
15157 
15158   /// Retrieve a version of the type 'T' that is elaborated by Keyword,
15159   /// qualified by the nested-name-specifier contained in SS, and that is
15160   /// (re)declared by OwnedTagDecl, which is nullptr if this is not a
15161   /// (re)declaration.
15162   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
15163                              const CXXScopeSpec &SS, QualType T,
15164                              TagDecl *OwnedTagDecl = nullptr);
15165 
15166   // Returns the underlying type of a decltype with the given expression.
15167   QualType getDecltypeForExpr(Expr *E);
15168 
15169   QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
15170   /// If AsUnevaluated is false, E is treated as though it were an evaluated
15171   /// context, such as when building a type for decltype(auto).
15172   QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15173 
15174   QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15175                                  SourceLocation Loc,
15176                                  SourceLocation EllipsisLoc);
15177   QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15178                                  SourceLocation Loc, SourceLocation EllipsisLoc,
15179                                  bool FullySubstituted = false,
15180                                  ArrayRef<QualType> Expansions = {});
15181 
15182   using UTTKind = UnaryTransformType::UTTKind;
15183   QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
15184                                    SourceLocation Loc);
15185   QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
15186   QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
15187   QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
15188   QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
15189   QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
15190                                SourceLocation Loc);
15191   QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
15192                                SourceLocation Loc);
15193   QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
15194                                   SourceLocation Loc);
15195 
BuiltinRemoveCVRef(QualType BaseType,SourceLocation Loc)15196   QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc) {
15197     return BuiltinRemoveReference(BaseType, UTTKind::RemoveCVRef, Loc);
15198   }
15199 
15200   QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
15201                                       SourceLocation Loc);
15202   QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
15203                                    SourceLocation Loc);
15204 
15205   bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15206 
15207   /// Ensure that the type T is a literal type.
15208   ///
15209   /// This routine checks whether the type @p T is a literal type. If @p T is an
15210   /// incomplete type, an attempt is made to complete it. If @p T is a literal
15211   /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15212   /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15213   /// it the type @p T), along with notes explaining why the type is not a
15214   /// literal type, and returns true.
15215   ///
15216   /// @param Loc  The location in the source that the non-literal type
15217   /// diagnostic should refer to.
15218   ///
15219   /// @param T  The type that this routine is examining for literalness.
15220   ///
15221   /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15222   ///
15223   /// @returns @c true if @p T is not a literal type and a diagnostic was
15224   /// emitted, @c false otherwise.
15225   bool RequireLiteralType(SourceLocation Loc, QualType T,
15226                           TypeDiagnoser &Diagnoser);
15227   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15228 
15229   template <typename... Ts>
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)15230   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15231                           const Ts &...Args) {
15232     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15233     return RequireLiteralType(Loc, T, Diagnoser);
15234   }
15235 
15236   bool isCompleteType(SourceLocation Loc, QualType T,
15237                       CompleteTypeKind Kind = CompleteTypeKind::Default) {
15238     return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
15239   }
15240 
15241   /// Ensure that the type T is a complete type.
15242   ///
15243   /// This routine checks whether the type @p T is complete in any
15244   /// context where a complete type is required. If @p T is a complete
15245   /// type, returns false. If @p T is a class template specialization,
15246   /// this routine then attempts to perform class template
15247   /// instantiation. If instantiation fails, or if @p T is incomplete
15248   /// and cannot be completed, issues the diagnostic @p diag (giving it
15249   /// the type @p T) and returns true.
15250   ///
15251   /// @param Loc  The location in the source that the incomplete type
15252   /// diagnostic should refer to.
15253   ///
15254   /// @param T  The type that this routine is examining for completeness.
15255   ///
15256   /// @param Kind Selects which completeness rules should be applied.
15257   ///
15258   /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15259   /// @c false otherwise.
15260   bool RequireCompleteType(SourceLocation Loc, QualType T,
15261                            CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15262   bool RequireCompleteType(SourceLocation Loc, QualType T,
15263                            CompleteTypeKind Kind, unsigned DiagID);
15264 
RequireCompleteType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)15265   bool RequireCompleteType(SourceLocation Loc, QualType T,
15266                            TypeDiagnoser &Diagnoser) {
15267     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
15268   }
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID)15269   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15270     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
15271   }
15272 
15273   template <typename... Ts>
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)15274   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15275                            const Ts &...Args) {
15276     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15277     return RequireCompleteType(Loc, T, Diagnoser);
15278   }
15279 
15280   /// Determine whether a declaration is visible to name lookup.
isVisible(const NamedDecl * D)15281   bool isVisible(const NamedDecl *D) {
15282     return D->isUnconditionallyVisible() ||
15283            isAcceptableSlow(D, AcceptableKind::Visible);
15284   }
15285 
15286   /// Determine whether a declaration is reachable.
isReachable(const NamedDecl * D)15287   bool isReachable(const NamedDecl *D) {
15288     // All visible declarations are reachable.
15289     return D->isUnconditionallyVisible() ||
15290            isAcceptableSlow(D, AcceptableKind::Reachable);
15291   }
15292 
15293   /// Determine whether a declaration is acceptable (visible/reachable).
isAcceptable(const NamedDecl * D,AcceptableKind Kind)15294   bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
15295     return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15296   }
15297 
15298   /// Determine if \p D and \p Suggested have a structurally compatible
15299   /// layout as described in C11 6.2.7/1.
15300   bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15301 
15302   /// Determine if \p D has a visible definition. If not, suggest a declaration
15303   /// that should be made visible to expose the definition.
15304   bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15305                             bool OnlyNeedComplete = false);
hasVisibleDefinition(const NamedDecl * D)15306   bool hasVisibleDefinition(const NamedDecl *D) {
15307     NamedDecl *Hidden;
15308     return hasVisibleDefinition(const_cast<NamedDecl *>(D), &Hidden);
15309   }
15310 
15311   /// Determine if \p D has a reachable definition. If not, suggest a
15312   /// declaration that should be made reachable to expose the definition.
15313   bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15314                               bool OnlyNeedComplete = false);
hasReachableDefinition(NamedDecl * D)15315   bool hasReachableDefinition(NamedDecl *D) {
15316     NamedDecl *Hidden;
15317     return hasReachableDefinition(D, &Hidden);
15318   }
15319 
15320   bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15321                                AcceptableKind Kind,
15322                                bool OnlyNeedComplete = false);
hasAcceptableDefinition(NamedDecl * D,AcceptableKind Kind)15323   bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
15324     NamedDecl *Hidden;
15325     return hasAcceptableDefinition(D, &Hidden, Kind);
15326   }
15327 
15328   /// Try to parse the conditional expression attached to an effect attribute
15329   /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15330   /// optional on error.
15331   std::optional<FunctionEffectMode>
15332   ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15333 
15334 private:
15335   /// The implementation of RequireCompleteType
15336   bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15337                                CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15338 
15339   /// Nullability type specifiers.
15340   IdentifierInfo *Ident__Nonnull = nullptr;
15341   IdentifierInfo *Ident__Nullable = nullptr;
15342   IdentifierInfo *Ident__Nullable_result = nullptr;
15343   IdentifierInfo *Ident__Null_unspecified = nullptr;
15344 
15345   ///@}
15346 
15347   //
15348   //
15349   // -------------------------------------------------------------------------
15350   //
15351   //
15352 
15353   /// \name FixIt Helpers
15354   /// Implementations are in SemaFixItUtils.cpp
15355   ///@{
15356 
15357 public:
15358   /// Get a string to suggest for zero-initialization of a type.
15359   std::string getFixItZeroInitializerForType(QualType T,
15360                                              SourceLocation Loc) const;
15361   std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15362 
15363   ///@}
15364 
15365   //
15366   //
15367   // -------------------------------------------------------------------------
15368   //
15369   //
15370 
15371   /// \name Function Effects
15372   /// Implementations are in SemaFunctionEffects.cpp
15373   ///@{
15374 public:
15375   struct FunctionEffectDiff {
15376     enum class Kind { Added, Removed, ConditionMismatch };
15377 
15378     FunctionEffect::Kind EffectKind;
15379     Kind DiffKind;
15380     std::optional<FunctionEffectWithCondition>
15381         Old; // Invalid when 'Kind' is 'Added'.
15382     std::optional<FunctionEffectWithCondition>
15383         New; // Invalid when 'Kind' is 'Removed'.
15384 
effectNameFunctionEffectDiff15385     StringRef effectName() const {
15386       if (Old)
15387         return Old.value().Effect.name();
15388       return New.value().Effect.name();
15389     }
15390 
15391     /// Describes the result of effects differing between a base class's virtual
15392     /// method and an overriding method in a subclass.
15393     enum class OverrideResult {
15394       NoAction,
15395       Warn,
15396       Merge // Merge missing effect from base to derived.
15397     };
15398 
15399     /// Return true if adding or removing the effect as part of a type
15400     /// conversion should generate a diagnostic.
15401     bool shouldDiagnoseConversion(QualType SrcType,
15402                                   const FunctionEffectsRef &SrcFX,
15403                                   QualType DstType,
15404                                   const FunctionEffectsRef &DstFX) const;
15405 
15406     /// Return true if adding or removing the effect in a redeclaration should
15407     /// generate a diagnostic.
15408     bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
15409                                      const FunctionEffectsRef &OldFX,
15410                                      const FunctionDecl &NewFunction,
15411                                      const FunctionEffectsRef &NewFX) const;
15412 
15413     /// Return true if adding or removing the effect in a C++ virtual method
15414     /// override should generate a diagnostic.
15415     OverrideResult shouldDiagnoseMethodOverride(
15416         const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
15417         const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
15418   };
15419 
15420   struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
15421     /// Caller should short-circuit by checking for equality first.
15422     FunctionEffectDiffVector(const FunctionEffectsRef &Old,
15423                              const FunctionEffectsRef &New);
15424   };
15425 
15426   /// All functions/lambdas/blocks which have bodies and which have a non-empty
15427   /// FunctionEffectsRef to be verified.
15428   SmallVector<const Decl *> DeclsWithEffectsToVerify;
15429 
15430   /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
15431   /// are all null.
15432   FunctionEffectKindSet AllEffectsToVerify;
15433 
15434 public:
15435   /// Warn and return true if adding a function effect to a set would create a
15436   /// conflict.
15437   bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX,
15438                                          const FunctionEffectWithCondition &EC,
15439                                          SourceLocation NewAttrLoc);
15440 
15441   // Report a failure to merge function effects between declarations due to a
15442   // conflict.
15443   void
15444   diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs,
15445                                        SourceLocation NewLoc,
15446                                        SourceLocation OldLoc);
15447 
15448   /// Inline checks from the start of maybeAddDeclWithEffects, to
15449   /// minimize performance impact on code not using effects.
15450   template <class FuncOrBlockDecl>
maybeAddDeclWithEffects(FuncOrBlockDecl * D)15451   void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
15452     if (Context.hasAnyFunctionEffects())
15453       if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
15454         maybeAddDeclWithEffects(D, FX);
15455   }
15456 
15457   /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
15458   void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15459 
15460   /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
15461   void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15462 
15463   void performFunctionEffectAnalysis(TranslationUnitDecl *TU);
15464 
15465   ///@}
15466 };
15467 
15468 DeductionFailureInfo
15469 MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK,
15470                          sema::TemplateDeductionInfo &Info);
15471 
15472 /// Contains a late templated function.
15473 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
15474 struct LateParsedTemplate {
15475   CachedTokens Toks;
15476   /// The template function declaration to be late parsed.
15477   Decl *D;
15478   /// Floating-point options in the point of definition.
15479   FPOptions FPO;
15480 };
15481 
15482 template <>
15483 void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
15484                                                  PragmaMsStackAction Action,
15485                                                  llvm::StringRef StackSlotLabel,
15486                                                  AlignPackInfo Value);
15487 
15488 } // end namespace clang
15489 
15490 #endif
15491