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/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h"
37#include "clang/Basic/AttrSubjectMatchRules.h"
38#include "clang/Basic/BuiltinTraits.h"
39#include "clang/Basic/Builtins.h"
40#include "clang/Basic/CapturedStmt.h"
41#include "clang/Basic/Cuda.h"
42#include "clang/Basic/DiagnosticSema.h"
43#include "clang/Basic/ExceptionSpecificationType.h"
44#include "clang/Basic/LLVM.h"
45#include "clang/Basic/Lambda.h"
46#include "clang/Basic/LangOptions.h"
47#include "clang/Basic/Module.h"
48#include "clang/Basic/OpenCLOptions.h"
49#include "clang/Basic/OperatorKinds.h"
50#include "clang/Basic/PartialDiagnostic.h"
51#include "clang/Basic/PragmaKinds.h"
52#include "clang/Basic/SourceLocation.h"
53#include "clang/Basic/Specifiers.h"
54#include "clang/Basic/StackExhaustionHandler.h"
55#include "clang/Basic/TemplateKinds.h"
56#include "clang/Basic/TokenKinds.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/SemaConcept.h"
69#include "clang/Sema/TypoCorrection.h"
70#include "clang/Sema/Weak.h"
71#include "llvm/ADT/APInt.h"
72#include "llvm/ADT/ArrayRef.h"
73#include "llvm/ADT/BitmaskEnum.h"
74#include "llvm/ADT/DenseMap.h"
75#include "llvm/ADT/DenseSet.h"
76#include "llvm/ADT/FloatingPointMode.h"
77#include "llvm/ADT/FoldingSet.h"
78#include "llvm/ADT/MapVector.h"
79#include "llvm/ADT/PointerIntPair.h"
80#include "llvm/ADT/PointerUnion.h"
81#include "llvm/ADT/STLExtras.h"
82#include "llvm/ADT/STLForwardCompat.h"
83#include "llvm/ADT/STLFunctionalExtras.h"
84#include "llvm/ADT/SetVector.h"
85#include "llvm/ADT/SmallBitVector.h"
86#include "llvm/ADT/SmallPtrSet.h"
87#include "llvm/ADT/SmallSet.h"
88#include "llvm/ADT/SmallVector.h"
89#include "llvm/ADT/StringExtras.h"
90#include "llvm/ADT/StringMap.h"
91#include "llvm/ADT/TinyPtrVector.h"
92#include "llvm/Support/Allocator.h"
93#include "llvm/Support/Compiler.h"
94#include "llvm/Support/Error.h"
95#include "llvm/Support/ErrorHandling.h"
96#include <cassert>
97#include <climits>
98#include <cstddef>
99#include <cstdint>
100#include <deque>
101#include <functional>
102#include <iterator>
103#include <memory>
104#include <optional>
105#include <string>
106#include <tuple>
107#include <type_traits>
108#include <utility>
109#include <vector>
110
111namespace llvm {
112struct InlineAsmIdentifierInfo;
113} // namespace llvm
114
115namespace clang {
116class ADLResult;
117class APValue;
118struct ASTConstraintSatisfaction;
119class ASTConsumer;
120class ASTContext;
121class ASTDeclReader;
122class ASTMutationListener;
123class ASTReader;
124class ASTWriter;
125class CXXBasePath;
126class CXXBasePaths;
127class CXXFieldCollector;
128class CodeCompleteConsumer;
129enum class ComparisonCategoryType : unsigned char;
130class ConstraintSatisfaction;
131class DarwinSDKInfo;
132class DeclGroupRef;
133class DeducedTemplateArgument;
134struct DeductionFailureInfo;
135class DependentDiagnostic;
136class Designation;
137class IdentifierInfo;
138struct ImplicitAllocationArguments;
139class ImplicitConversionSequence;
140typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
141class InitializationKind;
142class InitializationSequence;
143class InitializedEntity;
144enum class LangAS : unsigned int;
145class LocalInstantiationScope;
146class LookupResult;
147class MangleNumberingContext;
148typedef ArrayRef<IdentifierLoc> ModuleIdPath;
149class ModuleLoader;
150class MultiLevelTemplateArgumentList;
151struct NormalizedConstraint;
152class ObjCInterfaceDecl;
153class ObjCMethodDecl;
154struct OverloadCandidate;
155enum class OverloadCandidateParamOrder : char;
156enum OverloadCandidateRewriteKind : unsigned;
157class OverloadCandidateSet;
158class Preprocessor;
159struct APINotesSelectorDiagnosticState;
160struct ResolvedAllocation;
161class SemaAMDGPU;
162class SemaARM;
163class SemaAVR;
164class SemaBPF;
165class SemaCodeCompletion;
166class SemaCUDA;
167class SemaDirectX;
168class SemaHLSL;
169class SemaHexagon;
170class SemaLoongArch;
171class SemaM68k;
172class SemaMIPS;
173class SemaMSP430;
174class SemaNVPTX;
175class SemaObjC;
176class SemaOpenACC;
177class SemaOpenCL;
178class SemaOpenMP;
179class SemaPPC;
180class SemaPseudoObject;
181class SemaRISCV;
182class SemaSPIRV;
183class SemaSYCL;
184class SemaSwift;
185class SemaSystemZ;
186class SemaWasm;
187class SemaX86;
188class StandardConversionSequence;
189class TemplateArgument;
190class TemplateArgumentLoc;
191class TemplateInstantiationCallback;
192class TemplatePartialOrderingContext;
193class TemplateSpecCandidateSet;
194class Token;
195class TypeConstraint;
196class TypoCorrectionConsumer;
197class UnresolvedSetImpl;
198class UnresolvedSetIterator;
199class VisibleDeclConsumer;
200
201namespace sema {
202class BlockScopeInfo;
203class Capture;
204class CapturedRegionScopeInfo;
205class CapturingScopeInfo;
206class CompoundScopeInfo;
207class DelayedDiagnostic;
208class DelayedDiagnosticPool;
209class FunctionScopeInfo;
210class LambdaScopeInfo;
211class SemaPPCallbacks;
212class TemplateDeductionInfo;
213} // namespace sema
214
215// AssignmentAction - This is used by all the assignment diagnostic functions
216// to represent what is actually causing the operation
217enum class AssignmentAction {
218 Assigning,
219 Passing,
220 Returning,
221 Converting,
222 Initializing,
223 Sending,
224 Casting,
225 Passing_CFAudited
226};
227
228// Inline capacity for type-aware, aligned, and unaligned allocation argument
229// list candidates.
230using AllocationArgumentSet = SmallVector<ImplicitAllocationArguments, 3>;
231
232namespace threadSafety {
233class BeforeSet;
234void threadSafetyCleanup(BeforeSet *Cache);
235} // namespace threadSafety
236
237// FIXME: No way to easily map from TemplateTypeParmTypes to
238// TemplateTypeParmDecls, so we have this horrible PointerUnion.
239typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *,
240 const TemplateSpecializationType *,
241 const SubstBuiltinTemplatePackType *>,
242 SourceLocation>
243 UnexpandedParameterPack;
244
245/// Describes whether we've seen any nullability information for the given
246/// file.
247struct FileNullability {
248 /// The first pointer declarator (of any pointer kind) in the file that does
249 /// not have a corresponding nullability annotation.
250 SourceLocation PointerLoc;
251
252 /// The end location for the first pointer declarator in the file. Used for
253 /// placing fix-its.
254 SourceLocation PointerEndLoc;
255
256 /// Which kind of pointer declarator we saw.
257 uint8_t PointerKind;
258
259 /// Whether we saw any type nullability annotations in the given file.
260 bool SawTypeNullability = false;
261};
262
263/// A mapping from file IDs to a record of whether we've seen nullability
264/// information in that file.
265class FileNullabilityMap {
266 /// A mapping from file IDs to the nullability information for each file ID.
267 llvm::DenseMap<FileID, FileNullability> Map;
268
269 /// A single-element cache based on the file ID.
270 struct {
271 FileID File;
272 FileNullability Nullability;
273 } Cache;
274
275public:
276 FileNullability &operator[](FileID file) {
277 // Check the single-element cache.
278 if (file == Cache.File)
279 return Cache.Nullability;
280
281 // It's not in the single-element cache; flush the cache if we have one.
282 if (!Cache.File.isInvalid()) {
283 Map[Cache.File] = Cache.Nullability;
284 }
285
286 // Pull this entry into the cache.
287 Cache.File = file;
288 Cache.Nullability = Map[file];
289 return Cache.Nullability;
290 }
291};
292
293/// Tracks expected type during expression parsing, for use in code completion.
294/// The type is tied to a particular token, all functions that update or consume
295/// the type take a start location of the token they are looking at as a
296/// parameter. This avoids updating the type on hot paths in the parser.
297class PreferredTypeBuilder {
298public:
299 PreferredTypeBuilder(ASTContext *Ctx, bool Enabled)
300 : Ctx(Ctx), Enabled(Enabled) {}
301
302 void enterCondition(Sema &S, SourceLocation Tok);
303 void enterReturn(Sema &S, SourceLocation Tok);
304 void enterVariableInit(SourceLocation Tok, Decl *D);
305 /// Handles e.g. BaseType{ .D = Tok...
306 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
307 const Designation &D);
308 /// Computing a type for the function argument may require running
309 /// overloading, so we postpone its computation until it is actually needed.
310 ///
311 /// Clients should be very careful when using this function, as it stores a
312 /// function_ref, clients should make sure all calls to get() with the same
313 /// location happen while function_ref is alive.
314 ///
315 /// The callback should also emit signature help as a side-effect, but only
316 /// if the completion point has been reached.
317 void enterFunctionArgument(SourceLocation Tok,
318 llvm::function_ref<QualType()> ComputeType);
319
320 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
321 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
322 SourceLocation OpLoc);
323 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
324 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
325 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
326 /// Handles all type casts, including C-style cast, C++ casts, etc.
327 void enterTypeCast(SourceLocation Tok, QualType CastType);
328
329 /// Get the expected type associated with this location, if any.
330 ///
331 /// If the location is a function argument, determining the expected type
332 /// involves considering all function overloads and the arguments so far.
333 /// In this case, signature help for these function overloads will be reported
334 /// as a side-effect (only if the completion point has been reached).
335 QualType get(SourceLocation Tok) const {
336 if (!Enabled || Tok != ExpectedLoc)
337 return QualType();
338 if (!Type.isNull())
339 return Type;
340 if (ComputeType)
341 return ComputeType();
342 return QualType();
343 }
344
345private:
346 ASTContext *Ctx;
347 bool Enabled;
348 /// Start position of a token for which we store expected type.
349 SourceLocation ExpectedLoc;
350 /// Expected type for a token starting at ExpectedLoc.
351 QualType Type;
352 /// A function to compute expected type at ExpectedLoc. It is only considered
353 /// if Type is null.
354 llvm::function_ref<QualType()> ComputeType;
355};
356
357struct SkipBodyInfo {
358 SkipBodyInfo() = default;
359 bool ShouldSkip = false;
360 bool CheckSameAsPrevious = false;
361 NamedDecl *Previous = nullptr;
362 NamedDecl *New = nullptr;
363};
364
365/// Describes the result of template argument deduction.
366///
367/// The TemplateDeductionResult enumeration describes the result of
368/// template argument deduction, as returned from
369/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
370/// structure provides additional information about the results of
371/// template argument deduction, e.g., the deduced template argument
372/// list (if successful) or the specific template parameters or
373/// deduced arguments that were involved in the failure.
374enum class TemplateDeductionResult {
375 /// Template argument deduction was successful.
376 Success = 0,
377 /// The declaration was invalid; do nothing.
378 Invalid,
379 /// Template argument deduction exceeded the maximum template
380 /// instantiation depth (which has already been diagnosed).
381 InstantiationDepth,
382 /// Template argument deduction did not deduce a value
383 /// for every template parameter.
384 Incomplete,
385 /// Template argument deduction did not deduce a value for every
386 /// expansion of an expanded template parameter pack.
387 IncompletePack,
388 /// Template argument deduction produced inconsistent
389 /// deduced values for the given template parameter.
390 Inconsistent,
391 /// Template argument deduction failed due to inconsistent
392 /// cv-qualifiers on a template parameter type that would
393 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
394 /// but were given a non-const "X".
395 Underqualified,
396 /// Substitution of the deduced template argument values
397 /// resulted in an error.
398 SubstitutionFailure,
399 /// After substituting deduced template arguments, a dependent
400 /// parameter type did not match the corresponding argument.
401 DeducedMismatch,
402 /// After substituting deduced template arguments, an element of
403 /// a dependent parameter type did not match the corresponding element
404 /// of the corresponding argument (when deducing from an initializer list).
405 DeducedMismatchNested,
406 /// A non-depnedent component of the parameter did not match the
407 /// corresponding component of the argument.
408 NonDeducedMismatch,
409 /// When performing template argument deduction for a function
410 /// template, there were too many call arguments.
411 TooManyArguments,
412 /// When performing template argument deduction for a function
413 /// template, there were too few call arguments.
414 TooFewArguments,
415 /// The explicitly-specified template arguments were not valid
416 /// template arguments for the given template.
417 InvalidExplicitArguments,
418 /// Checking non-dependent argument conversions failed.
419 NonDependentConversionFailure,
420 /// The deduced arguments did not satisfy the constraints associated
421 /// with the template.
422 ConstraintsNotSatisfied,
423 /// Deduction failed; that's all we know.
424 MiscellaneousDeductionFailure,
425 /// CUDA Target attributes do not match.
426 CUDATargetMismatch,
427 /// Some error which was already diagnosed.
428 AlreadyDiagnosed
429};
430
431/// The kind of conversion being performed.
432enum class CheckedConversionKind {
433 /// An implicit conversion.
434 Implicit,
435 /// A C-style cast.
436 CStyleCast,
437 /// A functional-style cast.
438 FunctionalCast,
439 /// A cast other than a C-style cast.
440 OtherCast,
441 /// A conversion for an operand of a builtin overloaded operator.
442 ForBuiltinOverloadedOp
443};
444
445enum class TagUseKind {
446 Reference, // Reference to a tag: 'struct foo *X;'
447 Declaration, // Fwd decl of a tag: 'struct foo;'
448 Definition, // Definition of a tag: 'struct foo { int X; } Y;'
449 Friend // Friend declaration: 'friend struct foo;'
450};
451
452/// Used with attributes/effects with a boolean condition, e.g. `nonblocking`.
453enum class FunctionEffectMode : uint8_t {
454 None, // effect is not present.
455 False, // effect(false).
456 True, // effect(true).
457 Dependent // effect(expr) where expr is dependent.
458};
459
460/// pragma clang section kind
461enum class PragmaClangSectionKind {
462 Invalid = 0,
463 BSS = 1,
464 Data = 2,
465 Rodata = 3,
466 Text = 4,
467 Relro = 5
468};
469
470enum class PragmaClangSectionAction { Set = 0, Clear = 1 };
471
472enum class PragmaOptionsAlignKind {
473 Native, // #pragma options align=native
474 Natural, // #pragma options align=natural
475 Packed, // #pragma options align=packed
476 Power, // #pragma options align=power
477 Mac68k, // #pragma options align=mac68k
478 Reset // #pragma options align=reset
479};
480
481enum class TUFragmentKind {
482 /// The global module fragment, between 'module;' and a module-declaration.
483 Global,
484 /// A normal translation unit fragment. For a non-module unit, this is the
485 /// entire translation unit. Otherwise, it runs from the module-declaration
486 /// to the private-module-fragment (if any) or the end of the TU (if not).
487 Normal,
488 /// The private module fragment, between 'module :private;' and the end of
489 /// the translation unit.
490 Private
491};
492
493enum class FormatStringType {
494 Scanf,
495 Printf,
496 NSString,
497 Strftime,
498 Strfmon,
499 Kprintf,
500 FreeBSDKPrintf,
501 OSTrace,
502 OSLog,
503 Unknown
504};
505
506// Used for emitting the right warning by DefaultVariadicArgumentPromotion
507enum class VariadicCallType {
508 Function,
509 Block,
510 Method,
511 Constructor,
512 DoesNotApply
513};
514
515enum class BuiltinCountedByRefKind {
516 Assignment,
517 Initializer,
518 FunctionArg,
519 ReturnArg,
520 ArraySubscript,
521 BinaryExpr,
522};
523
524// Contexts where using non-trivial C union types can be disallowed. This is
525// passed to err_non_trivial_c_union_in_invalid_context.
526enum class NonTrivialCUnionContext {
527 // Function parameter.
528 FunctionParam,
529 // Function return.
530 FunctionReturn,
531 // Default-initialized object.
532 DefaultInitializedObject,
533 // Variable with automatic storage duration.
534 AutoVar,
535 // Initializer expression that might copy from another object.
536 CopyInit,
537 // Assignment.
538 Assignment,
539 // Compound literal.
540 CompoundLiteral,
541 // Block capture.
542 BlockCapture,
543 // lvalue-to-rvalue conversion of volatile type.
544 LValueToRValueVolatile,
545};
546
547/// Describes the result of the name lookup and resolution performed
548/// by \c Sema::ClassifyName().
549enum class NameClassificationKind {
550 /// This name is not a type or template in this context, but might be
551 /// something else.
552 Unknown,
553 /// Classification failed; an error has been produced.
554 Error,
555 /// The name has been typo-corrected to a keyword.
556 Keyword,
557 /// The name was classified as a type.
558 Type,
559 /// The name was classified as a specific non-type, non-template
560 /// declaration. ActOnNameClassifiedAsNonType should be called to
561 /// convert the declaration to an expression.
562 NonType,
563 /// The name was classified as an ADL-only function name.
564 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
565 /// result to an expression.
566 UndeclaredNonType,
567 /// The name denotes a member of a dependent type that could not be
568 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
569 /// convert the result to an expression.
570 DependentNonType,
571 /// The name was classified as an overload set, and an expression
572 /// representing that overload set has been formed.
573 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
574 /// expression referencing the overload set.
575 OverloadSet,
576 /// The name was classified as a template whose specializations are types.
577 TypeTemplate,
578 /// The name was classified as a variable template name.
579 VarTemplate,
580 /// The name was classified as a function template name.
581 FunctionTemplate,
582 /// The name was classified as an ADL-only function template name.
583 UndeclaredTemplate,
584 /// The name was classified as a concept name.
585 Concept,
586};
587
588enum class PointerAuthDiscArgKind {
589 // Address discrimination argument of __ptrauth.
590 Addr,
591
592 // Extra discriminator argument of __ptrauth.
593 Extra,
594};
595
596/// Common ways to introduce type names without a tag for use in diagnostics.
597/// Keep in sync with err_tag_reference_non_tag.
598enum class NonTagKind {
599 NonStruct,
600 NonClass,
601 NonUnion,
602 NonEnum,
603 Typedef,
604 TypeAlias,
605 Template,
606 TypeAliasTemplate,
607 TemplateTemplateArgument,
608};
609
610enum class OffsetOfKind {
611 // Not parsing a type within __builtin_offsetof.
612 Outside,
613 // Parsing a type within __builtin_offsetof.
614 Builtin,
615 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
616 // To improve our diagnostic message.
617 Macro,
618};
619
620/// Describes the kind of merge to perform for availability
621/// attributes (including "deprecated", "unavailable", and "availability").
622enum class AvailabilityMergeKind {
623 /// Don't merge availability attributes at all.
624 None,
625 /// Merge availability attributes for a redeclaration, which requires
626 /// an exact match.
627 Redeclaration,
628 /// Merge availability attributes for an override, which requires
629 /// an exact match or a weakening of constraints.
630 Override,
631 /// Merge availability attributes for an implementation of
632 /// a protocol requirement.
633 ProtocolImplementation,
634 /// Merge availability attributes for an implementation of
635 /// an optional protocol requirement.
636 OptionalProtocolImplementation
637};
638
639enum class TrivialABIHandling {
640 /// The triviality of a method unaffected by "trivial_abi".
641 IgnoreTrivialABI,
642
643 /// The triviality of a method affected by "trivial_abi".
644 ConsiderTrivialABI
645};
646
647enum class TryCaptureKind { Implicit, ExplicitByVal, ExplicitByRef };
648
649enum class AllowFoldKind {
650 No,
651 Allow,
652};
653
654/// Context in which we're performing a usual arithmetic conversion.
655enum class ArithConvKind {
656 /// An arithmetic operation.
657 Arithmetic,
658 /// A bitwise operation.
659 BitwiseOp,
660 /// A comparison.
661 Comparison,
662 /// A conditional (?:) operator.
663 Conditional,
664 /// A compound assignment expression.
665 CompAssign,
666};
667
668// Used for determining in which context a type is allowed to be passed to a
669// vararg function.
670enum class VarArgKind {
671 Valid,
672 ValidInCXX11,
673 Undefined,
674 MSVCUndefined,
675 Invalid
676};
677
678/// AssignConvertType - All of the 'assignment' semantic checks return this
679/// enum to indicate whether the assignment was allowed. These checks are
680/// done for simple assignments, as well as initialization, return from
681/// function, argument passing, etc. The query is phrased in terms of a
682/// source and destination type.
683enum class AssignConvertType {
684 /// Compatible - the types are compatible according to the standard.
685 Compatible,
686
687 /// CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because
688 /// a void * can implicitly convert to another pointer type, which we
689 /// differentiate for better diagnostic behavior.
690 CompatibleVoidPtrToNonVoidPtr,
691
692 /// PointerToInt - The assignment converts a pointer to an int, which we
693 /// accept as an extension.
694 PointerToInt,
695
696 /// IntToPointer - The assignment converts an int to a pointer, which we
697 /// accept as an extension.
698 IntToPointer,
699
700 /// FunctionVoidPointer - The assignment is between a function pointer and
701 /// void*, which the standard doesn't allow, but we accept as an extension.
702 FunctionVoidPointer,
703
704 /// IncompatiblePointer - The assignment is between two pointers types that
705 /// are not compatible, but we accept them as an extension.
706 IncompatiblePointer,
707
708 /// IncompatibleFunctionPointer - The assignment is between two function
709 /// pointers types that are not compatible, but we accept them as an
710 /// extension.
711 IncompatibleFunctionPointer,
712
713 /// IncompatibleFunctionPointerStrict - The assignment is between two
714 /// function pointer types that are not identical, but are compatible,
715 /// unless compiled with -fsanitize=cfi, in which case the type mismatch
716 /// may trip an indirect call runtime check.
717 IncompatibleFunctionPointerStrict,
718
719 /// IncompatiblePointerSign - The assignment is between two pointers types
720 /// which point to integers which have a different sign, but are otherwise
721 /// identical. This is a subset of the above, but broken out because it's by
722 /// far the most common case of incompatible pointers.
723 IncompatiblePointerSign,
724
725 /// CompatiblePointerDiscardsQualifiers - The assignment discards
726 /// c/v/r qualifiers, which we accept as an extension.
727 CompatiblePointerDiscardsQualifiers,
728
729 /// IncompatiblePointerDiscardsQualifiers - The assignment
730 /// discards qualifiers that we don't permit to be discarded,
731 /// like address spaces.
732 IncompatiblePointerDiscardsQualifiers,
733
734 /// IncompatiblePointerDiscardsOverflowBehavior - The assignment
735 /// discards overflow behavior annotations between otherwise compatible
736 /// pointer types.
737 IncompatiblePointerDiscardsOverflowBehavior,
738
739 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
740 /// changes address spaces in nested pointer types which is not allowed.
741 /// For instance, converting __private int ** to __generic int ** is
742 /// illegal even though __private could be converted to __generic.
743 IncompatibleNestedPointerAddressSpaceMismatch,
744
745 /// IncompatibleNestedPointerQualifiers - The assignment is between two
746 /// nested pointer types, and the qualifiers other than the first two
747 /// levels differ e.g. char ** -> const char **, but we accept them as an
748 /// extension.
749 IncompatibleNestedPointerQualifiers,
750
751 /// IncompatibleVectors - The assignment is between two vector types that
752 /// have the same size, which we accept as an extension.
753 IncompatibleVectors,
754
755 /// IntToBlockPointer - The assignment converts an int to a block
756 /// pointer. We disallow this.
757 IntToBlockPointer,
758
759 /// IncompatibleBlockPointer - The assignment is between two block
760 /// pointers types that are not compatible.
761 IncompatibleBlockPointer,
762
763 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
764 /// id type and something else (that is incompatible with it). For example,
765 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
766 IncompatibleObjCQualifiedId,
767
768 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
769 /// object with __weak qualifier.
770 IncompatibleObjCWeakRef,
771
772 /// IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType
773 /// kinds, e.g., from __ob_trap to __ob_wrap or vice versa.
774 IncompatibleOBTKinds,
775
776 /// CompatibleOBTDiscards - Assignment discards overflow behavior
777 CompatibleOBTDiscards,
778
779 /// Incompatible - We reject this conversion outright, it is invalid to
780 /// represent it in the AST.
781 Incompatible
782};
783
784/// The scope in which to find allocation functions.
785enum class AllocationFunctionScope {
786 /// Only look for allocation functions in the global scope.
787 Global,
788 /// Only look for allocation functions in the scope of the
789 /// allocated class.
790 Class,
791 /// Look for allocation functions in both the global scope
792 /// and in the scope of the allocated class.
793 Both
794};
795
796/// Describes the result of an "if-exists" condition check.
797enum class IfExistsResult {
798 /// The symbol exists.
799 Exists,
800
801 /// The symbol does not exist.
802 DoesNotExist,
803
804 /// The name is a dependent name, so the results will differ
805 /// from one instantiation to the next.
806 Dependent,
807
808 /// An error occurred.
809 Error
810};
811
812enum class CorrectTypoKind {
813 NonError, // CorrectTypo used in a non error recovery situation.
814 ErrorRecovery // CorrectTypo used in normal error recovery.
815};
816
817enum class OverloadKind {
818 /// This is a legitimate overload: the existing declarations are
819 /// functions or function templates with different signatures.
820 Overload,
821
822 /// This is not an overload because the signature exactly matches
823 /// an existing declaration.
824 Match,
825
826 /// This is not an overload because the lookup results contain a
827 /// non-function.
828 NonFunction
829};
830
831/// Contexts in which a converted constant expression is required.
832enum class CCEKind {
833 CaseValue, ///< Expression in a case label.
834 Enumerator, ///< Enumerator value with fixed underlying type.
835 TemplateArg, ///< Value of a non-type template parameter.
836 TempArgStrict, ///< As above, but applies strict template checking
837 ///< rules.
838 ArrayBound, ///< Array bound in array declarator or new-expression.
839 ExplicitBool, ///< Condition in an explicit(bool) specifier.
840 Noexcept, ///< Condition in a noexcept(bool) specifier.
841 StaticAssertMessageSize, ///< Call to size() in a static assert
842 ///< message.
843 StaticAssertMessageData, ///< Call to data() in a static assert
844 ///< message.
845 PackIndex ///< Index of a pack indexing expression or specifier.
846};
847
848/// Enums for the diagnostics of target, target_version and target_clones.
849namespace DiagAttrParams {
850enum DiagType { Unsupported, Duplicate, Unknown };
851enum Specifier { None, CPU, Tune };
852enum AttrName { Target, TargetClones, TargetVersion };
853} // end namespace DiagAttrParams
854
855void inferNoReturnAttr(Sema &S, Decl *D);
856
857#ifdef __GNUC__
858#pragma GCC diagnostic push
859#pragma GCC diagnostic ignored "-Wattributes"
860#endif
861/// Sema - This implements semantic analysis and AST building for C.
862/// \nosubgrouping
863class Sema final : public SemaBase {
864#ifdef __GNUC__
865#pragma GCC diagnostic pop
866#endif
867 // Table of Contents
868 // -----------------
869 // 1. Semantic Analysis (Sema.cpp)
870 // 2. API Notes (SemaAPINotes.cpp)
871 // 3. C++ Access Control (SemaAccess.cpp)
872 // 4. Attributes (SemaAttr.cpp)
873 // 5. Availability Attribute Handling (SemaAvailability.cpp)
874 // 6. Bounds Safety (SemaBoundsSafety.cpp)
875 // 7. Casts (SemaCast.cpp)
876 // 8. Extra Semantic Checking (SemaChecking.cpp)
877 // 9. C++ Coroutines (SemaCoroutine.cpp)
878 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
879 // 11. Declarations (SemaDecl.cpp)
880 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
881 // 13. C++ Declarations (SemaDeclCXX.cpp)
882 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
883 // 15. Expressions (SemaExpr.cpp)
884 // 16. C++ Expressions (SemaExprCXX.cpp)
885 // 17. Member Access Expressions (SemaExprMember.cpp)
886 // 18. Initializers (SemaInit.cpp)
887 // 19. C++ Lambda Expressions (SemaLambda.cpp)
888 // 20. Name Lookup (SemaLookup.cpp)
889 // 21. Modules (SemaModule.cpp)
890 // 22. C++ Overloading (SemaOverload.cpp)
891 // 23. Statements (SemaStmt.cpp)
892 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
893 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
894 // 26. C++ Templates (SemaTemplate.cpp)
895 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
896 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
897 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
898 // 30. C++ Template Declaration Instantiation
899 // (SemaTemplateInstantiateDecl.cpp)
900 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
901 // 32. Constraints and Concepts (SemaConcept.cpp)
902 // 33. Types (SemaType.cpp)
903 // 34. FixIt Helpers (SemaFixItUtils.cpp)
904 // 35. Function Effects (SemaFunctionEffects.cpp)
905 // 36. C++ Expansion Statements (SemaExpand.cpp)
906
907 /// \name Semantic Analysis
908 /// Implementations are in Sema.cpp
909 ///@{
910
911public:
912 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
913 TranslationUnitKind TUKind = TU_Complete,
914 CodeCompleteConsumer *CompletionConsumer = nullptr);
915 ~Sema();
916
917 /// Perform initialization that occurs after the parser has been
918 /// initialized but before it parses anything.
919 void Initialize();
920
921 /// This virtual key function only exists to limit the emission of debug info
922 /// describing the Sema class. GCC and Clang only emit debug info for a class
923 /// with a vtable when the vtable is emitted. Sema is final and not
924 /// polymorphic, but the debug info size savings are so significant that it is
925 /// worth adding a vtable just to take advantage of this optimization.
926 LLVM_DECLARE_VIRTUAL_ANCHOR_FUNCTION();
927
928 const LangOptions &getLangOpts() const { return LangOpts; }
929 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
930 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
931
932 DiagnosticsEngine &getDiagnostics() const { return Diags; }
933 SourceManager &getSourceManager() const { return SourceMgr; }
934 Preprocessor &getPreprocessor() const { return PP; }
935 ASTContext &getASTContext() const { return Context; }
936 ASTConsumer &getASTConsumer() const { return Consumer; }
937 ASTMutationListener *getASTMutationListener() const;
938 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
939
940 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
941 StringRef Platform);
942 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
943
944 /// Registers an external source. If an external source already exists,
945 /// creates a multiplex external source and appends to it.
946 ///
947 ///\param[in] E - A non-null external sema source.
948 ///
949 void addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E);
950
951 /// Print out statistics about the semantic analysis.
952 void PrintStats() const;
953
954 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
955 /// guaranteed). Produces a warning if we're low on stack space and allocates
956 /// more in that case. Use this in code that may recurse deeply (for example,
957 /// in template instantiation) to avoid stack overflow.
958 void runWithSufficientStackSpace(SourceLocation Loc,
959 llvm::function_ref<void()> Fn);
960
961 /// Returns default addr space for method qualifiers.
962 LangAS getDefaultCXXMethodAddrSpace() const;
963
964 /// Load weak undeclared identifiers from the external source.
965 void LoadExternalWeakUndeclaredIdentifiers();
966
967 /// Load #pragma redefine_extname'd undeclared identifiers from the external
968 /// source.
969 void LoadExternalExtnameUndeclaredIdentifiers();
970
971 /// Determine if VD, which must be a variable or function, is an external
972 /// symbol that nonetheless can't be referenced from outside this translation
973 /// unit because its type has no linkage and it's not extern "C".
974 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
975
976 /// Determines whether the given source location is in the main file
977 /// and we're in a context where we should warn about unused entities.
978 bool isMainFileLoc(SourceLocation Loc) const;
979
980 /// Obtain a sorted list of functions that are undefined but ODR-used.
981 void getUndefinedButUsed(
982 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
983
984 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
985 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
986 /// Retrieves list of suspicious delete-expressions that will be checked at
987 /// the end of translation unit.
988 const llvm::MapVector<FieldDecl *, DeleteLocs> &
989 getMismatchingDeleteExpressions() const;
990
991 /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
992 /// This is closely coupled to the SemaDiagnosticBuilder class and
993 /// should not be used elsewhere.
994 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
995
996 void addImplicitTypedef(StringRef Name, QualType T);
997
998 /// Whether uncompilable error has occurred. This includes error happens
999 /// in deferred diagnostics.
1000 bool hasUncompilableErrorOccurred() const;
1001
1002 /// Looks through the macro-expansion chain for the given
1003 /// location, looking for a macro expansion with the given name.
1004 /// If one is found, returns true and sets the location to that
1005 /// expansion loc.
1006 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1007
1008 /// Calls \c Lexer::getLocForEndOfToken()
1009 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1010
1011 /// Calls \c Lexer::findNextToken() to find the next token, and if the
1012 /// locations of both ends of the token can be resolved it return that
1013 /// range; Otherwise it returns an invalid SourceRange.
1014 SourceRange getRangeForNextToken(
1015 SourceLocation Loc, bool IncludeMacros, bool IncludeComments,
1016 std::optional<tok::TokenKind> ExpectedToken = std::nullopt);
1017
1018 /// Retrieve the module loader associated with the preprocessor.
1019 ModuleLoader &getModuleLoader() const;
1020
1021 /// Invent a new identifier for parameters of abbreviated templates.
1022 IdentifierInfo *
1023 InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName,
1024 unsigned Index);
1025
1026 void emitAndClearUnusedLocalTypedefWarnings();
1027
1028 // Emit all deferred diagnostics.
1029 void emitDeferredDiags();
1030
1031 /// This is called before the very first declaration in the translation unit
1032 /// is parsed. Note that the ASTContext may have already injected some
1033 /// declarations.
1034 void ActOnStartOfTranslationUnit();
1035 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1036 /// translation unit when EOF is reached and all but the top-level scope is
1037 /// popped.
1038 void ActOnEndOfTranslationUnit();
1039 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1040
1041 /// Determines the active Scope associated with the given declaration
1042 /// context.
1043 ///
1044 /// This routine maps a declaration context to the active Scope object that
1045 /// represents that declaration context in the parser. It is typically used
1046 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1047 /// declarations) that injects a name for name-lookup purposes and, therefore,
1048 /// must update the Scope.
1049 ///
1050 /// \returns The scope corresponding to the given declaraion context, or NULL
1051 /// if no such scope is open.
1052 Scope *getScopeForContext(DeclContext *Ctx);
1053
1054 void PushFunctionScope();
1055 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1056 sema::LambdaScopeInfo *PushLambdaScope();
1057
1058 /// This is used to inform Sema what the current TemplateParameterDepth
1059 /// is during Parsing. Currently it is used to pass on the depth
1060 /// when parsing generic lambda 'auto' parameters.
1061 void RecordParsingTemplateParameterDepth(unsigned Depth);
1062
1063 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1064 RecordDecl *RD, CapturedRegionKind K,
1065 unsigned OpenMPCaptureLevel = 0);
1066
1067 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1068 /// time after they've been popped.
1069 class PoppedFunctionScopeDeleter {
1070 Sema *Self;
1071
1072 public:
1073 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1074 void operator()(sema::FunctionScopeInfo *Scope) const;
1075 };
1076
1077 using PoppedFunctionScopePtr =
1078 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1079
1080 /// Pop a function (or block or lambda or captured region) scope from the
1081 /// stack.
1082 ///
1083 /// \param WP The warning policy to use for CFG-based warnings, or null if
1084 /// such warnings should not be produced.
1085 /// \param D The declaration corresponding to this function scope, if
1086 /// producing CFG-based warnings.
1087 /// \param BlockType The type of the block expression, if D is a BlockDecl.
1088 PoppedFunctionScopePtr
1089 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1090 Decl *D = nullptr, QualType BlockType = QualType());
1091
1092 sema::FunctionScopeInfo *getEnclosingFunction() const;
1093
1094 void setFunctionHasBranchIntoScope();
1095 void setFunctionHasBranchProtectedScope();
1096 void setFunctionHasIndirectGoto();
1097 void setFunctionHasMustTail();
1098
1099 void PushCompoundScope(bool IsStmtExpr);
1100 void PopCompoundScope();
1101
1102 /// Determine whether any errors occurred within this function/method/
1103 /// block.
1104 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1105
1106 /// Retrieve the current block, if any.
1107 sema::BlockScopeInfo *getCurBlock();
1108
1109 /// Get the innermost lambda or block enclosing the current location, if any.
1110 /// This looks through intervening non-lambda, non-block scopes such as local
1111 /// functions.
1112 sema::CapturingScopeInfo *getEnclosingLambdaOrBlock() const;
1113
1114 /// Retrieve the current lambda scope info, if any.
1115 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1116 /// lambda scope info ignoring all inner capturing scopes that are not
1117 /// lambda scopes.
1118 sema::LambdaScopeInfo *
1119 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1120
1121 /// Retrieve the current generic lambda info, if any.
1122 sema::LambdaScopeInfo *getCurGenericLambda();
1123
1124 /// Retrieve the current captured region, if any.
1125 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1126
1127 void ActOnComment(SourceRange Comment);
1128
1129 /// Retrieve the parser's current scope.
1130 ///
1131 /// This routine must only be used when it is certain that semantic analysis
1132 /// and the parser are in precisely the same context, which is not the case
1133 /// when, e.g., we are performing any kind of template instantiation.
1134 /// Therefore, the only safe places to use this scope are in the parser
1135 /// itself and in routines directly invoked from the parser and *never* from
1136 /// template substitution or instantiation.
1137 Scope *getCurScope() const { return CurScope; }
1138
1139 IdentifierInfo *getSuperIdentifier() const;
1140
1141 DeclContext *getCurLexicalContext() const {
1142 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
1143 }
1144
1145 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1146 const FunctionDecl *FD = nullptr);
1147 SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
1148 const PartialDiagnostic &PD,
1149 const FunctionDecl *FD = nullptr) {
1150 return targetDiag(Loc, DiagID: PD.getDiagID(), FD) << PD;
1151 }
1152
1153 /// Check if the type is allowed to be used for the current target.
1154 void checkTypeSupport(QualType Ty, SourceLocation Loc,
1155 ValueDecl *D = nullptr);
1156
1157 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1158 /// cast. If there is already an implicit cast, merge into the existing one.
1159 /// If isLvalue, the result of the cast is an lvalue.
1160 ExprResult ImpCastExprToType(
1161 Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue,
1162 const CXXCastPath *BasePath = nullptr,
1163 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
1164
1165 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1166 /// to the conversion from scalar type ScalarTy to the Boolean type.
1167 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
1168
1169 /// If \p AllowLambda is true, treat lambda as function.
1170 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1171
1172 /// Returns a pointer to the innermost enclosing function, or nullptr if the
1173 /// current context is not inside a function. If \p AllowLambda is true,
1174 /// this can return the call operator of an enclosing lambda, otherwise
1175 /// lambdas are skipped when looking for an enclosing function.
1176 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1177
1178 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1179 /// the method decl for the method being parsed. If we're currently
1180 /// in a 'block', this returns the containing context.
1181 ObjCMethodDecl *getCurMethodDecl();
1182
1183 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1184 /// or C function we're in, otherwise return null. If we're currently
1185 /// in a 'block', this returns the containing context.
1186 NamedDecl *getCurFunctionOrMethodDecl() const;
1187
1188 /// Warn if we're implicitly casting from a _Nullable pointer type to a
1189 /// _Nonnull one.
1190 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
1191 SourceLocation Loc);
1192
1193 /// Warn when implicitly casting 0 to nullptr.
1194 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1195
1196 /// Warn when implicitly changing function effects.
1197 void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType,
1198 SourceLocation Loc);
1199
1200 /// makeUnavailableInSystemHeader - There is an error in the current
1201 /// context. If we're still in a system header, and we can plausibly
1202 /// make the relevant declaration unavailable instead of erroring, do
1203 /// so and return true.
1204 bool makeUnavailableInSystemHeader(SourceLocation loc,
1205 UnavailableAttr::ImplicitReason reason);
1206
1207 /// Retrieve a suitable printing policy for diagnostics.
1208 PrintingPolicy getPrintingPolicy() const {
1209 return getPrintingPolicy(Ctx: Context, PP);
1210 }
1211
1212 /// Retrieve a suitable printing policy for diagnostics.
1213 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1214 const Preprocessor &PP);
1215
1216 /// Scope actions.
1217 void ActOnTranslationUnitScope(Scope *S);
1218
1219 /// Determine whether \param D is function like (function or function
1220 /// template) for parsing.
1221 bool isDeclaratorFunctionLike(Declarator &D);
1222
1223 /// The maximum alignment, same as in llvm::Value. We duplicate them here
1224 /// because that allows us not to duplicate the constants in clang code,
1225 /// which we must to since we can't directly use the llvm constants.
1226 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1227 ///
1228 /// This is the greatest alignment value supported by load, store, and alloca
1229 /// instructions, and global values.
1230 static const unsigned MaxAlignmentExponent = 32;
1231 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1232
1233 /// Flag indicating whether or not to collect detailed statistics.
1234 bool CollectStats;
1235
1236 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1237
1238 /// Stack containing information about each of the nested
1239 /// function, block, and method scopes that are currently active.
1240 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
1241
1242 /// The index of the first FunctionScope that corresponds to the current
1243 /// context.
1244 unsigned FunctionScopesStart = 0;
1245
1246 /// Track the number of currently active capturing scopes.
1247 unsigned CapturingFunctionScopes = 0;
1248
1249 llvm::BumpPtrAllocator BumpAlloc;
1250
1251 /// The kind of translation unit we are processing.
1252 ///
1253 /// When we're processing a complete translation unit, Sema will perform
1254 /// end-of-translation-unit semantic tasks (such as creating
1255 /// initializers for tentative definitions in C) once parsing has
1256 /// completed. Modules and precompiled headers perform different kinds of
1257 /// checks.
1258 const TranslationUnitKind TUKind;
1259
1260 /// Translation Unit Scope - useful to Objective-C actions that need
1261 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1262 /// For example, user-defined classes, built-in "id" type, etc.
1263 Scope *TUScope;
1264
1265 void incrementMSManglingNumber() const {
1266 return CurScope->incrementMSManglingNumber();
1267 }
1268
1269 /// Try to recover by turning the given expression into a
1270 /// call. Returns true if recovery was attempted or an error was
1271 /// emitted; this may also leave the ExprResult invalid.
1272 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1273 bool ForceComplain = false,
1274 bool (*IsPlausibleResult)(QualType) = nullptr);
1275
1276 // Adds implicit lifetime bound attribute for implicit this to its
1277 // TypeSourceInfo.
1278 void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD);
1279
1280 /// Figure out if an expression could be turned into a call.
1281 ///
1282 /// Use this when trying to recover from an error where the programmer may
1283 /// have written just the name of a function instead of actually calling it.
1284 ///
1285 /// \param E - The expression to examine.
1286 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1287 /// with no arguments, this parameter is set to the type returned by such a
1288 /// call; otherwise, it is set to an empty QualType.
1289 /// \param OverloadSet - If the expression is an overloaded function
1290 /// name, this parameter is populated with the decls of the various
1291 /// overloads.
1292 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1293 UnresolvedSetImpl &NonTemplateOverloads);
1294
1295 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
1296 typedef OpaquePtr<TemplateName> TemplateTy;
1297 typedef OpaquePtr<QualType> TypeTy;
1298
1299 OpenCLOptions OpenCLFeatures;
1300 FPOptions CurFPFeatures;
1301
1302 const LangOptions &LangOpts;
1303 Preprocessor &PP;
1304 ASTContext &Context;
1305 ASTConsumer &Consumer;
1306 DiagnosticsEngine &Diags;
1307 SourceManager &SourceMgr;
1308 api_notes::APINotesManager APINotes;
1309
1310 std::unique_ptr<APINotesSelectorDiagnosticState> APINotesSelectorDiagnostics;
1311
1312 /// A RAII object to enter scope of a compound statement.
1313 class CompoundScopeRAII {
1314 public:
1315 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1316 S.ActOnStartOfCompoundStmt(IsStmtExpr);
1317 }
1318
1319 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1320 CompoundScopeRAII(const CompoundScopeRAII &) = delete;
1321 CompoundScopeRAII &operator=(const CompoundScopeRAII &) = delete;
1322
1323 private:
1324 Sema &S;
1325 };
1326
1327 /// An RAII helper that pops function a function scope on exit.
1328 struct FunctionScopeRAII {
1329 Sema &S;
1330 bool Active;
1331 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
1332 ~FunctionScopeRAII() {
1333 if (Active)
1334 S.PopFunctionScopeInfo();
1335 }
1336 void disable() { Active = false; }
1337 };
1338
1339 sema::FunctionScopeInfo *getCurFunction() const {
1340 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1341 }
1342
1343 /// Worker object for performing CFG-based warnings.
1344 sema::AnalysisBasedWarnings AnalysisWarnings;
1345 threadSafety::BeforeSet *ThreadSafetyDeclCache;
1346
1347 /// Callback to the parser to parse templated functions when needed.
1348 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1349 LateTemplateParserCB *LateTemplateParser;
1350 void *OpaqueParser;
1351
1352 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
1353 LateTemplateParser = LTP;
1354 OpaqueParser = P;
1355 }
1356
1357 /// Callback to the parser to parse a type expressed as a string.
1358 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1359 ParseTypeFromStringCallback;
1360
1361 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1362 /// This is used as part of a hack to omit that class from ADL results.
1363 DeclarationName VAListTagName;
1364
1365 /// Is the last error level diagnostic immediate. This is used to determined
1366 /// whether the next info diagnostic should be immediate.
1367 bool IsLastErrorImmediate = true;
1368
1369 /// Track if we're currently analyzing overflow behavior types in assignment
1370 /// context.
1371 bool InOverflowBehaviorAssignmentContext = false;
1372
1373 class DelayedDiagnostics;
1374
1375 class DelayedDiagnosticsState {
1376 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1377 friend class Sema::DelayedDiagnostics;
1378 };
1379 typedef DelayedDiagnosticsState ParsingDeclState;
1380 typedef DelayedDiagnosticsState ProcessingContextState;
1381
1382 /// A class which encapsulates the logic for delaying diagnostics
1383 /// during parsing and other processing.
1384 class DelayedDiagnostics {
1385 /// The current pool of diagnostics into which delayed
1386 /// diagnostics should go.
1387 sema::DelayedDiagnosticPool *CurPool = nullptr;
1388
1389 public:
1390 DelayedDiagnostics() = default;
1391
1392 /// Adds a delayed diagnostic.
1393 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1394
1395 /// Determines whether diagnostics should be delayed.
1396 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1397
1398 /// Returns the current delayed-diagnostics pool.
1399 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1400
1401 /// Enter a new scope. Access and deprecation diagnostics will be
1402 /// collected in this pool.
1403 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
1404 DelayedDiagnosticsState state;
1405 state.SavedPool = CurPool;
1406 CurPool = &pool;
1407 return state;
1408 }
1409
1410 /// Leave a delayed-diagnostic state that was previously pushed.
1411 /// Do not emit any of the diagnostics. This is performed as part
1412 /// of the bookkeeping of popping a pool "properly".
1413 void popWithoutEmitting(DelayedDiagnosticsState state) {
1414 CurPool = state.SavedPool;
1415 }
1416
1417 /// Enter a new scope where access and deprecation diagnostics are
1418 /// not delayed.
1419 DelayedDiagnosticsState pushUndelayed() {
1420 DelayedDiagnosticsState state;
1421 state.SavedPool = CurPool;
1422 CurPool = nullptr;
1423 return state;
1424 }
1425
1426 /// Undo a previous pushUndelayed().
1427 void popUndelayed(DelayedDiagnosticsState state) {
1428 assert(CurPool == nullptr);
1429 CurPool = state.SavedPool;
1430 }
1431 } DelayedDiagnostics;
1432
1433 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
1434 return DelayedDiagnostics.push(pool);
1435 }
1436
1437 /// Diagnostics that are emitted only if we discover that the given function
1438 /// must be codegen'ed. Because handling these correctly adds overhead to
1439 /// compilation, this is currently only used for offload languages like CUDA,
1440 /// OpenMP, and SYCL.
1441 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1442
1443 /// CurContext - This is the current declaration context of parsing.
1444 DeclContext *CurContext;
1445
1446 SemaAMDGPU &AMDGPU() {
1447 assert(AMDGPUPtr);
1448 return *AMDGPUPtr;
1449 }
1450
1451 SemaARM &ARM() {
1452 assert(ARMPtr);
1453 return *ARMPtr;
1454 }
1455
1456 SemaAVR &AVR() {
1457 assert(AVRPtr);
1458 return *AVRPtr;
1459 }
1460
1461 SemaBPF &BPF() {
1462 assert(BPFPtr);
1463 return *BPFPtr;
1464 }
1465
1466 SemaCodeCompletion &CodeCompletion() {
1467 assert(CodeCompletionPtr);
1468 return *CodeCompletionPtr;
1469 }
1470
1471 SemaCUDA &CUDA() {
1472 assert(CUDAPtr);
1473 return *CUDAPtr;
1474 }
1475
1476 SemaDirectX &DirectX() {
1477 assert(DirectXPtr);
1478 return *DirectXPtr;
1479 }
1480
1481 SemaHLSL &HLSL() {
1482 assert(HLSLPtr);
1483 return *HLSLPtr;
1484 }
1485
1486 SemaHexagon &Hexagon() {
1487 assert(HexagonPtr);
1488 return *HexagonPtr;
1489 }
1490
1491 SemaLoongArch &LoongArch() {
1492 assert(LoongArchPtr);
1493 return *LoongArchPtr;
1494 }
1495
1496 SemaM68k &M68k() {
1497 assert(M68kPtr);
1498 return *M68kPtr;
1499 }
1500
1501 SemaMIPS &MIPS() {
1502 assert(MIPSPtr);
1503 return *MIPSPtr;
1504 }
1505
1506 SemaMSP430 &MSP430() {
1507 assert(MSP430Ptr);
1508 return *MSP430Ptr;
1509 }
1510
1511 SemaNVPTX &NVPTX() {
1512 assert(NVPTXPtr);
1513 return *NVPTXPtr;
1514 }
1515
1516 SemaObjC &ObjC() {
1517 assert(ObjCPtr);
1518 return *ObjCPtr;
1519 }
1520
1521 SemaOpenACC &OpenACC() {
1522 assert(OpenACCPtr);
1523 return *OpenACCPtr;
1524 }
1525
1526 SemaOpenCL &OpenCL() {
1527 assert(OpenCLPtr);
1528 return *OpenCLPtr;
1529 }
1530
1531 SemaOpenMP &OpenMP() {
1532 assert(OpenMPPtr && "SemaOpenMP is dead");
1533 return *OpenMPPtr;
1534 }
1535
1536 SemaPPC &PPC() {
1537 assert(PPCPtr);
1538 return *PPCPtr;
1539 }
1540
1541 SemaPseudoObject &PseudoObject() {
1542 assert(PseudoObjectPtr);
1543 return *PseudoObjectPtr;
1544 }
1545
1546 SemaRISCV &RISCV() {
1547 assert(RISCVPtr);
1548 return *RISCVPtr;
1549 }
1550
1551 SemaSPIRV &SPIRV() {
1552 assert(SPIRVPtr);
1553 return *SPIRVPtr;
1554 }
1555
1556 SemaSYCL &SYCL() {
1557 assert(SYCLPtr);
1558 return *SYCLPtr;
1559 }
1560
1561 SemaSwift &Swift() {
1562 assert(SwiftPtr);
1563 return *SwiftPtr;
1564 }
1565
1566 SemaSystemZ &SystemZ() {
1567 assert(SystemZPtr);
1568 return *SystemZPtr;
1569 }
1570
1571 SemaWasm &Wasm() {
1572 assert(WasmPtr);
1573 return *WasmPtr;
1574 }
1575
1576 SemaX86 &X86() {
1577 assert(X86Ptr);
1578 return *X86Ptr;
1579 }
1580
1581 /// Source of additional semantic information.
1582 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
1583
1584protected:
1585 friend class Parser;
1586 friend class InitializationSequence;
1587 friend class ASTReader;
1588 friend class ASTDeclReader;
1589 friend class ASTWriter;
1590
1591private:
1592 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1593 bool WarnedDarwinSDKInfoMissing = false;
1594
1595 StackExhaustionHandler StackHandler;
1596
1597 Sema(const Sema &) = delete;
1598 void operator=(const Sema &) = delete;
1599
1600 /// The handler for the FileChanged preprocessor events.
1601 ///
1602 /// Used for diagnostics that implement custom semantic analysis for #include
1603 /// directives, like -Wpragma-pack.
1604 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1605
1606 /// The parser's current scope.
1607 ///
1608 /// The parser maintains this state here.
1609 Scope *CurScope;
1610
1611 mutable IdentifierInfo *Ident_super;
1612
1613 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1614 std::unique_ptr<SemaARM> ARMPtr;
1615 std::unique_ptr<SemaAVR> AVRPtr;
1616 std::unique_ptr<SemaBPF> BPFPtr;
1617 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1618 std::unique_ptr<SemaCUDA> CUDAPtr;
1619 std::unique_ptr<SemaDirectX> DirectXPtr;
1620 std::unique_ptr<SemaHLSL> HLSLPtr;
1621 std::unique_ptr<SemaHexagon> HexagonPtr;
1622 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1623 std::unique_ptr<SemaM68k> M68kPtr;
1624 std::unique_ptr<SemaMIPS> MIPSPtr;
1625 std::unique_ptr<SemaMSP430> MSP430Ptr;
1626 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1627 std::unique_ptr<SemaObjC> ObjCPtr;
1628 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1629 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1630 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1631 std::unique_ptr<SemaPPC> PPCPtr;
1632 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1633 std::unique_ptr<SemaRISCV> RISCVPtr;
1634 std::unique_ptr<SemaSPIRV> SPIRVPtr;
1635 std::unique_ptr<SemaSYCL> SYCLPtr;
1636 std::unique_ptr<SemaSwift> SwiftPtr;
1637 std::unique_ptr<SemaSystemZ> SystemZPtr;
1638 std::unique_ptr<SemaWasm> WasmPtr;
1639 std::unique_ptr<SemaX86> X86Ptr;
1640
1641 ///@}
1642
1643 //
1644 //
1645 // -------------------------------------------------------------------------
1646 //
1647 //
1648
1649 /// \name API Notes
1650 /// Implementations are in SemaAPINotes.cpp
1651 ///@{
1652
1653public:
1654 /// Map any API notes provided for this declaration to attributes on the
1655 /// declaration.
1656 ///
1657 /// Triggered by declaration-attribute processing.
1658 void ProcessAPINotes(Decl *D);
1659 /// Apply the 'Nullability:' annotation to the specified declaration
1660 void ApplyNullability(Decl *D, NullabilityKind Nullability);
1661 /// Apply the 'Type:' annotation to the specified declaration
1662 void ApplyAPINotesType(Decl *D, StringRef TypeString);
1663
1664 /// Diagnose exact API notes selectors that were not matched by any
1665 /// declaration processed in this translation unit.
1666 void DiagnoseUnusedAPINotesSelectors();
1667
1668 /// Whether APINotes should be gathered for all applicable Swift language
1669 /// versions, without being applied. Leaving clients of the current module
1670 /// to select and apply the correct version.
1671 bool captureSwiftVersionIndependentAPINotes() {
1672 return APINotes.captureVersionIndependentSwift();
1673 }
1674 ///@}
1675
1676 //
1677 //
1678 // -------------------------------------------------------------------------
1679 //
1680 //
1681
1682 /// \name C++ Access Control
1683 /// Implementations are in SemaAccess.cpp
1684 ///@{
1685
1686public:
1687 enum AccessResult {
1688 AR_accessible,
1689 AR_inaccessible,
1690 AR_dependent,
1691 AR_delayed
1692 };
1693
1694 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1695 /// Returns true on error (when the previous member decl access specifier
1696 /// is different from the new member decl access specifier).
1697 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1698 NamedDecl *PrevMemberDecl,
1699 AccessSpecifier LexicalAS);
1700
1701 /// Perform access-control checking on a previously-unresolved member
1702 /// access which has now been resolved to a member.
1703 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
1704 DeclAccessPair FoundDecl);
1705 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
1706 DeclAccessPair FoundDecl);
1707
1708 /// Checks access to an overloaded operator new or delete.
1709 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
1710 SourceRange PlacementRange,
1711 CXXRecordDecl *NamingClass,
1712 DeclAccessPair FoundDecl,
1713 bool Diagnose = true);
1714
1715 /// Checks access to a constructor.
1716 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1717 DeclAccessPair FoundDecl,
1718 const InitializedEntity &Entity,
1719 bool IsCopyBindingRefToTemp = false);
1720
1721 /// Checks access to a constructor.
1722 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1723 DeclAccessPair FoundDecl,
1724 const InitializedEntity &Entity,
1725 const PartialDiagnostic &PDiag);
1726 AccessResult CheckDestructorAccess(SourceLocation Loc,
1727 CXXDestructorDecl *Dtor,
1728 const PartialDiagnostic &PDiag,
1729 QualType objectType = QualType());
1730
1731 /// Checks access to the target of a friend declaration.
1732 AccessResult CheckFriendAccess(NamedDecl *D);
1733
1734 /// Checks access to a member.
1735 AccessResult CheckMemberAccess(SourceLocation UseLoc,
1736 CXXRecordDecl *NamingClass,
1737 DeclAccessPair Found);
1738
1739 /// Checks implicit access to a member in a structured binding.
1740 AccessResult
1741 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
1742 CXXRecordDecl *DecomposedClass,
1743 DeclAccessPair Field);
1744 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1745 const SourceRange &,
1746 DeclAccessPair FoundDecl);
1747
1748 /// Checks access to an overloaded member operator, including
1749 /// conversion operators.
1750 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1751 Expr *ArgExpr,
1752 DeclAccessPair FoundDecl);
1753 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1754 ArrayRef<Expr *> ArgExprs,
1755 DeclAccessPair FoundDecl);
1756 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
1757 DeclAccessPair FoundDecl);
1758
1759 /// Checks access for a hierarchy conversion.
1760 ///
1761 /// \param ForceCheck true if this check should be performed even if access
1762 /// control is disabled; some things rely on this for semantics
1763 /// \param ForceUnprivileged true if this check should proceed as if the
1764 /// context had no special privileges
1765 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base,
1766 QualType Derived, const CXXBasePath &Path,
1767 unsigned DiagID, bool ForceCheck = false,
1768 bool ForceUnprivileged = false);
1769
1770 AccessResult CheckBaseClassAccess(
1771 SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1772 const CXXBasePath &Path, unsigned DiagID,
1773 llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1774 bool ForceCheck = false, bool ForceUnprivileged = false);
1775
1776 /// Checks access to all the declarations in the given result set.
1777 void CheckLookupAccess(const LookupResult &R);
1778
1779 /// Checks access to Target from the given class. The check will take access
1780 /// specifiers into account, but no member access expressions and such.
1781 ///
1782 /// \param Target the declaration to check if it can be accessed
1783 /// \param NamingClass the class in which the lookup was started.
1784 /// \param BaseType type of the left side of member access expression.
1785 /// \p BaseType and \p NamingClass are used for C++ access control.
1786 /// Depending on the lookup case, they should be set to the following:
1787 /// - lhs.target (member access without a qualifier):
1788 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1789 /// - lhs.X::target (member access with a qualifier):
1790 /// BaseType is the type of 'lhs', NamingClass is 'X'
1791 /// - X::target (qualified lookup without member access):
1792 /// BaseType is null, NamingClass is 'X'.
1793 /// - target (unqualified lookup).
1794 /// BaseType is null, NamingClass is the parent class of 'target'.
1795 /// \return true if the Target is accessible from the Class, false otherwise.
1796 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1797 QualType BaseType);
1798
1799 /// Is the given member accessible for the purposes of deciding whether to
1800 /// define a special member function as deleted?
1801 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1802 DeclAccessPair Found, QualType ObjectType,
1803 SourceLocation Loc,
1804 const PartialDiagnostic &Diag);
1805 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1806 DeclAccessPair Found,
1807 QualType ObjectType) {
1808 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1809 Loc: SourceLocation(), Diag: PDiag());
1810 }
1811
1812 void HandleDependentAccessCheck(
1813 const DependentDiagnostic &DD,
1814 const MultiLevelTemplateArgumentList &TemplateArgs);
1815 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
1816
1817 ///@}
1818
1819 //
1820 //
1821 // -------------------------------------------------------------------------
1822 //
1823 //
1824
1825 /// \name Attributes
1826 /// Implementations are in SemaAttr.cpp
1827 ///@{
1828
1829public:
1830 /// Controls member pointer representation format under the MS ABI.
1831 LangOptions::PragmaMSPointersToMembersKind
1832 MSPointerToMemberRepresentationMethod;
1833
1834 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1835
1836 /// Source location for newly created implicit MSInheritanceAttrs
1837 SourceLocation ImplicitMSInheritanceAttrLoc;
1838
1839 struct PragmaClangSection {
1840 std::string SectionName;
1841 bool Valid = false;
1842 SourceLocation PragmaLocation;
1843 };
1844
1845 PragmaClangSection PragmaClangBSSSection;
1846 PragmaClangSection PragmaClangDataSection;
1847 PragmaClangSection PragmaClangRodataSection;
1848 PragmaClangSection PragmaClangRelroSection;
1849 PragmaClangSection PragmaClangTextSection;
1850
1851 enum PragmaMsStackAction {
1852 PSK_Reset = 0x0, // #pragma ()
1853 PSK_Set = 0x1, // #pragma (value)
1854 PSK_Push = 0x2, // #pragma (push[, id])
1855 PSK_Pop = 0x4, // #pragma (pop[, id])
1856 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1857 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1858 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1859 };
1860
1861 struct PragmaPackInfo {
1862 PragmaMsStackAction Action;
1863 StringRef SlotLabel;
1864 Token Alignment;
1865 };
1866
1867 // #pragma pack and align.
1868 class AlignPackInfo {
1869 public:
1870 // `Native` represents default align mode, which may vary based on the
1871 // platform.
1872 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1873
1874 // #pragma pack info constructor
1875 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1876 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1877 assert(Num == PackNumber && "The pack number has been truncated.");
1878 }
1879
1880 // #pragma align info constructor
1881 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
1882 : PackAttr(false), AlignMode(M),
1883 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1884
1885 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1886
1887 AlignPackInfo() : AlignPackInfo(Native, false) {}
1888
1889 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1890 // integer encoding for it. This should only be passed to
1891 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1892 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
1893 std::uint32_t Encoding{};
1894 if (Info.IsXLStack())
1895 Encoding |= IsXLMask;
1896
1897 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1898
1899 if (Info.IsPackAttr())
1900 Encoding |= PackAttrMask;
1901
1902 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1903
1904 return Encoding;
1905 }
1906
1907 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1908 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1909 AlignPackInfo::Mode M =
1910 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1911 int PackNumber = (Encoding & PackNumMask) >> 4;
1912
1913 if (Encoding & PackAttrMask)
1914 return AlignPackInfo(M, PackNumber, IsXL);
1915
1916 return AlignPackInfo(M, IsXL);
1917 }
1918
1919 bool IsPackAttr() const { return PackAttr; }
1920
1921 bool IsAlignAttr() const { return !PackAttr; }
1922
1923 Mode getAlignMode() const { return AlignMode; }
1924
1925 unsigned getPackNumber() const { return PackNumber; }
1926
1927 bool IsPackSet() const {
1928 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1929 // attriute on a decl.
1930 return PackNumber != UninitPackVal && PackNumber != 0;
1931 }
1932
1933 bool IsXLStack() const { return XLStack; }
1934
1935 bool operator==(const AlignPackInfo &Info) const {
1936 return std::tie(args: AlignMode, args: PackNumber, args: PackAttr, args: XLStack) ==
1937 std::tie(args: Info.AlignMode, args: Info.PackNumber, args: Info.PackAttr,
1938 args: Info.XLStack);
1939 }
1940
1941 bool operator!=(const AlignPackInfo &Info) const {
1942 return !(*this == Info);
1943 }
1944
1945 private:
1946 /// \brief True if this is a pragma pack attribute,
1947 /// not a pragma align attribute.
1948 bool PackAttr;
1949
1950 /// \brief The alignment mode that is in effect.
1951 Mode AlignMode;
1952
1953 /// \brief The pack number of the stack.
1954 unsigned char PackNumber;
1955
1956 /// \brief True if it is a XL #pragma align/pack stack.
1957 bool XLStack;
1958
1959 /// \brief Uninitialized pack value.
1960 static constexpr unsigned char UninitPackVal = -1;
1961
1962 // Masks to encode and decode an AlignPackInfo.
1963 static constexpr uint32_t IsXLMask{0x0000'0001};
1964 static constexpr uint32_t AlignModeMask{0x0000'0006};
1965 static constexpr uint32_t PackAttrMask{0x00000'0008};
1966 static constexpr uint32_t PackNumMask{0x0000'01F0};
1967 };
1968
1969 template <typename ValueType> struct PragmaStack {
1970 struct Slot {
1971 llvm::StringRef StackSlotLabel;
1972 ValueType Value;
1973 SourceLocation PragmaLocation;
1974 SourceLocation PragmaPushLocation;
1975 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
1976 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
1977 : StackSlotLabel(StackSlotLabel), Value(Value),
1978 PragmaLocation(PragmaLocation),
1979 PragmaPushLocation(PragmaPushLocation) {}
1980 };
1981
1982 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
1983 llvm::StringRef StackSlotLabel, ValueType Value) {
1984 if (Action == PSK_Reset) {
1985 CurrentValue = DefaultValue;
1986 CurrentPragmaLocation = PragmaLocation;
1987 return;
1988 }
1989 if (Action & PSK_Push)
1990 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
1991 PragmaLocation);
1992 else if (Action & PSK_Pop) {
1993 if (!StackSlotLabel.empty()) {
1994 // If we've got a label, try to find it and jump there.
1995 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
1996 return x.StackSlotLabel == StackSlotLabel;
1997 });
1998 // If we found the label so pop from there.
1999 if (I != Stack.rend()) {
2000 CurrentValue = I->Value;
2001 CurrentPragmaLocation = I->PragmaLocation;
2002 Stack.erase(std::prev(I.base()), Stack.end());
2003 }
2004 } else if (!Stack.empty()) {
2005 // We do not have a label, just pop the last entry.
2006 CurrentValue = Stack.back().Value;
2007 CurrentPragmaLocation = Stack.back().PragmaLocation;
2008 Stack.pop_back();
2009 }
2010 }
2011 if (Action & PSK_Set) {
2012 CurrentValue = Value;
2013 CurrentPragmaLocation = PragmaLocation;
2014 }
2015 }
2016
2017 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
2018 // method body to restore the stacks on exit, so it works like this:
2019 //
2020 // struct S {
2021 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
2022 // void Method {}
2023 // #pragma <name>(pop, InternalPragmaSlot)
2024 // };
2025 //
2026 // It works even with #pragma vtordisp, although MSVC doesn't support
2027 // #pragma vtordisp(push [, id], n)
2028 // syntax.
2029 //
2030 // Push / pop a named sentinel slot.
2031 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
2032 assert((Action == PSK_Push || Action == PSK_Pop) &&
2033 "Can only push / pop #pragma stack sentinels!");
2034 Act(PragmaLocation: CurrentPragmaLocation, Action, StackSlotLabel: Label, Value: CurrentValue);
2035 }
2036
2037 // Constructors.
2038 explicit PragmaStack(const ValueType &Default)
2039 : DefaultValue(Default), CurrentValue(Default) {}
2040
2041 bool hasValue() const { return CurrentValue != DefaultValue; }
2042
2043 SmallVector<Slot, 2> Stack;
2044 ValueType DefaultValue; // Value used for PSK_Reset action.
2045 ValueType CurrentValue;
2046 SourceLocation CurrentPragmaLocation;
2047 };
2048 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2049 // we shouldn't do so if they're in a module).
2050
2051 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2052 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
2053 ///
2054 /// 0: Suppress all vtordisps
2055 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2056 /// structors
2057 /// 2: Always insert vtordisps to support RTTI on partially constructed
2058 /// objects
2059 PragmaStack<MSVtorDispMode> VtorDispStack;
2060 PragmaStack<AlignPackInfo> AlignPackStack;
2061 // The current #pragma align/pack values and locations at each #include.
2062 struct AlignPackIncludeState {
2063 AlignPackInfo CurrentValue;
2064 SourceLocation CurrentPragmaLocation;
2065 bool HasNonDefaultValue, ShouldWarnOnInclude;
2066 };
2067 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
2068 // Segment #pragmas.
2069 PragmaStack<StringLiteral *> DataSegStack;
2070 PragmaStack<StringLiteral *> BSSSegStack;
2071 PragmaStack<StringLiteral *> ConstSegStack;
2072 PragmaStack<StringLiteral *> CodeSegStack;
2073
2074 // #pragma strict_gs_check.
2075 PragmaStack<bool> StrictGuardStackCheckStack;
2076
2077 // This stack tracks the current state of Sema.CurFPFeatures.
2078 PragmaStack<FPOptionsOverride> FpPragmaStack;
2079 FPOptionsOverride CurFPFeatureOverrides() {
2080 FPOptionsOverride result;
2081 if (!FpPragmaStack.hasValue()) {
2082 result = FPOptionsOverride();
2083 } else {
2084 result = FpPragmaStack.CurrentValue;
2085 }
2086 return result;
2087 }
2088
2089 enum PragmaSectionKind {
2090 PSK_DataSeg,
2091 PSK_BSSSeg,
2092 PSK_ConstSeg,
2093 PSK_CodeSeg,
2094 };
2095
2096 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2097 // Actions should be performed only if we enter / exit a C++ method body.
2098 class PragmaStackSentinelRAII {
2099 public:
2100 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2101 ~PragmaStackSentinelRAII();
2102 PragmaStackSentinelRAII(const PragmaStackSentinelRAII &) = delete;
2103 PragmaStackSentinelRAII &
2104 operator=(const PragmaStackSentinelRAII &) = delete;
2105
2106 private:
2107 Sema &S;
2108 StringRef SlotLabel;
2109 bool ShouldAct;
2110 };
2111
2112 /// Last section used with #pragma init_seg.
2113 StringLiteral *CurInitSeg;
2114 SourceLocation CurInitSegLoc;
2115
2116 /// Sections used with #pragma alloc_text.
2117 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2118
2119 /// VisContext - Manages the stack for \#pragma GCC visibility.
2120 void *VisContext; // Really a "PragmaVisStack*"
2121
2122 /// This an attribute introduced by \#pragma clang attribute.
2123 struct PragmaAttributeEntry {
2124 SourceLocation Loc;
2125 ParsedAttr *Attribute;
2126 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
2127 bool IsUsed;
2128 };
2129
2130 /// A push'd group of PragmaAttributeEntries.
2131 struct PragmaAttributeGroup {
2132 /// The location of the push attribute.
2133 SourceLocation Loc;
2134 /// The namespace of this push group.
2135 const IdentifierInfo *Namespace;
2136 SmallVector<PragmaAttributeEntry, 2> Entries;
2137 };
2138
2139 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
2140
2141 /// The declaration that is currently receiving an attribute from the
2142 /// #pragma attribute stack.
2143 const Decl *PragmaAttributeCurrentTargetDecl;
2144
2145 /// This represents the last location of a "#pragma clang optimize off"
2146 /// directive if such a directive has not been closed by an "on" yet. If
2147 /// optimizations are currently "on", this is set to an invalid location.
2148 SourceLocation OptimizeOffPragmaLocation;
2149
2150 /// Get the location for the currently active "\#pragma clang optimize
2151 /// off". If this location is invalid, then the state of the pragma is "on".
2152 SourceLocation getOptimizeOffPragmaLocation() const {
2153 return OptimizeOffPragmaLocation;
2154 }
2155
2156 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2157 /// whether the optimizations in the list passed to the pragma should be
2158 /// turned off or on. This boolean is true by default because command line
2159 /// options are honored when `#pragma optimize("", on)`.
2160 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2161 bool MSPragmaOptimizeIsOn = true;
2162
2163 /// Set of no-builtin functions listed by \#pragma function.
2164 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
2165
2166 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2167 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2168 void AddAlignmentAttributesForRecord(RecordDecl *RD);
2169
2170 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2171 void AddMsStructLayoutForRecord(RecordDecl *RD);
2172
2173 /// Add gsl::Pointer attribute to std::container::iterator
2174 /// \param ND The declaration that introduces the name
2175 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2176 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2177
2178 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2179 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
2180
2181 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2182 void inferLifetimeBoundAttribute(FunctionDecl *FD);
2183
2184 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2185 void inferLifetimeCaptureByAttribute(FunctionDecl *FD);
2186
2187 /// Add [[gsl::Pointer]] attributes for std:: types.
2188 void inferGslPointerAttribute(TypedefNameDecl *TD);
2189
2190 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2191 StringRef ParamName);
2192 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2193 // can be the name of a function parameter, we need to parse the function
2194 // declaration and rest of the parameters before processesing 'X'. Therefore
2195 // do this lazily instead of processing while parsing the annotation itself.
2196 void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD);
2197
2198 /// Add _Nullable attributes for std:: types.
2199 void inferNullableClassAttribute(CXXRecordDecl *CRD);
2200
2201 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2202 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
2203 PragmaClangSectionAction Action,
2204 PragmaClangSectionKind SecKind,
2205 StringRef SecName);
2206
2207 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2208 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
2209 SourceLocation PragmaLoc);
2210
2211 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2212 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2213 StringRef SlotLabel, Expr *Alignment);
2214
2215 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2216 /// (unless they are value dependent or type dependent). Returns false
2217 /// and emits a diagnostic if one or more of the arguments could not be
2218 /// folded into a constant.
2219 bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
2220 MutableArrayRef<Expr *> Args);
2221
2222 enum class PragmaAlignPackDiagnoseKind {
2223 NonDefaultStateAtInclude,
2224 ChangedStateAtExit
2225 };
2226
2227 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
2228 SourceLocation IncludeLoc);
2229 void DiagnoseUnterminatedPragmaAlignPack();
2230
2231 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2232 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
2233
2234 /// ActOnPragmaMSComment - Called on well formed
2235 /// \#pragma comment(kind, "arg").
2236 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
2237 StringRef Arg);
2238
2239 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2240 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2241 StringRef Value);
2242
2243 /// Are precise floating point semantics currently enabled?
2244 bool isPreciseFPEnabled() {
2245 return !CurFPFeatures.getAllowFPReassociate() &&
2246 !CurFPFeatures.getNoSignedZero() &&
2247 !CurFPFeatures.getAllowReciprocal() &&
2248 !CurFPFeatures.getAllowApproxFunc();
2249 }
2250
2251 void ActOnPragmaFPEvalMethod(SourceLocation Loc,
2252 LangOptions::FPEvalMethodKind Value);
2253
2254 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2255 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2256 PragmaFloatControlKind Value);
2257
2258 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2259 /// pointers_to_members(representation method[, general purpose
2260 /// representation]).
2261 void ActOnPragmaMSPointersToMembers(
2262 LangOptions::PragmaMSPointersToMembersKind Kind,
2263 SourceLocation PragmaLoc);
2264
2265 /// Called on well formed \#pragma vtordisp().
2266 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2267 SourceLocation PragmaLoc, MSVtorDispMode Value);
2268
2269 bool UnifySection(StringRef SectionName, int SectionFlags,
2270 NamedDecl *TheDecl);
2271 bool UnifySection(StringRef SectionName, int SectionFlags,
2272 SourceLocation PragmaSectionLocation);
2273
2274 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2275 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2276 PragmaMsStackAction Action,
2277 llvm::StringRef StackSlotLabel,
2278 StringLiteral *SegmentName, llvm::StringRef PragmaName);
2279
2280 /// Called on well formed \#pragma section().
2281 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2282 StringLiteral *SegmentName);
2283
2284 /// Called on well-formed \#pragma init_seg().
2285 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2286 StringLiteral *SegmentName);
2287
2288 /// Called on well-formed \#pragma alloc_text().
2289 void ActOnPragmaMSAllocText(
2290 SourceLocation PragmaLocation, StringRef Section,
2291 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2292 &Functions);
2293
2294 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2295 /// strict_gs_check.
2296 void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
2297 PragmaMsStackAction Action,
2298 bool Value);
2299
2300 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2301 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2302 SourceLocation PragmaLoc);
2303
2304 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
2305 SourceLocation PragmaLoc,
2306 attr::ParsedSubjectMatchRuleSet Rules);
2307 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
2308 const IdentifierInfo *Namespace);
2309
2310 /// Called on well-formed '\#pragma clang attribute pop'.
2311 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
2312 const IdentifierInfo *Namespace);
2313
2314 /// Adds the attributes that have been specified using the
2315 /// '\#pragma clang attribute push' directives to the given declaration.
2316 void AddPragmaAttributes(Scope *S, Decl *D);
2317
2318 using InstantiationContextDiagFuncRef =
2319 llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
2320 auto getDefaultDiagFunc() {
2321 return [this](SourceLocation Loc, PartialDiagnostic PD) {
2322 // This bypasses a lot of the filters in the diag engine, as it's
2323 // to be used to attach notes to diagnostics which have already
2324 // been filtered through.
2325 DiagnosticBuilder Builder(Diags.Report(Loc, DiagID: PD.getDiagID()));
2326 PD.Emit(DB: Builder);
2327 };
2328 }
2329
2330 void PrintPragmaAttributeInstantiationPoint(
2331 InstantiationContextDiagFuncRef DiagFunc);
2332 void PrintPragmaAttributeInstantiationPoint() {
2333 PrintPragmaAttributeInstantiationPoint(DiagFunc: getDefaultDiagFunc());
2334 }
2335
2336 void DiagnoseUnterminatedPragmaAttribute();
2337
2338 /// Called on well formed \#pragma clang optimize.
2339 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2340
2341 /// #pragma optimize("[optimization-list]", on | off).
2342 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2343
2344 /// Call on well formed \#pragma function.
2345 void
2346 ActOnPragmaMSFunction(SourceLocation Loc,
2347 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2348
2349 NamedDecl *lookupExternCFunctionOrVariable(IdentifierInfo *IdentId,
2350 SourceLocation NameLoc,
2351 Scope *curScope);
2352
2353 /// Information from a C++ #pragma export, for a symbol that we
2354 /// haven't seen the declaration for yet.
2355 struct PendingPragmaInfo {
2356 SourceLocation NameLoc;
2357 bool Used;
2358 };
2359
2360 llvm::DenseMap<IdentifierInfo *, PendingPragmaInfo> PendingExportedNames;
2361
2362 /// ActonPragmaExport - called on well-formed '\#pragma export'.
2363 void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc,
2364 Scope *curScope);
2365
2366 /// Only called on function definitions; if there is a pragma in scope
2367 /// with the effect of a range-based optnone, consider marking the function
2368 /// with attribute optnone.
2369 void AddRangeBasedOptnone(FunctionDecl *FD);
2370
2371 /// Only called on function definitions; if there is a `#pragma alloc_text`
2372 /// that decides which code section the function should be in, add
2373 /// attribute section to the function.
2374 void AddSectionMSAllocText(FunctionDecl *FD);
2375
2376 /// Adds the 'optnone' attribute to the function declaration if there
2377 /// are no conflicts; Loc represents the location causing the 'optnone'
2378 /// attribute to be added (usually because of a pragma).
2379 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
2380
2381 /// Only called on function definitions; if there is a MSVC #pragma optimize
2382 /// in scope, consider changing the function's attributes based on the
2383 /// optimization list passed to the pragma.
2384 void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
2385
2386 /// Only called on function definitions; if there is a pragma in scope
2387 /// with the effect of a range-based no_builtin, consider marking the function
2388 /// with attribute no_builtin.
2389 void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
2390
2391 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2392 /// add an appropriate visibility attribute.
2393 void AddPushedVisibilityAttribute(Decl *RD);
2394
2395 /// FreeVisContext - Deallocate and null out VisContext.
2396 void FreeVisContext();
2397
2398 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2399 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2400 SourceLocation PragmaLoc);
2401
2402 /// ActOnPragmaFPContract - Called on well formed
2403 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2404 /// \#pragma clang fp contract
2405 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
2406
2407 /// Called on well formed
2408 /// \#pragma clang fp reassociate
2409 /// or
2410 /// \#pragma clang fp reciprocal
2411 void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind,
2412 bool IsEnabled);
2413
2414 /// ActOnPragmaFenvAccess - Called on well formed
2415 /// \#pragma STDC FENV_ACCESS
2416 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2417
2418 /// ActOnPragmaCXLimitedRange - Called on well formed
2419 /// \#pragma STDC CX_LIMITED_RANGE
2420 void ActOnPragmaCXLimitedRange(SourceLocation Loc,
2421 LangOptions::ComplexRangeKind Range);
2422
2423 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2424 void ActOnPragmaFPExceptions(SourceLocation Loc,
2425 LangOptions::FPExceptionModeKind);
2426
2427 /// Called to set constant rounding mode for floating point operations.
2428 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2429
2430 /// Called to set exception behavior for floating point operations.
2431 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
2432
2433 /// PushNamespaceVisibilityAttr - Note that we've entered a
2434 /// namespace with a visibility attribute.
2435 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2436 SourceLocation Loc);
2437
2438 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2439 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2440 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2441
2442 /// Handles semantic checking for features that are common to all attributes,
2443 /// such as checking whether a parameter was properly specified, or the
2444 /// correct number of arguments were passed, etc. Returns true if the
2445 /// attribute has been diagnosed.
2446 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2447 bool SkipArgCountCheck = false);
2448 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2449 bool SkipArgCountCheck = false);
2450
2451 ///@}
2452
2453 //
2454 //
2455 // -------------------------------------------------------------------------
2456 //
2457 //
2458
2459 /// \name Availability Attribute Handling
2460 /// Implementations are in SemaAvailability.cpp
2461 ///@{
2462
2463public:
2464 /// Issue any -Wunguarded-availability warnings in \c FD
2465 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
2466
2467 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2468
2469 /// Retrieve the current function, if any, that should be analyzed for
2470 /// potential availability violations.
2471 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2472
2473 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
2474 const ObjCInterfaceDecl *UnknownObjCClass,
2475 bool ObjCPropertyAccess,
2476 bool AvoidPartialAvailabilityChecks,
2477 ObjCInterfaceDecl *ClassReceiver);
2478
2479 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs);
2480
2481 std::pair<AvailabilityResult, const NamedDecl *>
2482 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2483 ObjCInterfaceDecl *ClassReceiver);
2484 ///@}
2485
2486 //
2487 //
2488 // -------------------------------------------------------------------------
2489 //
2490 //
2491
2492 /// \name Bounds Safety
2493 /// Implementations are in SemaBoundsSafety.cpp
2494 ///@{
2495public:
2496 /// Check if applying the specified attribute variant from the "counted by"
2497 /// family of attributes to FieldDecl \p FD is semantically valid. If
2498 /// semantically invalid diagnostics will be emitted explaining the problems.
2499 ///
2500 /// \param FD The FieldDecl to apply the attribute to
2501 /// \param E The count expression on the attribute
2502 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2503 /// attributes. If the false the attribute is from
2504 /// "counted_by" family of attributes.
2505 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2506 /// of attributes. If false the attribute does not have the
2507 /// suffix.
2508 ///
2509 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2510 /// \p CountInBytes and \p OrNull both being true indicates the
2511 /// `counted_by_or_null` attribute.
2512 ///
2513 /// \returns false iff semantically valid.
2514 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2515 bool OrNull);
2516
2517 /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2518 /// `__counted_by_or_null` pointer type \param LHSTy.
2519 ///
2520 /// \param LHSTy The type being assigned to. Checks will only be performed if
2521 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2522 /// \param RHSExpr The expression being assigned from.
2523 /// \param Action The type assignment being performed
2524 /// \param Loc The SourceLocation to use for error diagnostics
2525 /// \param Assignee The ValueDecl being assigned. This is used to compute
2526 /// the name of the assignee. If the assignee isn't known this can
2527 /// be set to nullptr.
2528 /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2529 /// Assignee to compute the name of the assignee use the fully
2530 /// qualified name, otherwise use the unqualified name.
2531 ///
2532 /// \returns True iff no diagnostic where emitted, false otherwise.
2533 bool BoundsSafetyCheckAssignmentToCountAttrPtr(
2534 QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2535 SourceLocation Loc, const ValueDecl *Assignee,
2536 bool ShowFullyQualifiedAssigneeName);
2537
2538 /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2539 /// pointer.
2540 ///
2541 /// \param Entity The entity being initialized
2542 /// \param Kind The kind of initialization being performed
2543 /// \param Action The type assignment being performed
2544 /// \param LHSTy The type being assigned to. Checks will only be performed if
2545 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2546 /// \param RHSExpr The expression being used for initialization.
2547 ///
2548 /// \returns True iff no diagnostic where emitted, false otherwise.
2549 bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity,
2550 const InitializationKind &Kind,
2551 AssignmentAction Action,
2552 QualType LHSType, Expr *RHSExpr);
2553
2554 /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2555 /// or counted_by_or_null pointers in \param E.
2556 ///
2557 /// \param E the expression to check
2558 ///
2559 /// \returns True iff no diagnostic where emitted, false otherwise.
2560 bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E);
2561 ///@}
2562
2563 //
2564 //
2565 // -------------------------------------------------------------------------
2566 //
2567 //
2568
2569 /// \name Casts
2570 /// Implementations are in SemaCast.cpp
2571 ///@{
2572
2573public:
2574 static bool isCast(CheckedConversionKind CCK) {
2575 return CCK == CheckedConversionKind::CStyleCast ||
2576 CCK == CheckedConversionKind::FunctionalCast ||
2577 CCK == CheckedConversionKind::OtherCast;
2578 }
2579
2580 /// ActOnCXXNamedCast - Parse
2581 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2582 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2583 SourceLocation LAngleBracketLoc, Declarator &D,
2584 SourceLocation RAngleBracketLoc,
2585 SourceLocation LParenLoc, Expr *E,
2586 SourceLocation RParenLoc);
2587
2588 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2589 TypeSourceInfo *Ty, Expr *E,
2590 SourceRange AngleBrackets, SourceRange Parens);
2591
2592 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
2593 ExprResult Operand,
2594 SourceLocation RParenLoc);
2595
2596 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
2597 Expr *Operand, SourceLocation RParenLoc);
2598
2599 // Checks that reinterpret casts don't have undefined behavior.
2600 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2601 bool IsDereference, SourceRange Range);
2602
2603 // Checks that the vector type should be initialized from a scalar
2604 // by splatting the value rather than populating a single element.
2605 // This is the case for AltiVecVector types as well as with
2606 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2607 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2608
2609 // Checks if the -faltivec-src-compat=gcc option is specified.
2610 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2611 // treated the same way as they are when trying to initialize
2612 // these vectors on gcc (an error is emitted).
2613 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
2614 QualType SrcTy);
2615
2616 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
2617 SourceLocation RParenLoc, Expr *Op);
2618
2619 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
2620 SourceLocation LParenLoc,
2621 Expr *CastExpr,
2622 SourceLocation RParenLoc);
2623
2624 ///@}
2625
2626 //
2627 //
2628 // -------------------------------------------------------------------------
2629 //
2630 //
2631
2632 /// \name Extra Semantic Checking
2633 /// Implementations are in SemaChecking.cpp
2634 ///@{
2635
2636public:
2637 /// Used to change context to isConstantEvaluated without pushing a heavy
2638 /// ExpressionEvaluationContextRecord object.
2639 bool isConstantEvaluatedOverride = false;
2640
2641 bool isConstantEvaluatedContext() const {
2642 return currentEvaluationContext().isConstantEvaluated() ||
2643 isConstantEvaluatedOverride;
2644 }
2645
2646 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
2647 unsigned ByteNo) const;
2648
2649 enum FormatArgumentPassingKind {
2650 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2651 FAPK_Variadic, // values to format are passed as variadic arguments
2652 FAPK_VAList, // values to format are passed in a va_list
2653 FAPK_Elsewhere, // values to format are not passed to this function
2654 };
2655
2656 // Used to grab the relevant information from a FormatAttr and a
2657 // FunctionDeclaration.
2658 struct FormatStringInfo {
2659 unsigned FormatIdx;
2660 unsigned FirstDataArg;
2661 FormatArgumentPassingKind ArgPassingKind;
2662 };
2663
2664 /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2665 /// populate the FormatStringInfo parameter with the attribute's correct
2666 /// format_idx and firstDataArg. Returns true when the format fits the
2667 /// function and the FormatStringInfo has been populated.
2668 static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2669 unsigned FirstArg, FormatStringInfo *FSI);
2670 static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2671 bool HasImplicitThisParam, bool IsVariadic,
2672 FormatStringInfo *FSI);
2673
2674 // Used by C++ template instantiation.
2675 ExprResult BuiltinShuffleVector(CallExpr *TheCall);
2676
2677 /// ConvertVectorExpr - Handle __builtin_convertvector
2678 ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2679 SourceLocation BuiltinLoc,
2680 SourceLocation RParenLoc);
2681
2682 static StringRef GetFormatStringTypeName(FormatStringType FST);
2683 static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2684 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2685 static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2686
2687 bool FormatStringHasSArg(const StringLiteral *FExpr);
2688
2689 /// Check for comparisons of floating-point values using == and !=. Issue a
2690 /// warning if the comparison is not likely to do what the programmer
2691 /// intended.
2692 void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2693 const Expr *RHS, BinaryOperatorKind Opcode);
2694
2695 /// Register a magic integral constant to be used as a type tag.
2696 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2697 uint64_t MagicValue, QualType Type,
2698 bool LayoutCompatible, bool MustBeNull);
2699
2700 struct TypeTagData {
2701 TypeTagData() {}
2702
2703 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
2704 : Type(Type), LayoutCompatible(LayoutCompatible),
2705 MustBeNull(MustBeNull) {}
2706
2707 QualType Type;
2708
2709 /// If true, \c Type should be compared with other expression's types for
2710 /// layout-compatibility.
2711 LLVM_PREFERRED_TYPE(bool)
2712 unsigned LayoutCompatible : 1;
2713 LLVM_PREFERRED_TYPE(bool)
2714 unsigned MustBeNull : 1;
2715 };
2716
2717 /// A pair of ArgumentKind identifier and magic value. This uniquely
2718 /// identifies the magic value.
2719 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2720
2721 /// Diagnoses the current set of gathered accesses. This happens at the end of
2722 /// each expression evaluation context. Diagnostics are emitted only for
2723 /// accesses gathered in the current evaluation context.
2724 void DiagnoseMisalignedMembers();
2725
2726 /// This function checks if the expression is in the sef of potentially
2727 /// misaligned members and it is converted to some pointer type T with lower
2728 /// or equal alignment requirements. If so it removes it. This is used when
2729 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2730 /// void*).
2731 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2732
2733 /// Returns true if `From` is a function or pointer to a function with the
2734 /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2735 /// function without this attribute.
2736 bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2737
2738 /// This function calls Action when it determines that E designates a
2739 /// misaligned member due to the packed attribute. This is used to emit
2740 /// local diagnostics like in reference binding.
2741 void RefersToMemberWithReducedAlignment(
2742 Expr *E,
2743 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2744 Action);
2745
2746 enum class AtomicArgumentOrder { API, AST };
2747 ExprResult
2748 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2749 SourceLocation RParenLoc, MultiExprArg Args,
2750 AtomicExpr::AtomicOp Op,
2751 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
2752
2753 /// Check to see if a given expression could have '.c_str()' called on it.
2754 bool hasCStrMethod(const Expr *E);
2755
2756 /// Diagnose pointers that are always non-null.
2757 /// \param E the expression containing the pointer
2758 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2759 /// compared to a null pointer
2760 /// \param IsEqual True when the comparison is equal to a null pointer
2761 /// \param Range Extra SourceRange to highlight in the diagnostic
2762 void DiagnoseAlwaysNonNullPointer(Expr *E,
2763 Expr::NullPointerConstantKind NullType,
2764 bool IsEqual, SourceRange Range);
2765
2766 /// CheckParmsForFunctionDef - Check that the parameters of the given
2767 /// function are appropriate for the definition of a function. This
2768 /// takes care of any checks that cannot be performed on the
2769 /// declaration itself, e.g., that the types of each of the function
2770 /// parameters are complete.
2771 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2772 bool CheckParameterNames);
2773
2774 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2775 /// pointer cast increases the alignment requirements.
2776 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2777
2778 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2779 /// to weak/__unsafe_unretained type.
2780 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2781
2782 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2783 /// to weak/__unsafe_unretained expression.
2784 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2785
2786 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2787 /// statement as a \p Body, and it is located on the same line.
2788 ///
2789 /// This helps prevent bugs due to typos, such as:
2790 /// if (condition);
2791 /// do_stuff();
2792 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2793 unsigned DiagID);
2794
2795 /// Warn if a for/while loop statement \p S, which is followed by
2796 /// \p PossibleBody, has a suspicious null statement as a body.
2797 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2798
2799 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2800 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2801 SourceLocation OpLoc);
2802
2803 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2804 bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
2805 const TypeSourceInfo *Derived);
2806
2807 /// CheckFunctionCall - Check a direct function call for various correctness
2808 /// and safety properties not strictly enforced by the C type system.
2809 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2810 const FunctionProtoType *Proto);
2811
2812 enum class EltwiseBuiltinArgTyRestriction {
2813 None,
2814 FloatTy,
2815 IntegerTy,
2816 SignedIntOrFloatTy,
2817 };
2818
2819 /// \param FPOnly restricts the arguments to floating-point types.
2820 std::optional<QualType>
2821 BuiltinVectorMath(CallExpr *TheCall,
2822 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2823 EltwiseBuiltinArgTyRestriction::None);
2824 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2825
2826 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2827 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2828
2829 /// Handles the checks for format strings, non-POD arguments to vararg
2830 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2831 /// attributes and AArch64 SME attributes.
2832 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2833 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2834 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2835 VariadicCallType CallType);
2836
2837 /// Verify that two format strings (as understood by attribute(format) and
2838 /// attribute(format_matches) are compatible. If they are incompatible,
2839 /// diagnostics are emitted with the assumption that \c
2840 /// AuthoritativeFormatString is correct and
2841 /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2842 /// diagnostics will point to it and a note will refer to \c
2843 /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2844 bool
2845 CheckFormatStringsCompatible(FormatStringType FST,
2846 const StringLiteral *AuthoritativeFormatString,
2847 const StringLiteral *TestedFormatString,
2848 const Expr *FunctionCallArg = nullptr);
2849
2850 /// Verify that one format string (as understood by attribute(format)) is
2851 /// self-consistent; for instance, that it doesn't have multiple positional
2852 /// arguments referring to the same argument in incompatible ways. Diagnose
2853 /// if it isn't.
2854 bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str);
2855
2856 /// \brief Enforce the bounds of a TCB
2857 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2858 /// directly calls other functions in the same TCB as marked by the
2859 /// enforce_tcb and enforce_tcb_leaf attributes.
2860 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2861 const NamedDecl *Callee);
2862
2863 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2864
2865 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2866 /// TheCall is a constant expression.
2867 bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
2868 llvm::APSInt &Result);
2869
2870 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2871 /// TheCall is a constant expression in the range [Low, High].
2872 bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
2873 int High, bool RangeIsError = true);
2874
2875 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2876 /// TheCall is a constant expression is a multiple of Num..
2877 bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
2878 unsigned Multiple);
2879
2880 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2881 /// constant expression representing a power of 2.
2882 bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum);
2883
2884 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2885 /// a constant expression representing an arbitrary byte value shifted left by
2886 /// a multiple of 8 bits.
2887 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
2888 unsigned ArgBits);
2889
2890 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2891 /// TheCall is a constant expression representing either a shifted byte value,
2892 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2893 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2894 /// Arm MVE intrinsics.
2895 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum,
2896 unsigned ArgBits);
2897
2898 /// Checks that a call expression's argument count is at least the desired
2899 /// number. This is useful when doing custom type-checking on a variadic
2900 /// function. Returns true on error.
2901 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2902
2903 /// Checks that a call expression's argument count is at most the desired
2904 /// number. This is useful when doing custom type-checking on a variadic
2905 /// function. Returns true on error.
2906 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
2907
2908 /// Checks that a call expression's argument count is in the desired range.
2909 /// This is useful when doing custom type-checking on a variadic function.
2910 /// Returns true on error.
2911 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
2912 unsigned MaxArgCount);
2913
2914 /// Checks that a call expression's argument count is the desired number.
2915 /// This is useful when doing custom type-checking. Returns true on error.
2916 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
2917
2918 /// Returns true if the argument consists of one contiguous run of 1s with any
2919 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
2920 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
2921 /// since all 1s are not contiguous.
2922 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2923
2924 void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
2925 bool *ICContext = nullptr,
2926 bool IsListInit = false);
2927
2928 /// Check for overflow behavior type related implicit conversion diagnostics.
2929 /// Returns true if OBT-related diagnostic was issued, false otherwise.
2930 bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
2931 SourceLocation CC);
2932
2933 bool
2934 BuiltinElementwiseTernaryMath(CallExpr *TheCall,
2935 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2936 EltwiseBuiltinArgTyRestriction::FloatTy);
2937 bool PrepareBuiltinElementwiseMathOneArgCall(
2938 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
2939 EltwiseBuiltinArgTyRestriction::None);
2940
2941private:
2942 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2943 const ArraySubscriptExpr *ASE = nullptr,
2944 bool AllowOnePastEnd = true, bool IndexNegated = false);
2945 void CheckArrayAccess(const Expr *E);
2946
2947 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2948 const FunctionProtoType *Proto);
2949
2950 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2951 /// such as function pointers returned from functions.
2952 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
2953
2954 /// CheckConstructorCall - Check a constructor call for correctness and safety
2955 /// properties not enforced by the C type system.
2956 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
2957 ArrayRef<const Expr *> Args,
2958 const FunctionProtoType *Proto, SourceLocation Loc);
2959
2960 /// Warn if a pointer or reference argument passed to a function points to an
2961 /// object that is less aligned than the parameter. This can happen when
2962 /// creating a typedef with a lower alignment than the original type and then
2963 /// calling functions defined in terms of the original type.
2964 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
2965 StringRef ParamName, QualType ArgTy, QualType ParamTy);
2966
2967 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
2968
2969 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2970 CallExpr *TheCall);
2971
2972 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2973 CallExpr *TheCall);
2974
2975 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
2976
2977 /// Argument-value fortify checks for libc functions that are not builtins,
2978 /// dispatched by name (e.g. umask). Diagnostics belong to -Wfortify-source.
2979 void checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall);
2980
2981 /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
2982 /// or '__builtin_c23_va_start' for validity. Emit an error and return true
2983 /// on failure; return false on success.
2984 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
2985 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
2986
2987 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2988 /// friends. This is declared to take (...), so we have to check everything.
2989 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
2990
2991 /// BuiltinSemaBuiltinFPClassification - Handle functions like
2992 /// __builtin_isnan and friends. This is declared to take (...), so we have
2993 /// to check everything.
2994 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
2995 unsigned BuiltinID);
2996
2997 /// Perform semantic analysis for a call to __builtin_complex.
2998 bool BuiltinComplex(CallExpr *TheCall);
2999 bool BuiltinOSLogFormat(CallExpr *TheCall);
3000
3001 /// BuiltinPrefetch - Handle __builtin_prefetch.
3002 /// This is declared to take (const void*, ...) and can take two
3003 /// optional constant int args.
3004 bool BuiltinPrefetch(CallExpr *TheCall);
3005
3006 /// Handle __builtin_alloca_with_align. This is declared
3007 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3008 /// than 8.
3009 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
3010
3011 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
3012 bool BuiltinArithmeticFence(CallExpr *TheCall);
3013
3014 /// BuiltinAssume - Handle __assume (MS Extension).
3015 /// __assume does not evaluate its arguments, and should warn if its argument
3016 /// has side effects.
3017 bool BuiltinAssume(CallExpr *TheCall);
3018
3019 /// Handle __builtin_assume_aligned. This is declared
3020 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3021 bool BuiltinAssumeAligned(CallExpr *TheCall);
3022
3023 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3024 /// This checks that the target supports __builtin_longjmp and
3025 /// that val is a constant 1.
3026 bool BuiltinLongjmp(CallExpr *TheCall);
3027
3028 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3029 /// This checks that the target supports __builtin_setjmp.
3030 bool BuiltinSetjmp(CallExpr *TheCall);
3031
3032 /// We have a call to a function like __sync_fetch_and_add, which is an
3033 /// overloaded function based on the pointer type of its first argument.
3034 /// The main BuildCallExpr routines have already promoted the types of
3035 /// arguments because all of these calls are prototyped as void(...).
3036 ///
3037 /// This function goes through and does final semantic checking for these
3038 /// builtins, as well as generating any warnings.
3039 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
3040
3041 /// BuiltinNontemporalOverloaded - We have a call to
3042 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3043 /// overloaded function based on the pointer type of its last argument.
3044 ///
3045 /// This function goes through and does final semantic checking for these
3046 /// builtins.
3047 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
3048 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
3049 AtomicExpr::AtomicOp Op);
3050
3051 /// \param FPOnly restricts the arguments to floating-point types.
3052 bool BuiltinElementwiseMath(CallExpr *TheCall,
3053 EltwiseBuiltinArgTyRestriction ArgTyRestr =
3054 EltwiseBuiltinArgTyRestriction::None);
3055 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
3056
3057 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
3058
3059 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
3060 BuiltinCountedByRefKind K);
3061 bool BuiltinCountedByRef(CallExpr *TheCall);
3062
3063 // Matrix builtin handling.
3064 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
3065 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
3066 ExprResult CallResult);
3067 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
3068 ExprResult CallResult);
3069
3070 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3071 /// functions) for correct use of format strings.
3072 /// Returns true if a format string has been fully checked.
3073 bool CheckFormatArguments(const FormatAttr *Format,
3074 ArrayRef<const Expr *> Args, bool IsCXXMember,
3075 VariadicCallType CallType, SourceLocation Loc,
3076 SourceRange Range,
3077 llvm::SmallBitVector &CheckedVarArgs);
3078 bool CheckFormatString(const FormatMatchesAttr *Format,
3079 ArrayRef<const Expr *> Args, bool IsCXXMember,
3080 VariadicCallType CallType, SourceLocation Loc,
3081 SourceRange Range,
3082 llvm::SmallBitVector &CheckedVarArgs);
3083 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3084 FormatArgumentPassingKind FAPK,
3085 StringLiteral *ReferenceFormatString,
3086 unsigned format_idx, unsigned firstDataArg,
3087 FormatStringType Type, VariadicCallType CallType,
3088 SourceLocation Loc, SourceRange range,
3089 llvm::SmallBitVector &CheckedVarArgs);
3090
3091 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3092
3093 /// Warn when using the wrong abs() function.
3094 void CheckAbsoluteValueFunction(const CallExpr *Call,
3095 const FunctionDecl *FDecl);
3096
3097 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3098
3099 /// Check for dangerous or invalid arguments to memset().
3100 ///
3101 /// This issues warnings on known problematic, dangerous or unspecified
3102 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3103 /// function calls.
3104 ///
3105 /// \param Call The call expression to diagnose.
3106 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3107 IdentifierInfo *FnName);
3108
3109 bool CheckSizeofMemaccessArgument(const Expr *SizeOfArg, const Expr *Dest,
3110 IdentifierInfo *FnName);
3111 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3112 // be the size of the source, instead of the destination.
3113 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3114
3115 // Warn on anti-patterns as the 'size' argument to strncat.
3116 // The correct size argument should look like following:
3117 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3118 void CheckStrncatArguments(const CallExpr *Call,
3119 const IdentifierInfo *FnName);
3120
3121 /// Alerts the user that they are attempting to free a non-malloc'd object.
3122 void CheckFreeArguments(const CallExpr *E);
3123
3124 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3125 SourceLocation ReturnLoc, bool isObjCMethod = false,
3126 const AttrVec *Attrs = nullptr,
3127 const FunctionDecl *FD = nullptr);
3128
3129 /// Diagnoses "dangerous" implicit conversions within the given
3130 /// expression (which is a full expression). Implements -Wconversion
3131 /// and -Wsign-compare.
3132 ///
3133 /// \param CC the "context" location of the implicit conversion, i.e.
3134 /// the most location of the syntactic entity requiring the implicit
3135 /// conversion
3136 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3137
3138 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3139 /// Input argument E is a logical expression.
3140 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
3141
3142 /// Diagnose when expression is an integer constant expression and its
3143 /// evaluation results in integer overflow
3144 void CheckForIntOverflow(const Expr *E);
3145 void CheckUnsequencedOperations(const Expr *E);
3146
3147 /// Perform semantic checks on a completed expression. This will either
3148 /// be a full-expression or a default argument expression.
3149 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3150 bool IsConstexpr = false);
3151
3152 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3153 Expr *Init);
3154
3155 /// A map from magic value to type information.
3156 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3157 TypeTagForDatatypeMagicValues;
3158
3159 /// Peform checks on a call of a function with argument_with_type_tag
3160 /// or pointer_with_type_tag attributes.
3161 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3162 const ArrayRef<const Expr *> ExprArgs,
3163 SourceLocation CallSiteLoc);
3164
3165 /// Check if we are taking the address of a packed field
3166 /// as this may be a problem if the pointer value is dereferenced.
3167 void CheckAddressOfPackedMember(Expr *rhs);
3168
3169 /// Helper class that collects misaligned member designations and
3170 /// their location info for delayed diagnostics.
3171 struct MisalignedMember {
3172 Expr *E;
3173 RecordDecl *RD;
3174 ValueDecl *MD;
3175 CharUnits Alignment;
3176
3177 MisalignedMember() : E(), RD(), MD() {}
3178 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3179 CharUnits Alignment)
3180 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
3181 explicit MisalignedMember(Expr *E)
3182 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3183
3184 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3185 };
3186
3187 /// Adds an expression to the set of gathered misaligned members.
3188 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3189 CharUnits Alignment);
3190 ///@}
3191
3192 //
3193 //
3194 // -------------------------------------------------------------------------
3195 //
3196 //
3197
3198 /// \name C++ Coroutines
3199 /// Implementations are in SemaCoroutine.cpp
3200 ///@{
3201
3202public:
3203 /// The C++ "std::coroutine_traits" template, which is defined in
3204 /// \<coroutine_traits>
3205 ClassTemplateDecl *StdCoroutineTraitsCache;
3206
3207 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
3208 StringRef Keyword);
3209 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3210 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3211 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
3212
3213 ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
3214 ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
3215 UnresolvedLookupExpr *Lookup);
3216 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3217 Expr *Awaiter, bool IsImplicit = false);
3218 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3219 UnresolvedLookupExpr *Lookup);
3220 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
3221 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
3222 bool IsImplicit = false);
3223 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
3224 bool buildCoroutineParameterMoves(SourceLocation Loc);
3225 VarDecl *buildCoroutinePromise(SourceLocation Loc);
3226 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
3227
3228 // As a clang extension, enforces that a non-coroutine function must be marked
3229 // with [[clang::coro_wrapper]] if it returns a type marked with
3230 // [[clang::coro_return_type]].
3231 // Expects that FD is not a coroutine.
3232 void CheckCoroutineWrapper(FunctionDecl *FD);
3233 /// Lookup 'coroutine_traits' in std namespace and std::experimental
3234 /// namespace. The namespace found is recorded in Namespace.
3235 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
3236 SourceLocation FuncLoc);
3237 /// Check that the expression co_await promise.final_suspend() shall not be
3238 /// potentially-throwing.
3239 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3240
3241 ///@}
3242
3243 //
3244 //
3245 // -------------------------------------------------------------------------
3246 //
3247 //
3248
3249 /// \name C++ Scope Specifiers
3250 /// Implementations are in SemaCXXScopeSpec.cpp
3251 ///@{
3252
3253public:
3254 // Marks SS invalid if it represents an incomplete type.
3255 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
3256 // Complete an enum decl, maybe without a scope spec.
3257 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
3258 CXXScopeSpec *SS = nullptr);
3259
3260 /// Compute the DeclContext that is associated with the given type.
3261 ///
3262 /// \param T the type for which we are attempting to find a DeclContext.
3263 ///
3264 /// \returns the declaration context represented by the type T,
3265 /// or NULL if the declaration context cannot be computed (e.g., because it is
3266 /// dependent and not the current instantiation).
3267 DeclContext *computeDeclContext(QualType T);
3268
3269 /// Compute the DeclContext that is associated with the given
3270 /// scope specifier.
3271 ///
3272 /// \param SS the C++ scope specifier as it appears in the source
3273 ///
3274 /// \param EnteringContext when true, we will be entering the context of
3275 /// this scope specifier, so we can retrieve the declaration context of a
3276 /// class template or class template partial specialization even if it is
3277 /// not the current instantiation.
3278 ///
3279 /// \returns the declaration context represented by the scope specifier @p SS,
3280 /// or NULL if the declaration context cannot be computed (e.g., because it is
3281 /// dependent and not the current instantiation).
3282 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
3283 bool EnteringContext = false);
3284 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
3285
3286 /// If the given nested name specifier refers to the current
3287 /// instantiation, return the declaration that corresponds to that
3288 /// current instantiation (C++0x [temp.dep.type]p1).
3289 ///
3290 /// \param NNS a dependent nested name specifier.
3291 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier NNS);
3292
3293 /// The parser has parsed a global nested-name-specifier '::'.
3294 ///
3295 /// \param CCLoc The location of the '::'.
3296 ///
3297 /// \param SS The nested-name-specifier, which will be updated in-place
3298 /// to reflect the parsed nested-name-specifier.
3299 ///
3300 /// \returns true if an error occurred, false otherwise.
3301 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
3302
3303 /// The parser has parsed a '__super' nested-name-specifier.
3304 ///
3305 /// \param SuperLoc The location of the '__super' keyword.
3306 ///
3307 /// \param ColonColonLoc The location of the '::'.
3308 ///
3309 /// \param SS The nested-name-specifier, which will be updated in-place
3310 /// to reflect the parsed nested-name-specifier.
3311 ///
3312 /// \returns true if an error occurred, false otherwise.
3313 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
3314 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3315
3316 /// Determines whether the given declaration is an valid acceptable
3317 /// result for name lookup of a nested-name-specifier.
3318 /// \param SD Declaration checked for nested-name-specifier.
3319 /// \param IsExtension If not null and the declaration is accepted as an
3320 /// extension, the pointed variable is assigned true.
3321 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
3322 bool *CanCorrect = nullptr);
3323
3324 /// If the given nested-name-specifier begins with a bare identifier
3325 /// (e.g., Base::), perform name lookup for that identifier as a
3326 /// nested-name-specifier within the given scope, and return the result of
3327 /// that name lookup.
3328 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier NNS);
3329
3330 /// Keeps information about an identifier in a nested-name-spec.
3331 ///
3332 struct NestedNameSpecInfo {
3333 /// The type of the object, if we're parsing nested-name-specifier in
3334 /// a member access expression.
3335 ParsedType ObjectType;
3336
3337 /// The identifier preceding the '::'.
3338 IdentifierInfo *Identifier;
3339
3340 /// The location of the identifier.
3341 SourceLocation IdentifierLoc;
3342
3343 /// The location of the '::'.
3344 SourceLocation CCLoc;
3345
3346 /// Creates info object for the most typical case.
3347 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3348 SourceLocation ColonColonLoc,
3349 ParsedType ObjectType = ParsedType())
3350 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
3351 CCLoc(ColonColonLoc) {}
3352
3353 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3354 SourceLocation ColonColonLoc, QualType ObjectType)
3355 : ObjectType(ParsedType::make(P: ObjectType)), Identifier(II),
3356 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3357 };
3358
3359 /// Build a new nested-name-specifier for "identifier::", as described
3360 /// by ActOnCXXNestedNameSpecifier.
3361 ///
3362 /// \param S Scope in which the nested-name-specifier occurs.
3363 /// \param IdInfo Parser information about an identifier in the
3364 /// nested-name-spec.
3365 /// \param EnteringContext If true, enter the context specified by the
3366 /// nested-name-specifier.
3367 /// \param SS Optional nested name specifier preceding the identifier.
3368 /// \param ScopeLookupResult Provides the result of name lookup within the
3369 /// scope of the nested-name-specifier that was computed at template
3370 /// definition time.
3371 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3372 /// error recovery and what kind of recovery is performed.
3373 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3374 /// are allowed. The bool value pointed by this parameter is set to
3375 /// 'true' if the identifier is treated as if it was followed by ':',
3376 /// not '::'.
3377 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3378 ///
3379 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3380 /// that it contains an extra parameter \p ScopeLookupResult, which provides
3381 /// the result of name lookup within the scope of the nested-name-specifier
3382 /// that was computed at template definition time.
3383 ///
3384 /// If ErrorRecoveryLookup is true, then this call is used to improve error
3385 /// recovery. This means that it should not emit diagnostics, it should
3386 /// just return true on failure. It also means it should only return a valid
3387 /// scope if it *knows* that the result is correct. It should not return in a
3388 /// dependent context, for example. Nor will it extend \p SS with the scope
3389 /// specifier.
3390 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3391 bool EnteringContext, CXXScopeSpec &SS,
3392 NamedDecl *ScopeLookupResult,
3393 bool ErrorRecoveryLookup,
3394 bool *IsCorrectedToColon = nullptr,
3395 bool OnlyNamespace = false);
3396
3397 /// The parser has parsed a nested-name-specifier 'identifier::'.
3398 ///
3399 /// \param S The scope in which this nested-name-specifier occurs.
3400 ///
3401 /// \param IdInfo Parser information about an identifier in the
3402 /// nested-name-spec.
3403 ///
3404 /// \param EnteringContext Whether we're entering the context nominated by
3405 /// this nested-name-specifier.
3406 ///
3407 /// \param SS The nested-name-specifier, which is both an input
3408 /// parameter (the nested-name-specifier before this type) and an
3409 /// output parameter (containing the full nested-name-specifier,
3410 /// including this new type).
3411 ///
3412 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3413 /// are allowed. The bool value pointed by this parameter is set to 'true'
3414 /// if the identifier is treated as if it was followed by ':', not '::'.
3415 ///
3416 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3417 ///
3418 /// \returns true if an error occurred, false otherwise.
3419 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3420 bool EnteringContext, CXXScopeSpec &SS,
3421 bool *IsCorrectedToColon = nullptr,
3422 bool OnlyNamespace = false);
3423
3424 /// The parser has parsed a nested-name-specifier
3425 /// 'template[opt] template-name < template-args >::'.
3426 ///
3427 /// \param S The scope in which this nested-name-specifier occurs.
3428 ///
3429 /// \param SS The nested-name-specifier, which is both an input
3430 /// parameter (the nested-name-specifier before this type) and an
3431 /// output parameter (containing the full nested-name-specifier,
3432 /// including this new type).
3433 ///
3434 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3435 /// \param TemplateName the template name.
3436 /// \param TemplateNameLoc The location of the template name.
3437 /// \param LAngleLoc The location of the opening angle bracket ('<').
3438 /// \param TemplateArgs The template arguments.
3439 /// \param RAngleLoc The location of the closing angle bracket ('>').
3440 /// \param CCLoc The location of the '::'.
3441 ///
3442 /// \param EnteringContext Whether we're entering the context of the
3443 /// nested-name-specifier.
3444 ///
3445 ///
3446 /// \returns true if an error occurred, false otherwise.
3447 bool ActOnCXXNestedNameSpecifier(
3448 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3449 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3450 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3451 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3452
3453 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS,
3454 SourceLocation ColonColonLoc);
3455
3456 bool ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS,
3457 const DeclSpec &DS,
3458 SourceLocation ColonColonLoc,
3459 QualType Type);
3460
3461 /// IsInvalidUnlessNestedName - This method is used for error recovery
3462 /// purposes to determine whether the specified identifier is only valid as
3463 /// a nested name specifier, for example a namespace name. It is
3464 /// conservatively correct to always return false from this method.
3465 ///
3466 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3467 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3468 NestedNameSpecInfo &IdInfo,
3469 bool EnteringContext);
3470
3471 /// Given a C++ nested-name-specifier, produce an annotation value
3472 /// that the parser can use later to reconstruct the given
3473 /// nested-name-specifier.
3474 ///
3475 /// \param SS A nested-name-specifier.
3476 ///
3477 /// \returns A pointer containing all of the information in the
3478 /// nested-name-specifier \p SS.
3479 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3480
3481 /// Given an annotation pointer for a nested-name-specifier, restore
3482 /// the nested-name-specifier structure.
3483 ///
3484 /// \param Annotation The annotation pointer, produced by
3485 /// \c SaveNestedNameSpecifierAnnotation().
3486 ///
3487 /// \param AnnotationRange The source range corresponding to the annotation.
3488 ///
3489 /// \param SS The nested-name-specifier that will be updated with the contents
3490 /// of the annotation pointer.
3491 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3492 SourceRange AnnotationRange,
3493 CXXScopeSpec &SS);
3494
3495 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3496
3497 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3498 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3499 /// After this method is called, according to [C++ 3.4.3p3], names should be
3500 /// looked up in the declarator-id's scope, until the declarator is parsed and
3501 /// ActOnCXXExitDeclaratorScope is called.
3502 /// The 'SS' should be a non-empty valid CXXScopeSpec.
3503 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
3504
3505 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3506 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3507 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3508 /// Used to indicate that names should revert to being looked up in the
3509 /// defining scope.
3510 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3511
3512 ///@}
3513
3514 //
3515 //
3516 // -------------------------------------------------------------------------
3517 //
3518 //
3519
3520 /// \name Declarations
3521 /// Implementations are in SemaDecl.cpp
3522 ///@{
3523
3524public:
3525 IdentifierResolver IdResolver;
3526
3527 /// The index of the first InventedParameterInfo that refers to the current
3528 /// context.
3529 unsigned InventedParameterInfosStart = 0;
3530
3531 /// A RAII object to temporarily push a declaration context.
3532 class ContextRAII {
3533 private:
3534 Sema &S;
3535 DeclContext *SavedContext;
3536 ProcessingContextState SavedContextState;
3537 QualType SavedCXXThisTypeOverride;
3538 unsigned SavedFunctionScopesStart;
3539 unsigned SavedInventedParameterInfosStart;
3540
3541 public:
3542 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3543 : S(S), SavedContext(S.CurContext),
3544 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3545 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3546 SavedFunctionScopesStart(S.FunctionScopesStart),
3547 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3548 assert(ContextToPush && "pushing null context");
3549 S.CurContext = ContextToPush;
3550 if (NewThisContext)
3551 S.CXXThisTypeOverride = QualType();
3552 // Any saved FunctionScopes do not refer to this context.
3553 S.FunctionScopesStart = S.FunctionScopes.size();
3554 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3555 }
3556
3557 void pop() {
3558 if (!SavedContext)
3559 return;
3560 S.CurContext = SavedContext;
3561 S.DelayedDiagnostics.popUndelayed(state: SavedContextState);
3562 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3563 S.FunctionScopesStart = SavedFunctionScopesStart;
3564 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3565 SavedContext = nullptr;
3566 }
3567
3568 ~ContextRAII() { pop(); }
3569 ContextRAII(const ContextRAII &) = delete;
3570 ContextRAII &operator=(const ContextRAII &) = delete;
3571 };
3572
3573 void DiagnoseInvalidJumps(Stmt *Body);
3574
3575 /// The function definitions which were renamed as part of typo-correction
3576 /// to match their respective declarations. We want to keep track of them
3577 /// to ensure that we don't emit a "redefinition" error if we encounter a
3578 /// correctly named definition after the renamed definition.
3579 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
3580
3581 /// A cache of the flags available in enumerations with the flag_enum
3582 /// attribute.
3583 llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3584
3585 /// A cache of enumerator values for enums checked by -Wassign-enum.
3586 llvm::DenseMap<const EnumDecl *, llvm::SmallVector<llvm::APSInt>>
3587 AssignEnumCache;
3588
3589 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3590 /// declared. Rare. May alias another identifier, declared or undeclared.
3591 ///
3592 /// For aliases, the target identifier is used as a key for eventual
3593 /// processing when the target is declared. For the single-identifier form,
3594 /// the sole identifier is used as the key. Each entry is a `SetVector`
3595 /// (ordered by parse order) of aliases (identified by the alias name) in case
3596 /// of multiple aliases to the same undeclared identifier.
3597 llvm::MapVector<
3598 IdentifierInfo *,
3599 llvm::SetVector<
3600 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
3601 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3602 WeakUndeclaredIdentifiers;
3603
3604 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3605 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3606 /// to define functions that occur in multiple standards to call the version
3607 /// in the currently selected standard.
3608 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>
3609 ExtnameUndeclaredIdentifiers;
3610
3611 /// Set containing all typedefs that are likely unused.
3612 llvm::SmallPtrSet<const TypedefNameDecl *, 4>
3613 UnusedLocalTypedefNameCandidates;
3614
3615 /// Store UnusedLocalTypedefNameCandidates in \p Sorted in a deterministic
3616 /// order.
3617 void getSortedUnusedLocalTypedefNameCandidates(
3618 SmallVectorImpl<const TypedefNameDecl *> &Sorted) const;
3619
3620 typedef LazyVector<const DeclaratorDecl *,
3621 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
3622 UnusedFileScopedDeclsType;
3623
3624 /// The set of file scoped decls seen so far that have not been used
3625 /// and must warn if not used. Only contains the first declaration.
3626 UnusedFileScopedDeclsType UnusedFileScopedDecls;
3627
3628 typedef LazyVector<VarDecl *, &ExternalSemaSource::ReadTentativeDefinitions,
3629 2, 2>
3630 TentativeDefinitionsType;
3631
3632 /// All the tentative definitions encountered in the TU.
3633 TentativeDefinitionsType TentativeDefinitions;
3634
3635 /// All the external declarations encoutered and used in the TU.
3636 SmallVector<DeclaratorDecl *, 4> ExternalDeclarations;
3637
3638 /// Generally null except when we temporarily switch decl contexts,
3639 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3640 DeclContext *OriginalLexicalContext;
3641
3642 /// Is the module scope we are in a C++ Header Unit?
3643 bool currentModuleIsHeaderUnit() const {
3644 return ModuleScopes.empty() ? false
3645 : ModuleScopes.back().Module->isHeaderUnit();
3646 }
3647
3648 /// Get the module owning an entity.
3649 Module *getOwningModule(const Decl *Entity) {
3650 return Entity->getOwningModule();
3651 }
3652
3653 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3654
3655 enum class DiagCtorKind { None, Implicit, Typename };
3656 /// Returns the TypeDeclType for the given type declaration,
3657 /// as ASTContext::getTypeDeclType would, but
3658 /// performs the required semantic checks for name lookup of said entity.
3659 void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD,
3660 SourceLocation NameLoc);
3661
3662 /// If the identifier refers to a type name within this scope,
3663 /// return the declaration of that type.
3664 ///
3665 /// This routine performs ordinary name lookup of the identifier II
3666 /// within the given scope, with optional C++ scope specifier SS, to
3667 /// determine whether the name refers to a type. If so, returns an
3668 /// opaque pointer (actually a QualType) corresponding to that
3669 /// type. Otherwise, returns NULL.
3670 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
3671 Scope *S, CXXScopeSpec *SS = nullptr,
3672 bool isClassName = false, bool HasTrailingDot = false,
3673 ParsedType ObjectType = nullptr,
3674 bool IsCtorOrDtorName = false,
3675 bool WantNontrivialTypeSourceInfo = false,
3676 bool IsClassTemplateDeductionContext = true,
3677 ImplicitTypenameContext AllowImplicitTypename =
3678 ImplicitTypenameContext::No,
3679 IdentifierInfo **CorrectedII = nullptr);
3680
3681 /// isTagName() - This method is called *for error recovery purposes only*
3682 /// to determine if the specified name is a valid tag name ("struct foo"). If
3683 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3684 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3685 /// diagnose cases in C where the user forgot to specify the tag.
3686 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
3687
3688 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3689 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3690 /// then downgrade the missing typename error to a warning.
3691 /// This is needed for MSVC compatibility; Example:
3692 /// @code
3693 /// template<class T> class A {
3694 /// public:
3695 /// typedef int TYPE;
3696 /// };
3697 /// template<class T> class B : public A<T> {
3698 /// public:
3699 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3700 /// };
3701 /// @endcode
3702 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3703 void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc,
3704 Scope *S, CXXScopeSpec *SS,
3705 ParsedType &SuggestedType,
3706 bool IsTemplateName = false);
3707
3708 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3709 /// type name has failed in a dependent context. In these situations, we
3710 /// automatically form a DependentTypeName that will retry lookup in a related
3711 /// scope during instantiation.
3712 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
3713 SourceLocation NameLoc,
3714 bool IsTemplateTypeArg);
3715
3716 class NameClassification {
3717 NameClassificationKind Kind;
3718 union {
3719 ExprResult Expr;
3720 NamedDecl *NonTypeDecl;
3721 TemplateName Template;
3722 ParsedType Type;
3723 };
3724
3725 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3726
3727 public:
3728 NameClassification(ParsedType Type)
3729 : Kind(NameClassificationKind::Type), Type(Type) {}
3730
3731 NameClassification(const IdentifierInfo *Keyword)
3732 : Kind(NameClassificationKind::Keyword) {}
3733
3734 static NameClassification Error() {
3735 return NameClassification(NameClassificationKind::Error);
3736 }
3737
3738 static NameClassification Unknown() {
3739 return NameClassification(NameClassificationKind::Unknown);
3740 }
3741
3742 static NameClassification OverloadSet(ExprResult E) {
3743 NameClassification Result(NameClassificationKind::OverloadSet);
3744 Result.Expr = E;
3745 return Result;
3746 }
3747
3748 static NameClassification NonType(NamedDecl *D) {
3749 NameClassification Result(NameClassificationKind::NonType);
3750 Result.NonTypeDecl = D;
3751 return Result;
3752 }
3753
3754 static NameClassification UndeclaredNonType() {
3755 return NameClassification(NameClassificationKind::UndeclaredNonType);
3756 }
3757
3758 static NameClassification DependentNonType() {
3759 return NameClassification(NameClassificationKind::DependentNonType);
3760 }
3761
3762 static NameClassification TypeTemplate(TemplateName Name) {
3763 NameClassification Result(NameClassificationKind::TypeTemplate);
3764 Result.Template = Name;
3765 return Result;
3766 }
3767
3768 static NameClassification VarTemplate(TemplateName Name) {
3769 NameClassification Result(NameClassificationKind::VarTemplate);
3770 Result.Template = Name;
3771 return Result;
3772 }
3773
3774 static NameClassification FunctionTemplate(TemplateName Name) {
3775 NameClassification Result(NameClassificationKind::FunctionTemplate);
3776 Result.Template = Name;
3777 return Result;
3778 }
3779
3780 static NameClassification Concept(TemplateName Name) {
3781 NameClassification Result(NameClassificationKind::Concept);
3782 Result.Template = Name;
3783 return Result;
3784 }
3785
3786 static NameClassification UndeclaredTemplate(TemplateName Name) {
3787 NameClassification Result(NameClassificationKind::UndeclaredTemplate);
3788 Result.Template = Name;
3789 return Result;
3790 }
3791
3792 NameClassificationKind getKind() const { return Kind; }
3793
3794 ExprResult getExpression() const {
3795 assert(Kind == NameClassificationKind::OverloadSet);
3796 return Expr;
3797 }
3798
3799 ParsedType getType() const {
3800 assert(Kind == NameClassificationKind::Type);
3801 return Type;
3802 }
3803
3804 NamedDecl *getNonTypeDecl() const {
3805 assert(Kind == NameClassificationKind::NonType);
3806 return NonTypeDecl;
3807 }
3808
3809 TemplateName getTemplateName() const {
3810 assert(Kind == NameClassificationKind::TypeTemplate ||
3811 Kind == NameClassificationKind::FunctionTemplate ||
3812 Kind == NameClassificationKind::VarTemplate ||
3813 Kind == NameClassificationKind::Concept ||
3814 Kind == NameClassificationKind::UndeclaredTemplate);
3815 return Template;
3816 }
3817
3818 TemplateNameKind getTemplateNameKind() const {
3819 switch (Kind) {
3820 case NameClassificationKind::TypeTemplate:
3821 return TNK_Type_template;
3822 case NameClassificationKind::FunctionTemplate:
3823 return TNK_Function_template;
3824 case NameClassificationKind::VarTemplate:
3825 return TNK_Var_template;
3826 case NameClassificationKind::Concept:
3827 return TNK_Concept_template;
3828 case NameClassificationKind::UndeclaredTemplate:
3829 return TNK_Undeclared_template;
3830 default:
3831 llvm_unreachable("unsupported name classification.");
3832 }
3833 }
3834 };
3835
3836 /// Perform name lookup on the given name, classifying it based on
3837 /// the results of name lookup and the following token.
3838 ///
3839 /// This routine is used by the parser to resolve identifiers and help direct
3840 /// parsing. When the identifier cannot be found, this routine will attempt
3841 /// to correct the typo and classify based on the resulting name.
3842 ///
3843 /// \param S The scope in which we're performing name lookup.
3844 ///
3845 /// \param SS The nested-name-specifier that precedes the name.
3846 ///
3847 /// \param Name The identifier. If typo correction finds an alternative name,
3848 /// this pointer parameter will be updated accordingly.
3849 ///
3850 /// \param NameLoc The location of the identifier.
3851 ///
3852 /// \param NextToken The token following the identifier. Used to help
3853 /// disambiguate the name.
3854 ///
3855 /// \param CCC The correction callback, if typo correction is desired.
3856 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3857 IdentifierInfo *&Name, SourceLocation NameLoc,
3858 const Token &NextToken,
3859 CorrectionCandidateCallback *CCC = nullptr);
3860
3861 /// Act on the result of classifying a name as an undeclared (ADL-only)
3862 /// non-type declaration.
3863 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
3864 SourceLocation NameLoc);
3865 /// Act on the result of classifying a name as an undeclared member of a
3866 /// dependent base class.
3867 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
3868 IdentifierInfo *Name,
3869 SourceLocation NameLoc,
3870 bool IsAddressOfOperand);
3871 /// Act on the result of classifying a name as a specific non-type
3872 /// declaration.
3873 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
3874 NamedDecl *Found,
3875 SourceLocation NameLoc,
3876 const Token &NextToken);
3877 /// Act on the result of classifying a name as an overload set.
3878 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
3879
3880 /// Describes the detailed kind of a template name. Used in diagnostics.
3881 enum class TemplateNameKindForDiagnostics {
3882 ClassTemplate,
3883 FunctionTemplate,
3884 VarTemplate,
3885 AliasTemplate,
3886 TemplateTemplateParam,
3887 Concept,
3888 DependentTemplate
3889 };
3890 TemplateNameKindForDiagnostics
3891 getTemplateNameKindForDiagnostics(TemplateName Name);
3892
3893 /// Determine whether it's plausible that E was intended to be a
3894 /// template-name.
3895 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
3896 if (!getLangOpts().CPlusPlus || E.isInvalid())
3897 return false;
3898 Dependent = false;
3899 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E.get()))
3900 return !DRE->hasExplicitTemplateArgs();
3901 if (auto *ME = dyn_cast<MemberExpr>(Val: E.get()))
3902 return !ME->hasExplicitTemplateArgs();
3903 Dependent = true;
3904 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(Val: E.get()))
3905 return !DSDRE->hasExplicitTemplateArgs();
3906 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(Val: E.get()))
3907 return !DSME->hasExplicitTemplateArgs();
3908 // Any additional cases recognized here should also be handled by
3909 // diagnoseExprIntendedAsTemplateName.
3910 return false;
3911 }
3912
3913 void warnOnReservedIdentifier(const NamedDecl *D);
3914 void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D);
3915
3916 void ProcessPragmaExport(DeclaratorDecl *newDecl);
3917
3918 Decl *ActOnDeclarator(Scope *S, Declarator &D);
3919
3920 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
3921 MultiTemplateParamsArg TemplateParameterLists);
3922
3923 /// Attempt to fold a variable-sized type to a constant-sized type, returning
3924 /// true if we were successful.
3925 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T,
3926 SourceLocation Loc,
3927 unsigned FailedFoldDiagID);
3928
3929 /// Register the given locally-scoped extern "C" declaration so
3930 /// that it can be found later for redeclarations. We include any extern "C"
3931 /// declaration that is not visible in the translation unit here, not just
3932 /// function-scope declarations.
3933 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
3934
3935 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3936 /// If T is the name of a class, then each of the following shall have a
3937 /// name different from T:
3938 /// - every static data member of class T;
3939 /// - every member function of class T
3940 /// - every member of class T that is itself a type;
3941 /// \returns true if the declaration name violates these rules.
3942 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
3943
3944 /// Diagnose a declaration whose declarator-id has the given
3945 /// nested-name-specifier.
3946 ///
3947 /// \param SS The nested-name-specifier of the declarator-id.
3948 ///
3949 /// \param DC The declaration context to which the nested-name-specifier
3950 /// resolves.
3951 ///
3952 /// \param Name The name of the entity being declared.
3953 ///
3954 /// \param Loc The location of the name of the entity being declared.
3955 ///
3956 /// \param IsMemberSpecialization Whether we are declaring a member
3957 /// specialization.
3958 ///
3959 /// \param TemplateId The template-id, if any.
3960 ///
3961 /// \returns true if we cannot safely recover from this error, false
3962 /// otherwise.
3963 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3964 DeclarationName Name, SourceLocation Loc,
3965 TemplateIdAnnotation *TemplateId,
3966 bool IsMemberSpecialization);
3967
3968 bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range);
3969
3970 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
3971
3972 bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind,
3973 unsigned &IntVal);
3974
3975 /// Diagnose function specifiers on a declaration of an identifier that
3976 /// does not identify a function.
3977 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
3978
3979 /// Return the declaration shadowed by the given typedef \p D, or null
3980 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3981 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
3982 const LookupResult &R);
3983
3984 /// Return the declaration shadowed by the given variable \p D, or null
3985 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3986 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
3987
3988 /// Return the declaration shadowed by the given variable \p D, or null
3989 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3990 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
3991 const LookupResult &R);
3992 /// Diagnose variable or built-in function shadowing. Implements
3993 /// -Wshadow.
3994 ///
3995 /// This method is called whenever a VarDecl is added to a "useful"
3996 /// scope.
3997 ///
3998 /// \param ShadowedDecl the declaration that is shadowed by the given variable
3999 /// \param R the lookup of the name
4000 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
4001 const LookupResult &R);
4002
4003 /// Check -Wshadow without the advantage of a previous lookup.
4004 void CheckShadow(Scope *S, VarDecl *D);
4005
4006 /// Warn if 'E', which is an expression that is about to be modified, refers
4007 /// to a shadowing declaration.
4008 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
4009
4010 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
4011 /// when these variables are captured by the lambda.
4012 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
4013
4014 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
4015 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4016 TypedefNameDecl *NewTD);
4017 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
4018 NamedDecl *ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4019 TypeSourceInfo *TInfo,
4020 LookupResult &Previous);
4021
4022 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4023 /// declares a typedef-name, either using the 'typedef' type specifier or via
4024 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4025 NamedDecl *ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D,
4026 LookupResult &Previous, bool &Redeclaration);
4027 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4028 TypeSourceInfo *TInfo,
4029 LookupResult &Previous,
4030 MultiTemplateParamsArg TemplateParamLists,
4031 bool &AddToScope,
4032 ArrayRef<BindingDecl *> Bindings = {});
4033
4034private:
4035 // Perform a check on an AsmLabel to verify its consistency and emit
4036 // diagnostics in case of an error.
4037 void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
4038 TypeSourceInfo *TInfo, VarDecl *);
4039
4040public:
4041 /// Perform semantic checking on a newly-created variable
4042 /// declaration.
4043 ///
4044 /// This routine performs all of the type-checking required for a
4045 /// variable declaration once it has been built. It is used both to
4046 /// check variables after they have been parsed and their declarators
4047 /// have been translated into a declaration, and to check variables
4048 /// that have been instantiated from a template.
4049 ///
4050 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4051 ///
4052 /// Returns true if the variable declaration is a redeclaration.
4053 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
4054 void CheckVariableDeclarationType(VarDecl *NewVD);
4055 void CheckCompleteVariableDeclaration(VarDecl *VD);
4056
4057 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4058 TypeSourceInfo *TInfo,
4059 LookupResult &Previous,
4060 MultiTemplateParamsArg TemplateParamLists,
4061 bool &AddToScope);
4062
4063 /// Attach the ABI tag a standard calling convention variant requires, as an
4064 /// implicit abi_tag attribute. Call this once the function type is final.
4065 void addImplicitCallingConvAbiTag(FunctionDecl *FD);
4066
4067 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4068 /// and if so, check that it's a valid override and remember it.
4069 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
4070
4071 /// Perform semantic checking of a new function declaration.
4072 ///
4073 /// Performs semantic analysis of the new function declaration
4074 /// NewFD. This routine performs all semantic checking that does not
4075 /// require the actual declarator involved in the declaration, and is
4076 /// used both for the declaration of functions as they are parsed
4077 /// (called via ActOnDeclarator) and for the declaration of functions
4078 /// that have been instantiated via C++ template instantiation (called
4079 /// via InstantiateDecl).
4080 ///
4081 /// \param IsMemberSpecialization whether this new function declaration is
4082 /// a member specialization (that replaces any definition provided by the
4083 /// previous declaration).
4084 ///
4085 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4086 ///
4087 /// \returns true if the function declaration is a redeclaration.
4088 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4089 LookupResult &Previous,
4090 bool IsMemberSpecialization, bool DeclIsDefn);
4091
4092 /// Checks if the new declaration declared in dependent context must be
4093 /// put in the same redeclaration chain as the specified declaration.
4094 ///
4095 /// \param D Declaration that is checked.
4096 /// \param PrevDecl Previous declaration found with proper lookup method for
4097 /// the same declaration name.
4098 /// \returns True if D must be added to the redeclaration chain which PrevDecl
4099 /// belongs to.
4100 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4101
4102 /// Determines if we can perform a correct type check for \p D as a
4103 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4104 /// best-effort check.
4105 ///
4106 /// \param NewD The new declaration.
4107 /// \param OldD The old declaration.
4108 /// \param NewT The portion of the type of the new declaration to check.
4109 /// \param OldT The portion of the type of the old declaration to check.
4110 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4111 QualType NewT, QualType OldT);
4112 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4113 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4114
4115 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4116 /// containing class. Otherwise it will return implicit SectionAttr if the
4117 /// function is a definition and there is an active value on CodeSegStack
4118 /// (from the current #pragma code-seg value).
4119 ///
4120 /// \param FD Function being declared.
4121 /// \param IsDefinition Whether it is a definition or just a declaration.
4122 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4123 /// nullptr if no attribute should be added.
4124 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4125 bool IsDefinition);
4126
4127 /// Common checks for a parameter-declaration that should apply to both
4128 /// function parameters and non-type template parameters.
4129 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4130
4131 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4132 /// to introduce parameters into function prototype scope.
4133 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4134 SourceLocation ExplicitThisLoc = {});
4135
4136 /// Synthesizes a variable for a parameter arising from a
4137 /// typedef.
4138 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4139 QualType T);
4140 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4141 SourceLocation NameLoc,
4142 const IdentifierInfo *Name, QualType T,
4143 TypeSourceInfo *TSInfo, StorageClass SC);
4144
4145 /// Emit diagnostics if the initializer or any of its explicit or
4146 /// implicitly-generated subexpressions require copying or
4147 /// default-initializing a type that is or contains a C union type that is
4148 /// non-trivial to copy or default-initialize.
4149 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4150
4151 // These flags are passed to checkNonTrivialCUnion.
4152 enum NonTrivialCUnionKind {
4153 NTCUK_Init = 0x1,
4154 NTCUK_Destruct = 0x2,
4155 NTCUK_Copy = 0x4,
4156 };
4157
4158 /// Emit diagnostics if a non-trivial C union type or a struct that contains
4159 /// a non-trivial C union is used in an invalid context.
4160 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
4161 NonTrivialCUnionContext UseContext,
4162 unsigned NonTrivialKind);
4163
4164 /// Certain globally-unique variables might be accidentally duplicated if
4165 /// built into multiple shared libraries with hidden visibility. This can
4166 /// cause problems if the variable is mutable, its initialization is
4167 /// effectful, or its address is taken.
4168 bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl);
4169 void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl);
4170
4171 /// AddInitializerToDecl - Adds the initializer Init to the
4172 /// declaration dcl. If DirectInit is true, this is C++ direct
4173 /// initialization rather than copy initialization.
4174 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4175 void ActOnUninitializedDecl(Decl *dcl);
4176
4177 /// ActOnInitializerError - Given that there was an error parsing an
4178 /// initializer for the given declaration, try to at least re-establish
4179 /// invariants such as whether a variable's type is either dependent or
4180 /// complete.
4181 void ActOnInitializerError(Decl *Dcl);
4182
4183 void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt);
4184 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
4185 IdentifierInfo *Ident,
4186 ParsedAttributes &Attrs);
4187
4188 /// Check if VD needs to be dllexport/dllimport due to being in a
4189 /// dllexport/import function.
4190 void CheckStaticLocalForDllExport(VarDecl *VD);
4191 void CheckThreadLocalForLargeAlignment(VarDecl *VD);
4192
4193 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4194 /// any semantic actions necessary after any initializer has been attached.
4195 void FinalizeDeclaration(Decl *D);
4196 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4197 ArrayRef<Decl *> Group);
4198
4199 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4200 /// group, performing any necessary semantic checking.
4201 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
4202
4203 /// Should be called on all declarations that might have attached
4204 /// documentation comments.
4205 void ActOnDocumentableDecl(Decl *D);
4206 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
4207
4208 enum class FnBodyKind {
4209 /// C++26 [dcl.fct.def.general]p1
4210 /// function-body:
4211 /// ctor-initializer[opt] compound-statement
4212 /// function-try-block
4213 Other,
4214 /// = default ;
4215 Default,
4216 /// deleted-function-body
4217 ///
4218 /// deleted-function-body:
4219 /// = delete ;
4220 /// = delete ( unevaluated-string ) ;
4221 Delete
4222 };
4223
4224 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4225 SourceLocation LocAfterDecls);
4226 void CheckForFunctionRedefinition(
4227 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4228 SkipBodyInfo *SkipBody = nullptr);
4229 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
4230 MultiTemplateParamsArg TemplateParamLists,
4231 SkipBodyInfo *SkipBody = nullptr,
4232 FnBodyKind BodyKind = FnBodyKind::Other);
4233 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
4234 SkipBodyInfo *SkipBody = nullptr,
4235 FnBodyKind BodyKind = FnBodyKind::Other);
4236 void applyFunctionAttributesBeforeParsingBody(Decl *FD);
4237
4238 /// Determine whether we can delay parsing the body of a function or
4239 /// function template until it is used, assuming we don't care about emitting
4240 /// code for that function.
4241 ///
4242 /// This will be \c false if we may need the body of the function in the
4243 /// middle of parsing an expression (where it's impractical to switch to
4244 /// parsing a different function), for instance, if it's constexpr in C++11
4245 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4246 bool canDelayFunctionBody(const Declarator &D);
4247
4248 /// Determine whether we can skip parsing the body of a function
4249 /// definition, assuming we don't care about analyzing its body or emitting
4250 /// code for that function.
4251 ///
4252 /// This will be \c false only if we may need the body of the function in
4253 /// order to parse the rest of the program (for instance, if it is
4254 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4255 bool canSkipFunctionBody(Decl *D);
4256
4257 /// Given the set of return statements within a function body,
4258 /// compute the variables that are subject to the named return value
4259 /// optimization.
4260 ///
4261 /// Each of the variables that is subject to the named return value
4262 /// optimization will be marked as NRVO variables in the AST, and any
4263 /// return statement that has a marked NRVO variable as its NRVO candidate can
4264 /// use the named return value optimization.
4265 ///
4266 /// This function applies a very simplistic algorithm for NRVO: if every
4267 /// return statement in the scope of a variable has the same NRVO candidate,
4268 /// that candidate is an NRVO variable.
4269 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
4270
4271 /// Performs semantic analysis at the end of a function body.
4272 ///
4273 /// \param RetainFunctionScopeInfo If \c true, the client is responsible for
4274 /// releasing the associated \p FunctionScopeInfo. This is useful when
4275 /// building e.g. LambdaExprs.
4276 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body,
4277 bool IsInstantiation = false,
4278 bool RetainFunctionScopeInfo = false);
4279 Decl *ActOnSkippedFunctionBody(Decl *Decl);
4280 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
4281
4282 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4283 /// attribute for which parsing is delayed.
4284 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
4285
4286 /// Diagnose any unused parameters in the given sequence of
4287 /// ParmVarDecl pointers.
4288 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
4289
4290 /// Diagnose whether the size of parameters or return value of a
4291 /// function or obj-c method definition is pass-by-value and larger than a
4292 /// specified threshold.
4293 void
4294 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
4295 QualType ReturnTy, NamedDecl *D);
4296
4297 Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc,
4298 SourceLocation RParenLoc);
4299
4300 TopLevelStmtDecl *ActOnStartTopLevelStmtDecl(Scope *S);
4301 void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement);
4302
4303 void ActOnPopScope(SourceLocation Loc, Scope *S);
4304
4305 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4306 /// no declarator (e.g. "struct foo;") is parsed.
4307 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4308 const ParsedAttributesView &DeclAttrs,
4309 RecordDecl *&AnonRecord);
4310
4311 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4312 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4313 /// parameters to cope with template friend declarations.
4314 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4315 const ParsedAttributesView &DeclAttrs,
4316 MultiTemplateParamsArg TemplateParams,
4317 bool IsExplicitInstantiation,
4318 RecordDecl *&AnonRecord,
4319 SourceLocation EllipsisLoc = {});
4320
4321 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4322 /// anonymous structure or union. Anonymous unions are a C++ feature
4323 /// (C++ [class.union]) and a C11 feature; anonymous structures
4324 /// are a C11 feature and GNU C++ extension.
4325 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4326 RecordDecl *Record,
4327 const PrintingPolicy &Policy);
4328
4329 /// Called once it is known whether
4330 /// a tag declaration is an anonymous union or struct.
4331 void ActOnDefinedDeclarationSpecifier(Decl *D);
4332
4333 /// Emit diagnostic warnings for placeholder members.
4334 /// We can only do that after the class is fully constructed,
4335 /// as anonymous union/structs can insert placeholders
4336 /// in their parent scope (which might be a Record).
4337 void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record);
4338
4339 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4340 /// Microsoft C anonymous structure.
4341 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4342 /// Example:
4343 ///
4344 /// struct A { int a; };
4345 /// struct B { struct A; int b; };
4346 ///
4347 /// void foo() {
4348 /// B var;
4349 /// var.a = 3;
4350 /// }
4351 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4352 RecordDecl *Record);
4353
4354 /// Given a non-tag type declaration, returns an enum useful for indicating
4355 /// what kind of non-tag type this is.
4356 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4357
4358 /// Determine whether a tag with a given kind is acceptable
4359 /// as a redeclaration of the given tag declaration.
4360 ///
4361 /// \returns true if the new tag kind is acceptable, false otherwise.
4362 bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag,
4363 bool isDefinition, SourceLocation NewTagLoc,
4364 const IdentifierInfo *Name);
4365
4366 /// This is invoked when we see 'struct foo' or 'struct {'. In the
4367 /// former case, Name will be non-null. In the later case, Name will be null.
4368 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4369 /// a reference/declaration/definition of a tag.
4370 ///
4371 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4372 /// trailing-type-specifier) other than one in an alias-declaration.
4373 ///
4374 /// \param SkipBody If non-null, will be set to indicate if the caller should
4375 /// skip the definition of this tag and treat it as if it were a declaration.
4376 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4377 SourceLocation KWLoc, CXXScopeSpec &SS,
4378 IdentifierInfo *Name, SourceLocation NameLoc,
4379 const ParsedAttributesView &Attr, AccessSpecifier AS,
4380 SourceLocation ModulePrivateLoc,
4381 MultiTemplateParamsArg TemplateParameterLists,
4382 bool &OwnedDecl, bool &IsDependent,
4383 SourceLocation ScopedEnumKWLoc,
4384 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4385 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4386 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4387
4388 /// ActOnField - Each field of a C struct/union is passed into this in order
4389 /// to create a FieldDecl object for it.
4390 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4391 Declarator &D, Expr *BitfieldWidth);
4392
4393 /// HandleField - Analyze a field of a C struct or a C++ data member.
4394 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4395 Declarator &D, Expr *BitfieldWidth,
4396 InClassInitStyle InitStyle, AccessSpecifier AS);
4397
4398 /// Build a new FieldDecl and check its well-formedness.
4399 ///
4400 /// This routine builds a new FieldDecl given the fields name, type,
4401 /// record, etc. \p PrevDecl should refer to any previous declaration
4402 /// with the same name and in the same scope as the field to be
4403 /// created.
4404 ///
4405 /// \returns a new FieldDecl.
4406 ///
4407 /// \todo The Declarator argument is a hack. It will be removed once
4408 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4409 TypeSourceInfo *TInfo, RecordDecl *Record,
4410 SourceLocation Loc, bool Mutable,
4411 Expr *BitfieldWidth, InClassInitStyle InitStyle,
4412 SourceLocation TSSL, AccessSpecifier AS,
4413 NamedDecl *PrevDecl, Declarator *D = nullptr);
4414
4415 bool CheckNontrivialField(FieldDecl *FD);
4416
4417 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4418 /// class and class extensions. For every class \@interface and class
4419 /// extension \@interface, if the last ivar is a bitfield of any type,
4420 /// then add an implicit `char :0` ivar to the end of that interface.
4421 void ActOnLastBitfield(SourceLocation DeclStart,
4422 SmallVectorImpl<Decl *> &AllIvarDecls);
4423
4424 // This is used for both record definitions and ObjC interface declarations.
4425 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4426 ArrayRef<Decl *> Fields, SourceLocation LBrac,
4427 SourceLocation RBrac, const ParsedAttributesView &AttrList);
4428
4429 /// ActOnTagStartDefinition - Invoked when we have entered the
4430 /// scope of a tag's definition (e.g., for an enumeration, class,
4431 /// struct, or union).
4432 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4433
4434 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4435 /// Differently from C++, actually parse the body and reject / error out
4436 /// in case of a structural mismatch.
4437 bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4438
4439 typedef void *SkippedDefinitionContext;
4440
4441 /// Invoked when we enter a tag definition that we're skipping.
4442 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
4443
4444 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4445 /// C++ record definition's base-specifiers clause and are starting its
4446 /// member declarations.
4447 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
4448 SourceLocation FinalLoc,
4449 bool IsFinalSpelledSealed,
4450 bool IsAbstract,
4451 SourceLocation LBraceLoc);
4452
4453 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4454 /// the definition of a tag (enumeration, class, struct, or union).
4455 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
4456 SourceRange BraceRange);
4457
4458 ASTContext::CXXRecordDeclRelocationInfo
4459 CheckCXX2CRelocatable(const clang::CXXRecordDecl *D);
4460
4461 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
4462
4463 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4464 /// error parsing the definition of a tag.
4465 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
4466
4467 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
4468 EnumConstantDecl *LastEnumConst,
4469 SourceLocation IdLoc, IdentifierInfo *Id,
4470 Expr *val);
4471
4472 /// Check that this is a valid underlying type for an enum declaration.
4473 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
4474
4475 /// Check whether this is a valid redeclaration of a previous enumeration.
4476 /// \return true if the redeclaration was invalid.
4477 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4478 QualType EnumUnderlyingTy, bool IsFixed,
4479 const EnumDecl *Prev);
4480
4481 /// Determine whether the body of an anonymous enumeration should be skipped.
4482 /// \param II The name of the first enumerator.
4483 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
4484 SourceLocation IILoc);
4485
4486 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4487 SourceLocation IdLoc, IdentifierInfo *Id,
4488 const ParsedAttributesView &Attrs,
4489 SourceLocation EqualLoc, Expr *Val,
4490 SkipBodyInfo *SkipBody = nullptr);
4491 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4492 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4493 const ParsedAttributesView &Attr);
4494
4495 /// Set the current declaration context until it gets popped.
4496 void PushDeclContext(Scope *S, DeclContext *DC);
4497 void PopDeclContext();
4498
4499 /// EnterDeclaratorContext - Used when we must lookup names in the context
4500 /// of a declarator's nested name specifier.
4501 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
4502 void ExitDeclaratorContext(Scope *S);
4503
4504 /// Enter a template parameter scope, after it's been associated with a
4505 /// particular DeclContext. Causes lookup within the scope to chain through
4506 /// enclosing contexts in the correct order.
4507 void EnterTemplatedContext(Scope *S, DeclContext *DC);
4508
4509 /// Push the parameters of D, which must be a function, into scope.
4510 void ActOnReenterFunctionContext(Scope *S, Decl *D);
4511 void ActOnExitFunctionContext();
4512
4513 /// Add this decl to the scope shadowed decl chains.
4514 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4515
4516 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4517 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4518 /// true if 'D' belongs to the given declaration context.
4519 ///
4520 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4521 /// enclosing namespace set of the context, rather than contained
4522 /// directly within it.
4523 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4524 bool AllowInlineNamespace = false) const;
4525
4526 /// Finds the scope corresponding to the given decl context, if it
4527 /// happens to be an enclosing scope. Otherwise return NULL.
4528 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
4529
4530 /// Subroutines of ActOnDeclarator().
4531 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4532 TypeSourceInfo *TInfo);
4533 bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New);
4534
4535 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4536 void mergeDeclAttributes(
4537 NamedDecl *New, Decl *Old,
4538 AvailabilityMergeKind AMK = AvailabilityMergeKind::Redeclaration);
4539
4540 /// CheckAttributesOnDeducedType - Calls Sema functions for attributes that
4541 /// requires the type to be deduced.
4542 void CheckAttributesOnDeducedType(Decl *D);
4543
4544 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4545 /// same name and scope as a previous declaration 'Old'. Figure out
4546 /// how to resolve this situation, merging decls or emitting
4547 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4548 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
4549 LookupResult &OldDecls);
4550
4551 /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4552 /// definition visible.
4553 /// This method performs any necessary cleanup on the parser state to discard
4554 /// child nodes from newly parsed decl we are retiring.
4555 void CleanupMergedEnum(Scope *S, Decl *New);
4556
4557 /// MergeFunctionDecl - We just parsed a function 'New' from
4558 /// declarator D which has the same name and scope as a previous
4559 /// declaration 'Old'. Figure out how to resolve this situation,
4560 /// merging decls or emitting diagnostics as appropriate.
4561 ///
4562 /// In C++, New and Old must be declarations that are not
4563 /// overloaded. Use IsOverload to determine whether New and Old are
4564 /// overloaded, and to select the Old declaration that New should be
4565 /// merged with.
4566 ///
4567 /// Returns true if there was an error, false otherwise.
4568 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
4569 bool MergeTypeWithOld, bool NewDeclIsDefn);
4570
4571 /// Completes the merge of two function declarations that are
4572 /// known to be compatible.
4573 ///
4574 /// This routine handles the merging of attributes and other
4575 /// properties of function declarations from the old declaration to
4576 /// the new declaration, once we know that New is in fact a
4577 /// redeclaration of Old.
4578 ///
4579 /// \returns false
4580 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4581 Scope *S, bool MergeTypeWithOld);
4582 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
4583
4584 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4585 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4586 /// situation, merging decls or emitting diagnostics as appropriate.
4587 ///
4588 /// Tentative definition rules (C99 6.9.2p2) are checked by
4589 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4590 /// definitions here, since the initializer hasn't been attached.
4591 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
4592
4593 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4594 /// scope as a previous declaration 'Old'. Figure out how to merge their
4595 /// types, emitting diagnostics as appropriate.
4596 ///
4597 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4598 /// back to here in AddInitializerToDecl. We can't check them before the
4599 /// initializer is attached.
4600 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4601
4602 /// We've just determined that \p Old and \p New both appear to be definitions
4603 /// of the same variable. Either diagnose or fix the problem.
4604 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4605 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
4606
4607 /// Filters out lookup results that don't fall within the given scope
4608 /// as determined by isDeclInScope.
4609 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4610 bool ConsiderLinkage, bool AllowInlineNamespace);
4611
4612 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4613 /// have compatible owning modules.
4614 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4615
4616 /// [module.interface]p6:
4617 /// A redeclaration of an entity X is implicitly exported if X was introduced
4618 /// by an exported declaration; otherwise it shall not be exported.
4619 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4620
4621 /// A wrapper function for checking the semantic restrictions of
4622 /// a redeclaration within a module.
4623 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4624
4625 /// Check the redefinition in C++20 Modules.
4626 ///
4627 /// [basic.def.odr]p14:
4628 /// For any definable item D with definitions in multiple translation units,
4629 /// - if D is a non-inline non-templated function or variable, or
4630 /// - if the definitions in different translation units do not satisfy the
4631 /// following requirements,
4632 /// the program is ill-formed; a diagnostic is required only if the
4633 /// definable item is attached to a named module and a prior definition is
4634 /// reachable at the point where a later definition occurs.
4635 /// - Each such definition shall not be attached to a named module
4636 /// ([module.unit]).
4637 /// - Each such definition shall consist of the same sequence of tokens, ...
4638 /// ...
4639 ///
4640 /// Return true if the redefinition is not allowed. Return false otherwise.
4641 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4642
4643 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4644
4645 /// If it's a file scoped decl that must warn if not used, keep track
4646 /// of it.
4647 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4648
4649 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4650 DiagReceiverTy;
4651
4652 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4653 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
4654 DiagReceiverTy DiagReceiver);
4655 void DiagnoseUnusedDecl(const NamedDecl *ND);
4656
4657 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4658 /// unless they are marked attr(unused).
4659 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4660
4661 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4662 /// variable.
4663 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4664
4665 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4666 /// from S, where a non-field would be declared. This routine copes
4667 /// with the difference between C and C++ scoping rules in structs and
4668 /// unions. For example, the following code is well-formed in C but
4669 /// ill-formed in C++:
4670 /// @code
4671 /// struct S6 {
4672 /// enum { BAR } e;
4673 /// };
4674 ///
4675 /// void test_S6() {
4676 /// struct S6 a;
4677 /// a.e = BAR;
4678 /// }
4679 /// @endcode
4680 /// For the declaration of BAR, this routine will return a different
4681 /// scope. The scope S will be the scope of the unnamed enumeration
4682 /// within S6. In C++, this routine will return the scope associated
4683 /// with S6, because the enumeration's scope is a transparent
4684 /// context but structures can contain non-field names. In C, this
4685 /// routine will return the translation unit scope, since the
4686 /// enumeration's scope is a transparent context and structures cannot
4687 /// contain non-field names.
4688 Scope *getNonFieldDeclScope(Scope *S);
4689
4690 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4691 SourceLocation Loc);
4692
4693 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4694 /// file scope. lazily create a decl for it. ForRedeclaration is true
4695 /// if we're creating this built-in in anticipation of redeclaring the
4696 /// built-in.
4697 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4698 bool ForRedeclaration, SourceLocation Loc);
4699
4700 /// Get the outermost AttributedType node that sets a calling convention.
4701 /// Valid types should not have multiple attributes with different CCs.
4702 const AttributedType *getCallingConvAttributedType(QualType T) const;
4703
4704 /// GetNameForDeclarator - Determine the full declaration name for the
4705 /// given Declarator.
4706 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
4707
4708 /// Retrieves the declaration name from a parsed unqualified-id.
4709 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
4710
4711 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4712 /// we are currently parsing the initializer.
4713 llvm::SmallPtrSet<const Decl *, 4> ParsingInitForAutoVars;
4714
4715 /// Look for a locally scoped extern "C" declaration by the given name.
4716 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
4717
4718 void deduceOpenCLAddressSpace(VarDecl *decl);
4719 void deduceHLSLAddressSpace(VarDecl *decl);
4720
4721 /// Adjust the \c DeclContext for a function or variable that might be a
4722 /// function-local external declaration.
4723 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
4724
4725 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4726
4727 /// Checks if the variant/multiversion functions are compatible.
4728 bool areMultiversionVariantFunctionsCompatible(
4729 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4730 const PartialDiagnostic &NoProtoDiagID,
4731 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4732 const PartialDiagnosticAt &NoSupportDiagIDAt,
4733 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4734 bool ConstexprSupported, bool CLinkageMayDiffer);
4735
4736 /// type checking declaration initializers (C99 6.7.8)
4737 bool CheckForConstantInitializer(
4738 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4739
4740 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
4741 QualType Type, TypeSourceInfo *TSI,
4742 SourceRange Range, bool DirectInit,
4743 Expr *Init);
4744
4745 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
4746 Expr *Init);
4747
4748 sema::LambdaScopeInfo *RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator);
4749
4750 // Heuristically tells if the function is `get_return_object` member of a
4751 // coroutine promise_type by matching the function name.
4752 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4753 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4754
4755 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4756 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4757 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4758 Scope *S);
4759
4760 /// If this function is a C++ replaceable global allocation function
4761 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4762 /// adds any function attributes that we know a priori based on the standard.
4763 ///
4764 /// We need to check for duplicate attributes both here and where user-written
4765 /// attributes are applied to declarations.
4766 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4767 FunctionDecl *FD);
4768
4769 /// Adds any function attributes that we know a priori based on
4770 /// the declaration of this function.
4771 ///
4772 /// These attributes can apply both to implicitly-declared builtins
4773 /// (like __builtin___printf_chk) or to library-declared functions
4774 /// like NSLog or printf.
4775 ///
4776 /// We need to check for duplicate attributes both here and where user-written
4777 /// attributes are applied to declarations.
4778 void AddKnownFunctionAttributes(FunctionDecl *FD);
4779
4780 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4781 /// the correct width, and that the field type is valid.
4782 /// Returns false on success.
4783 ExprResult VerifyBitField(SourceLocation FieldLoc,
4784 const IdentifierInfo *FieldName, QualType FieldTy,
4785 bool IsMsStruct, Expr *BitWidth);
4786
4787 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4788 /// enum. If AllowMask is true, then we also allow the complement of a valid
4789 /// value, to be used as a mask.
4790 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4791 bool AllowMask) const;
4792
4793 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4794 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4795 SourceLocation WeakNameLoc);
4796
4797 /// ActOnPragmaRedefineExtname - Called on well formed
4798 /// \#pragma redefine_extname oldname newname.
4799 void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName,
4800 IdentifierInfo *AliasName,
4801 SourceLocation PragmaLoc,
4802 SourceLocation WeakNameLoc,
4803 SourceLocation AliasNameLoc);
4804
4805 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4806 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4807 SourceLocation PragmaLoc,
4808 SourceLocation WeakNameLoc,
4809 SourceLocation AliasNameLoc);
4810
4811 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4812 enum class FunctionEmissionStatus {
4813 Emitted,
4814 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4815 OMPDiscarded, // Discarded due to OpenMP hostness
4816 TemplateDiscarded, // Discarded due to uninstantiated templates
4817 Unknown,
4818 };
4819 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4820 bool Final = false);
4821
4822 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4823 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4824
4825 /// Function or variable declarations to be checked for whether the deferred
4826 /// diagnostics should be emitted.
4827 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
4828
4829private:
4830 /// Map of current shadowing declarations to shadowed declarations. Warn if
4831 /// it looks like the user is trying to modify the shadowing declaration.
4832 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4833
4834 // We need this to handle
4835 //
4836 // typedef struct {
4837 // void *foo() { return 0; }
4838 // } A;
4839 //
4840 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4841 // for example. If 'A', foo will have external linkage. If we have '*A',
4842 // foo will have no linkage. Since we can't know until we get to the end
4843 // of the typedef, this function finds out if D might have non-external
4844 // linkage. Callers should verify at the end of the TU if it D has external
4845 // linkage or not.
4846 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4847
4848#include "clang/Sema/AttrIsTypeDependent.inc"
4849
4850 ///@}
4851
4852 //
4853 //
4854 // -------------------------------------------------------------------------
4855 //
4856 //
4857
4858 /// \name Declaration Attribute Handling
4859 /// Implementations are in SemaDeclAttr.cpp
4860 ///@{
4861
4862public:
4863 /// Describes the kind of priority given to an availability attribute.
4864 ///
4865 /// The sum of priorities deteremines the final priority of the attribute.
4866 /// The final priority determines how the attribute will be merged.
4867 /// An attribute with a lower priority will always remove higher priority
4868 /// attributes for the specified platform when it is being applied. An
4869 /// attribute with a higher priority will not be applied if the declaration
4870 /// already has an availability attribute with a lower priority for the
4871 /// specified platform. The final prirority values are not expected to match
4872 /// the values in this enumeration, but instead should be treated as a plain
4873 /// integer value. This enumeration just names the priority weights that are
4874 /// used to calculate that final vaue.
4875 enum AvailabilityPriority : int {
4876 /// The availability attribute was specified explicitly next to the
4877 /// declaration.
4878 AP_Explicit = 0,
4879
4880 /// The availability attribute was applied using '#pragma clang attribute'.
4881 AP_PragmaClangAttribute = 1,
4882
4883 /// The availability attribute for a specific platform was inferred from
4884 /// an availability attribute for another platform.
4885 AP_InferredFromOtherPlatform = 2,
4886
4887 /// The availability attribute was inferred from an 'anyAppleOS'
4888 /// availability attribute.
4889 AP_InferredFromAnyAppleOS = 3,
4890
4891 /// The availability attribute was inferred from an 'anyAppleOS'
4892 /// availability attribute that was applied using '#pragma clang attribute'.
4893 /// This has the lowest priority.
4894 AP_PragmaClangAttribute_InferredFromAnyAppleOS = 4
4895 };
4896
4897 /// Describes the reason a calling convention specification was ignored, used
4898 /// for diagnostics.
4899 enum class CallingConventionIgnoredReason {
4900 ForThisTarget = 0,
4901 VariadicFunction,
4902 ConstructorDestructor,
4903 BuiltinFunction
4904 };
4905
4906 /// A helper function to provide Attribute Location for the Attr types
4907 /// AND the ParsedAttr.
4908 template <typename AttrInfo>
4909 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
4910 getAttrLoc(const AttrInfo &AL) {
4911 return AL.getLocation();
4912 }
4913 SourceLocation getAttrLoc(const AttributeCommonInfo &CI);
4914
4915 /// If Expr is a valid integer constant, get the value of the integer
4916 /// expression and return success or failure. May output an error.
4917 ///
4918 /// Negative argument is implicitly converted to unsigned, unless
4919 /// \p StrictlyUnsigned is true.
4920 template <typename AttrInfo>
4921 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
4922 unsigned Idx = UINT_MAX,
4923 bool StrictlyUnsigned = false) {
4924 std::optional<llvm::APSInt> I = llvm::APSInt(32);
4925 if (Expr->isTypeDependent() ||
4926 !(I = Expr->getIntegerConstantExpr(Ctx: Context))) {
4927 if (Idx != UINT_MAX)
4928 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
4929 << &AI << Idx << AANT_ArgumentIntegerConstant
4930 << Expr->getSourceRange();
4931 else
4932 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
4933 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
4934 return false;
4935 }
4936
4937 if (!I->isIntN(N: 32)) {
4938 Diag(Loc: Expr->getExprLoc(), DiagID: diag::err_ice_too_large)
4939 << toString(I: *I, Radix: 10, Signed: false) << 32 << /* Unsigned */ 1;
4940 return false;
4941 }
4942
4943 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
4944 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
4945 << &AI << /*non-negative*/ 1;
4946 return false;
4947 }
4948
4949 Val = (uint32_t)I->getZExtValue();
4950 return true;
4951 }
4952
4953 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
4954 /// \#pragma weak during processing of other Decls.
4955 /// I couldn't figure out a clean way to generate these in-line, so
4956 /// we store them here and handle separately -- which is a hack.
4957 /// It would be best to refactor this.
4958 SmallVector<Decl *, 2> WeakTopLevelDecl;
4959
4960 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
4961 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
4962
4963 typedef LazyVector<TypedefNameDecl *, &ExternalSemaSource::ReadExtVectorDecls,
4964 2, 2>
4965 ExtVectorDeclsType;
4966
4967 /// ExtVectorDecls - This is a list all the extended vector types. This allows
4968 /// us to associate a raw vector type with one of the ext_vector type names.
4969 /// This is only necessary for issuing pretty diagnostics.
4970 ExtVectorDeclsType ExtVectorDecls;
4971
4972 /// Check if the argument \p E is a ASCII string literal. If not emit an error
4973 /// and return false, otherwise set \p Str to the value of the string literal
4974 /// and return true.
4975 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
4976 const Expr *E, StringRef &Str,
4977 SourceLocation *ArgLocation = nullptr);
4978
4979 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
4980 /// If not emit an error and return false. If the argument is an identifier it
4981 /// will emit an error with a fixit hint and treat it as if it was a string
4982 /// literal.
4983 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4984 StringRef &Str,
4985 SourceLocation *ArgLocation = nullptr);
4986
4987 /// Determine if type T is a valid subject for a nonnull and similar
4988 /// attributes. Dependent types are considered valid so they can be checked
4989 /// during instantiation time. By default, we look through references (the
4990 /// behavior used by nonnull), but if the second parameter is true, then we
4991 /// treat a reference type as valid.
4992 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4993
4994 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
4995 /// declaration.
4996 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4997 Expr *OE);
4998
4999 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
5000 /// declaration.
5001 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
5002 Expr *ParamExpr);
5003
5004 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
5005 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
5006
5007 AvailabilityAttr *
5008 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
5009 const IdentifierInfo *Platform, bool Implicit,
5010 VersionTuple Introduced, VersionTuple Deprecated,
5011 VersionTuple Obsoleted, bool IsUnavailable,
5012 StringRef Message, bool IsStrict, StringRef Replacement,
5013 AvailabilityMergeKind AMK, int Priority,
5014 const IdentifierInfo *IIEnvironment,
5015 const IdentifierInfo *InferredPlatformII = nullptr);
5016
5017 AvailabilityAttr *mergeAndInferAvailabilityAttr(
5018 NamedDecl *D, const AttributeCommonInfo &CI,
5019 const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced,
5020 VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable,
5021 StringRef Message, bool IsStrict, StringRef Replacement,
5022 AvailabilityMergeKind AMK, int Priority,
5023 const IdentifierInfo *IIEnvironment,
5024 const IdentifierInfo *InferredPlatformII);
5025
5026 TypeVisibilityAttr *
5027 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5028 TypeVisibilityAttr::VisibilityType Vis);
5029 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5030 VisibilityAttr::VisibilityType Vis);
5031 void mergeVisibilityType(Decl *D, SourceLocation Loc,
5032 VisibilityAttr::VisibilityType Type);
5033 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
5034 StringRef Name);
5035
5036 /// Used to implement to perform semantic checking on
5037 /// attribute((section("foo"))) specifiers.
5038 ///
5039 /// In this case, "foo" is passed in to be checked. If the section
5040 /// specifier is invalid, return an Error that indicates the problem.
5041 ///
5042 /// This is a simple quality of implementation feature to catch errors
5043 /// and give good diagnostics in cases when the assembler or code generator
5044 /// would otherwise reject the section specifier.
5045 llvm::Error isValidSectionSpecifier(StringRef Str);
5046 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
5047 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
5048 StringRef Name);
5049
5050 // Check for things we'd like to warn about. Multiversioning issues are
5051 // handled later in the process, once we know how many exist.
5052 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
5053
5054 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
5055 StringRef NewUserDiagnostic);
5056 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
5057 const IdentifierInfo *Format, int FormatIdx,
5058 int FirstArg);
5059 FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
5060 const AttributeCommonInfo &CI,
5061 const IdentifierInfo *Format,
5062 int FormatIdx,
5063 StringLiteral *FormatStr);
5064 ModularFormatAttr *mergeModularFormatAttr(Decl *D,
5065 const AttributeCommonInfo &CI,
5066 const IdentifierInfo *ModularImplFn,
5067 StringRef ImplName,
5068 MutableArrayRef<StringRef> Aspects);
5069
5070 PersonalityAttr *mergePersonalityAttr(Decl *D, FunctionDecl *Routine,
5071 const AttributeCommonInfo &CI);
5072
5073 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5074 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5075 bool IsPackExpansion);
5076 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
5077 bool IsPackExpansion);
5078
5079 /// AddAlignValueAttr - Adds an align_value attribute to a particular
5080 /// declaration.
5081 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
5082
5083 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
5084 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
5085 MutableArrayRef<Expr *> Args);
5086 Attr *CreateAnnotationAttr(const ParsedAttr &AL);
5087
5088 bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range,
5089 bool BestCase,
5090 MSInheritanceModel SemanticSpelling);
5091
5092 void CheckAlignasUnderalignment(Decl *D);
5093
5094 /// AddModeAttr - Adds a mode attribute to a particular declaration.
5095 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
5096 const IdentifierInfo *Name, bool InInstantiation = false);
5097 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
5098 const AttributeCommonInfo &CI,
5099 const IdentifierInfo *Ident);
5100 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
5101 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
5102 const AttributeCommonInfo &CI);
5103 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
5104 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
5105 const InternalLinkageAttr &AL);
5106
5107 /// Check validaty of calling convention attribute \p attr. If \p FD
5108 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
5109 /// target. Otherwise, it is specified by \p CFT.
5110 bool CheckCallingConvAttr(
5111 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
5112 CUDAFunctionTarget CFT = CUDAFunctionTarget::InvalidTarget);
5113
5114 /// Checks a regparm attribute, returning true if it is ill-formed and
5115 /// otherwise setting numParams to the appropriate value.
5116 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
5117
5118 /// Create a CUDALaunchBoundsAttr attribute. By default, the function only
5119 /// supports nvptx target architectures and skips MaxBlocks if it is previous
5120 /// to sm_90. Use \p IgnoreArch to skip the architecture check.
5121 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
5122 Expr *MaxThreads,
5123 Expr *MinBlocks, Expr *MaxBlocks,
5124 bool IgnoreArch = false);
5125
5126 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
5127 /// declaration.
5128 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5129 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
5130
5131 /// Add a cluster_dims attribute to a particular declaration.
5132 CUDAClusterDimsAttr *createClusterDimsAttr(const AttributeCommonInfo &CI,
5133 Expr *X, Expr *Y, Expr *Z);
5134 void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
5135 Expr *Y, Expr *Z);
5136 /// Add a no_cluster attribute to a particular declaration.
5137 void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI);
5138
5139 enum class RetainOwnershipKind { NS, CF, OS };
5140
5141 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5142 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5143
5144 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5145
5146 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5147 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5148 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5149 const AttributeCommonInfo &CI,
5150 bool BestCase,
5151 MSInheritanceModel Model);
5152
5153 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5154 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5155 const EnforceTCBLeafAttr &AL);
5156
5157 /// Helper for delayed processing TransparentUnion or
5158 /// BPFPreserveAccessIndexAttr attribute.
5159 void ProcessDeclAttributeDelayed(Decl *D,
5160 const ParsedAttributesView &AttrList);
5161
5162 // Options for ProcessDeclAttributeList().
5163 struct ProcessDeclAttributeOptions {
5164 ProcessDeclAttributeOptions()
5165 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
5166
5167 ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
5168 ProcessDeclAttributeOptions Result = *this;
5169 Result.IncludeCXX11Attributes = Val;
5170 return Result;
5171 }
5172
5173 ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
5174 ProcessDeclAttributeOptions Result = *this;
5175 Result.IgnoreTypeAttributes = Val;
5176 return Result;
5177 }
5178
5179 // Should C++11 attributes be processed?
5180 bool IncludeCXX11Attributes;
5181
5182 // Should any type attributes encountered be ignored?
5183 // If this option is false, a diagnostic will be emitted for any type
5184 // attributes of a kind that does not "slide" from the declaration to
5185 // the decl-specifier-seq.
5186 bool IgnoreTypeAttributes;
5187 };
5188
5189 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5190 /// attribute list to the specified decl, ignoring any type attributes.
5191 void ProcessDeclAttributeList(Scope *S, Decl *D,
5192 const ParsedAttributesView &AttrList,
5193 const ProcessDeclAttributeOptions &Options =
5194 ProcessDeclAttributeOptions());
5195
5196 /// Annotation attributes are the only attributes allowed after an access
5197 /// specifier.
5198 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5199 const ParsedAttributesView &AttrList);
5200
5201 /// checkUnusedDeclAttributes - Given a declarator which is not being
5202 /// used to build a declaration, complain about any decl attributes
5203 /// which might be lying around on it.
5204 void checkUnusedDeclAttributes(Declarator &D);
5205
5206 void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5207
5208 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5209 /// \#pragma weak needs a non-definition decl and source may not have one.
5210 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
5211 SourceLocation Loc);
5212
5213 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5214 /// applied to it, possibly with an alias.
5215 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5216
5217 void ProcessPragmaWeak(Scope *S, Decl *D);
5218 // Decl attributes - this routine is the top level dispatcher.
5219 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5220
5221 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5222
5223 /// Given a set of delayed diagnostics, re-emit them as if they had
5224 /// been delayed in the current context instead of in the given pool.
5225 /// Essentially, this just moves them to the current pool.
5226 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5227
5228 /// Check that the type is a plain record with one field being a pointer
5229 /// type and the other field being an integer. This matches the common
5230 /// implementation of std::span or sized_allocation_t in P0901R11.
5231 bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty);
5232
5233 /// Check if IdxExpr is a valid parameter index for a function or
5234 /// instance method D. May output an error.
5235 ///
5236 /// \returns true if IdxExpr is a valid index.
5237 template <typename AttrInfo>
5238 bool checkFunctionOrMethodParameterIndex(
5239 const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5240 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5241 bool CanIndexVariadicArguments = false) {
5242 assert(isFunctionOrMethodOrBlockForAttrSubject(D));
5243
5244 // In C++ the implicit 'this' function parameter also counts.
5245 // Parameters are counted from one.
5246 bool HP = hasFunctionProto(D);
5247 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
5248 bool IV = HP && isFunctionOrMethodVariadic(D);
5249 unsigned NumParams =
5250 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
5251
5252 std::optional<llvm::APSInt> IdxInt;
5253 if (IdxExpr->isTypeDependent() ||
5254 !(IdxInt = IdxExpr->getIntegerConstantExpr(Ctx: Context))) {
5255 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5256 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5257 << IdxExpr->getSourceRange();
5258 return false;
5259 }
5260
5261 constexpr unsigned Limit = 1 << ParamIdx::IdxBitWidth;
5262 unsigned IdxSource = IdxInt->getLimitedValue(Limit);
5263 if (IdxSource < 1 || IdxSource == Limit ||
5264 ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5265 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5266 << &AI << AttrArgNum << IdxExpr->getSourceRange();
5267 return false;
5268 }
5269 if (HasImplicitThisParam && !CanIndexImplicitThis) {
5270 if (IdxSource == 1) {
5271 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5272 << &AI << IdxExpr->getSourceRange();
5273 return false;
5274 }
5275 }
5276
5277 Idx = ParamIdx(IdxSource, D);
5278 return true;
5279 }
5280
5281 ///@}
5282
5283 //
5284 //
5285 // -------------------------------------------------------------------------
5286 //
5287 //
5288
5289 /// \name C++ Declarations
5290 /// Implementations are in SemaDeclCXX.cpp
5291 ///@{
5292
5293public:
5294 void CheckDelegatingCtorCycles();
5295
5296 /// Called before parsing a function declarator belonging to a function
5297 /// declaration.
5298 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
5299 unsigned TemplateParameterDepth);
5300
5301 /// Called after parsing a function declarator belonging to a function
5302 /// declaration.
5303 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
5304
5305 // Act on C++ namespaces
5306 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5307 SourceLocation NamespaceLoc,
5308 SourceLocation IdentLoc, IdentifierInfo *Ident,
5309 SourceLocation LBrace,
5310 const ParsedAttributesView &AttrList,
5311 UsingDirectiveDecl *&UsingDecl, bool IsNested);
5312
5313 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5314 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5315 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5316
5317 NamespaceDecl *getStdNamespace() const;
5318
5319 /// Retrieve the special "std" namespace, which may require us to
5320 /// implicitly define the namespace.
5321 NamespaceDecl *getOrCreateStdNamespace();
5322
5323 CXXRecordDecl *getStdBadAlloc() const;
5324 EnumDecl *getStdAlignValT() const;
5325
5326 TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const;
5327 FunctionDecl *BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl,
5328 QualType AllocType, SourceLocation);
5329
5330 ValueDecl *tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
5331 const IdentifierInfo *MemberOrBase);
5332
5333 enum class ComparisonCategoryUsage {
5334 /// The '<=>' operator was used in an expression and a builtin operator
5335 /// was selected.
5336 OperatorInExpression,
5337 /// A defaulted 'operator<=>' needed the comparison category. This
5338 /// typically only applies to 'std::strong_ordering', due to the implicit
5339 /// fallback return value.
5340 DefaultedOperator,
5341 /// A builtin needed 'std::strong_ordering' (eg. '__builtin_type_order').
5342 Builtin,
5343 };
5344
5345 /// Lookup the specified comparison category types in the standard
5346 /// library, an check the VarDecls possibly returned by the operator<=>
5347 /// builtins for that type.
5348 ///
5349 /// \return The type of the comparison category type corresponding to the
5350 /// specified Kind, or a null type if an error occurs
5351 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5352 SourceLocation Loc,
5353 ComparisonCategoryUsage Usage);
5354
5355 /// Tests whether Ty is an instance of std::initializer_list and, if
5356 /// it is and Element is not NULL, assigns the element type to Element.
5357 bool isStdInitializerList(QualType Ty, QualType *Element);
5358
5359 /// Tests whether Ty is an instance of std::type_identity and, if
5360 /// it is and TypeArgument is not NULL, assigns the element type to Element.
5361 /// If MalformedDecl is not null, and type_identity was ruled out due to being
5362 /// incorrectly structured despite having the correct name, the faulty Decl
5363 /// will be assigned to MalformedDecl.
5364 bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5365 const Decl **MalformedDecl = nullptr);
5366
5367 /// Looks for the std::initializer_list template and instantiates it
5368 /// with Element, or emits an error if it's not found.
5369 ///
5370 /// \returns The instantiated template, or null on error.
5371 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5372
5373 /// Looks for the std::type_identity template and instantiates it
5374 /// with Type, or returns a null type if type_identity has not been declared
5375 ///
5376 /// \returns The instantiated template, or null if std::type_identity is not
5377 /// declared
5378 QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc);
5379
5380 /// Determine whether Ctor is an initializer-list constructor, as
5381 /// defined in [dcl.init.list]p2.
5382 bool isInitListConstructor(const FunctionDecl *Ctor);
5383
5384 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5385 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5386 SourceLocation IdentLoc,
5387 IdentifierInfo *NamespcName,
5388 const ParsedAttributesView &AttrList);
5389
5390 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5391
5392 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5393 SourceLocation AliasLoc, IdentifierInfo *Alias,
5394 CXXScopeSpec &SS, SourceLocation IdentLoc,
5395 IdentifierInfo *Ident);
5396
5397 /// Remove decls we can't actually see from a lookup being used to declare
5398 /// shadow using decls.
5399 ///
5400 /// \param S - The scope of the potential shadow decl
5401 /// \param Previous - The lookup of a potential shadow decl's name.
5402 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5403
5404 /// Hides a using shadow declaration. This is required by the current
5405 /// using-decl implementation when a resolvable using declaration in a
5406 /// class is followed by a declaration which would hide or override
5407 /// one or more of the using decl's targets; for example:
5408 ///
5409 /// struct Base { void foo(int); };
5410 /// struct Derived : Base {
5411 /// using Base::foo;
5412 /// void foo(int);
5413 /// };
5414 ///
5415 /// The governing language is C++03 [namespace.udecl]p12:
5416 ///
5417 /// When a using-declaration brings names from a base class into a
5418 /// derived class scope, member functions in the derived class
5419 /// override and/or hide member functions with the same name and
5420 /// parameter types in a base class (rather than conflicting).
5421 ///
5422 /// There are two ways to implement this:
5423 /// (1) optimistically create shadow decls when they're not hidden
5424 /// by existing declarations, or
5425 /// (2) don't create any shadow decls (or at least don't make them
5426 /// visible) until we've fully parsed/instantiated the class.
5427 /// The problem with (1) is that we might have to retroactively remove
5428 /// a shadow decl, which requires several O(n) operations because the
5429 /// decl structures are (very reasonably) not designed for removal.
5430 /// (2) avoids this but is very fiddly and phase-dependent.
5431 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5432
5433 /// Determines whether to create a using shadow decl for a particular
5434 /// decl, given the set of decls existing prior to this using lookup.
5435 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5436 const LookupResult &PreviousDecls,
5437 UsingShadowDecl *&PrevShadow);
5438
5439 /// Builds a shadow declaration corresponding to a 'using' declaration.
5440 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5441 NamedDecl *Target,
5442 UsingShadowDecl *PrevDecl);
5443
5444 /// Checks that the given using declaration is not an invalid
5445 /// redeclaration. Note that this is checking only for the using decl
5446 /// itself, not for any ill-formedness among the UsingShadowDecls.
5447 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5448 bool HasTypenameKeyword,
5449 const CXXScopeSpec &SS,
5450 SourceLocation NameLoc,
5451 const LookupResult &Previous);
5452
5453 /// Checks that the given nested-name qualifier used in a using decl
5454 /// in the current context is appropriately related to the current
5455 /// scope. If an error is found, diagnoses it and returns true.
5456 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5457 /// the result of that lookup. UD is likewise nullptr, except when we have an
5458 /// already-populated UsingDecl whose shadow decls contain the same
5459 /// information (i.e. we're instantiating a UsingDecl with non-dependent
5460 /// scope).
5461 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5462 const CXXScopeSpec &SS,
5463 const DeclarationNameInfo &NameInfo,
5464 SourceLocation NameLoc,
5465 const LookupResult *R = nullptr,
5466 const UsingDecl *UD = nullptr);
5467
5468 /// Builds a using declaration.
5469 ///
5470 /// \param IsInstantiation - Whether this call arises from an
5471 /// instantiation of an unresolved using declaration. We treat
5472 /// the lookup differently for these declarations.
5473 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5474 SourceLocation UsingLoc,
5475 bool HasTypenameKeyword,
5476 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5477 DeclarationNameInfo NameInfo,
5478 SourceLocation EllipsisLoc,
5479 const ParsedAttributesView &AttrList,
5480 bool IsInstantiation, bool IsUsingIfExists);
5481 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
5482 SourceLocation UsingLoc,
5483 SourceLocation EnumLoc,
5484 SourceLocation NameLoc,
5485 TypeSourceInfo *EnumType, EnumDecl *ED);
5486 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5487 ArrayRef<NamedDecl *> Expansions);
5488
5489 /// Additional checks for a using declaration referring to a constructor name.
5490 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5491
5492 /// Given a derived-class using shadow declaration for a constructor and the
5493 /// correspnding base class constructor, find or create the implicit
5494 /// synthesized derived class constructor to use for this initialization.
5495 CXXConstructorDecl *
5496 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5497 ConstructorUsingShadowDecl *DerivedShadow);
5498
5499 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5500 SourceLocation UsingLoc,
5501 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5502 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5503 const ParsedAttributesView &AttrList);
5504 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
5505 SourceLocation UsingLoc,
5506 SourceLocation EnumLoc, SourceRange TyLoc,
5507 const IdentifierInfo &II, ParsedType Ty,
5508 const CXXScopeSpec &SS);
5509 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5510 MultiTemplateParamsArg TemplateParams,
5511 SourceLocation UsingLoc, UnqualifiedId &Name,
5512 const ParsedAttributesView &AttrList,
5513 TypeResult Type, Decl *DeclFromDeclSpec);
5514
5515 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5516 /// including handling of its default argument expressions.
5517 ///
5518 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5519 ExprResult BuildCXXConstructExpr(
5520 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5521 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5522 bool HadMultipleCandidates, bool IsListInitialization,
5523 bool IsStdInitListInitialization, bool RequiresZeroInit,
5524 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5525
5526 /// Build a CXXConstructExpr whose constructor has already been resolved if
5527 /// it denotes an inherited constructor.
5528 ExprResult BuildCXXConstructExpr(
5529 SourceLocation ConstructLoc, QualType DeclInitType,
5530 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5531 bool HadMultipleCandidates, bool IsListInitialization,
5532 bool IsStdInitListInitialization, bool RequiresZeroInit,
5533 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5534
5535 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5536 // the constructor can be elidable?
5537 ExprResult BuildCXXConstructExpr(
5538 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5539 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5540 bool HadMultipleCandidates, bool IsListInitialization,
5541 bool IsStdInitListInitialization, bool RequiresZeroInit,
5542 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5543
5544 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr,
5545 SourceLocation InitLoc);
5546
5547 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5548 /// constructed variable.
5549 void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit);
5550
5551 /// Helper class that collects exception specifications for
5552 /// implicitly-declared special member functions.
5553 class ImplicitExceptionSpecification {
5554 // Pointer to allow copying
5555 Sema *Self;
5556 // We order exception specifications thus:
5557 // noexcept is the most restrictive, but is only used in C++11.
5558 // throw() comes next.
5559 // Then a throw(collected exceptions)
5560 // Finally no specification, which is expressed as noexcept(false).
5561 // throw(...) is used instead if any called function uses it.
5562 ExceptionSpecificationType ComputedEST;
5563 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5564 SmallVector<QualType, 4> Exceptions;
5565
5566 void ClearExceptions() {
5567 ExceptionsSeen.clear();
5568 Exceptions.clear();
5569 }
5570
5571 public:
5572 explicit ImplicitExceptionSpecification(Sema &Self)
5573 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5574 if (!Self.getLangOpts().CPlusPlus11)
5575 ComputedEST = EST_DynamicNone;
5576 }
5577
5578 /// Get the computed exception specification type.
5579 ExceptionSpecificationType getExceptionSpecType() const {
5580 assert(!isComputedNoexcept(ComputedEST) &&
5581 "noexcept(expr) should not be a possible result");
5582 return ComputedEST;
5583 }
5584
5585 /// The number of exceptions in the exception specification.
5586 unsigned size() const { return Exceptions.size(); }
5587
5588 /// The set of exceptions in the exception specification.
5589 const QualType *data() const { return Exceptions.data(); }
5590
5591 /// Integrate another called method into the collected data.
5592 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5593
5594 /// Integrate an invoked expression into the collected data.
5595 void CalledExpr(Expr *E) { CalledStmt(S: E); }
5596
5597 /// Integrate an invoked statement into the collected data.
5598 void CalledStmt(Stmt *S);
5599
5600 /// Overwrite an EPI's exception specification with this
5601 /// computed exception specification.
5602 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5603 FunctionProtoType::ExceptionSpecInfo ESI;
5604 ESI.Type = getExceptionSpecType();
5605 if (ESI.Type == EST_Dynamic) {
5606 ESI.Exceptions = Exceptions;
5607 } else if (ESI.Type == EST_None) {
5608 /// C++11 [except.spec]p14:
5609 /// The exception-specification is noexcept(false) if the set of
5610 /// potential exceptions of the special member function contains "any"
5611 ESI.Type = EST_NoexceptFalse;
5612 ESI.NoexceptExpr =
5613 Self->ActOnCXXBoolLiteral(OpLoc: SourceLocation(), Kind: tok::kw_false).get();
5614 }
5615 return ESI;
5616 }
5617 };
5618
5619 /// Evaluate the implicit exception specification for a defaulted
5620 /// special member function.
5621 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5622
5623 /// Check the given exception-specification and update the
5624 /// exception specification information with the results.
5625 void checkExceptionSpecification(bool IsTopLevel,
5626 ExceptionSpecificationType EST,
5627 ArrayRef<ParsedType> DynamicExceptions,
5628 ArrayRef<SourceRange> DynamicExceptionRanges,
5629 Expr *NoexceptExpr,
5630 SmallVectorImpl<QualType> &Exceptions,
5631 FunctionProtoType::ExceptionSpecInfo &ESI);
5632
5633 /// Add an exception-specification to the given member or friend function
5634 /// (or function template). The exception-specification was parsed
5635 /// after the function itself was declared.
5636 void actOnDelayedExceptionSpecification(
5637 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5638 ArrayRef<ParsedType> DynamicExceptions,
5639 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5640
5641 class InheritedConstructorInfo;
5642
5643 /// Determine if a special member function should have a deleted
5644 /// definition when it is defaulted.
5645 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
5646 InheritedConstructorInfo *ICI = nullptr,
5647 bool Diagnose = false);
5648
5649 /// Produce notes explaining why a defaulted function was defined as deleted.
5650 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5651
5652 /// Declare the implicit default constructor for the given class.
5653 ///
5654 /// \param ClassDecl The class declaration into which the implicit
5655 /// default constructor will be added.
5656 ///
5657 /// \returns The implicitly-declared default constructor.
5658 CXXConstructorDecl *
5659 DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl);
5660
5661 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5662 /// defining this constructor as the default constructor.
5663 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5664 CXXConstructorDecl *Constructor);
5665
5666 /// Declare the implicit destructor for the given class.
5667 ///
5668 /// \param ClassDecl The class declaration into which the implicit
5669 /// destructor will be added.
5670 ///
5671 /// \returns The implicitly-declared destructor.
5672 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5673
5674 /// DefineImplicitDestructor - Checks for feasibility of
5675 /// defining this destructor as the default destructor.
5676 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5677 CXXDestructorDecl *Destructor);
5678
5679 /// Build an exception spec for destructors that don't have one.
5680 ///
5681 /// C++11 says that user-defined destructors with no exception spec get one
5682 /// that looks as if the destructor was implicitly declared.
5683 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5684
5685 /// Define the specified inheriting constructor.
5686 void DefineInheritingConstructor(SourceLocation UseLoc,
5687 CXXConstructorDecl *Constructor);
5688
5689 /// Declare the implicit copy constructor for the given class.
5690 ///
5691 /// \param ClassDecl The class declaration into which the implicit
5692 /// copy constructor will be added.
5693 ///
5694 /// \returns The implicitly-declared copy constructor.
5695 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5696
5697 /// DefineImplicitCopyConstructor - Checks for feasibility of
5698 /// defining this constructor as the copy constructor.
5699 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5700 CXXConstructorDecl *Constructor);
5701
5702 /// Declare the implicit move constructor for the given class.
5703 ///
5704 /// \param ClassDecl The Class declaration into which the implicit
5705 /// move constructor will be added.
5706 ///
5707 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5708 /// declared.
5709 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5710
5711 /// DefineImplicitMoveConstructor - Checks for feasibility of
5712 /// defining this constructor as the move constructor.
5713 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5714 CXXConstructorDecl *Constructor);
5715
5716 /// Declare the implicit copy assignment operator for the given class.
5717 ///
5718 /// \param ClassDecl The class declaration into which the implicit
5719 /// copy assignment operator will be added.
5720 ///
5721 /// \returns The implicitly-declared copy assignment operator.
5722 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5723
5724 /// Defines an implicitly-declared copy assignment operator.
5725 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5726 CXXMethodDecl *MethodDecl);
5727
5728 /// Declare the implicit move assignment operator for the given class.
5729 ///
5730 /// \param ClassDecl The Class declaration into which the implicit
5731 /// move assignment operator will be added.
5732 ///
5733 /// \returns The implicitly-declared move assignment operator, or NULL if it
5734 /// wasn't declared.
5735 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5736
5737 /// Defines an implicitly-declared move assignment operator.
5738 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5739 CXXMethodDecl *MethodDecl);
5740
5741 /// Check a completed declaration of an implicit special member.
5742 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5743
5744 /// Determine whether the given function is an implicitly-deleted
5745 /// special member function.
5746 bool isImplicitlyDeleted(FunctionDecl *FD);
5747
5748 /// Check whether 'this' shows up in the type of a static member
5749 /// function after the (naturally empty) cv-qualifier-seq would be.
5750 ///
5751 /// \returns true if an error occurred.
5752 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5753
5754 /// Whether this' shows up in the exception specification of a static
5755 /// member function.
5756 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5757
5758 /// Check whether 'this' shows up in the attributes of the given
5759 /// static member function.
5760 ///
5761 /// \returns true if an error occurred.
5762 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5763
5764 bool CheckImmediateEscalatingFunctionDefinition(
5765 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5766
5767 void DiagnoseImmediateEscalatingReason(FunctionDecl *FD);
5768
5769 /// Given a constructor and the set of arguments provided for the
5770 /// constructor, convert the arguments and add any required default arguments
5771 /// to form a proper call to this constructor.
5772 ///
5773 /// \returns true if an error occurred, false otherwise.
5774 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5775 QualType DeclInitType, MultiExprArg ArgsPtr,
5776 SourceLocation Loc,
5777 SmallVectorImpl<Expr *> &ConvertedArgs,
5778 bool AllowExplicit = false,
5779 bool IsListInitialization = false);
5780
5781 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5782 /// initializer for the declaration 'Dcl'.
5783 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5784 /// static data member of class X, names should be looked up in the scope of
5785 /// class X.
5786 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5787
5788 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5789 /// initializer for the declaration 'Dcl'.
5790 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5791
5792 /// Define the "body" of the conversion from a lambda object to a
5793 /// function pointer.
5794 ///
5795 /// This routine doesn't actually define a sensible body; rather, it fills
5796 /// in the initialization expression needed to copy the lambda object into
5797 /// the block, and IR generation actually generates the real body of the
5798 /// block pointer conversion.
5799 void
5800 DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc,
5801 CXXConversionDecl *Conv);
5802
5803 /// Define the "body" of the conversion from a lambda object to a
5804 /// block pointer.
5805 ///
5806 /// This routine doesn't actually define a sensible body; rather, it fills
5807 /// in the initialization expression needed to copy the lambda object into
5808 /// the block, and IR generation actually generates the real body of the
5809 /// block pointer conversion.
5810 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5811 CXXConversionDecl *Conv);
5812
5813 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5814 /// linkage specification, including the language and (if present)
5815 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5816 /// language string literal. LBraceLoc, if valid, provides the location of
5817 /// the '{' brace. Otherwise, this linkage specification does not
5818 /// have any braces.
5819 Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5820 Expr *LangStr, SourceLocation LBraceLoc);
5821
5822 /// ActOnFinishLinkageSpecification - Complete the definition of
5823 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5824 /// valid, it's the position of the closing '}' brace in a linkage
5825 /// specification that uses braces.
5826 Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec,
5827 SourceLocation RBraceLoc);
5828
5829 //===--------------------------------------------------------------------===//
5830 // C++ Classes
5831 //
5832
5833 /// Get the class that is directly named by the current context. This is the
5834 /// class for which an unqualified-id in this scope could name a constructor
5835 /// or destructor.
5836 ///
5837 /// If the scope specifier denotes a class, this will be that class.
5838 /// If the scope specifier is empty, this will be the class whose
5839 /// member-specification we are currently within. Otherwise, there
5840 /// is no such class.
5841 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
5842
5843 /// isCurrentClassName - Determine whether the identifier II is the
5844 /// name of the class type currently being defined. In the case of
5845 /// nested classes, this will only return true if II is the name of
5846 /// the innermost class.
5847 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5848 const CXXScopeSpec *SS = nullptr);
5849
5850 /// Determine whether the identifier II is a typo for the name of
5851 /// the class type currently being defined. If so, update it to the identifier
5852 /// that should have been used.
5853 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5854
5855 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5856 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
5857 SourceLocation ColonLoc,
5858 const ParsedAttributesView &Attrs);
5859
5860 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5861 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5862 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
5863 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
5864 /// present (but parsing it has been deferred).
5865 NamedDecl *
5866 ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
5867 MultiTemplateParamsArg TemplateParameterLists,
5868 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5869 InClassInitStyle InitStyle);
5870
5871 /// Enter a new C++ default initializer scope. After calling this, the
5872 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
5873 /// parsing or instantiating the initializer failed.
5874 void ActOnStartCXXInClassMemberInitializer();
5875
5876 /// This is invoked after parsing an in-class initializer for a
5877 /// non-static C++ class member, and after instantiating an in-class
5878 /// initializer in a class template. Such actions are deferred until the class
5879 /// is complete.
5880 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5881 SourceLocation EqualLoc,
5882 ExprResult Init);
5883
5884 /// Handle a C++ member initializer using parentheses syntax.
5885 MemInitResult
5886 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
5887 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
5888 const DeclSpec &DS, SourceLocation IdLoc,
5889 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
5890 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
5891
5892 /// Handle a C++ member initializer using braced-init-list syntax.
5893 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
5894 CXXScopeSpec &SS,
5895 IdentifierInfo *MemberOrBase,
5896 ParsedType TemplateTypeTy,
5897 const DeclSpec &DS, SourceLocation IdLoc,
5898 Expr *InitList, SourceLocation EllipsisLoc);
5899
5900 /// Handle a C++ member initializer.
5901 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
5902 CXXScopeSpec &SS,
5903 IdentifierInfo *MemberOrBase,
5904 ParsedType TemplateTypeTy,
5905 const DeclSpec &DS, SourceLocation IdLoc,
5906 Expr *Init, SourceLocation EllipsisLoc);
5907
5908 MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init,
5909 SourceLocation IdLoc);
5910
5911 MemInitResult BuildBaseInitializer(QualType BaseType,
5912 TypeSourceInfo *BaseTInfo, Expr *Init,
5913 CXXRecordDecl *ClassDecl,
5914 SourceLocation EllipsisLoc);
5915
5916 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
5917 CXXRecordDecl *ClassDecl);
5918
5919 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5920 CXXCtorInitializer *Initializer);
5921
5922 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5923 ArrayRef<CXXCtorInitializer *> Initializers = {});
5924
5925 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5926 /// mark all the non-trivial destructors of its members and bases as
5927 /// referenced.
5928 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5929 CXXRecordDecl *Record);
5930
5931 /// Mark destructors of virtual bases of this class referenced. In the Itanium
5932 /// C++ ABI, this is done when emitting a destructor for any non-abstract
5933 /// class. In the Microsoft C++ ABI, this is done any time a class's
5934 /// destructor is referenced.
5935 void MarkVirtualBaseDestructorsReferenced(
5936 SourceLocation Location, CXXRecordDecl *ClassDecl,
5937 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
5938 nullptr);
5939
5940 /// Do semantic checks to allow the complete destructor variant to be emitted
5941 /// when the destructor is defined in another translation unit. In the Itanium
5942 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
5943 /// can be emitted in separate TUs. To emit the complete variant, run a subset
5944 /// of the checks performed when emitting a regular destructor.
5945 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
5946 CXXDestructorDecl *Dtor);
5947
5948 /// The list of classes whose vtables have been used within
5949 /// this translation unit, and the source locations at which the
5950 /// first use occurred.
5951 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
5952
5953 /// The list of vtables that are required but have not yet been
5954 /// materialized.
5955 SmallVector<VTableUse, 16> VTableUses;
5956
5957 /// The set of classes whose vtables have been used within
5958 /// this translation unit, and a bit that will be true if the vtable is
5959 /// required to be emitted (otherwise, it should be emitted only if needed
5960 /// by code generation).
5961 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5962
5963 /// Load any externally-stored vtable uses.
5964 void LoadExternalVTableUses();
5965
5966 /// Note that the vtable for the given class was used at the
5967 /// given location.
5968 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5969 bool DefinitionRequired = false);
5970
5971 /// Mark the exception specifications of all virtual member functions
5972 /// in the given class as needed.
5973 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5974 const CXXRecordDecl *RD);
5975
5976 /// MarkVirtualMembersReferenced - Will mark all members of the given
5977 /// CXXRecordDecl referenced.
5978 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
5979 bool ConstexprOnly = false);
5980
5981 /// Define all of the vtables that have been used in this
5982 /// translation unit and reference any virtual members used by those
5983 /// vtables.
5984 ///
5985 /// \returns true if any work was done, false otherwise.
5986 bool DefineUsedVTables();
5987
5988 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5989 /// special functions, such as the default constructor, copy
5990 /// constructor, or destructor, to the given C++ class (C++
5991 /// [special]p1). This routine can only be executed just before the
5992 /// definition of the class is complete.
5993 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5994
5995 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5996 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
5997 ArrayRef<CXXCtorInitializer *> MemInits,
5998 bool AnyErrors);
5999
6000 /// Check class-level dllimport/dllexport attribute. The caller must
6001 /// ensure that referenceDLLExportedClassMethods is called some point later
6002 /// when all outer classes of Class are complete.
6003 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
6004 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
6005
6006 void referenceDLLExportedClassMethods();
6007
6008 /// Perform propagation of DLL attributes from a derived class to a
6009 /// templated base class for MS compatibility.
6010 void propagateDLLAttrToBaseClassTemplate(
6011 CXXRecordDecl *Class, Attr *ClassAttr,
6012 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6013 SourceLocation BaseLoc);
6014
6015 /// Perform semantic checks on a class definition that has been
6016 /// completing, introducing implicitly-declared members, checking for
6017 /// abstract types, etc.
6018 ///
6019 /// \param S The scope in which the class was parsed. Null if we didn't just
6020 /// parse a class definition.
6021 /// \param Record The completed class.
6022 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
6023
6024 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6025 /// conditions that are needed for the attribute to have an effect.
6026 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6027
6028 /// Check that VTable Pointer authentication is only being set on the first
6029 /// first instantiation of the vtable
6030 void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD);
6031
6032 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6033 Decl *TagDecl, SourceLocation LBrac,
6034 SourceLocation RBrac,
6035 const ParsedAttributesView &AttrList);
6036
6037 /// Perform any semantic analysis which needs to be delayed until all
6038 /// pending class member declarations have been parsed.
6039 void ActOnFinishCXXMemberDecls();
6040 void ActOnFinishCXXNonNestedClass();
6041
6042 /// This is used to implement the constant expression evaluation part of the
6043 /// attribute enable_if extension. There is nothing in standard C++ which
6044 /// would require reentering parameters.
6045 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6046 unsigned ActOnReenterTemplateScope(Decl *Template,
6047 llvm::function_ref<Scope *()> EnterScope);
6048 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6049
6050 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6051 /// parsing a top-level (non-nested) C++ class, and we are now
6052 /// parsing those parts of the given Method declaration that could
6053 /// not be parsed earlier (C++ [class.mem]p2), such as default
6054 /// arguments. This action should enter the scope of the given
6055 /// Method declaration as if we had just parsed the qualified method
6056 /// name. However, it should not bring the parameters into scope;
6057 /// that will be performed by ActOnDelayedCXXMethodParameter.
6058 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6059 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6060 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6061
6062 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6063 /// processing the delayed method declaration for Method. The method
6064 /// declaration is now considered finished. There may be a separate
6065 /// ActOnStartOfFunctionDef action later (not necessarily
6066 /// immediately!) for this method, if it was also defined inside the
6067 /// class body.
6068 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6069 void ActOnFinishDelayedMemberInitializers(Decl *Record);
6070
6071 enum class StringEvaluationContext { StaticAssert = 0, Asm = 1 };
6072
6073 bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
6074 StringEvaluationContext EvalContext,
6075 bool ErrorOnInvalidMessage);
6076 bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
6077 StringEvaluationContext EvalContext,
6078 bool ErrorOnInvalidMessage);
6079
6080 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6081 Expr *AssertExpr, Expr *AssertMessageExpr,
6082 SourceLocation RParenLoc);
6083 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6084 Expr *AssertExpr, Expr *AssertMessageExpr,
6085 SourceLocation RParenLoc, bool Failed);
6086
6087 /// Try to print more useful information about a failed static_assert
6088 /// with expression \E
6089 void DiagnoseStaticAssertDetails(const Expr *E);
6090
6091 /// If E represents a built-in type trait, or a known standard type trait,
6092 /// try to print more information about why the type type-trait failed.
6093 /// This assumes we already evaluated the expression to a false boolean value.
6094 void DiagnoseTypeTraitDetails(const Expr *E);
6095
6096 /// Handle a friend type declaration. This works in tandem with
6097 /// ActOnTag.
6098 ///
6099 /// Notes on friend class templates:
6100 ///
6101 /// We generally treat friend class declarations as if they were
6102 /// declaring a class. So, for example, the elaborated type specifier
6103 /// in a friend declaration is required to obey the restrictions of a
6104 /// class-head (i.e. no typedefs in the scope chain), template
6105 /// parameters are required to match up with simple template-ids, &c.
6106 /// However, unlike when declaring a template specialization, it's
6107 /// okay to refer to a template specialization without an empty
6108 /// template parameter declaration, e.g.
6109 /// friend class A<T>::B<unsigned>;
6110 /// We permit this as a special case; if there are any template
6111 /// parameters present at all, require proper matching, i.e.
6112 /// template <> template \<class T> friend class A<int>::B;
6113 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6114 MultiTemplateParamsArg TemplateParams,
6115 SourceLocation EllipsisLoc);
6116 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6117 MultiTemplateParamsArg TemplateParams);
6118
6119 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6120 /// the well-formedness of the constructor declarator @p D with type @p
6121 /// R. If there are any errors in the declarator, this routine will
6122 /// emit diagnostics and set the invalid bit to true. In any case, the type
6123 /// will be updated to reflect a well-formed type for the constructor and
6124 /// returned.
6125 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6126 StorageClass &SC);
6127
6128 /// CheckConstructor - Checks a fully-formed constructor for
6129 /// well-formedness, issuing any diagnostics required. Returns true if
6130 /// the constructor declarator is invalid.
6131 void CheckConstructor(CXXConstructorDecl *Constructor);
6132
6133 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6134 /// the well-formednes of the destructor declarator @p D with type @p
6135 /// R. If there are any errors in the declarator, this routine will
6136 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6137 /// will be updated to reflect a well-formed type for the destructor and
6138 /// returned.
6139 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6140 StorageClass &SC);
6141
6142 /// CheckDestructor - Checks a fully-formed destructor definition for
6143 /// well-formedness, issuing any diagnostics required. Returns true
6144 /// on error.
6145 bool CheckDestructor(CXXDestructorDecl *Destructor);
6146
6147 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6148 /// well-formednes of the conversion function declarator @p D with
6149 /// type @p R. If there are any errors in the declarator, this routine
6150 /// will emit diagnostics and return true. Otherwise, it will return
6151 /// false. Either way, the type @p R will be updated to reflect a
6152 /// well-formed type for the conversion operator.
6153 void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC);
6154
6155 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6156 /// the declaration of the given C++ conversion function. This routine
6157 /// is responsible for recording the conversion function in the C++
6158 /// class, if possible.
6159 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6160
6161 /// Check the validity of a declarator that we parsed for a deduction-guide.
6162 /// These aren't actually declarators in the grammar, so we need to check that
6163 /// the user didn't specify any pieces that are not part of the
6164 /// deduction-guide grammar. Return true on invalid deduction-guide.
6165 bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6166 StorageClass &SC);
6167
6168 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6169
6170 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6171 CXXSpecialMemberKind CSM,
6172 SourceLocation DefaultLoc);
6173 void CheckDelayedMemberExceptionSpecs();
6174
6175 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6176 DefaultedComparisonKind DCK);
6177 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6178 FunctionDecl *Spaceship);
6179 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6180 DefaultedComparisonKind DCK);
6181
6182 void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name,
6183 QualType R, bool IsLambda,
6184 DeclContext *DC = nullptr);
6185 void CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
6186 DeclarationName Name, QualType R);
6187 void CheckExplicitObjectLambda(Declarator &D);
6188
6189 //===--------------------------------------------------------------------===//
6190 // C++ Derived Classes
6191 //
6192
6193 /// Check the validity of a C++ base class specifier.
6194 ///
6195 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6196 /// and returns NULL otherwise.
6197 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6198 SourceRange SpecifierRange, bool Virtual,
6199 AccessSpecifier Access,
6200 TypeSourceInfo *TInfo,
6201 SourceLocation EllipsisLoc);
6202
6203 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6204 /// one entry in the base class list of a class specifier, for
6205 /// example:
6206 /// class foo : public bar, virtual private baz {
6207 /// 'public bar' and 'virtual private baz' are each base-specifiers.
6208 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6209 const ParsedAttributesView &Attrs, bool Virtual,
6210 AccessSpecifier Access, ParsedType basetype,
6211 SourceLocation BaseLoc,
6212 SourceLocation EllipsisLoc);
6213
6214 /// Performs the actual work of attaching the given base class
6215 /// specifiers to a C++ class.
6216 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6217 MutableArrayRef<CXXBaseSpecifier *> Bases);
6218
6219 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6220 /// class, after checking whether there are any duplicate base
6221 /// classes.
6222 void ActOnBaseSpecifiers(Decl *ClassDecl,
6223 MutableArrayRef<CXXBaseSpecifier *> Bases);
6224
6225 /// Determine whether the type \p Derived is a C++ class that is
6226 /// derived from the type \p Base.
6227 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6228 CXXRecordDecl *Base, CXXBasePaths &Paths);
6229 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6230 CXXRecordDecl *Base);
6231 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6232 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6233 CXXBasePaths &Paths);
6234
6235 // FIXME: I don't like this name.
6236 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6237
6238 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6239 SourceLocation Loc, SourceRange Range,
6240 CXXCastPath *BasePath = nullptr,
6241 bool IgnoreAccess = false);
6242
6243 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6244 /// conversion (where Derived and Base are class types) is
6245 /// well-formed, meaning that the conversion is unambiguous (and
6246 /// that all of the base classes are accessible). Returns true
6247 /// and emits a diagnostic if the code is ill-formed, returns false
6248 /// otherwise. Loc is the location where this routine should point to
6249 /// if there is an error, and Range is the source range to highlight
6250 /// if there is an error.
6251 ///
6252 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6253 /// diagnostic for the respective type of error will be suppressed, but the
6254 /// check for ill-formed code will still be performed.
6255 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6256 unsigned InaccessibleBaseID,
6257 unsigned AmbiguousBaseConvID,
6258 SourceLocation Loc, SourceRange Range,
6259 DeclarationName Name, CXXCastPath *BasePath,
6260 bool IgnoreAccess = false);
6261
6262 /// Builds a string representing ambiguous paths from a
6263 /// specific derived class to different subobjects of the same base
6264 /// class.
6265 ///
6266 /// This function builds a string that can be used in error messages
6267 /// to show the different paths that one can take through the
6268 /// inheritance hierarchy to go from the derived class to different
6269 /// subobjects of a base class. The result looks something like this:
6270 /// @code
6271 /// struct D -> struct B -> struct A
6272 /// struct D -> struct C -> struct A
6273 /// @endcode
6274 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6275
6276 bool CheckOverridingFunctionAttributes(CXXMethodDecl *New,
6277 const CXXMethodDecl *Old);
6278
6279 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6280 /// covariant, according to C++ [class.virtual]p5.
6281 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6282 const CXXMethodDecl *Old);
6283
6284 // Check that the overriding method has no explicit object parameter.
6285 bool CheckExplicitObjectOverride(CXXMethodDecl *New,
6286 const CXXMethodDecl *Old);
6287
6288 /// Mark the given method pure.
6289 ///
6290 /// \param Method the method to be marked pure.
6291 ///
6292 /// \param InitRange the source range that covers the "0" initializer.
6293 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6294
6295 /// CheckOverrideControl - Check C++11 override control semantics.
6296 void CheckOverrideControl(NamedDecl *D);
6297
6298 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6299 /// not used in the declaration of an overriding method.
6300 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
6301
6302 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6303 /// function overrides a virtual member function marked 'final', according to
6304 /// C++11 [class.virtual]p4.
6305 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6306 const CXXMethodDecl *Old);
6307
6308 enum AbstractDiagSelID {
6309 AbstractNone = -1,
6310 AbstractReturnType,
6311 AbstractParamType,
6312 AbstractVariableType,
6313 AbstractFieldType,
6314 AbstractIvarType,
6315 AbstractSynthesizedIvarType,
6316 AbstractArrayType
6317 };
6318
6319 struct TypeDiagnoser;
6320
6321 bool isAbstractType(SourceLocation Loc, QualType T);
6322 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6323 TypeDiagnoser &Diagnoser);
6324 template <typename... Ts>
6325 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6326 const Ts &...Args) {
6327 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6328 return RequireNonAbstractType(Loc, T, Diagnoser);
6329 }
6330
6331 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6332
6333 //===--------------------------------------------------------------------===//
6334 // C++ Overloaded Operators [C++ 13.5]
6335 //
6336
6337 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6338 /// of this overloaded operator is well-formed. If so, returns false;
6339 /// otherwise, emits appropriate diagnostics and returns true.
6340 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6341
6342 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6343 /// of this literal operator function is well-formed. If so, returns
6344 /// false; otherwise, emits appropriate diagnostics and returns true.
6345 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6346
6347 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6348 /// found in an explicit(bool) specifier.
6349 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
6350
6351 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6352 /// Returns true if the explicit specifier is now resolved.
6353 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
6354
6355 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6356 /// C++ if/switch/while/for statement.
6357 /// e.g: "if (int x = f()) {...}"
6358 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
6359
6360 // Emitting members of dllexported classes is delayed until the class
6361 // (including field initializers) is fully parsed.
6362 SmallVector<CXXRecordDecl *, 4> DelayedDllExportClasses;
6363 SmallVector<CXXMethodDecl *, 4> DelayedDllExportMemberFunctions;
6364
6365 /// Merge the exception specifications of two variable declarations.
6366 ///
6367 /// This is called when there's a redeclaration of a VarDecl. The function
6368 /// checks if the redeclaration might have an exception specification and
6369 /// validates compatibility and merges the specs if necessary.
6370 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
6371
6372 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6373 /// function, once we already know that they have the same
6374 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6375 /// error, false otherwise.
6376 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
6377
6378 /// Helpers for dealing with blocks and functions.
6379 void CheckCXXDefaultArguments(FunctionDecl *FD);
6380
6381 /// CheckExtraCXXDefaultArguments - Check for any extra default
6382 /// arguments in the declarator, which is not a function declaration
6383 /// or definition and therefore is not permitted to have default
6384 /// arguments. This routine should be invoked for every declarator
6385 /// that is not a function declaration or definition.
6386 void CheckExtraCXXDefaultArguments(Declarator &D);
6387
6388 /// Perform semantic analysis for the variable declaration that
6389 /// occurs within a C++ catch clause, returning the newly-created
6390 /// variable.
6391 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
6392 SourceLocation StartLoc,
6393 SourceLocation IdLoc,
6394 const IdentifierInfo *Id);
6395
6396 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6397 /// handler.
6398 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
6399
6400 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
6401
6402 /// Handle a friend tag declaration where the scope specifier was
6403 /// templated.
6404 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6405 unsigned TagSpec, SourceLocation TagLoc,
6406 CXXScopeSpec &SS, IdentifierInfo *Name,
6407 SourceLocation NameLoc,
6408 SourceLocation EllipsisLoc,
6409 const ParsedAttributesView &Attr,
6410 MultiTemplateParamsArg TempParamLists,
6411 TemplateIdAnnotation *TemplateId);
6412
6413 bool CheckDependentFriend(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc,
6414 ArrayRef<TemplateParameterList *> TPLs,
6415 bool IsInstantiation);
6416
6417 bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc,
6418 NestedNameSpecifierLoc NNSLoc);
6419
6420 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
6421 SourceLocation DeclStart, Declarator &D,
6422 Expr *BitfieldWidth,
6423 InClassInitStyle InitStyle,
6424 AccessSpecifier AS,
6425 const ParsedAttr &MSPropertyAttr);
6426
6427 /// Diagnose why the specified class does not have a trivial special member of
6428 /// the given kind.
6429 void DiagnoseNontrivial(const CXXRecordDecl *Record,
6430 CXXSpecialMemberKind CSM);
6431
6432 /// Determine whether a defaulted or deleted special member function is
6433 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6434 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6435 bool SpecialMemberIsTrivial(
6436 CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
6437 TrivialABIHandling TAH = TrivialABIHandling::IgnoreTrivialABI,
6438 bool Diagnose = false);
6439
6440 /// Handle a C++11 empty-declaration and attribute-declaration.
6441 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
6442 SourceLocation SemiLoc);
6443
6444 enum class CheckConstexprKind {
6445 /// Diagnose issues that are non-constant or that are extensions.
6446 Diagnose,
6447 /// Identify whether this function satisfies the formal rules for constexpr
6448 /// functions in the current lanugage mode (with no extensions).
6449 CheckValid
6450 };
6451
6452 // Check whether a function declaration satisfies the requirements of a
6453 // constexpr function definition or a constexpr constructor definition. If so,
6454 // return true. If not, produce appropriate diagnostics (unless asked not to
6455 // by Kind) and return false.
6456 //
6457 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6458 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
6459 CheckConstexprKind Kind);
6460
6461 /// Diagnose methods which overload virtual methods in a base class
6462 /// without overriding any.
6463 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
6464
6465 /// Check if a method overloads virtual methods in a base class without
6466 /// overriding any.
6467 void
6468 FindHiddenVirtualMethods(CXXMethodDecl *MD,
6469 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6470 void
6471 NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6472 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6473
6474 /// ActOnParamDefaultArgument - Check whether the default argument
6475 /// provided for a function parameter is well-formed. If so, attach it
6476 /// to the parameter declaration.
6477 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6478 Expr *defarg);
6479
6480 /// ActOnParamUnparsedDefaultArgument - We've seen a default
6481 /// argument for a function parameter, but we can't parse it yet
6482 /// because we're inside a class definition. Note that this default
6483 /// argument will be parsed later.
6484 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
6485 SourceLocation ArgLoc);
6486
6487 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6488 /// the default argument for the parameter param failed.
6489 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
6490 Expr *DefaultArg);
6491 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6492 SourceLocation EqualLoc);
6493 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6494 SourceLocation EqualLoc);
6495
6496 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6497 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6498 StringLiteral *Message = nullptr);
6499 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
6500
6501 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6502 StringLiteral *DeletedMessage = nullptr);
6503 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
6504 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
6505 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
6506
6507 NamedDecl *
6508 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
6509 MultiTemplateParamsArg TemplateParamLists);
6510 void DiagPlaceholderVariableDefinition(SourceLocation Loc);
6511 bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
6512 RecordDecl *ClassDecl,
6513 const IdentifierInfo *Name);
6514
6515 UnsignedOrNone GetDecompositionElementCount(QualType DecompType,
6516 SourceLocation Loc);
6517 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
6518
6519 /// Stack containing information needed when in C++2a an 'auto' is encountered
6520 /// in a function declaration parameter type specifier in order to invent a
6521 /// corresponding template parameter in the enclosing abbreviated function
6522 /// template. This information is also present in LambdaScopeInfo, stored in
6523 /// the FunctionScopes stack.
6524 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
6525
6526 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6527 std::unique_ptr<CXXFieldCollector> FieldCollector;
6528
6529 typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType;
6530 /// Set containing all declared private fields that are not used.
6531 NamedDeclSetType UnusedPrivateFields;
6532
6533 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 8> RecordDeclSetTy;
6534
6535 /// PureVirtualClassDiagSet - a set of class declarations which we have
6536 /// emitted a list of pure virtual functions. Used to prevent emitting the
6537 /// same list more than once.
6538 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6539
6540 typedef LazyVector<CXXConstructorDecl *,
6541 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
6542 DelegatingCtorDeclsType;
6543
6544 /// All the delegating constructors seen so far in the file, used for
6545 /// cycle detection at the end of the TU.
6546 DelegatingCtorDeclsType DelegatingCtorDecls;
6547
6548 /// The C++ "std" namespace, where the standard library resides.
6549 LazyDeclPtr StdNamespace;
6550
6551 /// The C++ "std::initializer_list" template, which is defined in
6552 /// \<initializer_list>.
6553 ClassTemplateDecl *StdInitializerList;
6554
6555 /// The C++ "std::type_identity" template, which is defined in
6556 /// \<type_traits>.
6557 ClassTemplateDecl *StdTypeIdentity;
6558
6559 // Contains the locations of the beginning of unparsed default
6560 // argument locations.
6561 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6562
6563 /// UndefinedInternals - all the used, undefined objects which require a
6564 /// definition in this translation unit.
6565 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6566
6567 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6568 SpecialMemberDecl;
6569
6570 /// The C++ special members which we are currently in the process of
6571 /// declaring. If this process recursively triggers the declaration of the
6572 /// same special member, we should act as if it is not yet declared.
6573 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
6574
6575 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
6576
6577 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6578
6579 typedef ProcessingContextState ParsingClassState;
6580 ParsingClassState PushParsingClass() {
6581 ParsingClassDepth++;
6582 return DelayedDiagnostics.pushUndelayed();
6583 }
6584 void PopParsingClass(ParsingClassState state) {
6585 ParsingClassDepth--;
6586 DelayedDiagnostics.popUndelayed(state);
6587 }
6588
6589 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
6590 CXXScopeSpec &SS,
6591 ParsedType TemplateTypeTy,
6592 IdentifierInfo *MemberOrBase);
6593
6594private:
6595 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6596 QualType ResultTy,
6597 ArrayRef<QualType> Args);
6598 // Helper for ActOnFields to check for all function pointer members.
6599 bool EntirelyFunctionPointers(const RecordDecl *Record);
6600
6601 // A cache representing if we've fully checked the various comparison category
6602 // types stored in ASTContext. The bit-index corresponds to the integer value
6603 // of a ComparisonCategoryType enumerator.
6604 llvm::SmallBitVector FullyCheckedComparisonCategories;
6605
6606 /// Check if there is a field shadowing.
6607 void CheckShadowInheritedFields(const SourceLocation &Loc,
6608 DeclarationName FieldName,
6609 const CXXRecordDecl *RD,
6610 bool DeclIsField = true);
6611
6612 ///@}
6613
6614 //
6615 //
6616 // -------------------------------------------------------------------------
6617 //
6618 //
6619
6620 /// \name C++ Exception Specifications
6621 /// Implementations are in SemaExceptionSpec.cpp
6622 ///@{
6623
6624public:
6625 /// All the overriding functions seen during a class definition
6626 /// that had their exception spec checks delayed, plus the overridden
6627 /// function.
6628 SmallVector<std::pair<const CXXMethodDecl *, const CXXMethodDecl *>, 2>
6629 DelayedOverridingExceptionSpecChecks;
6630
6631 /// All the function redeclarations seen during a class definition that had
6632 /// their exception spec checks delayed, plus the prior declaration they
6633 /// should be checked against. Except during error recovery, the new decl
6634 /// should always be a friend declaration, as that's the only valid way to
6635 /// redeclare a special member before its class is complete.
6636 SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 2>
6637 DelayedEquivalentExceptionSpecChecks;
6638
6639 /// Determine if we're in a case where we need to (incorrectly) eagerly
6640 /// parse an exception specification to work around a libstdc++ bug.
6641 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6642
6643 /// Check the given noexcept-specifier, convert its expression, and compute
6644 /// the appropriate ExceptionSpecificationType.
6645 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6646 ExceptionSpecificationType &EST);
6647
6648 CanThrowResult canThrow(const Stmt *E);
6649 /// Determine whether the callee of a particular function call can throw.
6650 /// E, D and Loc are all optional.
6651 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6652 SourceLocation Loc = SourceLocation());
6653 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
6654 const FunctionProtoType *FPT);
6655 void UpdateExceptionSpec(FunctionDecl *FD,
6656 const FunctionProtoType::ExceptionSpecInfo &ESI);
6657
6658 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6659 /// exception specification. Incomplete types, or pointers to incomplete types
6660 /// other than void are not allowed.
6661 ///
6662 /// \param[in,out] T The exception type. This will be decayed to a pointer
6663 /// type
6664 /// when the input is an array or a function type.
6665 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
6666
6667 /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6668 /// pointer to member to a function with an exception specification. This
6669 /// means that it is invalid to add another level of indirection.
6670 bool CheckDistantExceptionSpec(QualType T);
6671 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
6672
6673 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6674 /// exception specifications. Exception specifications are equivalent if
6675 /// they allow exactly the same set of exception types. It does not matter how
6676 /// that is achieved. See C++ [except.spec]p2.
6677 bool CheckEquivalentExceptionSpec(const FunctionProtoType *Old,
6678 SourceLocation OldLoc,
6679 const FunctionProtoType *New,
6680 SourceLocation NewLoc);
6681 bool CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
6682 const PartialDiagnostic &NoteID,
6683 const FunctionProtoType *Old,
6684 SourceLocation OldLoc,
6685 const FunctionProtoType *New,
6686 SourceLocation NewLoc);
6687 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6688
6689 /// CheckExceptionSpecSubset - Check whether the second function type's
6690 /// exception specification is a subset (or equivalent) of the first function
6691 /// type. This is used by override and pointer assignment checks.
6692 bool CheckExceptionSpecSubset(
6693 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6694 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6695 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6696 SourceLocation SuperLoc, const FunctionProtoType *Subset,
6697 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6698
6699 /// CheckParamExceptionSpec - Check if the parameter and return types of the
6700 /// two functions have equivalent exception specs. This is part of the
6701 /// assignment and override compatibility check. We do not check the
6702 /// parameters of parameter function pointers recursively, as no sane
6703 /// programmer would even be able to write such a function type.
6704 bool CheckParamExceptionSpec(
6705 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6706 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6707 SourceLocation TargetLoc, const FunctionProtoType *Source,
6708 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6709
6710 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6711
6712 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6713 /// spec is a subset of base spec.
6714 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6715 const CXXMethodDecl *Old);
6716
6717 ///@}
6718
6719 //
6720 //
6721 // -------------------------------------------------------------------------
6722 //
6723 //
6724
6725 /// \name Expressions
6726 /// Implementations are in SemaExpr.cpp
6727 ///@{
6728
6729public:
6730 /// Describes how the expressions currently being parsed are
6731 /// evaluated at run-time, if at all.
6732 enum class ExpressionEvaluationContext {
6733 /// The current expression and its subexpressions occur within an
6734 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6735 /// \c sizeof, where the type of the expression may be significant but
6736 /// no code will be generated to evaluate the value of the expression at
6737 /// run time.
6738 Unevaluated,
6739
6740 /// The current expression occurs within a braced-init-list within
6741 /// an unevaluated operand. This is mostly like a regular unevaluated
6742 /// context, except that we still instantiate constexpr functions that are
6743 /// referenced here so that we can perform narrowing checks correctly.
6744 UnevaluatedList,
6745
6746 /// The current expression occurs within a discarded statement.
6747 /// This behaves largely similarly to an unevaluated operand in preventing
6748 /// definitions from being required, but not in other ways.
6749 DiscardedStatement,
6750
6751 /// The current expression occurs within an unevaluated
6752 /// operand that unconditionally permits abstract references to
6753 /// fields, such as a SIZE operator in MS-style inline assembly.
6754 UnevaluatedAbstract,
6755
6756 /// The current context is "potentially evaluated" in C++11 terms,
6757 /// but the expression is evaluated at compile-time (like the values of
6758 /// cases in a switch statement).
6759 ConstantEvaluated,
6760
6761 /// In addition of being constant evaluated, the current expression
6762 /// occurs in an immediate function context - either a consteval function
6763 /// or a consteval if statement.
6764 ImmediateFunctionContext,
6765
6766 /// The current expression is potentially evaluated at run time,
6767 /// which means that code may be generated to evaluate the value of the
6768 /// expression at run time.
6769 PotentiallyEvaluated,
6770
6771 /// The current expression is potentially evaluated, but any
6772 /// declarations referenced inside that expression are only used if
6773 /// in fact the current expression is used.
6774 ///
6775 /// This value is used when parsing default function arguments, for which
6776 /// we would like to provide diagnostics (e.g., passing non-POD arguments
6777 /// through varargs) but do not want to mark declarations as "referenced"
6778 /// until the default argument is used.
6779 PotentiallyEvaluatedIfUsed
6780 };
6781
6782 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6783 /// to a variable (constant) that may or may not be odr-used in this Expr, and
6784 /// we won't know until all lvalue-to-rvalue and discarded value conversions
6785 /// have been applied to all subexpressions of the enclosing full expression.
6786 /// This is cleared at the end of each full expression.
6787 using MaybeODRUseExprSet = llvm::SmallSetVector<Expr *, 4>;
6788 MaybeODRUseExprSet MaybeODRUseExprs;
6789
6790 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6791
6792 /// Data structure used to record current or nested
6793 /// expression evaluation contexts.
6794 struct ExpressionEvaluationContextRecord {
6795 /// The expression evaluation context.
6796 ExpressionEvaluationContext Context;
6797
6798 /// Whether the enclosing context needed a cleanup.
6799 CleanupInfo ParentCleanup;
6800
6801 /// The number of active cleanup objects when we entered
6802 /// this expression evaluation context.
6803 unsigned NumCleanupObjects;
6804
6805 MaybeODRUseExprSet SavedMaybeODRUseExprs;
6806
6807 /// The lambdas that are present within this context, if it
6808 /// is indeed an unevaluated context.
6809 SmallVector<LambdaExpr *, 2> Lambdas;
6810
6811 /// The declaration that provides context for lambda expressions
6812 /// and block literals if the normal declaration context does not
6813 /// suffice, e.g., in a default function argument.
6814 Decl *ManglingContextDecl;
6815
6816 /// Declaration for initializer if one is currently being
6817 /// parsed. Used when an expression has a possibly unreachable
6818 /// diagnostic to reference the declaration as a whole.
6819 VarDecl *DeclForInitializer = nullptr;
6820
6821 /// If we are processing a decltype type, a set of call expressions
6822 /// for which we have deferred checking the completeness of the return type.
6823 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
6824
6825 /// If we are processing a decltype type, a set of temporary binding
6826 /// expressions for which we have deferred checking the destructor.
6827 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
6828
6829 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
6830
6831 /// Expressions appearing as the LHS of a volatile assignment in this
6832 /// context. We produce a warning for these when popping the context if
6833 /// they are not discarded-value expressions nor unevaluated operands.
6834 SmallVector<Expr *, 2> VolatileAssignmentLHSs;
6835
6836 /// Set of candidates for starting an immediate invocation.
6837 llvm::SmallVector<ImmediateInvocationCandidate, 4>
6838 ImmediateInvocationCandidates;
6839
6840 /// Set of DeclRefExprs referencing a consteval function when used in a
6841 /// context not already known to be immediately invoked.
6842 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
6843
6844 /// P2718R0 - Lifetime extension in range-based for loops.
6845 /// MaterializeTemporaryExprs in for-range-init expressions which need to
6846 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
6847 /// InLifetimeExtendingContext is true.
6848 SmallVector<MaterializeTemporaryExpr *, 8> ForRangeLifetimeExtendTemps;
6849
6850 /// Small set of gathered accesses to potentially misaligned members
6851 /// due to the packed attribute.
6852 SmallVector<MisalignedMember, 4> MisalignedMembers;
6853
6854 /// \brief Describes whether we are in an expression constext which we have
6855 /// to handle differently.
6856 enum ExpressionKind {
6857 EK_Decltype,
6858 EK_TemplateArgument,
6859 EK_AttrArgument,
6860 EK_VariableInit,
6861 EK_Other
6862 } ExprContext;
6863
6864 // A context can be nested in both a discarded statement context and
6865 // an immediate function context, so they need to be tracked independently.
6866 bool InDiscardedStatement;
6867 bool InImmediateFunctionContext;
6868 bool InImmediateEscalatingFunctionContext;
6869
6870 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
6871
6872 // We are in a constant context, but we also allow
6873 // non constant expressions, for example for array bounds (which may be
6874 // VLAs).
6875 bool InConditionallyConstantEvaluateContext = false;
6876
6877 /// Whether we are currently in a context in which all temporaries must be
6878 /// lifetime-extended, even if they're not bound to a reference (for
6879 /// example, in a for-range initializer).
6880 bool InLifetimeExtendingContext = false;
6881
6882 /// Whether evaluating an expression for a switch case label.
6883 bool IsCaseExpr = false;
6884
6885 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
6886 bool RebuildDefaultArgOrDefaultInit = false;
6887
6888 // When evaluating immediate functions in the initializer of a default
6889 // argument or default member initializer, this is the declaration whose
6890 // default initializer is being evaluated and the location of the call
6891 // or constructor definition.
6892 struct InitializationContext {
6893 InitializationContext(SourceLocation Loc, ValueDecl *Decl,
6894 DeclContext *Context)
6895 : Loc(Loc), Decl(Decl), Context(Context) {
6896 assert(Decl && Context && "invalid initialization context");
6897 }
6898
6899 SourceLocation Loc;
6900 ValueDecl *Decl = nullptr;
6901 DeclContext *Context = nullptr;
6902 };
6903 std::optional<InitializationContext> DelayedDefaultInitializationContext;
6904
6905 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
6906 unsigned NumCleanupObjects,
6907 CleanupInfo ParentCleanup,
6908 Decl *ManglingContextDecl,
6909 ExpressionKind ExprContext)
6910 : Context(Context), ParentCleanup(ParentCleanup),
6911 NumCleanupObjects(NumCleanupObjects),
6912 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
6913 InDiscardedStatement(false), InImmediateFunctionContext(false),
6914 InImmediateEscalatingFunctionContext(false) {}
6915
6916 bool isUnevaluated() const {
6917 return Context == ExpressionEvaluationContext::Unevaluated ||
6918 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
6919 Context == ExpressionEvaluationContext::UnevaluatedList;
6920 }
6921
6922 bool isPotentiallyEvaluated() const {
6923 return Context == ExpressionEvaluationContext::PotentiallyEvaluated ||
6924 Context ==
6925 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed ||
6926 Context == ExpressionEvaluationContext::ConstantEvaluated;
6927 }
6928
6929 bool isConstantEvaluated() const {
6930 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
6931 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
6932 }
6933
6934 bool isImmediateFunctionContext() const {
6935 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
6936 (Context == ExpressionEvaluationContext::DiscardedStatement &&
6937 InImmediateFunctionContext) ||
6938 // C++23 [expr.const]p14:
6939 // An expression or conversion is in an immediate function
6940 // context if it is potentially evaluated and either:
6941 // * its innermost enclosing non-block scope is a function
6942 // parameter scope of an immediate function, or
6943 // * its enclosing statement is enclosed by the compound-
6944 // statement of a consteval if statement.
6945 (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
6946 InImmediateFunctionContext);
6947 }
6948
6949 bool isDiscardedStatementContext() const {
6950 return Context == ExpressionEvaluationContext::DiscardedStatement ||
6951 ((Context ==
6952 ExpressionEvaluationContext::ImmediateFunctionContext ||
6953 isPotentiallyEvaluated()) &&
6954 InDiscardedStatement);
6955 }
6956 };
6957
6958 const ExpressionEvaluationContextRecord &currentEvaluationContext() const {
6959 assert(!ExprEvalContexts.empty() &&
6960 "Must be in an expression evaluation context");
6961 return ExprEvalContexts.back();
6962 }
6963
6964 ExpressionEvaluationContextRecord &currentEvaluationContext() {
6965 assert(!ExprEvalContexts.empty() &&
6966 "Must be in an expression evaluation context");
6967 return ExprEvalContexts.back();
6968 }
6969
6970 ExpressionEvaluationContextRecord &parentEvaluationContext() {
6971 assert(ExprEvalContexts.size() >= 2 &&
6972 "Must be in an expression evaluation context");
6973 return ExprEvalContexts[ExprEvalContexts.size() - 2];
6974 }
6975
6976 const ExpressionEvaluationContextRecord &parentEvaluationContext() const {
6977 return const_cast<Sema *>(this)->parentEvaluationContext();
6978 }
6979
6980 bool isAttrContext() const {
6981 return ExprEvalContexts.back().ExprContext ==
6982 ExpressionEvaluationContextRecord::ExpressionKind::EK_AttrArgument;
6983 }
6984
6985 /// Increment when we find a reference; decrement when we find an ignored
6986 /// assignment. Ultimately the value is 0 if every reference is an ignored
6987 /// assignment.
6988 ///
6989 /// Uses canonical VarDecl as key so in-class decls and out-of-class defs of
6990 /// static data members get tracked as a single entry.
6991 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
6992
6993 /// Used to control the generation of ExprWithCleanups.
6994 CleanupInfo Cleanup;
6995
6996 /// ExprCleanupObjects - This is the stack of objects requiring
6997 /// cleanup that are created by the current full expression.
6998 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
6999
7000 /// Determine whether the use of this declaration is valid, without
7001 /// emitting diagnostics.
7002 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
7003 // A version of DiagnoseUseOfDecl that should be used if overload resolution
7004 // has been used to find this declaration, which means we don't have to bother
7005 // checking the trailing requires clause.
7006 bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) {
7007 return DiagnoseUseOfDecl(
7008 D, Locs: Loc, /*UnknownObjCClass=*/UnknownObjCClass: nullptr, /*ObjCPropertyAccess=*/ObjCPropertyAccess: false,
7009 /*AvoidPartialAvailabilityChecks=*/AvoidPartialAvailabilityChecks: false, /*ClassReceiver=*/ClassReceiver: nullptr,
7010 /*SkipTrailingRequiresClause=*/SkipTrailingRequiresClause: true);
7011 }
7012
7013 /// Determine whether the use of this declaration is valid, and
7014 /// emit any corresponding diagnostics.
7015 ///
7016 /// This routine diagnoses various problems with referencing
7017 /// declarations that can occur when using a declaration. For example,
7018 /// it might warn if a deprecated or unavailable declaration is being
7019 /// used, or produce an error (and return true) if a C++0x deleted
7020 /// function is being used.
7021 ///
7022 /// \returns true if there was an error (this declaration cannot be
7023 /// referenced), false otherwise.
7024 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
7025 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
7026 bool ObjCPropertyAccess = false,
7027 bool AvoidPartialAvailabilityChecks = false,
7028 ObjCInterfaceDecl *ClassReceiver = nullptr,
7029 bool SkipTrailingRequiresClause = false);
7030
7031 /// Emit a note explaining that this function is deleted.
7032 void NoteDeletedFunction(FunctionDecl *FD);
7033
7034 /// DiagnoseSentinelCalls - This routine checks whether a call or
7035 /// message-send is to a declaration with the sentinel attribute, and
7036 /// if so, it checks that the requirements of the sentinel are
7037 /// satisfied.
7038 void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
7039 ArrayRef<Expr *> Args);
7040
7041 void PushExpressionEvaluationContext(
7042 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
7043 ExpressionEvaluationContextRecord::ExpressionKind Type =
7044 ExpressionEvaluationContextRecord::EK_Other);
7045
7046 void PushExpressionEvaluationContextForFunction(
7047 ExpressionEvaluationContext NewContext, FunctionDecl *FD);
7048
7049 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
7050 void PushExpressionEvaluationContext(
7051 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
7052 ExpressionEvaluationContextRecord::ExpressionKind Type =
7053 ExpressionEvaluationContextRecord::EK_Other);
7054 void PopExpressionEvaluationContext();
7055
7056 void DiscardCleanupsInEvaluationContext();
7057
7058 ExprResult TransformToPotentiallyEvaluated(Expr *E);
7059 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
7060 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
7061
7062 /// Check whether E, which is either a discarded-value expression or an
7063 /// unevaluated operand, is a simple-assignment to a volatlie-qualified
7064 /// lvalue, and if so, remove it from the list of volatile-qualified
7065 /// assignments that we are going to warn are deprecated.
7066 void CheckUnusedVolatileAssignment(Expr *E);
7067
7068 ExprResult ActOnConstantExpression(ExprResult Res);
7069
7070 // Functions for marking a declaration referenced. These functions also
7071 // contain the relevant logic for marking if a reference to a function or
7072 // variable is an odr-use (in the C++11 sense). There are separate variants
7073 // for expressions referring to a decl; these exist because odr-use marking
7074 // needs to be delayed for some constant variables when we build one of the
7075 // named expressions.
7076 //
7077 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
7078 // should usually be true. This only needs to be set to false if the lack of
7079 // odr-use cannot be determined from the current context (for instance,
7080 // because the name denotes a virtual function and was written without an
7081 // explicit nested-name-specifier).
7082 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
7083
7084 /// Mark a function referenced, and check whether it is odr-used
7085 /// (C++ [basic.def.odr]p2, C99 6.9p3)
7086 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
7087 bool MightBeOdrUse = true);
7088
7089 /// Mark a variable referenced, and check whether it is odr-used
7090 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
7091 /// used directly for normal expressions referring to VarDecl.
7092 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
7093
7094 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7095 ///
7096 /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7097 /// be handled with care if the DeclRefExpr is not newly-created.
7098 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7099
7100 /// Perform reference-marking and odr-use handling for a MemberExpr.
7101 void MarkMemberReferenced(MemberExpr *E);
7102
7103 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7104 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
7105 void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc,
7106 unsigned CapturingScopeIndex);
7107
7108 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
7109 void CleanupVarDeclMarking();
7110
7111 /// Try to capture the given variable.
7112 ///
7113 /// \param Var The variable to capture.
7114 ///
7115 /// \param Loc The location at which the capture occurs.
7116 ///
7117 /// \param Kind The kind of capture, which may be implicit (for either a
7118 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7119 ///
7120 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7121 /// an explicit lambda capture.
7122 ///
7123 /// \param BuildAndDiagnose Whether we are actually supposed to add the
7124 /// captures or diagnose errors. If false, this routine merely check whether
7125 /// the capture can occur without performing the capture itself or complaining
7126 /// if the variable cannot be captured.
7127 ///
7128 /// \param CaptureType Will be set to the type of the field used to capture
7129 /// this variable in the innermost block or lambda. Only valid when the
7130 /// variable can be captured.
7131 ///
7132 /// \param DeclRefType Will be set to the type of a reference to the capture
7133 /// from within the current scope. Only valid when the variable can be
7134 /// captured.
7135 ///
7136 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7137 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7138 /// This is useful when enclosing lambdas must speculatively capture
7139 /// variables that may or may not be used in certain specializations of
7140 /// a nested generic lambda.
7141 ///
7142 /// \returns true if an error occurred (i.e., the variable cannot be
7143 /// captured) and false if the capture succeeded.
7144 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7145 TryCaptureKind Kind, SourceLocation EllipsisLoc,
7146 bool BuildAndDiagnose, QualType &CaptureType,
7147 QualType &DeclRefType,
7148 const unsigned *const FunctionScopeIndexToStopAt);
7149
7150 /// Try to capture the given variable.
7151 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7152 TryCaptureKind Kind = TryCaptureKind::Implicit,
7153 SourceLocation EllipsisLoc = SourceLocation());
7154
7155 /// Checks if the variable must be captured.
7156 bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc);
7157
7158 /// Given a variable, determine the type that a reference to that
7159 /// variable will have in the given scope.
7160 QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc);
7161
7162 /// Mark all of the declarations referenced within a particular AST node as
7163 /// referenced. Used when template instantiation instantiates a non-dependent
7164 /// type -- entities referenced by the type are now referenced.
7165 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
7166
7167 /// Mark any declarations that appear within this expression or any
7168 /// potentially-evaluated subexpressions as "referenced".
7169 ///
7170 /// \param SkipLocalVariables If true, don't mark local variables as
7171 /// 'referenced'.
7172 /// \param StopAt Subexpressions that we shouldn't recurse into.
7173 void MarkDeclarationsReferencedInExpr(Expr *E,
7174 bool SkipLocalVariables = false,
7175 ArrayRef<const Expr *> StopAt = {});
7176
7177 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7178 /// conversion.
7179 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7180
7181 /// Conditionally issue a diagnostic based on the statements's reachability
7182 /// analysis.
7183 ///
7184 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7185 /// the function body is parsed, and then do a basic reachability analysis to
7186 /// determine if the statement is reachable. If it is unreachable, the
7187 /// diagnostic will not be emitted.
7188 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7189 const PartialDiagnostic &PD);
7190
7191 /// Conditionally issue a diagnostic based on the current
7192 /// evaluation context.
7193 ///
7194 /// \param Statement If Statement is non-null, delay reporting the
7195 /// diagnostic until the function body is parsed, and then do a basic
7196 /// reachability analysis to determine if the statement is reachable.
7197 /// If it is unreachable, the diagnostic will not be emitted.
7198 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7199 const PartialDiagnostic &PD);
7200 /// Similar, but diagnostic is only produced if all the specified statements
7201 /// are reachable.
7202 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7203 const PartialDiagnostic &PD);
7204
7205 // Primary Expressions.
7206 SourceRange getExprRange(Expr *E) const;
7207
7208 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7209 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7210 bool HasTrailingLParen, bool IsAddressOfOperand,
7211 CorrectionCandidateCallback *CCC = nullptr,
7212 bool IsInlineAsmIdentifier = false);
7213
7214 /// Decomposes the given name into a DeclarationNameInfo, its location, and
7215 /// possibly a list of template arguments.
7216 ///
7217 /// If this produces template arguments, it is permitted to call
7218 /// DecomposeTemplateName.
7219 ///
7220 /// This actually loses a lot of source location information for
7221 /// non-standard name kinds; we should consider preserving that in
7222 /// some way.
7223 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7224 TemplateArgumentListInfo &Buffer,
7225 DeclarationNameInfo &NameInfo,
7226 const TemplateArgumentListInfo *&TemplateArgs);
7227
7228 /// Diagnose a lookup that found results in an enclosing class during error
7229 /// recovery. This usually indicates that the results were found in a
7230 /// dependent base class that could not be searched as part of a template
7231 /// definition. Always issues a diagnostic (though this may be only a warning
7232 /// in MS compatibility mode).
7233 ///
7234 /// Return \c true if the error is unrecoverable, or \c false if the caller
7235 /// should attempt to recover using these lookup results.
7236 bool DiagnoseDependentMemberLookup(const LookupResult &R);
7237
7238 /// Diagnose an empty lookup.
7239 ///
7240 /// \return false if new lookup candidates were found
7241 bool
7242 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7243 CorrectionCandidateCallback &CCC,
7244 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7245 ArrayRef<Expr *> Args = {},
7246 DeclContext *LookupCtx = nullptr);
7247
7248 /// If \p D cannot be odr-used in the current expression evaluation context,
7249 /// return a reason explaining why. Otherwise, return NOUR_None.
7250 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
7251
7252 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7253 SourceLocation Loc,
7254 const CXXScopeSpec *SS = nullptr);
7255 DeclRefExpr *
7256 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7257 const DeclarationNameInfo &NameInfo,
7258 const CXXScopeSpec *SS = nullptr,
7259 NamedDecl *FoundD = nullptr,
7260 SourceLocation TemplateKWLoc = SourceLocation(),
7261 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7262
7263 /// BuildDeclRefExpr - Build an expression that references a
7264 /// declaration that does not require a closure capture.
7265 DeclRefExpr *
7266 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7267 const DeclarationNameInfo &NameInfo,
7268 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7269 SourceLocation TemplateKWLoc = SourceLocation(),
7270 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7271
7272 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7273 bool HasTrailingLParen);
7274
7275 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7276 /// declaration name, generally during template instantiation.
7277 /// There's a large number of things which don't need to be done along
7278 /// this path.
7279 ExprResult BuildQualifiedDeclarationNameExpr(
7280 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7281 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7282
7283 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7284 bool NeedsADL,
7285 bool AcceptInvalidDecl = false);
7286
7287 /// Complete semantic analysis for a reference to the given declaration.
7288 ExprResult BuildDeclarationNameExpr(
7289 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7290 NamedDecl *FoundD = nullptr,
7291 const TemplateArgumentListInfo *TemplateArgs = nullptr,
7292 bool AcceptInvalidDecl = false);
7293
7294 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7295 // where Tokens representing function local predefined macros (such as
7296 // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7297 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7298
7299 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7300 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7301 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7302
7303 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7304
7305 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7306 ExprResult ActOnCharacterConstant(const Token &Tok,
7307 Scope *UDLScope = nullptr);
7308 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7309 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7310 MultiExprArg Val);
7311 ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7312 unsigned NumUserSpecifiedExprs,
7313 SourceLocation InitLoc,
7314 SourceLocation LParenLoc,
7315 SourceLocation RParenLoc);
7316
7317 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7318 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle
7319 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7320 /// from multiple tokens. However, the common case is that StringToks points
7321 /// to one string.
7322 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7323 Scope *UDLScope = nullptr);
7324
7325 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7326
7327 /// ControllingExprOrType is either an opaque pointer coming out of a
7328 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7329 /// into two so we don't take a void *, but that's awkward because one of
7330 /// the operands is either a ParsedType or an Expr *, which doesn't lend
7331 /// itself to generic code very well.
7332 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7333 SourceLocation DefaultLoc,
7334 SourceLocation RParenLoc,
7335 bool PredicateIsExpr,
7336 void *ControllingExprOrType,
7337 ArrayRef<ParsedType> ArgTypes,
7338 ArrayRef<Expr *> ArgExprs);
7339 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7340 /// it'd be better to split this interface into two so we don't take a
7341 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7342 /// isn't a trivial change.
7343 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7344 SourceLocation DefaultLoc,
7345 SourceLocation RParenLoc,
7346 bool PredicateIsExpr,
7347 void *ControllingExprOrType,
7348 ArrayRef<TypeSourceInfo *> Types,
7349 ArrayRef<Expr *> Exprs);
7350
7351 // Binary/Unary Operators. 'Tok' is the token for the operator.
7352 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7353 Expr *InputExpr, bool IsAfterAmp = false);
7354 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7355 Expr *Input, bool IsAfterAmp = false);
7356
7357 /// Unary Operators. 'Tok' is the token for the operator.
7358 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7359 Expr *Input, bool IsAfterAmp = false);
7360
7361 /// Determine whether the given expression is a qualified member
7362 /// access expression, of a form that could be turned into a pointer to member
7363 /// with the address-of operator.
7364 bool isQualifiedMemberAccess(Expr *E);
7365 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7366 const Expr *Op,
7367 const CXXMethodDecl *MD);
7368
7369 /// CheckAddressOfOperand - The operand of & must be either a function
7370 /// designator or an lvalue designating an object. If it is an lvalue, the
7371 /// object cannot be declared with storage class register or be a bit field.
7372 /// Note: The usual conversions are *not* applied to the operand of the &
7373 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7374 /// In C++, the operand might be an overloaded function name, in which case
7375 /// we allow the '&' but retain the overloaded-function type.
7376 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7377
7378 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7379 /// _Alignas(type-name) .
7380 /// [dcl.align] An alignment-specifier of the form
7381 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7382 ///
7383 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7384 /// _Alignas(_Alignof(type-name)).
7385 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7386 SourceLocation OpLoc, SourceRange R);
7387 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7388 SourceLocation OpLoc, SourceRange R);
7389
7390 /// Build a sizeof or alignof expression given a type operand.
7391 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7392 SourceLocation OpLoc,
7393 UnaryExprOrTypeTrait ExprKind,
7394 SourceRange R);
7395
7396 /// Build a sizeof or alignof expression given an expression
7397 /// operand.
7398 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7399 UnaryExprOrTypeTrait ExprKind);
7400
7401 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7402 /// expr and the same for @c alignof and @c __alignof
7403 /// Note that the ArgRange is invalid if isType is false.
7404 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7405 UnaryExprOrTypeTrait ExprKind,
7406 bool IsType, void *TyOrEx,
7407 SourceRange ArgRange);
7408
7409 /// Check for operands with placeholder types and complain if found.
7410 /// Returns ExprError() if there was an error and no recovery was possible.
7411 ExprResult CheckPlaceholderExpr(Expr *E);
7412 bool CheckVecStepExpr(Expr *E);
7413
7414 /// Check the constraints on expression operands to unary type expression
7415 /// and type traits.
7416 ///
7417 /// Completes any types necessary and validates the constraints on the operand
7418 /// expression. The logic mostly mirrors the type-based overload, but may
7419 /// modify the expression as it completes the type for that expression through
7420 /// template instantiation, etc.
7421 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
7422
7423 /// Check the constraints on operands to unary expression and type
7424 /// traits.
7425 ///
7426 /// This will complete any types necessary, and validate the various
7427 /// constraints on those operands.
7428 ///
7429 /// The UsualUnaryConversions() function is *not* called by this routine.
7430 /// C99 6.3.2.1p[2-4] all state:
7431 /// Except when it is the operand of the sizeof operator ...
7432 ///
7433 /// C++ [expr.sizeof]p4
7434 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7435 /// standard conversions are not applied to the operand of sizeof.
7436 ///
7437 /// This policy is followed for all of the unary trait expressions.
7438 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7439 SourceRange ExprRange,
7440 UnaryExprOrTypeTrait ExprKind,
7441 StringRef KWName);
7442
7443 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7444 tok::TokenKind Kind, Expr *Input);
7445
7446 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7447 MultiExprArg ArgExprs,
7448 SourceLocation RLoc);
7449 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7450 Expr *Idx, SourceLocation RLoc);
7451
7452 ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx,
7453 SourceLocation RBLoc);
7454
7455 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7456 Expr *ColumnIdx,
7457 SourceLocation RBLoc);
7458
7459 /// ConvertArgumentsForCall - Converts the arguments specified in
7460 /// Args/NumArgs to the parameter types of the function FDecl with
7461 /// function prototype Proto. Call is the call expression itself, and
7462 /// Fn is the function expression. For a C++ member function, this
7463 /// routine does not attempt to convert the object argument. Returns
7464 /// true if the call is ill-formed.
7465 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7466 const FunctionProtoType *Proto,
7467 ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7468 bool ExecConfig = false);
7469
7470 /// CheckStaticArrayArgument - If the given argument corresponds to a static
7471 /// array parameter, check that it is non-null, and that if it is formed by
7472 /// array-to-pointer decay, the underlying array is sufficiently large.
7473 ///
7474 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7475 /// the array type derivation, then for each call to the function, the value
7476 /// of the corresponding actual argument shall provide access to the first
7477 /// element of an array with at least as many elements as specified by the
7478 /// size expression.
7479 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7480 const Expr *ArgExpr);
7481
7482 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7483 /// This provides the location of the left/right parens and a list of comma
7484 /// locations.
7485 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7486 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7487 Expr *ExecConfig = nullptr);
7488
7489 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7490 /// This provides the location of the left/right parens and a list of comma
7491 /// locations.
7492 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7493 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7494 Expr *ExecConfig = nullptr,
7495 bool IsExecConfig = false,
7496 bool AllowRecovery = false);
7497
7498 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7499 // with the specified CallArgs
7500 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7501 MultiExprArg CallArgs);
7502
7503 using ADLCallKind = CallExpr::ADLCallKind;
7504
7505 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7506 /// i.e. an expression not of \p OverloadTy. The expression should
7507 /// unary-convert to an expression of function-pointer or
7508 /// block-pointer type.
7509 ///
7510 /// \param NDecl the declaration being called, if available
7511 ExprResult
7512 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7513 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7514 Expr *Config = nullptr, bool IsExecConfig = false,
7515 ADLCallKind UsesADL = ADLCallKind::NotADL);
7516
7517 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D,
7518 ParsedType &Ty, SourceLocation RParenLoc,
7519 Expr *CastExpr);
7520
7521 /// Prepares for a scalar cast, performing all the necessary stages
7522 /// except the final cast and returning the kind required.
7523 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
7524
7525 /// Build an altivec or OpenCL literal.
7526 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
7527 SourceLocation RParenLoc, Expr *E,
7528 TypeSourceInfo *TInfo);
7529
7530 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7531 /// the ParenListExpr into a sequence of comma binary operators.
7532 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
7533
7534 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7535 SourceLocation RParenLoc, Expr *InitExpr);
7536
7537 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
7538 TypeSourceInfo *TInfo,
7539 SourceLocation RParenLoc,
7540 Expr *LiteralExpr);
7541
7542 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7543 SourceLocation RBraceLoc);
7544
7545 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7546 SourceLocation RBraceLoc, bool IsExplicit);
7547
7548 /// Binary Operators. 'Tok' is the token for the operator.
7549 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind,
7550 Expr *LHSExpr, Expr *RHSExpr);
7551 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7552 Expr *LHSExpr, Expr *RHSExpr,
7553 bool ForFoldExpression = false);
7554
7555 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7556 /// operator @p Opc at location @c TokLoc. This routine only supports
7557 /// built-in operations; ActOnBinOp handles overloaded operators.
7558 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
7559 Expr *LHSExpr, Expr *RHSExpr,
7560 bool ForFoldExpression = false);
7561 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7562 UnresolvedSetImpl &Functions);
7563
7564 /// Look for instances where it is likely the comma operator is confused with
7565 /// another operator. There is an explicit list of acceptable expressions for
7566 /// the left hand side of the comma operator, otherwise emit a warning.
7567 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7568
7569 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7570 /// in the case of a the GNU conditional expr extension.
7571 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
7572 SourceLocation ColonLoc, Expr *CondExpr,
7573 Expr *LHSExpr, Expr *RHSExpr);
7574
7575 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7576 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
7577 LabelDecl *TheDecl);
7578
7579 void ActOnStartStmtExpr();
7580 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7581 SourceLocation RPLoc);
7582 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
7583 SourceLocation RPLoc, unsigned TemplateDepth);
7584 // Handle the final expression in a statement expression.
7585 ExprResult ActOnStmtExprResult(ExprResult E);
7586 void ActOnStmtExprError();
7587
7588 /// __builtin_offsetof(type, a.b[123][456].c)
7589 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
7590 TypeSourceInfo *TInfo,
7591 const Designation &Desig,
7592 SourceLocation RParenLoc);
7593 ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
7594 SourceLocation TypeLoc,
7595 ParsedType ParsedArgTy,
7596 const Designation &Desig,
7597 SourceLocation RParenLoc);
7598
7599 // __builtin_choose_expr(constExpr, expr1, expr2)
7600 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7601 Expr *LHSExpr, Expr *RHSExpr,
7602 SourceLocation RPLoc);
7603
7604 // __builtin_va_arg(expr, type)
7605 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
7606 SourceLocation RPLoc);
7607 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
7608 TypeSourceInfo *TInfo, SourceLocation RPLoc);
7609
7610 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7611 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7612 ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind,
7613 SourceLocation BuiltinLoc,
7614 SourceLocation RPLoc);
7615
7616 // #embed
7617 ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
7618 StringLiteral *BinaryData, StringRef FileName);
7619
7620 // Build a potentially resolved SourceLocExpr.
7621 ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
7622 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7623 DeclContext *ParentContext);
7624
7625 // __null
7626 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
7627
7628 bool CheckCaseExpression(Expr *E);
7629
7630 //===------------------------- "Block" Extension ------------------------===//
7631
7632 /// ActOnBlockStart - This callback is invoked when a block literal is
7633 /// started.
7634 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7635
7636 /// ActOnBlockArguments - This callback allows processing of block arguments.
7637 /// If there are no arguments, this is still invoked.
7638 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7639 Scope *CurScope);
7640
7641 /// ActOnBlockError - If there is an error parsing a block, this callback
7642 /// is invoked to pop the information about the block from the action impl.
7643 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7644
7645 /// ActOnBlockStmtExpr - This is called when the body of a block statement
7646 /// literal was successfully completed. ^(int x){...}
7647 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
7648 Scope *CurScope);
7649
7650 //===---------------------------- Clang Extensions ----------------------===//
7651
7652 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7653 /// provided arguments.
7654 ///
7655 /// __builtin_convertvector( value, dst type )
7656 ///
7657 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7658 SourceLocation BuiltinLoc,
7659 SourceLocation RParenLoc);
7660
7661 //===---------------------------- OpenCL Features -----------------------===//
7662
7663 /// Parse a __builtin_astype expression.
7664 ///
7665 /// __builtin_astype( value, dst type )
7666 ///
7667 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7668 SourceLocation BuiltinLoc,
7669 SourceLocation RParenLoc);
7670
7671 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7672 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
7673 SourceLocation BuiltinLoc,
7674 SourceLocation RParenLoc);
7675
7676 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7677 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
7678 ArrayRef<Expr *> SubExprs,
7679 QualType T = QualType());
7680
7681 /// Cast a base object to a member's actual type.
7682 ///
7683 /// There are two relevant checks:
7684 ///
7685 /// C++ [class.access.base]p7:
7686 ///
7687 /// If a class member access operator [...] is used to access a non-static
7688 /// data member or non-static member function, the reference is ill-formed
7689 /// if the left operand [...] cannot be implicitly converted to a pointer to
7690 /// the naming class of the right operand.
7691 ///
7692 /// C++ [expr.ref]p7:
7693 ///
7694 /// If E2 is a non-static data member or a non-static member function, the
7695 /// program is ill-formed if the class of which E2 is directly a member is
7696 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7697 ///
7698 /// Note that the latter check does not consider access; the access of the
7699 /// "real" base class is checked as appropriate when checking the access of
7700 /// the member name.
7701 ExprResult PerformObjectMemberConversion(Expr *From,
7702 NestedNameSpecifier Qualifier,
7703 NamedDecl *FoundDecl,
7704 NamedDecl *Member);
7705
7706 /// CheckCallReturnType - Checks that a call expression's return type is
7707 /// complete. Returns true on failure. The location passed in is the location
7708 /// that best represents the call.
7709 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7710 CallExpr *CE, FunctionDecl *FD);
7711
7712 /// Emit a warning for all pending noderef expressions that we recorded.
7713 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
7714
7715 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
7716
7717 /// Instantiate or parse a C++ default argument expression as necessary.
7718 /// Return true on error.
7719 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7720 ParmVarDecl *Param, Expr *Init = nullptr,
7721 bool SkipImmediateInvocations = true);
7722
7723 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7724 /// the default expr if needed.
7725 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7726 ParmVarDecl *Param, Expr *Init = nullptr);
7727
7728 /// Wrap the expression in a ConstantExpr if it is a potential immediate
7729 /// invocation.
7730 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
7731
7732 void MarkExpressionAsImmediateEscalating(Expr *E);
7733
7734 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7735 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7736
7737 /// Abstract base class used for diagnosing integer constant
7738 /// expression violations.
7739 class VerifyICEDiagnoser {
7740 public:
7741 bool Suppress;
7742
7743 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) {}
7744
7745 virtual SemaDiagnosticBuilder
7746 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7747 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7748 SourceLocation Loc) = 0;
7749 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
7750 virtual ~VerifyICEDiagnoser() {}
7751 };
7752
7753 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7754 /// and reports the appropriate diagnostics. Returns false on success.
7755 /// Can optionally return the value of the expression.
7756 ExprResult
7757 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7758 VerifyICEDiagnoser &Diagnoser,
7759 AllowFoldKind CanFold = AllowFoldKind::No);
7760 ExprResult
7761 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7762 unsigned DiagID,
7763 AllowFoldKind CanFold = AllowFoldKind::No);
7764 ExprResult
7765 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7766 AllowFoldKind CanFold = AllowFoldKind::No);
7767 ExprResult
7768 VerifyIntegerConstantExpression(Expr *E,
7769 AllowFoldKind CanFold = AllowFoldKind::No) {
7770 return VerifyIntegerConstantExpression(E, Result: nullptr, CanFold);
7771 }
7772
7773 /// DiagnoseAssignmentAsCondition - Given that an expression is
7774 /// being used as a boolean condition, warn if it's an assignment.
7775 void DiagnoseAssignmentAsCondition(Expr *E);
7776
7777 /// Redundant parentheses over an equality comparison can indicate
7778 /// that the user intended an assignment used as condition.
7779 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7780
7781 class FullExprArg {
7782 public:
7783 FullExprArg() : E(nullptr) {}
7784 FullExprArg(Sema &actions) : E(nullptr) {}
7785
7786 ExprResult release() { return E; }
7787
7788 Expr *get() const { return E; }
7789
7790 Expr *operator->() { return E; }
7791
7792 private:
7793 // FIXME: No need to make the entire Sema class a friend when it's just
7794 // Sema::MakeFullExpr that needs access to the constructor below.
7795 friend class Sema;
7796
7797 explicit FullExprArg(Expr *expr) : E(expr) {}
7798
7799 Expr *E;
7800 };
7801
7802 FullExprArg MakeFullExpr(Expr *Arg) {
7803 return MakeFullExpr(Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation());
7804 }
7805 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
7806 return FullExprArg(
7807 ActOnFinishFullExpr(Expr: Arg, CC, /*DiscardedValue*/ DiscardedValue: false).get());
7808 }
7809 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
7810 ExprResult FE =
7811 ActOnFinishFullExpr(Expr: Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation(),
7812 /*DiscardedValue*/ DiscardedValue: true);
7813 return FullExprArg(FE.get());
7814 }
7815
7816 class ConditionResult {
7817 Decl *ConditionVar;
7818 ExprResult Condition;
7819 bool Invalid;
7820 std::optional<bool> KnownValue;
7821
7822 friend class Sema;
7823 ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
7824 bool IsConstexpr)
7825 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
7826 if (IsConstexpr && Condition.get()) {
7827 if (std::optional<llvm::APSInt> Val =
7828 Condition.get()->getIntegerConstantExpr(Ctx: S.Context)) {
7829 KnownValue = !!(*Val);
7830 }
7831 }
7832 }
7833 explicit ConditionResult(bool Invalid)
7834 : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
7835 KnownValue(std::nullopt) {}
7836
7837 public:
7838 ConditionResult() : ConditionResult(false) {}
7839 bool isInvalid() const { return Invalid; }
7840 std::pair<VarDecl *, Expr *> get() const {
7841 return std::make_pair(x: cast_or_null<VarDecl>(Val: ConditionVar),
7842 y: Condition.get());
7843 }
7844 std::optional<bool> getKnownValue() const { return KnownValue; }
7845 };
7846 static ConditionResult ConditionError() { return ConditionResult(true); }
7847
7848 /// CheckBooleanCondition - Diagnose problems involving the use of
7849 /// the given expression as a boolean condition (e.g. in an if
7850 /// statement). Also performs the standard function and array
7851 /// decays, possibly changing the input variable.
7852 ///
7853 /// \param Loc - A location associated with the condition, e.g. the
7854 /// 'if' keyword.
7855 /// \return true iff there were any errors
7856 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
7857 bool IsConstexpr = false);
7858
7859 enum class ConditionKind {
7860 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
7861 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
7862 Switch ///< An integral condition for a 'switch' statement.
7863 };
7864
7865 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
7866 ConditionKind CK, bool MissingOK = false);
7867
7868 QualType CheckConditionalOperands( // C99 6.5.15
7869 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
7870 ExprObjectKind &OK, SourceLocation QuestionLoc);
7871
7872 /// Emit a specialized diagnostic when one expression is a null pointer
7873 /// constant and the other is not a pointer. Returns true if a diagnostic is
7874 /// emitted.
7875 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7876 SourceLocation QuestionLoc);
7877
7878 /// type checking for vector binary operators.
7879 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7880 SourceLocation Loc, bool IsCompAssign,
7881 bool AllowBothBool, bool AllowBoolConversion,
7882 bool AllowBoolOperation, bool ReportInvalid);
7883
7884 /// Return a signed ext_vector_type that is of identical size and number of
7885 /// elements. For floating point vectors, return an integer type of identical
7886 /// size and number of elements. In the non ext_vector_type case, search from
7887 /// the largest type to the smallest type to avoid cases where long long ==
7888 /// long, where long gets picked over long long.
7889 QualType GetSignedVectorType(QualType V);
7890 QualType GetSignedSizelessVectorType(QualType V);
7891
7892 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7893 /// operates on extended vector types. Instead of producing an IntTy result,
7894 /// like a scalar comparison, a vector comparison produces a vector of integer
7895 /// types.
7896 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7897 SourceLocation Loc,
7898 BinaryOperatorKind Opc);
7899 QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7900 SourceLocation Loc,
7901 BinaryOperatorKind Opc);
7902 QualType CheckMatrixCompareOperands(ExprResult &LHS, ExprResult &RHS,
7903 SourceLocation Loc,
7904 BinaryOperatorKind Opc);
7905 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7906 SourceLocation Loc,
7907 BinaryOperatorKind Opc);
7908 QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7909 SourceLocation Loc,
7910 BinaryOperatorKind Opc);
7911 // type checking for sizeless vector binary operators.
7912 QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
7913 SourceLocation Loc, bool IsCompAssign,
7914 ArithConvKind OperationKind);
7915
7916 /// Type checking for matrix binary operators.
7917 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
7918 SourceLocation Loc,
7919 bool IsCompAssign);
7920 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
7921 SourceLocation Loc, bool IsCompAssign);
7922
7923 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
7924 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
7925 /// VLST) allowed?
7926 ///
7927 /// This will also return false if the two given types do not make sense from
7928 /// the perspective of SVE bitcasts.
7929 bool isValidSveBitcast(QualType srcType, QualType destType);
7930
7931 /// Are the two types matrix types and do they have the same dimensions i.e.
7932 /// do they have the same number of rows and the same number of columns?
7933 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
7934
7935 bool areVectorTypesSameSize(QualType srcType, QualType destType);
7936
7937 /// Are the two types lax-compatible vector types? That is, given
7938 /// that one of them is a vector, do they have equal storage sizes,
7939 /// where the storage size is the number of elements times the element
7940 /// size?
7941 ///
7942 /// This will also return false if either of the types is neither a
7943 /// vector nor a real type.
7944 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
7945
7946 /// Is this a legal conversion between two types, one of which is
7947 /// known to be a vector type?
7948 bool isLaxVectorConversion(QualType srcType, QualType destType);
7949
7950 // This returns true if at least one of the types is an altivec vector.
7951 bool anyAltivecTypes(QualType srcType, QualType destType);
7952
7953 // type checking C++ declaration initializers (C++ [dcl.init]).
7954
7955 /// Check a cast of an unknown-any type. We intentionally only
7956 /// trigger this for C-style casts.
7957 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
7958 Expr *CastExpr, CastKind &CastKind,
7959 ExprValueKind &VK, CXXCastPath &Path);
7960
7961 /// Force an expression with unknown-type to an expression of the
7962 /// given type.
7963 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
7964
7965 /// Type-check an expression that's being passed to an
7966 /// __unknown_anytype parameter.
7967 ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result,
7968 QualType &paramType);
7969
7970 // CheckMatrixCast - Check type constraints for matrix casts.
7971 // We allow casting between matrixes of the same dimensions i.e. when they
7972 // have the same number of rows and column. Returns true if the cast is
7973 // invalid.
7974 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7975 CastKind &Kind);
7976
7977 // CheckVectorCast - check type constraints for vectors.
7978 // Since vectors are an extension, there are no C standard reference for this.
7979 // We allow casting between vectors and integer datatypes of the same size.
7980 // returns true if the cast is invalid
7981 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7982 CastKind &Kind);
7983
7984 /// Prepare `SplattedExpr` for a vector splat operation, adding
7985 /// implicit casts if necessary.
7986 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
7987
7988 /// Prepare `SplattedExpr` for a matrix splat operation, adding
7989 /// implicit casts if necessary.
7990 ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr);
7991
7992 // CheckExtVectorCast - check type constraints for extended vectors.
7993 // Since vectors are an extension, there are no C standard reference for this.
7994 // We allow casting between vectors and integer datatypes of the same size,
7995 // or vectors and the element type of that vector.
7996 // returns the cast expr
7997 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
7998 CastKind &Kind);
7999
8000 QualType PreferredConditionType(ConditionKind K) const {
8001 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
8002 }
8003
8004 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
8005 // functions and arrays to their respective pointers (C99 6.3.2.1), and
8006 // promotes floating-piont types according to the language semantics.
8007 ExprResult UsualUnaryConversions(Expr *E);
8008
8009 // UsualUnaryFPConversions - promotes floating-point types according to the
8010 // current language semantics.
8011 ExprResult UsualUnaryFPConversions(Expr *E);
8012
8013 /// CallExprUnaryConversions - a special case of an unary conversion
8014 /// performed on a function designator of a call expression.
8015 ExprResult CallExprUnaryConversions(Expr *E);
8016
8017 // DefaultFunctionArrayConversion - converts functions and arrays
8018 // to their respective pointers (C99 6.3.2.1).
8019 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8020
8021 // DefaultFunctionArrayLvalueConversion - converts functions and
8022 // arrays to their respective pointers and performs the
8023 // lvalue-to-rvalue conversion.
8024 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8025 bool Diagnose = true);
8026
8027 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8028 // the operand. This function is a no-op if the operand has a function type
8029 // or an array type.
8030 ExprResult DefaultLvalueConversion(Expr *E);
8031
8032 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8033 // do not have a prototype. Integer promotions are performed on each
8034 // argument, and arguments that have type float are promoted to double.
8035 ExprResult DefaultArgumentPromotion(Expr *E);
8036
8037 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8038 const FunctionProtoType *Proto,
8039 Expr *Fn);
8040
8041 /// Determine the degree of POD-ness for an expression.
8042 /// Incomplete types are considered POD, since this check can be performed
8043 /// when we're in an unevaluated context.
8044 VarArgKind isValidVarArgType(const QualType &Ty);
8045
8046 /// Check to see if the given expression is a valid argument to a variadic
8047 /// function, issuing a diagnostic if not.
8048 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8049
8050 /// GatherArgumentsForCall - Collector argument expressions for various
8051 /// form of call prototypes.
8052 bool GatherArgumentsForCall(
8053 SourceLocation CallLoc, FunctionDecl *FDecl,
8054 const FunctionProtoType *Proto, unsigned FirstParam,
8055 ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs,
8056 VariadicCallType CallType = VariadicCallType::DoesNotApply,
8057 bool AllowExplicit = false, bool IsListInitialization = false);
8058
8059 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8060 // will create a runtime trap if the resulting type is not a POD type.
8061 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8062 FunctionDecl *FDecl);
8063
8064 // Check that the usual arithmetic conversions can be performed on this pair
8065 // of expressions that might be of enumeration type.
8066 void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc,
8067 ArithConvKind ACK);
8068
8069 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8070 // operands and then handles various conversions that are common to binary
8071 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8072 // routine returns the first non-arithmetic type found. The client is
8073 // responsible for emitting appropriate error diagnostics.
8074 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8075 SourceLocation Loc, ArithConvKind ACK);
8076
8077 bool IsAssignConvertCompatible(AssignConvertType ConvTy) {
8078 switch (ConvTy) {
8079 default:
8080 return false;
8081 case AssignConvertType::Compatible:
8082 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
8083 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
8084 return true;
8085 }
8086 llvm_unreachable("impossible");
8087 }
8088
8089 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8090 /// assignment conversion type specified by ConvTy. This returns true if the
8091 /// conversion was invalid or false if the conversion was accepted.
8092 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc,
8093 QualType DstType, QualType SrcType,
8094 Expr *SrcExpr, AssignmentAction Action,
8095 bool *Complained = nullptr);
8096
8097 /// CheckAssignmentConstraints - Perform type checking for assignment,
8098 /// argument passing, variable initialization, and function return values.
8099 /// C99 6.5.16.
8100 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8101 QualType LHSType,
8102 QualType RHSType);
8103
8104 /// Check assignment constraints and optionally prepare for a conversion of
8105 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8106 /// is true.
8107 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8108 ExprResult &RHS, CastKind &Kind,
8109 bool ConvertRHS = true);
8110
8111 /// Check assignment constraints for an assignment of RHS to LHSType.
8112 ///
8113 /// \param LHSType The destination type for the assignment.
8114 /// \param RHS The source expression for the assignment.
8115 /// \param Diagnose If \c true, diagnostics may be produced when checking
8116 /// for assignability. If a diagnostic is produced, \p RHS will be
8117 /// set to ExprError(). Note that this function may still return
8118 /// without producing a diagnostic, even for an invalid assignment.
8119 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8120 /// in an audited Core Foundation API and does not need to be checked
8121 /// for ARC retain issues.
8122 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8123 /// conversions necessary to perform the assignment. If \c false,
8124 /// \p Diagnose must also be \c false.
8125 AssignConvertType CheckSingleAssignmentConstraints(
8126 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8127 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8128
8129 // If the lhs type is a transparent union, check whether we
8130 // can initialize the transparent union with the given expression.
8131 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8132 ExprResult &RHS);
8133
8134 /// the following "Check" methods will return a valid/converted QualType
8135 /// or a null QualType (indicating an error diagnostic was issued).
8136
8137 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8138 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8139 ExprResult &RHS);
8140
8141 /// Diagnose cases where a scalar was implicitly converted to a vector and
8142 /// diagnose the underlying types. Otherwise, diagnose the error
8143 /// as invalid vector logical operands for non-C++ cases.
8144 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8145 ExprResult &RHS);
8146
8147 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8148 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8149 BinaryOperatorKind Opc);
8150 QualType CheckRemainderOperands( // C99 6.5.5
8151 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8152 bool IsCompAssign = false);
8153 QualType CheckAdditionOperands( // C99 6.5.6
8154 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8155 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8156 QualType CheckSubtractionOperands( // C99 6.5.6
8157 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8158 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8159 QualType CheckShiftOperands( // C99 6.5.7
8160 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8161 BinaryOperatorKind Opc, bool IsCompAssign = false);
8162 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
8163 QualType CheckCompareOperands( // C99 6.5.8/9
8164 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8165 BinaryOperatorKind Opc);
8166 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8167 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8168 BinaryOperatorKind Opc);
8169 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8170 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8171 BinaryOperatorKind Opc);
8172 // CheckAssignmentOperands is used for both simple and compound assignment.
8173 // For simple assignment, pass both expressions and a null converted type.
8174 // For compound assignment, pass both expressions and the converted type.
8175 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8176 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8177 BinaryOperatorKind Opc);
8178
8179 /// To be used for checking whether the arguments being passed to
8180 /// function exceeds the number of parameters expected for it.
8181 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8182 bool PartialOverloading = false) {
8183 // We check whether we're just after a comma in code-completion.
8184 if (NumArgs > 0 && PartialOverloading)
8185 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8186 return NumArgs > NumParams;
8187 }
8188
8189 /// Whether the AST is currently being rebuilt to correct immediate
8190 /// invocations. Immediate invocation candidates and references to consteval
8191 /// functions aren't tracked when this is set.
8192 bool RebuildingImmediateInvocation = false;
8193
8194 bool isAlwaysConstantEvaluatedContext() const {
8195 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8196 return (Ctx.isConstantEvaluated() || isConstantEvaluatedOverride) &&
8197 !Ctx.InConditionallyConstantEvaluateContext;
8198 }
8199
8200 /// Determines whether we are currently in a context that
8201 /// is not evaluated as per C++ [expr] p5.
8202 bool isUnevaluatedContext() const {
8203 return currentEvaluationContext().isUnevaluated();
8204 }
8205
8206 bool isImmediateFunctionContext() const {
8207 return currentEvaluationContext().isImmediateFunctionContext();
8208 }
8209
8210 bool isInLifetimeExtendingContext() const {
8211 return currentEvaluationContext().InLifetimeExtendingContext;
8212 }
8213
8214 bool needsRebuildOfDefaultArgOrInit() const {
8215 return currentEvaluationContext().RebuildDefaultArgOrDefaultInit;
8216 }
8217
8218 bool isCheckingDefaultArgumentOrInitializer() const {
8219 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8220 return (Ctx.Context ==
8221 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) ||
8222 Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer;
8223 }
8224
8225 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8226 InnermostDeclarationWithDelayedImmediateInvocations() const {
8227 assert(!ExprEvalContexts.empty() &&
8228 "Must be in an expression evaluation context");
8229 for (const auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8230 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8231 Ctx.DelayedDefaultInitializationContext)
8232 return Ctx.DelayedDefaultInitializationContext;
8233 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8234 Ctx.isUnevaluated())
8235 break;
8236 }
8237 return std::nullopt;
8238 }
8239
8240 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8241 OutermostDeclarationWithDelayedImmediateInvocations() const {
8242 assert(!ExprEvalContexts.empty() &&
8243 "Must be in an expression evaluation context");
8244 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8245 for (auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8246 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8247 !Ctx.DelayedDefaultInitializationContext && Res)
8248 break;
8249 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8250 Ctx.isUnevaluated())
8251 break;
8252 Res = Ctx.DelayedDefaultInitializationContext;
8253 }
8254 return Res;
8255 }
8256
8257 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8258 /// SelfAssigned when inside a CXXMethodDecl.
8259 const FieldDecl *
8260 getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
8261
8262 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
8263
8264 template <typename... Ts>
8265 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
8266 const Ts &...Args) {
8267 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8268 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8269 }
8270
8271 template <typename... Ts>
8272 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8273 const Ts &...Args) {
8274 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8275 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
8276 }
8277
8278 /// Abstract class used to diagnose incomplete types.
8279 struct TypeDiagnoser {
8280 TypeDiagnoser() {}
8281
8282 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
8283 virtual ~TypeDiagnoser() {}
8284 };
8285
8286 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8287 protected:
8288 unsigned DiagID;
8289 std::tuple<const Ts &...> Args;
8290
8291 template <std::size_t... Is>
8292 void emit(const SemaDiagnosticBuilder &DB,
8293 std::index_sequence<Is...>) const {
8294 // Apply all tuple elements to the builder in order.
8295 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8296 (void)Dummy;
8297 }
8298
8299 public:
8300 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8301 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8302 assert(DiagID != 0 && "no diagnostic for type diagnoser");
8303 }
8304
8305 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8306 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8307 emit(DB, std::index_sequence_for<Ts...>());
8308 DB << T;
8309 }
8310 };
8311
8312 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8313 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8314 /// For example, a diagnostic with no other parameters would generally have
8315 /// the form "...%select{incomplete|sizeless}0 type %1...".
8316 template <typename... Ts>
8317 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
8318 public:
8319 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8320 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8321
8322 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8323 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8324 this->emit(DB, std::index_sequence_for<Ts...>());
8325 DB << T->isSizelessType() << T;
8326 }
8327 };
8328
8329 /// Check an argument list for placeholders that we won't try to
8330 /// handle later.
8331 bool CheckArgsForPlaceholders(MultiExprArg args);
8332
8333 /// The C++ "std::source_location::__impl" struct, defined in
8334 /// \<source_location>.
8335 RecordDecl *StdSourceLocationImplDecl;
8336
8337 /// A stack of expression evaluation contexts.
8338 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
8339
8340 // Set of failed immediate invocations to avoid double diagnosing.
8341 llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
8342
8343 /// List of SourceLocations where 'self' is implicitly retained inside a
8344 /// block.
8345 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
8346 ImplicitlyRetainedSelfLocs;
8347
8348 /// Do an explicit extend of the given block pointer if we're in ARC.
8349 void maybeExtendBlockObject(ExprResult &E);
8350
8351 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8352 SourceLocation LocationOfExcessPrecisionNotSatisfied;
8353 void DiagnosePrecisionLossInComplexDivision();
8354
8355private:
8356 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8357
8358 /// Methods for marking which expressions involve dereferencing a pointer
8359 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8360 /// they are parsed, meaning that a noderef pointer may not be accessed. For
8361 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8362 /// `*p`, but need to check that `address of` is called on it. This requires
8363 /// keeping a container of all pending expressions and checking if the address
8364 /// of them are eventually taken.
8365 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8366 void CheckAddressOfNoDeref(const Expr *E);
8367
8368 ///@}
8369
8370 //
8371 //
8372 // -------------------------------------------------------------------------
8373 //
8374 //
8375
8376 /// \name C++ Expressions
8377 /// Implementations are in SemaExprCXX.cpp
8378 ///@{
8379
8380public:
8381 /// The C++ "std::bad_alloc" class, which is defined by the C++
8382 /// standard library.
8383 LazyDeclPtr StdBadAlloc;
8384
8385 /// The C++ "std::align_val_t" enum class, which is defined by the C++
8386 /// standard library.
8387 LazyDeclPtr StdAlignValT;
8388
8389 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
8390 RecordDecl *CXXTypeInfoDecl;
8391
8392 /// A flag to remember whether the implicit forms of operator new and delete
8393 /// have been declared.
8394 bool GlobalNewDeleteDeclared;
8395
8396 /// Delete-expressions to be analyzed at the end of translation unit
8397 ///
8398 /// This list contains class members, and locations of delete-expressions
8399 /// that could not be proven as to whether they mismatch with new-expression
8400 /// used in initializer of the field.
8401 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8402
8403 /// Handle the result of the special case name lookup for inheriting
8404 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8405 /// constructor names in member using declarations, even if 'X' is not the
8406 /// name of the corresponding type.
8407 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
8408 SourceLocation NameLoc,
8409 const IdentifierInfo &Name);
8410
8411 ParsedType getConstructorName(const IdentifierInfo &II,
8412 SourceLocation NameLoc, Scope *S,
8413 CXXScopeSpec &SS, bool EnteringContext);
8414 ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc,
8415 Scope *S, CXXScopeSpec &SS,
8416 ParsedType ObjectType, bool EnteringContext);
8417
8418 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
8419 ParsedType ObjectType);
8420
8421 /// Build a C++ typeid expression with a type operand.
8422 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8423 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8424
8425 /// Build a C++ typeid expression with an expression operand.
8426 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8427 Expr *Operand, SourceLocation RParenLoc);
8428
8429 /// ActOnCXXTypeid - Parse typeid( something ).
8430 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
8431 bool isType, void *TyOrExpr,
8432 SourceLocation RParenLoc);
8433
8434 /// Build a Microsoft __uuidof expression with a type operand.
8435 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8436 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8437
8438 /// Build a Microsoft __uuidof expression with an expression operand.
8439 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8440 Expr *Operand, SourceLocation RParenLoc);
8441
8442 /// ActOnCXXUuidof - Parse __uuidof( something ).
8443 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
8444 bool isType, void *TyOrExpr,
8445 SourceLocation RParenLoc);
8446
8447 //// ActOnCXXThis - Parse 'this' pointer.
8448 ExprResult ActOnCXXThis(SourceLocation Loc);
8449
8450 /// Check whether the type of 'this' is valid in the current context.
8451 bool CheckCXXThisType(SourceLocation Loc, QualType Type);
8452
8453 /// Build a CXXThisExpr and mark it referenced in the current context.
8454 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8455 void MarkThisReferenced(CXXThisExpr *This);
8456
8457 /// Try to retrieve the type of the 'this' pointer.
8458 ///
8459 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8460 QualType getCurrentThisType();
8461
8462 /// When non-NULL, the C++ 'this' expression is allowed despite the
8463 /// current context not being a non-static member function. In such cases,
8464 /// this provides the type used for 'this'.
8465 QualType CXXThisTypeOverride;
8466
8467 /// RAII object used to temporarily allow the C++ 'this' expression
8468 /// to be used, with the given qualifiers on the current class type.
8469 class CXXThisScopeRAII {
8470 Sema &S;
8471 QualType OldCXXThisTypeOverride;
8472 bool Enabled;
8473
8474 public:
8475 /// Introduce a new scope where 'this' may be allowed (when enabled),
8476 /// using the given declaration (which is either a class template or a
8477 /// class) along with the given qualifiers.
8478 /// along with the qualifiers placed on '*this'.
8479 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8480 bool Enabled = true);
8481
8482 ~CXXThisScopeRAII();
8483 CXXThisScopeRAII(const CXXThisScopeRAII &) = delete;
8484 CXXThisScopeRAII &operator=(const CXXThisScopeRAII &) = delete;
8485 };
8486
8487 /// Make sure the value of 'this' is actually available in the current
8488 /// context, if it is a potentially evaluated context.
8489 ///
8490 /// \param Loc The location at which the capture of 'this' occurs.
8491 ///
8492 /// \param Explicit Whether 'this' is explicitly captured in a lambda
8493 /// capture list.
8494 ///
8495 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8496 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8497 /// This is useful when enclosing lambdas must speculatively capture
8498 /// 'this' that may or may not be used in certain specializations of
8499 /// a nested generic lambda (depending on whether the name resolves to
8500 /// a non-static member function or a static function).
8501 /// \return returns 'true' if failed, 'false' if success.
8502 bool CheckCXXThisCapture(
8503 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8504 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8505 bool ByCopy = false);
8506
8507 /// Determine whether the given type is the type of *this that is used
8508 /// outside of the body of a member function for a type that is currently
8509 /// being defined.
8510 bool isThisOutsideMemberFunctionBody(QualType BaseType);
8511
8512 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8513 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
8514
8515 /// Build a boolean-typed literal expression.
8516 ExprResult BuildBoolLiteral(SourceLocation Loc, bool Value);
8517
8518 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8519 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
8520
8521 //// ActOnCXXThrow - Parse throw expressions.
8522 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
8523 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
8524 bool IsThrownVarInScope);
8525
8526 /// CheckCXXThrowOperand - Validate the operand of a throw.
8527 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8528
8529 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8530 /// Can be interpreted either as function-style casting ("int(x)")
8531 /// or class type construction ("ClassType(x,y,z)")
8532 /// or creation of a value-initialized type ("int()").
8533 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
8534 SourceLocation LParenOrBraceLoc,
8535 MultiExprArg Exprs,
8536 SourceLocation RParenOrBraceLoc,
8537 bool ListInitialization);
8538
8539 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
8540 SourceLocation LParenLoc,
8541 MultiExprArg Exprs,
8542 SourceLocation RParenLoc,
8543 bool ListInitialization);
8544
8545 /// Parsed a C++ 'new' expression (C++ 5.3.4).
8546 ///
8547 /// E.g.:
8548 /// @code new (memory) int[size][4] @endcode
8549 /// or
8550 /// @code ::new Foo(23, "hello") @endcode
8551 ///
8552 /// \param StartLoc The first location of the expression.
8553 /// \param UseGlobal True if 'new' was prefixed with '::'.
8554 /// \param PlacementLParen Opening paren of the placement arguments.
8555 /// \param PlacementArgs Placement new arguments.
8556 /// \param PlacementRParen Closing paren of the placement arguments.
8557 /// \param TypeIdParens If the type is in parens, the source range.
8558 /// \param D The type to be allocated, as well as array dimensions.
8559 /// \param Initializer The initializing expression or initializer-list, or
8560 /// null if there is none.
8561 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8562 SourceLocation PlacementLParen,
8563 MultiExprArg PlacementArgs,
8564 SourceLocation PlacementRParen,
8565 SourceRange TypeIdParens, Declarator &D,
8566 Expr *Initializer);
8567 ExprResult
8568 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8569 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8570 SourceRange TypeIdParens, QualType AllocType,
8571 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8572 SourceRange DirectInitRange, Expr *Initializer);
8573
8574 /// Determine whether \p FD is an aligned allocation or deallocation
8575 /// function that is unavailable.
8576 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
8577
8578 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8579 /// function that is unavailable.
8580 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
8581 SourceLocation Loc);
8582
8583 /// Checks that a type is suitable as the allocated type
8584 /// in a new-expression.
8585 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8586 SourceRange R);
8587
8588 /// Finds the overloads of operator new and delete that are appropriate
8589 /// for the allocation.
8590 std::optional<ResolvedAllocation> FindAllocationFunctions(
8591 SourceLocation StartLoc, SourceRange Range,
8592 AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope,
8593 QualType AllocType, bool IsArray, const ImplicitAllocationParameters &IAP,
8594 MultiExprArg PlaceArgs, bool Diagnose = true);
8595
8596 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8597 /// delete. These are:
8598 /// @code
8599 /// // C++03:
8600 /// void* operator new(std::size_t) throw(std::bad_alloc);
8601 /// void* operator new[](std::size_t) throw(std::bad_alloc);
8602 /// void operator delete(void *) throw();
8603 /// void operator delete[](void *) throw();
8604 /// // C++11:
8605 /// void* operator new(std::size_t);
8606 /// void* operator new[](std::size_t);
8607 /// void operator delete(void *) noexcept;
8608 /// void operator delete[](void *) noexcept;
8609 /// // C++1y:
8610 /// void* operator new(std::size_t);
8611 /// void* operator new[](std::size_t);
8612 /// void operator delete(void *) noexcept;
8613 /// void operator delete[](void *) noexcept;
8614 /// void operator delete(void *, std::size_t) noexcept;
8615 /// void operator delete[](void *, std::size_t) noexcept;
8616 /// @endcode
8617 /// Note that the placement and nothrow forms of new are *not* implicitly
8618 /// declared. Their use requires including \<new\>.
8619 void DeclareGlobalNewDelete();
8620 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
8621 ArrayRef<QualType> Params);
8622
8623 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
8624 DeclarationName Name, FunctionDecl *&Operator,
8625 ImplicitDeallocationParameters,
8626 bool Diagnose = true);
8627 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
8628 ImplicitDeallocationParameters,
8629 DeclarationName Name,
8630 bool Diagnose = true);
8631 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
8632 CXXRecordDecl *RD,
8633 bool Diagnose,
8634 bool LookForGlobal,
8635 DeclarationName Name);
8636
8637 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8638 /// @code ::delete ptr; @endcode
8639 /// or
8640 /// @code delete [] ptr; @endcode
8641 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8642 bool ArrayForm, Expr *Operand);
8643 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
8644 bool IsDelete, bool CallCanBeVirtual,
8645 bool WarnOnNonAbstractTypes,
8646 SourceLocation DtorLoc);
8647
8648 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
8649 Expr *Operand, SourceLocation RParen);
8650 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8651 SourceLocation RParen);
8652
8653 ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base,
8654 SourceLocation OpLoc,
8655 tok::TokenKind OpKind,
8656 ParsedType &ObjectType,
8657 bool &MayBePseudoDestructor);
8658
8659 ExprResult BuildPseudoDestructorExpr(
8660 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8661 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8662 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8663
8664 ExprResult ActOnPseudoDestructorExpr(
8665 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8666 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8667 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8668
8669 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
8670 SourceLocation OpLoc,
8671 tok::TokenKind OpKind,
8672 SourceLocation TildeLoc,
8673 const DeclSpec &DS);
8674
8675 /// MaybeCreateExprWithCleanups - If the current full-expression
8676 /// requires any cleanups, surround it with a ExprWithCleanups node.
8677 /// Otherwise, just returns the passed-in expression.
8678 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
8679 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
8680 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
8681
8682 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8683 return ActOnFinishFullExpr(
8684 Expr, CC: Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8685 }
8686 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
8687 bool DiscardedValue, bool IsConstexpr = false,
8688 bool IsTemplateArgument = false);
8689 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
8690
8691 /// Process the expression contained within a decltype. For such expressions,
8692 /// certain semantic checks on temporaries are delayed until this point, and
8693 /// are omitted for the 'topmost' call in the decltype expression. If the
8694 /// topmost call bound a temporary, strip that temporary off the expression.
8695 ExprResult ActOnDecltypeExpression(Expr *E);
8696
8697 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8698 bool IsUDSuffix);
8699
8700 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
8701
8702 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8703 SourceLocation StmtLoc,
8704 ConditionKind CK);
8705
8706 /// Check the use of the given variable as a C++ condition in an if,
8707 /// while, do-while, or switch statement.
8708 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
8709 SourceLocation StmtLoc, ConditionKind CK);
8710
8711 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8712 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8713
8714 /// Helper function to determine whether this is the (deprecated) C++
8715 /// conversion from a string literal to a pointer to non-const char or
8716 /// non-const wchar_t (for narrow and wide string literals,
8717 /// respectively).
8718 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8719
8720 /// PerformImplicitConversion - Perform an implicit conversion of the
8721 /// expression From to the type ToType using the pre-computed implicit
8722 /// conversion sequence ICS. Returns the converted
8723 /// expression. Action is the kind of conversion we're performing,
8724 /// used in the error message.
8725 ExprResult PerformImplicitConversion(
8726 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8727 AssignmentAction Action,
8728 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
8729
8730 /// PerformImplicitConversion - Perform an implicit conversion of the
8731 /// expression From to the type ToType by following the standard
8732 /// conversion sequence SCS. Returns the converted
8733 /// expression. Flavor is the context in which we're performing this
8734 /// conversion, for use in error messages.
8735 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8736 const StandardConversionSequence &SCS,
8737 AssignmentAction Action,
8738 CheckedConversionKind CCK);
8739
8740 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8741
8742 /// Parsed one of the type trait support pseudo-functions.
8743 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8744 ArrayRef<ParsedType> Args,
8745 SourceLocation RParenLoc);
8746 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8747 ArrayRef<TypeSourceInfo *> Args,
8748 SourceLocation RParenLoc);
8749
8750 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8751 /// pseudo-functions.
8752 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8753 ParsedType LhsTy, Expr *DimExpr,
8754 SourceLocation RParen);
8755
8756 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8757 TypeSourceInfo *TSInfo, Expr *DimExpr,
8758 SourceLocation RParen);
8759
8760 /// ActOnExpressionTrait - Parsed one of the unary type trait support
8761 /// pseudo-functions.
8762 ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8763 Expr *Queried, SourceLocation RParen);
8764
8765 ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8766 Expr *Queried, SourceLocation RParen);
8767
8768 QualType CheckPointerToMemberOperands( // C++ 5.5
8769 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc,
8770 bool isIndirect);
8771 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
8772 ExprResult &RHS,
8773 SourceLocation QuestionLoc);
8774
8775 //// Determines if a type is trivially relocatable
8776 /// according to the C++26 rules.
8777 // FIXME: This is in Sema because it requires
8778 // overload resolution, can we move to ASTContext?
8779 bool IsCXXTriviallyRelocatableType(QualType T);
8780 bool IsCXXTriviallyRelocatableType(const CXXRecordDecl &RD);
8781
8782 /// Check the operands of ?: under C++ semantics.
8783 ///
8784 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8785 /// extension. In this case, LHS == Cond. (But they're not aliases.)
8786 ///
8787 /// This function also implements GCC's vector extension and the
8788 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8789 /// permit the use of a?b:c where the type of a is that of a integer vector
8790 /// with the same number of elements and size as the vectors of b and c. If
8791 /// one of either b or c is a scalar it is implicitly converted to match the
8792 /// type of the vector. Otherwise the expression is ill-formed. If both b and
8793 /// c are scalars, then b and c are checked and converted to the type of a if
8794 /// possible.
8795 ///
8796 /// The expressions are evaluated differently for GCC's and OpenCL's
8797 /// extensions. For the GCC extension, the ?: operator is evaluated as
8798 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8799 /// For the OpenCL extensions, the ?: operator is evaluated as
8800 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
8801 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
8802 QualType CXXCheckConditionalOperands( // C++ 5.16
8803 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8804 ExprObjectKind &OK, SourceLocation questionLoc);
8805
8806 /// Find a merged pointer type and convert the two expressions to it.
8807 ///
8808 /// This finds the composite pointer type for \p E1 and \p E2 according to
8809 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8810 /// it. It does not emit diagnostics (FIXME: that's not true if \p
8811 /// ConvertArgs is \c true).
8812 ///
8813 /// \param Loc The location of the operator requiring these two expressions to
8814 /// be converted to the composite pointer type.
8815 ///
8816 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
8817 /// type.
8818 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8819 bool ConvertArgs = true);
8820 QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1,
8821 ExprResult &E2, bool ConvertArgs = true) {
8822 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8823 QualType Composite =
8824 FindCompositePointerType(Loc, E1&: E1Tmp, E2&: E2Tmp, ConvertArgs);
8825 E1 = E1Tmp;
8826 E2 = E2Tmp;
8827 return Composite;
8828 }
8829
8830 /// MaybeBindToTemporary - If the passed in expression has a record type with
8831 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
8832 /// it simply returns the passed in expression.
8833 ExprResult MaybeBindToTemporary(Expr *E);
8834
8835 /// IgnoredValueConversions - Given that an expression's result is
8836 /// syntactically ignored, perform any conversions that are
8837 /// required.
8838 ExprResult IgnoredValueConversions(Expr *E);
8839
8840 ExprResult CheckUnevaluatedOperand(Expr *E);
8841
8842 IfExistsResult
8843 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
8844 const DeclarationNameInfo &TargetNameInfo);
8845
8846 IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S,
8847 SourceLocation KeywordLoc,
8848 bool IsIfExists, CXXScopeSpec &SS,
8849 UnqualifiedId &Name);
8850
8851 RequiresExprBodyDecl *
8852 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8853 ArrayRef<ParmVarDecl *> LocalParameters,
8854 Scope *BodyScope);
8855 void ActOnFinishRequiresExpr();
8856 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8857 concepts::Requirement *ActOnTypeRequirement(SourceLocation TypenameKWLoc,
8858 CXXScopeSpec &SS,
8859 SourceLocation NameLoc,
8860 const IdentifierInfo *TypeName,
8861 TemplateIdAnnotation *TemplateId);
8862 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8863 SourceLocation NoexceptLoc);
8864 concepts::Requirement *ActOnCompoundRequirement(
8865 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8866 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8867 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8868 concepts::ExprRequirement *BuildExprRequirement(
8869 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8870 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8871 concepts::ExprRequirement *BuildExprRequirement(
8872 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8873 bool IsSatisfied, SourceLocation NoexceptLoc,
8874 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8875 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8876 concepts::TypeRequirement *BuildTypeRequirement(
8877 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8878 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8879 concepts::NestedRequirement *
8880 BuildNestedRequirement(StringRef InvalidConstraintEntity,
8881 const ASTConstraintSatisfaction &Satisfaction);
8882 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8883 RequiresExprBodyDecl *Body,
8884 SourceLocation LParenLoc,
8885 ArrayRef<ParmVarDecl *> LocalParameters,
8886 SourceLocation RParenLoc,
8887 ArrayRef<concepts::Requirement *> Requirements,
8888 SourceLocation ClosingBraceLoc);
8889
8890private:
8891 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
8892 bool IsDelete);
8893
8894 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8895 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8896 bool DeleteWasArrayForm);
8897
8898 std::optional<AllocationArgumentSet>
8899 resolveAllocationArguments(LookupResult &R,
8900 const ImplicitAllocationParameters &,
8901 ArrayRef<Expr *> PlacementArguments);
8902
8903 // Attempts to construct the type identity argument for the call to a
8904 // type aware operator new. Returns null on failure.
8905 Expr *tryGetTypeIdentityArgument(QualType Type, SourceLocation);
8906
8907 Expr *AllocationSizeExpr = nullptr;
8908 Expr *AllocationAlignmentExpr = nullptr;
8909 llvm::DenseMap<QualType, Expr *> AllocationTypeIdentityArguments;
8910
8911 ///@}
8912
8913 //
8914 //
8915 // -------------------------------------------------------------------------
8916 //
8917 //
8918
8919 /// \name Member Access Expressions
8920 /// Implementations are in SemaExprMember.cpp
8921 ///@{
8922
8923public:
8924 /// Check whether an expression might be an implicit class member access.
8925 bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R,
8926 bool IsAddressOfOperand);
8927
8928 /// Builds an expression which might be an implicit member expression.
8929 ExprResult BuildPossibleImplicitMemberExpr(
8930 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
8931 const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
8932
8933 /// Builds an implicit member access expression. The current context
8934 /// is known to be an instance method, and the given unqualified lookup
8935 /// set is known to contain only instance members, at least one of which
8936 /// is from an appropriate type.
8937 ExprResult
8938 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8939 LookupResult &R,
8940 const TemplateArgumentListInfo *TemplateArgs,
8941 bool IsDefiniteInstance, const Scope *S);
8942
8943 ExprResult ActOnDependentMemberExpr(
8944 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
8945 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8946 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
8947 const TemplateArgumentListInfo *TemplateArgs);
8948
8949 /// The main callback when the parser finds something like
8950 /// expression . [nested-name-specifier] identifier
8951 /// expression -> [nested-name-specifier] identifier
8952 /// where 'identifier' encompasses a fairly broad spectrum of
8953 /// possibilities, including destructor and operator references.
8954 ///
8955 /// \param OpKind either tok::arrow or tok::period
8956 /// \param ObjCImpDecl the current Objective-C \@implementation
8957 /// decl; this is an ugly hack around the fact that Objective-C
8958 /// \@implementations aren't properly put in the context chain
8959 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
8960 tok::TokenKind OpKind, CXXScopeSpec &SS,
8961 SourceLocation TemplateKWLoc,
8962 UnqualifiedId &Member, Decl *ObjCImpDecl);
8963
8964 MemberExpr *
8965 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
8966 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
8967 ValueDecl *Member, DeclAccessPair FoundDecl,
8968 bool HadMultipleCandidates,
8969 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
8970 ExprValueKind VK, ExprObjectKind OK,
8971 const TemplateArgumentListInfo *TemplateArgs = nullptr);
8972
8973 // Check whether the declarations we found through a nested-name
8974 // specifier in a member expression are actually members of the base
8975 // type. The restriction here is:
8976 //
8977 // C++ [expr.ref]p2:
8978 // ... In these cases, the id-expression shall name a
8979 // member of the class or of one of its base classes.
8980 //
8981 // So it's perfectly legitimate for the nested-name specifier to name
8982 // an unrelated class, and for us to find an overload set including
8983 // decls from classes which are not superclasses, as long as the decl
8984 // we actually pick through overload resolution is from a superclass.
8985 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
8986 const CXXScopeSpec &SS,
8987 const LookupResult &R);
8988
8989 // This struct is for use by ActOnMemberAccess to allow
8990 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
8991 // changing the access operator from a '.' to a '->' (to see if that is the
8992 // change needed to fix an error about an unknown member, e.g. when the class
8993 // defines a custom operator->).
8994 struct ActOnMemberAccessExtraArgs {
8995 Scope *S;
8996 UnqualifiedId &Id;
8997 Decl *ObjCImpDecl;
8998 };
8999
9000 ExprResult BuildMemberReferenceExpr(
9001 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
9002 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9003 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9004 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
9005 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9006
9007 ExprResult
9008 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
9009 bool IsArrow, const CXXScopeSpec &SS,
9010 SourceLocation TemplateKWLoc,
9011 NamedDecl *FirstQualifierInScope, LookupResult &R,
9012 const TemplateArgumentListInfo *TemplateArgs,
9013 const Scope *S, bool SuppressQualifierCheck = false,
9014 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9015
9016 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
9017 SourceLocation OpLoc,
9018 const CXXScopeSpec &SS, FieldDecl *Field,
9019 DeclAccessPair FoundDecl,
9020 const DeclarationNameInfo &MemberNameInfo);
9021
9022 /// Perform conversions on the LHS of a member access expression.
9023 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
9024
9025 ExprResult BuildAnonymousStructUnionMemberReference(
9026 const CXXScopeSpec &SS, SourceLocation nameLoc,
9027 IndirectFieldDecl *indirectField,
9028 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none),
9029 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
9030
9031private:
9032 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
9033
9034 ///@}
9035
9036 //
9037 //
9038 // -------------------------------------------------------------------------
9039 //
9040 //
9041
9042 /// \name Initializers
9043 /// Implementations are in SemaInit.cpp
9044 ///@{
9045
9046public:
9047 /// Stack of types that correspond to the parameter entities that are
9048 /// currently being copy-initialized. Can be empty.
9049 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
9050
9051 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
9052 AggregateDeductionCandidates;
9053
9054 bool IsStringInit(Expr *Init, const ArrayType *AT);
9055
9056 /// Determine whether we can perform aggregate initialization for the purposes
9057 /// of overload resolution.
9058 bool CanPerformAggregateInitializationForOverloadResolution(
9059 const InitializedEntity &Entity, InitListExpr *From);
9060
9061 ExprResult ActOnDesignatedInitializer(Designation &Desig,
9062 SourceLocation EqualOrColonLoc,
9063 bool GNUSyntax, ExprResult Init);
9064
9065 /// Check that the lifetime of the initializer (and its subobjects) is
9066 /// sufficient for initializing the entity, and perform lifetime extension
9067 /// (when permitted) if not.
9068 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
9069
9070 MaterializeTemporaryExpr *
9071 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
9072 bool BoundToLvalueReference);
9073
9074 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9075 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9076 /// we don't have xvalues there.
9077 ExprResult TemporaryMaterializationConversion(Expr *E);
9078
9079 ExprResult PerformQualificationConversion(
9080 Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
9081 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
9082
9083 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
9084 ExprResult Init);
9085 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
9086 SourceLocation EqualLoc, ExprResult Init,
9087 bool TopLevelOfInitList = false,
9088 bool AllowExplicit = false);
9089
9090 QualType DeduceTemplateSpecializationFromInitializer(
9091 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9092 const InitializationKind &Kind, MultiExprArg Init);
9093
9094 ///@}
9095
9096 //
9097 //
9098 // -------------------------------------------------------------------------
9099 //
9100 //
9101
9102 /// \name C++ Lambda Expressions
9103 /// Implementations are in SemaLambda.cpp
9104 ///@{
9105
9106public:
9107 /// Create a new lambda closure type.
9108 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
9109 TypeSourceInfo *Info,
9110 unsigned LambdaDependencyKind,
9111 LambdaCaptureDefault CaptureDefault);
9112
9113 /// Number lambda for linkage purposes if necessary.
9114 void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method,
9115 std::optional<CXXRecordDecl::LambdaNumbering>
9116 NumberingOverride = std::nullopt);
9117
9118 /// Endow the lambda scope info with the relevant properties.
9119 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9120 SourceRange IntroducerRange,
9121 LambdaCaptureDefault CaptureDefault,
9122 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9123 bool Mutable);
9124
9125 CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange,
9126 CXXRecordDecl *Class);
9127
9128 void AddTemplateParametersToLambdaCallOperator(
9129 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9130 TemplateParameterList *TemplateParams);
9131
9132 void
9133 CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc,
9134 SourceLocation CallOperatorLoc,
9135 const AssociatedConstraint &TrailingRequiresClause,
9136 TypeSourceInfo *MethodTyInfo,
9137 ConstexprSpecKind ConstexprKind, StorageClass SC,
9138 ArrayRef<ParmVarDecl *> Params,
9139 bool HasExplicitResultType);
9140
9141 /// Returns true if the explicit object parameter was invalid.
9142 bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method,
9143 SourceLocation CallLoc);
9144
9145 /// Perform initialization analysis of the init-capture and perform
9146 /// any implicit conversions such as an lvalue-to-rvalue conversion if
9147 /// not being used to initialize a reference.
9148 ParsedType actOnLambdaInitCaptureInitialization(
9149 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9150 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9151 return ParsedType::make(P: buildLambdaInitCaptureInitialization(
9152 Loc, ByRef, EllipsisLoc, NumExpansions: std::nullopt, Id,
9153 DirectInit: InitKind != LambdaCaptureInitKind::CopyInit, Init));
9154 }
9155 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
9156 SourceLocation EllipsisLoc,
9157 UnsignedOrNone NumExpansions,
9158 IdentifierInfo *Id,
9159 bool DirectInit, Expr *&Init);
9160
9161 /// Create a dummy variable within the declcontext of the lambda's
9162 /// call operator, for name lookup purposes for a lambda init capture.
9163 ///
9164 /// CodeGen handles emission of lambda captures, ignoring these dummy
9165 /// variables appropriately.
9166 VarDecl *createLambdaInitCaptureVarDecl(
9167 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9168 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9169
9170 /// Add an init-capture to a lambda scope.
9171 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9172
9173 /// Note that we have finished the explicit captures for the
9174 /// given lambda.
9175 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
9176
9177 /// Deduce a block or lambda's return type based on the return
9178 /// statements present in the body.
9179 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
9180
9181 /// Once the Lambdas capture are known, we can start to create the closure,
9182 /// call operator method, and keep track of the captures.
9183 /// We do the capture lookup here, but they are not actually captured until
9184 /// after we know what the qualifiers of the call operator are.
9185 void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
9186 Scope *CurContext);
9187
9188 /// This is called after parsing the explicit template parameter list
9189 /// on a lambda (if it exists) in C++2a.
9190 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
9191 SourceLocation LAngleLoc,
9192 ArrayRef<NamedDecl *> TParams,
9193 SourceLocation RAngleLoc,
9194 ExprResult RequiresClause);
9195
9196 void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
9197 SourceLocation MutableLoc);
9198
9199 void ActOnLambdaClosureParameters(
9200 Scope *LambdaScope,
9201 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo);
9202
9203 /// ActOnStartOfLambdaDefinition - This is called just before we start
9204 /// parsing the body of a lambda; it analyzes the explicit captures and
9205 /// arguments, and sets up various data-structures for the body of the
9206 /// lambda.
9207 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
9208 Declarator &ParamInfo, const DeclSpec &DS);
9209
9210 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9211 /// is invoked to pop the information about the lambda.
9212 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9213 bool IsInstantiation = false);
9214
9215 /// ActOnLambdaExpr - This is called when the body of a lambda expression
9216 /// was successfully completed.
9217 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body);
9218
9219 /// Does copying/destroying the captured variable have side effects?
9220 bool CaptureHasSideEffects(const sema::Capture &From);
9221
9222 /// Diagnose if an explicit lambda capture is unused. Returns true if a
9223 /// diagnostic is emitted.
9224 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9225 SourceRange FixItRange,
9226 const sema::Capture &From);
9227
9228 /// Build a FieldDecl suitable to hold the given capture.
9229 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
9230
9231 /// Initialize the given capture with a suitable expression.
9232 ExprResult BuildCaptureInit(const sema::Capture &Capture,
9233 SourceLocation ImplicitCaptureLoc,
9234 bool IsOpenMPMapping = false);
9235
9236 /// Complete a lambda-expression having processed and attached the
9237 /// lambda body.
9238 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc);
9239
9240 /// Get the return type to use for a lambda's conversion function(s) to
9241 /// function pointer type, given the type of the call operator.
9242 QualType
9243 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
9244 CallingConv CC);
9245
9246 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
9247 SourceLocation ConvLocation,
9248 CXXConversionDecl *Conv, Expr *Src);
9249
9250 class LambdaScopeForCallOperatorInstantiationRAII
9251 : private FunctionScopeRAII {
9252 public:
9253 LambdaScopeForCallOperatorInstantiationRAII(
9254 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9255 LocalInstantiationScope &Scope,
9256 bool ShouldAddDeclsFromParentScope = true);
9257 };
9258
9259 /// Compute the mangling number context for a lambda expression or
9260 /// block literal. Also return the extra mangling decl if any.
9261 ///
9262 /// \param DC - The DeclContext containing the lambda expression or
9263 /// block literal.
9264 std::tuple<MangleNumberingContext *, Decl *>
9265 getCurrentMangleNumberContext(const DeclContext *DC);
9266
9267 ///@}
9268
9269 //
9270 //
9271 // -------------------------------------------------------------------------
9272 //
9273 //
9274
9275 /// \name Name Lookup
9276 ///
9277 /// These routines provide name lookup that is used during semantic
9278 /// analysis to resolve the various kinds of names (identifiers,
9279 /// overloaded operator names, constructor names, etc.) into zero or
9280 /// more declarations within a particular scope. The major entry
9281 /// points are LookupName, which performs unqualified name lookup,
9282 /// and LookupQualifiedName, which performs qualified name lookup.
9283 ///
9284 /// All name lookup is performed based on some specific criteria,
9285 /// which specify what names will be visible to name lookup and how
9286 /// far name lookup should work. These criteria are important both
9287 /// for capturing language semantics (certain lookups will ignore
9288 /// certain names, for example) and for performance, since name
9289 /// lookup is often a bottleneck in the compilation of C++. Name
9290 /// lookup criteria is specified via the LookupCriteria enumeration.
9291 ///
9292 /// The results of name lookup can vary based on the kind of name
9293 /// lookup performed, the current language, and the translation
9294 /// unit. In C, for example, name lookup will either return nothing
9295 /// (no entity found) or a single declaration. In C++, name lookup
9296 /// can additionally refer to a set of overloaded functions or
9297 /// result in an ambiguity. All of the possible results of name
9298 /// lookup are captured by the LookupResult class, which provides
9299 /// the ability to distinguish among them.
9300 ///
9301 /// Implementations are in SemaLookup.cpp
9302 ///@{
9303
9304public:
9305 /// Tracks whether we are in a context where typo correction is
9306 /// disabled.
9307 bool DisableTypoCorrection;
9308
9309 /// The number of typos corrected by CorrectTypo.
9310 unsigned TyposCorrected;
9311
9312 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9313 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9314
9315 /// A cache containing identifiers for which typo correction failed and
9316 /// their locations, so that repeated attempts to correct an identifier in a
9317 /// given location are ignored if typo correction already failed for it.
9318 IdentifierSourceLocations TypoCorrectionFailures;
9319
9320 /// SpecialMemberOverloadResult - The overloading result for a special member
9321 /// function.
9322 ///
9323 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9324 /// integer are used to determine whether overload resolution succeeded.
9325 class SpecialMemberOverloadResult {
9326 public:
9327 enum Kind { NoMemberOrDeleted, Ambiguous, Success };
9328
9329 private:
9330 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9331
9332 public:
9333 SpecialMemberOverloadResult() {}
9334 SpecialMemberOverloadResult(CXXMethodDecl *MD)
9335 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9336
9337 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
9338 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9339
9340 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
9341 void setKind(Kind K) { Pair.setInt(K); }
9342 };
9343
9344 class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode,
9345 public SpecialMemberOverloadResult {
9346 public:
9347 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
9348 : FastFoldingSetNode(ID) {}
9349 };
9350
9351 /// A cache of special member function overload resolution results
9352 /// for C++ records.
9353 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
9354
9355 enum class AcceptableKind { Visible, Reachable };
9356
9357 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9358 // TODO: make this is a typesafe union.
9359 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
9360 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
9361
9362 /// Describes the kind of name lookup to perform.
9363 enum LookupNameKind {
9364 /// Ordinary name lookup, which finds ordinary names (functions,
9365 /// variables, typedefs, etc.) in C and most kinds of names
9366 /// (functions, variables, members, types, etc.) in C++.
9367 LookupOrdinaryName = 0,
9368 /// Tag name lookup, which finds the names of enums, classes,
9369 /// structs, and unions.
9370 LookupTagName,
9371 /// Label name lookup.
9372 LookupLabel,
9373 /// Member name lookup, which finds the names of
9374 /// class/struct/union members.
9375 LookupMemberName,
9376 /// Look up of an operator name (e.g., operator+) for use with
9377 /// operator overloading. This lookup is similar to ordinary name
9378 /// lookup, but will ignore any declarations that are class members.
9379 LookupOperatorName,
9380 /// Look up a name following ~ in a destructor name. This is an ordinary
9381 /// lookup, but prefers tags to typedefs.
9382 LookupDestructorName,
9383 /// Look up of a name that precedes the '::' scope resolution
9384 /// operator in C++. This lookup completely ignores operator, object,
9385 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9386 LookupNestedNameSpecifierName,
9387 /// Look up a namespace name within a C++ using directive or
9388 /// namespace alias definition, ignoring non-namespace names (C++
9389 /// [basic.lookup.udir]p1).
9390 LookupNamespaceName,
9391 /// Look up all declarations in a scope with the given name,
9392 /// including resolved using declarations. This is appropriate
9393 /// for checking redeclarations for a using declaration.
9394 LookupUsingDeclName,
9395 /// Look up an ordinary name that is going to be redeclared as a
9396 /// name with linkage. This lookup ignores any declarations that
9397 /// are outside of the current scope unless they have linkage. See
9398 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9399 LookupRedeclarationWithLinkage,
9400 /// Look up a friend of a local class. This lookup does not look
9401 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9402 LookupLocalFriendName,
9403 /// Look up the name of an Objective-C protocol.
9404 LookupObjCProtocolName,
9405 /// Look up implicit 'self' parameter of an objective-c method.
9406 LookupObjCImplicitSelfParam,
9407 /// Look up the name of an OpenMP user-defined reduction operation.
9408 LookupOMPReductionName,
9409 /// Look up the name of an OpenMP user-defined mapper.
9410 LookupOMPMapperName,
9411 /// Look up any declaration with any name.
9412 LookupAnyName
9413 };
9414
9415 /// The possible outcomes of name lookup for a literal operator.
9416 enum LiteralOperatorLookupResult {
9417 /// The lookup resulted in an error.
9418 LOLR_Error,
9419 /// The lookup found no match but no diagnostic was issued.
9420 LOLR_ErrorNoDiagnostic,
9421 /// The lookup found a single 'cooked' literal operator, which
9422 /// expects a normal literal to be built and passed to it.
9423 LOLR_Cooked,
9424 /// The lookup found a single 'raw' literal operator, which expects
9425 /// a string literal containing the spelling of the literal token.
9426 LOLR_Raw,
9427 /// The lookup found an overload set of literal operator templates,
9428 /// which expect the characters of the spelling of the literal token to be
9429 /// passed as a non-type template argument pack.
9430 LOLR_Template,
9431 /// The lookup found an overload set of literal operator templates,
9432 /// which expect the character type and characters of the spelling of the
9433 /// string literal token to be passed as template arguments.
9434 LOLR_StringTemplatePack,
9435 };
9436
9437 SpecialMemberOverloadResult
9438 LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg,
9439 bool VolatileArg, bool RValueThis, bool ConstThis,
9440 bool VolatileThis);
9441
9442 RedeclarationKind forRedeclarationInCurContext() const;
9443
9444 /// Look up a name, looking for a single declaration. Return
9445 /// null if the results were absent, ambiguous, or overloaded.
9446 ///
9447 /// It is preferable to use the elaborated form and explicitly handle
9448 /// ambiguity and overloaded.
9449 NamedDecl *LookupSingleName(
9450 Scope *S, DeclarationName Name, SourceLocation Loc,
9451 LookupNameKind NameKind,
9452 RedeclarationKind Redecl = RedeclarationKind::NotForRedeclaration);
9453
9454 /// Lookup a builtin function, when name lookup would otherwise
9455 /// fail.
9456 bool LookupBuiltin(LookupResult &R);
9457 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9458
9459 /// Perform unqualified name lookup starting from a given
9460 /// scope.
9461 ///
9462 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9463 /// used to find names within the current scope. For example, 'x' in
9464 /// @code
9465 /// int x;
9466 /// int f() {
9467 /// return x; // unqualified name look finds 'x' in the global scope
9468 /// }
9469 /// @endcode
9470 ///
9471 /// Different lookup criteria can find different names. For example, a
9472 /// particular scope can have both a struct and a function of the same
9473 /// name, and each can be found by certain lookup criteria. For more
9474 /// information about lookup criteria, see the documentation for the
9475 /// class LookupCriteria.
9476 ///
9477 /// @param S The scope from which unqualified name lookup will
9478 /// begin. If the lookup criteria permits, name lookup may also search
9479 /// in the parent scopes.
9480 ///
9481 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9482 /// look up and the lookup kind), and is updated with the results of lookup
9483 /// including zero or more declarations and possibly additional information
9484 /// used to diagnose ambiguities.
9485 ///
9486 /// @returns \c true if lookup succeeded and false otherwise.
9487 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9488 bool ForceNoCPlusPlus = false);
9489
9490 /// Perform qualified name lookup into a given context.
9491 ///
9492 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9493 /// names when the context of those names is explicit specified, e.g.,
9494 /// "std::vector" or "x->member", or as part of unqualified name lookup.
9495 ///
9496 /// Different lookup criteria can find different names. For example, a
9497 /// particular scope can have both a struct and a function of the same
9498 /// name, and each can be found by certain lookup criteria. For more
9499 /// information about lookup criteria, see the documentation for the
9500 /// class LookupCriteria.
9501 ///
9502 /// \param R captures both the lookup criteria and any lookup results found.
9503 ///
9504 /// \param LookupCtx The context in which qualified name lookup will
9505 /// search. If the lookup criteria permits, name lookup may also search
9506 /// in the parent contexts or (for C++ classes) base classes.
9507 ///
9508 /// \param InUnqualifiedLookup true if this is qualified name lookup that
9509 /// occurs as part of unqualified name lookup.
9510 ///
9511 /// \returns true if lookup succeeded, false if it failed.
9512 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9513 bool InUnqualifiedLookup = false);
9514
9515 /// Performs qualified name lookup or special type of lookup for
9516 /// "__super::" scope specifier.
9517 ///
9518 /// This routine is a convenience overload meant to be called from contexts
9519 /// that need to perform a qualified name lookup with an optional C++ scope
9520 /// specifier that might require special kind of lookup.
9521 ///
9522 /// \param R captures both the lookup criteria and any lookup results found.
9523 ///
9524 /// \param LookupCtx The context in which qualified name lookup will
9525 /// search.
9526 ///
9527 /// \param SS An optional C++ scope-specifier.
9528 ///
9529 /// \returns true if lookup succeeded, false if it failed.
9530 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9531 CXXScopeSpec &SS);
9532
9533 /// Performs name lookup for a name that was parsed in the
9534 /// source code, and may contain a C++ scope specifier.
9535 ///
9536 /// This routine is a convenience routine meant to be called from
9537 /// contexts that receive a name and an optional C++ scope specifier
9538 /// (e.g., "N::M::x"). It will then perform either qualified or
9539 /// unqualified name lookup (with LookupQualifiedName or LookupName,
9540 /// respectively) on the given name and return those results. It will
9541 /// perform a special type of lookup for "__super::" scope specifier.
9542 ///
9543 /// @param S The scope from which unqualified name lookup will
9544 /// begin.
9545 ///
9546 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
9547 ///
9548 /// @param EnteringContext Indicates whether we are going to enter the
9549 /// context of the scope-specifier SS (if present).
9550 ///
9551 /// @returns True if any decls were found (but possibly ambiguous)
9552 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
9553 QualType ObjectType, bool AllowBuiltinCreation = false,
9554 bool EnteringContext = false);
9555
9556 /// Perform qualified name lookup into all base classes of the given
9557 /// class.
9558 ///
9559 /// \param R captures both the lookup criteria and any lookup results found.
9560 ///
9561 /// \param Class The context in which qualified name lookup will
9562 /// search. Name lookup will search in all base classes merging the results.
9563 ///
9564 /// @returns True if any decls were found (but possibly ambiguous)
9565 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
9566
9567 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
9568 UnresolvedSetImpl &Functions);
9569
9570 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9571 /// If GnuLabelLoc is a valid source location, then this is a definition
9572 /// of an __label__ label name, otherwise it is a normal label definition
9573 /// or use. If IsLabelStmt is true, then this is the label of a
9574 /// labeled-statement.
9575 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
9576 SourceLocation GnuLabelLoc = SourceLocation(),
9577 bool IsLabelStmt = false);
9578
9579 /// Perform a name lookup for a label with the specified name; this does not
9580 /// create a new label if the lookup fails.
9581 LabelDecl *LookupExistingLabel(IdentifierInfo *II, SourceLocation IdentLoc);
9582
9583 /// Look up the constructors for the given class.
9584 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
9585
9586 /// Look up the default constructor for the given class.
9587 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
9588
9589 /// Look up the copying constructor for the given class.
9590 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
9591 unsigned Quals);
9592
9593 /// Look up the copying assignment operator for the given class.
9594 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
9595 bool RValueThis, unsigned ThisQuals);
9596
9597 /// Look up the moving constructor for the given class.
9598 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
9599 unsigned Quals);
9600
9601 /// Look up the moving assignment operator for the given class.
9602 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
9603 bool RValueThis, unsigned ThisQuals);
9604
9605 /// Look for the destructor of the given class.
9606 ///
9607 /// During semantic analysis, this routine should be used in lieu of
9608 /// CXXRecordDecl::getDestructor().
9609 ///
9610 /// \returns The destructor for this class.
9611 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
9612
9613 /// Force the declaration of any implicitly-declared members of this
9614 /// class.
9615 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
9616
9617 /// Make a merged definition of an existing hidden definition \p ND
9618 /// visible at the specified location.
9619 void makeMergedDefinitionVisible(NamedDecl *ND);
9620
9621 /// Check ODR hashes for C/ObjC when merging types from modules.
9622 /// Differently from C++, actually parse the body and reject in case
9623 /// of a mismatch.
9624 template <typename T,
9625 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
9626 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
9627 if (Duplicate->getODRHash() != Previous->getODRHash())
9628 return false;
9629
9630 // Make the previous decl visible.
9631 makeMergedDefinitionVisible(ND: Previous);
9632 return true;
9633 }
9634
9635 /// Get the set of additional modules that should be checked during
9636 /// name lookup. A module and its imports become visible when instanting a
9637 /// template defined within it.
9638 llvm::DenseSet<Module *> &getLookupModules();
9639
9640 bool hasVisibleMergedDefinition(const NamedDecl *Def);
9641 bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
9642
9643 /// Determine if the template parameter \p D has a visible default argument.
9644 bool
9645 hasVisibleDefaultArgument(const NamedDecl *D,
9646 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9647 /// Determine if the template parameter \p D has a reachable default argument.
9648 bool hasReachableDefaultArgument(
9649 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9650 /// Determine if the template parameter \p D has a reachable default argument.
9651 bool hasAcceptableDefaultArgument(const NamedDecl *D,
9652 llvm::SmallVectorImpl<Module *> *Modules,
9653 Sema::AcceptableKind Kind);
9654
9655 /// Determine if there is a visible declaration of \p D that is an explicit
9656 /// specialization declaration for a specialization of a template. (For a
9657 /// member specialization, use hasVisibleMemberSpecialization.)
9658 bool hasVisibleExplicitSpecialization(
9659 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9660 /// Determine if there is a reachable declaration of \p D that is an explicit
9661 /// specialization declaration for a specialization of a template. (For a
9662 /// member specialization, use hasReachableMemberSpecialization.)
9663 bool hasReachableExplicitSpecialization(
9664 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9665
9666 /// Determine if there is a visible declaration of \p D that is a member
9667 /// specialization declaration (as opposed to an instantiated declaration).
9668 bool hasVisibleMemberSpecialization(
9669 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9670 /// Determine if there is a reachable declaration of \p D that is a member
9671 /// specialization declaration (as opposed to an instantiated declaration).
9672 bool hasReachableMemberSpecialization(
9673 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9674
9675 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9676
9677 /// Determine whether any declaration of an entity is visible.
9678 bool
9679 hasVisibleDeclaration(const NamedDecl *D,
9680 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9681 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9682 }
9683
9684 bool hasVisibleDeclarationSlow(const NamedDecl *D,
9685 llvm::SmallVectorImpl<Module *> *Modules);
9686 /// Determine whether any declaration of an entity is reachable.
9687 bool
9688 hasReachableDeclaration(const NamedDecl *D,
9689 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9690 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9691 }
9692 bool hasReachableDeclarationSlow(
9693 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9694
9695 void diagnoseTypo(const TypoCorrection &Correction,
9696 const PartialDiagnostic &TypoDiag,
9697 bool ErrorRecovery = true);
9698
9699 /// Diagnose a successfully-corrected typo. Separated from the correction
9700 /// itself to allow external validation of the result, etc.
9701 ///
9702 /// \param Correction The result of performing typo correction.
9703 /// \param TypoDiag The diagnostic to produce. This will have the corrected
9704 /// string added to it (and usually also a fixit).
9705 /// \param PrevNote A note to use when indicating the location of the entity
9706 /// to which we are correcting. Will have the correction string added
9707 /// to it.
9708 /// \param ErrorRecovery If \c true (the default), the caller is going to
9709 /// recover from the typo as if the corrected string had been typed.
9710 /// In this case, \c PDiag must be an error, and we will attach a fixit
9711 /// to it.
9712 void diagnoseTypo(const TypoCorrection &Correction,
9713 const PartialDiagnostic &TypoDiag,
9714 const PartialDiagnostic &PrevNote,
9715 bool ErrorRecovery = true);
9716
9717 /// Find the associated classes and namespaces for
9718 /// argument-dependent lookup for a call with the given set of
9719 /// arguments.
9720 ///
9721 /// This routine computes the sets of associated classes and associated
9722 /// namespaces searched by argument-dependent lookup
9723 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9724 void FindAssociatedClassesAndNamespaces(
9725 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9726 AssociatedNamespaceSet &AssociatedNamespaces,
9727 AssociatedClassSet &AssociatedClasses);
9728
9729 /// Produce a diagnostic describing the ambiguity that resulted
9730 /// from name lookup.
9731 ///
9732 /// \param Result The result of the ambiguous lookup to be diagnosed.
9733 void DiagnoseAmbiguousLookup(LookupResult &Result);
9734
9735 /// LookupLiteralOperator - Determine which literal operator should be used
9736 /// for a user-defined literal, per C++11 [lex.ext].
9737 ///
9738 /// Normal overload resolution is not used to select which literal operator to
9739 /// call for a user-defined literal. Look up the provided literal operator
9740 /// name, and filter the results to the appropriate set for the given argument
9741 /// types.
9742 LiteralOperatorLookupResult
9743 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
9744 bool AllowRaw, bool AllowTemplate,
9745 bool AllowStringTemplate, bool DiagnoseMissing,
9746 StringLiteral *StringLit = nullptr);
9747
9748 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
9749 ArrayRef<Expr *> Args, ADLResult &Functions);
9750
9751 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9752 VisibleDeclConsumer &Consumer,
9753 bool IncludeGlobalScope = true,
9754 bool LoadExternal = true);
9755 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9756 VisibleDeclConsumer &Consumer,
9757 bool IncludeGlobalScope = true,
9758 bool IncludeDependentBases = false,
9759 bool LoadExternal = true);
9760
9761 /// Try to "correct" a typo in the source code by finding
9762 /// visible declarations whose names are similar to the name that was
9763 /// present in the source code.
9764 ///
9765 /// \param TypoName the \c DeclarationNameInfo structure that contains
9766 /// the name that was present in the source code along with its location.
9767 ///
9768 /// \param LookupKind the name-lookup criteria used to search for the name.
9769 ///
9770 /// \param S the scope in which name lookup occurs.
9771 ///
9772 /// \param SS the nested-name-specifier that precedes the name we're
9773 /// looking for, if present.
9774 ///
9775 /// \param CCC A CorrectionCandidateCallback object that provides further
9776 /// validation of typo correction candidates. It also provides flags for
9777 /// determining the set of keywords permitted.
9778 ///
9779 /// \param MemberContext if non-NULL, the context in which to look for
9780 /// a member access expression.
9781 ///
9782 /// \param EnteringContext whether we're entering the context described by
9783 /// the nested-name-specifier SS.
9784 ///
9785 /// \param OPT when non-NULL, the search for visible declarations will
9786 /// also walk the protocols in the qualified interfaces of \p OPT.
9787 ///
9788 /// \returns a \c TypoCorrection containing the corrected name if the typo
9789 /// along with information such as the \c NamedDecl where the corrected name
9790 /// was declared, and any additional \c NestedNameSpecifier needed to access
9791 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9792 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
9793 Sema::LookupNameKind LookupKind, Scope *S,
9794 CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9795 CorrectTypoKind Mode,
9796 DeclContext *MemberContext = nullptr,
9797 bool EnteringContext = false,
9798 const ObjCObjectPointerType *OPT = nullptr,
9799 bool RecordFailure = true);
9800
9801 /// Kinds of missing import. Note, the values of these enumerators correspond
9802 /// to %select values in diagnostics.
9803 enum class MissingImportKind {
9804 Declaration,
9805 Definition,
9806 DefaultArgument,
9807 ExplicitSpecialization,
9808 PartialSpecialization
9809 };
9810
9811 /// Diagnose that the specified declaration needs to be visible but
9812 /// isn't, and suggest a module import that would resolve the problem.
9813 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9814 MissingImportKind MIK, bool Recover = true);
9815 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9816 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
9817 MissingImportKind MIK, bool Recover);
9818
9819 /// Called on #pragma clang __debug dump II
9820 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9821
9822 /// Called on #pragma clang __debug dump E
9823 void ActOnPragmaDump(Expr *E);
9824
9825private:
9826 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
9827 //
9828 // The boolean value will be true to indicate that the namespace was loaded
9829 // from an AST/PCH file, or false otherwise.
9830 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
9831
9832 /// Whether we have already loaded known namespaces from an extenal
9833 /// source.
9834 bool LoadedExternalKnownNamespaces;
9835
9836 bool CppLookupName(LookupResult &R, Scope *S);
9837
9838 /// Determine if we could use all the declarations in the module.
9839 bool isUsableModule(const Module *M);
9840
9841 /// Helper for CorrectTypo used to create and populate a new
9842 /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
9843 /// skipped entirely.
9844 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
9845 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
9846 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9847 DeclContext *MemberContext, bool EnteringContext,
9848 const ObjCObjectPointerType *OPT, bool ErrorRecovery);
9849
9850 /// Cache for module units which is usable for current module.
9851 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
9852
9853 /// Record the typo correction failure and return an empty correction.
9854 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
9855 bool RecordFailure = true) {
9856 if (RecordFailure)
9857 TypoCorrectionFailures[Typo].insert(V: TypoLoc);
9858 return TypoCorrection();
9859 }
9860
9861 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
9862
9863 /// Determine whether two declarations should be linked together, given that
9864 /// the old declaration might not be visible and the new declaration might
9865 /// not have external linkage.
9866 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
9867 const NamedDecl *New) {
9868 if (isVisible(D: Old))
9869 return true;
9870 // See comment in below overload for why it's safe to compute the linkage
9871 // of the new declaration here.
9872 if (New->isExternallyDeclarable()) {
9873 assert(Old->isExternallyDeclarable() &&
9874 "should not have found a non-externally-declarable previous decl");
9875 return true;
9876 }
9877 return false;
9878 }
9879 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
9880
9881 ///@}
9882
9883 //
9884 //
9885 // -------------------------------------------------------------------------
9886 //
9887 //
9888
9889 /// \name Modules
9890 /// Implementations are in SemaModule.cpp
9891 ///@{
9892
9893public:
9894 /// Get the module unit whose scope we are currently within.
9895 Module *getCurrentModule() const {
9896 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
9897 }
9898
9899 /// Is the module scope we are an implementation unit?
9900 bool currentModuleIsImplementation() const {
9901 if (ModuleScopes.empty())
9902 return false;
9903 const Module *M = ModuleScopes.back().Module;
9904 return M->isModuleImplementation() || M->isModulePartitionImplementation();
9905 }
9906
9907 // When loading a non-modular PCH files, this is used to restore module
9908 // visibility.
9909 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
9910 VisibleModules.setVisible(M: Mod, Loc: ImportLoc);
9911 }
9912
9913 enum class ModuleDeclKind {
9914 Interface, ///< 'export module X;'
9915 Implementation, ///< 'module X;'
9916 PartitionInterface, ///< 'export module X:Y;'
9917 PartitionImplementation, ///< 'module X:Y;'
9918 };
9919
9920 /// An enumeration to represent the transition of states in parsing module
9921 /// fragments and imports. If we are not parsing a C++20 TU, or we find
9922 /// an error in state transition, the state is set to NotACXX20Module.
9923 enum class ModuleImportState {
9924 FirstDecl, ///< Parsing the first decl in a TU.
9925 GlobalFragment, ///< after 'module;' but before 'module X;'
9926 ImportAllowed, ///< after 'module X;' but before any non-import decl.
9927 ImportFinished, ///< after any non-import decl.
9928 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
9929 ///< non-import decl.
9930 PrivateFragmentImportFinished, ///< after 'module :private;' but a
9931 ///< non-import decl has already been seen.
9932 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
9933 };
9934
9935 /// The parser has processed a module-declaration that begins the definition
9936 /// of a module interface or implementation.
9937 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
9938 SourceLocation ModuleLoc, ModuleDeclKind MDK,
9939 ModuleIdPath Path, ModuleIdPath Partition,
9940 ModuleImportState &ImportState,
9941 bool SeenNoTrivialPPDirective);
9942
9943 /// The parser has processed a global-module-fragment declaration that begins
9944 /// the definition of the global module fragment of the current module unit.
9945 /// \param ModuleLoc The location of the 'module' keyword.
9946 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
9947
9948 /// The parser has processed a private-module-fragment declaration that begins
9949 /// the definition of the private module fragment of the current module unit.
9950 /// \param ModuleLoc The location of the 'module' keyword.
9951 /// \param PrivateLoc The location of the 'private' keyword.
9952 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
9953 SourceLocation PrivateLoc);
9954
9955 /// The parser has processed a module import declaration.
9956 ///
9957 /// \param StartLoc The location of the first token in the declaration. This
9958 /// could be the location of an '@', 'export', or 'import'.
9959 /// \param ExportLoc The location of the 'export' keyword, if any.
9960 /// \param ImportLoc The location of the 'import' keyword.
9961 /// \param Path The module toplevel name as an access path.
9962 /// \param IsPartition If the name is for a partition.
9963 DeclResult ActOnModuleImport(SourceLocation StartLoc,
9964 SourceLocation ExportLoc,
9965 SourceLocation ImportLoc, ModuleIdPath Path,
9966 bool IsPartition = false);
9967 DeclResult ActOnModuleImport(SourceLocation StartLoc,
9968 SourceLocation ExportLoc,
9969 SourceLocation ImportLoc, Module *M,
9970 ModuleIdPath Path = {});
9971
9972 /// The parser has processed a module import translated from a
9973 /// #include or similar preprocessing directive.
9974 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
9975 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
9976
9977 /// The parsed has entered a submodule.
9978 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
9979 /// The parser has left a submodule.
9980 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
9981
9982 /// Create an implicit import of the given module at the given
9983 /// source location, for error recovery, if possible.
9984 ///
9985 /// This routine is typically used when an entity found by name lookup
9986 /// is actually hidden within a module that we know about but the user
9987 /// has forgotten to import.
9988 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
9989 Module *Mod);
9990
9991 /// We have parsed the start of an export declaration, including the '{'
9992 /// (if present).
9993 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
9994 SourceLocation LBraceLoc);
9995
9996 /// Complete the definition of an export declaration.
9997 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
9998 SourceLocation RBraceLoc);
9999
10000private:
10001 /// The parser has begun a translation unit to be compiled as a C++20
10002 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
10003 void HandleStartOfHeaderUnit();
10004
10005 struct ModuleScope {
10006 SourceLocation BeginLoc;
10007 clang::Module *Module = nullptr;
10008 VisibleModuleSet OuterVisibleModules;
10009 };
10010 /// The modules we're currently parsing.
10011 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
10012
10013 /// For an interface unit, this is the implicitly imported interface unit.
10014 clang::Module *ThePrimaryInterface = nullptr;
10015
10016 /// The explicit global module fragment of the current translation unit.
10017 /// The explicit Global Module Fragment, as specified in C++
10018 /// [module.global.frag].
10019 clang::Module *TheGlobalModuleFragment = nullptr;
10020
10021 /// The implicit global module fragments of the current translation unit.
10022 ///
10023 /// The contents in the implicit global module fragment can't be discarded.
10024 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
10025
10026 /// Namespace definitions that we will export when they finish.
10027 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
10028
10029 /// In a C++ standard module, inline declarations require a definition to be
10030 /// present at the end of a definition domain. This set holds the decls to
10031 /// be checked at the end of the TU.
10032 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
10033
10034 /// Helper function to judge if we are in module purview.
10035 /// Return false if we are not in a module.
10036 bool isCurrentModulePurview() const;
10037
10038 /// Enter the scope of the explicit global module fragment.
10039 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
10040 /// Leave the scope of the explicit global module fragment.
10041 void PopGlobalModuleFragment();
10042
10043 /// Enter the scope of an implicit global module fragment.
10044 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
10045 /// Leave the scope of an implicit global module fragment.
10046 void PopImplicitGlobalModuleFragment();
10047
10048 VisibleModuleSet VisibleModules;
10049
10050 /// Whether we had imported any named modules.
10051 bool HadImportedNamedModules = false;
10052 /// The set of instantiations we need to check if they references TU-local
10053 /// entity from TUs. This only makes sense if we imported any named modules.
10054 llvm::SmallVector<std::pair<FunctionDecl *, SourceLocation>>
10055 PendingCheckReferenceForTULocal;
10056 /// Implement [basic.link]p18, which requires that we can't use TU-local
10057 /// entities from other TUs (ignoring header units).
10058 void checkReferenceToTULocalFromOtherTU(FunctionDecl *FD,
10059 SourceLocation PointOfInstantiation);
10060 /// Implement [basic.link]p17, which diagnose for non TU local exposure in
10061 /// module interface or module partition.
10062 void checkExposure(const TranslationUnitDecl *TU);
10063
10064 ///@}
10065
10066 //
10067 //
10068 // -------------------------------------------------------------------------
10069 //
10070 //
10071
10072 /// \name C++ Overloading
10073 /// Implementations are in SemaOverload.cpp
10074 ///@{
10075
10076public:
10077 /// Whether deferrable diagnostics should be deferred.
10078 bool DeferDiags = false;
10079
10080 /// RAII class to control scope of DeferDiags.
10081 class DeferDiagsRAII {
10082 Sema &S;
10083 bool SavedDeferDiags = false;
10084
10085 public:
10086 DeferDiagsRAII(Sema &S, bool DeferDiags)
10087 : S(S), SavedDeferDiags(S.DeferDiags) {
10088 S.DeferDiags = SavedDeferDiags || DeferDiags;
10089 }
10090 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
10091 DeferDiagsRAII(const DeferDiagsRAII &) = delete;
10092 DeferDiagsRAII &operator=(const DeferDiagsRAII &) = delete;
10093 };
10094
10095 /// Flag indicating if Sema is building a recovery call expression.
10096 ///
10097 /// This flag is used to avoid building recovery call expressions
10098 /// if Sema is already doing so, which would cause infinite recursions.
10099 bool IsBuildingRecoveryCallExpr;
10100
10101 /// Determine whether the given New declaration is an overload of the
10102 /// declarations in Old. This routine returns OverloadKind::Match or
10103 /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
10104 /// New has the same signature as some function in Old (C++ 1.3.10) or if the
10105 /// Old declarations aren't functions (or function templates) at all. When it
10106 /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
10107 /// will point to the decl that New cannot be overloaded with. This decl may
10108 /// be a UsingShadowDecl on top of the underlying declaration.
10109 ///
10110 /// Example: Given the following input:
10111 ///
10112 /// void f(int, float); // #1
10113 /// void f(int, int); // #2
10114 /// int f(int, int); // #3
10115 ///
10116 /// When we process #1, there is no previous declaration of "f", so IsOverload
10117 /// will not be used.
10118 ///
10119 /// When we process #2, Old contains only the FunctionDecl for #1. By
10120 /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10121 /// they have different signatures), so this routine returns
10122 /// OverloadKind::Overload; MatchedDecl is unchanged.
10123 ///
10124 /// When we process #3, Old is an overload set containing #1 and #2. We
10125 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10126 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10127 /// types of functions are not part of the signature), IsOverload returns
10128 /// OverloadKind::Match and MatchedDecl will be set to point to the
10129 /// FunctionDecl for #2.
10130 ///
10131 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10132 /// class by a using declaration. The rules for whether to hide shadow
10133 /// declarations ignore some properties which otherwise figure into a function
10134 /// template's signature.
10135 OverloadKind CheckOverload(Scope *S, FunctionDecl *New,
10136 const LookupResult &OldDecls, NamedDecl *&OldDecl,
10137 bool UseMemberUsingDeclRules);
10138 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
10139 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10140
10141 // Checks whether MD constitutes an override the base class method BaseMD.
10142 // When checking for overrides, the object object members are ignored.
10143 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10144 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10145
10146 enum class AllowedExplicit {
10147 /// Allow no explicit functions to be used.
10148 None,
10149 /// Allow explicit conversion functions but not explicit constructors.
10150 Conversions,
10151 /// Allow both explicit conversion functions and explicit constructors.
10152 All
10153 };
10154
10155 ImplicitConversionSequence TryImplicitConversion(
10156 Expr *From, QualType ToType, bool SuppressUserConversions,
10157 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10158 bool AllowObjCWritebackConversion);
10159
10160 /// PerformImplicitConversion - Perform an implicit conversion of the
10161 /// expression From to the type ToType. Returns the
10162 /// converted expression. Flavor is the kind of conversion we're
10163 /// performing, used in the error message. If @p AllowExplicit,
10164 /// explicit user-defined conversions are permitted.
10165 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10166 AssignmentAction Action,
10167 bool AllowExplicit = false);
10168
10169 /// IsIntegralPromotion - Determines whether the conversion from the
10170 /// expression From (whose potentially-adjusted type is FromType) to
10171 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10172 /// sets PromotedType to the promoted type.
10173 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10174
10175 /// IsFloatingPointPromotion - Determines whether the conversion from
10176 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10177 /// returns true and sets PromotedType to the promoted type.
10178 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10179
10180 /// Determine if a conversion is a complex promotion.
10181 ///
10182 /// A complex promotion is defined as a complex -> complex conversion
10183 /// where the conversion between the underlying real types is a
10184 /// floating-point or integral promotion.
10185 bool IsComplexPromotion(QualType FromType, QualType ToType);
10186
10187 /// IsOverflowBehaviorTypePromotion - Determines whether the conversion from
10188 /// FromType to ToType involves an OverflowBehaviorType FromType being
10189 /// promoted to an OverflowBehaviorType ToType which has a larger bitwidth.
10190 /// If so, returns true and sets FromType to ToType.
10191 bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType);
10192
10193 /// IsOverflowBehaviorTypeConversion - Determines whether the conversion from
10194 /// FromType to ToType necessarily involves both an OverflowBehaviorType and
10195 /// a non-OverflowBehaviorType. If so, returns true and sets FromType to
10196 /// ToType.
10197 bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType);
10198
10199 /// IsPointerConversion - Determines whether the conversion of the
10200 /// expression From, which has the (possibly adjusted) type FromType,
10201 /// can be converted to the type ToType via a pointer conversion (C++
10202 /// 4.10). If so, returns true and places the converted type (that
10203 /// might differ from ToType in its cv-qualifiers at some level) into
10204 /// ConvertedType.
10205 ///
10206 /// This routine also supports conversions to and from block pointers
10207 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10208 /// pointers to interfaces. FIXME: Once we've determined the
10209 /// appropriate overloading rules for Objective-C, we may want to
10210 /// split the Objective-C checks into a different routine; however,
10211 /// GCC seems to consider all of these conversions to be pointer
10212 /// conversions, so for now they live here. IncompatibleObjC will be
10213 /// set if the conversion is an allowed Objective-C conversion that
10214 /// should result in a warning.
10215 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10216 bool InOverloadResolution, QualType &ConvertedType,
10217 bool &IncompatibleObjC);
10218
10219 /// isObjCPointerConversion - Determines whether this is an
10220 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10221 /// with the same arguments and return values.
10222 bool isObjCPointerConversion(QualType FromType, QualType ToType,
10223 QualType &ConvertedType, bool &IncompatibleObjC);
10224 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10225 QualType &ConvertedType);
10226
10227 /// FunctionParamTypesAreEqual - This routine checks two function proto types
10228 /// for equality of their parameter types. Caller has already checked that
10229 /// they have same number of parameters. If the parameters are different,
10230 /// ArgPos will have the parameter index of the first different parameter.
10231 /// If `Reversed` is true, the parameters of `NewType` will be compared in
10232 /// reverse order. That's useful if one of the functions is being used as a
10233 /// C++20 synthesized operator overload with a reversed parameter order.
10234 bool FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
10235 ArrayRef<QualType> New,
10236 unsigned *ArgPos = nullptr,
10237 bool Reversed = false);
10238
10239 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
10240 const FunctionProtoType *NewType,
10241 unsigned *ArgPos = nullptr,
10242 bool Reversed = false);
10243
10244 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10245 const FunctionDecl *NewFunction,
10246 unsigned *ArgPos = nullptr,
10247 bool Reversed = false);
10248
10249 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10250 /// function types. Catches different number of parameter, mismatch in
10251 /// parameter types, and different return types.
10252 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType,
10253 QualType ToType);
10254
10255 /// CheckPointerConversion - Check the pointer conversion from the
10256 /// expression From to the type ToType. This routine checks for
10257 /// ambiguous or inaccessible derived-to-base pointer
10258 /// conversions for which IsPointerConversion has already returned
10259 /// true. It returns true and produces a diagnostic if there was an
10260 /// error, or returns false otherwise.
10261 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10262 CXXCastPath &BasePath, bool IgnoreBaseAccess,
10263 bool Diagnose = true);
10264
10265 /// IsMemberPointerConversion - Determines whether the conversion of the
10266 /// expression From, which has the (possibly adjusted) type FromType, can be
10267 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10268 /// If so, returns true and places the converted type (that might differ from
10269 /// ToType in its cv-qualifiers at some level) into ConvertedType.
10270 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10271 bool InOverloadResolution,
10272 QualType &ConvertedType);
10273
10274 enum class MemberPointerConversionResult {
10275 Success,
10276 DifferentPointee,
10277 NotDerived,
10278 Ambiguous,
10279 Virtual,
10280 Inaccessible
10281 };
10282 enum class MemberPointerConversionDirection : bool { Downcast, Upcast };
10283 /// CheckMemberPointerConversion - Check the member pointer conversion from
10284 /// the expression From to the type ToType. This routine checks for ambiguous
10285 /// or virtual or inaccessible base-to-derived member pointer conversions for
10286 /// which IsMemberPointerConversion has already returned true. It produces a
10287 // diagnostic if there was an error.
10288 MemberPointerConversionResult CheckMemberPointerConversion(
10289 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10290 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10291 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10292
10293 /// IsQualificationConversion - Determines whether the conversion from
10294 /// an rvalue of type FromType to ToType is a qualification conversion
10295 /// (C++ 4.4).
10296 ///
10297 /// \param ObjCLifetimeConversion Output parameter that will be set to
10298 /// indicate when the qualification conversion involves a change in the
10299 /// Objective-C object lifetime.
10300 bool IsQualificationConversion(QualType FromType, QualType ToType,
10301 bool CStyle, bool &ObjCLifetimeConversion);
10302
10303 /// Determine whether the conversion from FromType to ToType is a valid
10304 /// conversion of ExtInfo/ExtProtoInfo on the nested function type.
10305 /// More precisely, this method checks whether FromType can be transformed
10306 /// into an exact match for ToType, by transforming its extended function
10307 /// type information in legal manner (e.g. by strictly stripping "noreturn"
10308 /// or "noexcept", or by stripping "noescape" for arguments).
10309 bool IsFunctionConversion(QualType FromType, QualType ToType) const;
10310
10311 /// Same as `IsFunctionConversion`, but if this would return true, it sets
10312 /// `ResultTy` to `ToType`.
10313 bool TryFunctionConversion(QualType FromType, QualType ToType,
10314 QualType &ResultTy) const;
10315
10316 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
10317 void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
10318 DeclarationName Name,
10319 OverloadCandidateSet &CandidateSet,
10320 FunctionDecl *Fn, MultiExprArg Args,
10321 bool IsMember = false);
10322
10323 ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
10324 FunctionDecl *Fun);
10325 ExprResult PerformImplicitObjectArgumentInitialization(
10326 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
10327 CXXMethodDecl *Method);
10328
10329 /// PerformContextuallyConvertToBool - Perform a contextual conversion
10330 /// of the expression From to bool (C++0x [conv]p3).
10331 ExprResult PerformContextuallyConvertToBool(Expr *From);
10332
10333 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10334 /// conversion of the expression From to an Objective-C pointer type.
10335 /// Returns a valid but null ExprResult if no conversion sequence exists.
10336 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
10337
10338 ExprResult BuildConvertedConstantExpression(Expr *From, QualType T,
10339 CCEKind CCE,
10340 NamedDecl *Dest = nullptr);
10341
10342 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10343 llvm::APSInt &Value, CCEKind CCE);
10344 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10345 APValue &Value, CCEKind CCE,
10346 NamedDecl *Dest = nullptr);
10347
10348 /// EvaluateConvertedConstantExpression - Evaluate an Expression
10349 /// That is a converted constant expression
10350 /// (which was built with BuildConvertedConstantExpression)
10351 ExprResult
10352 EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
10353 CCEKind CCE, bool RequireInt,
10354 const APValue &PreNarrowingValue);
10355
10356 /// Abstract base class used to perform a contextual implicit
10357 /// conversion from an expression to any type passing a filter.
10358 class ContextualImplicitConverter {
10359 public:
10360 bool Suppress;
10361 bool SuppressConversion;
10362
10363 ContextualImplicitConverter(bool Suppress = false,
10364 bool SuppressConversion = false)
10365 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
10366
10367 /// Determine whether the specified type is a valid destination type
10368 /// for this conversion.
10369 virtual bool match(QualType T) = 0;
10370
10371 /// Emits a diagnostic complaining that the expression does not have
10372 /// integral or enumeration type.
10373 virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10374 QualType T) = 0;
10375
10376 /// Emits a diagnostic when the expression has incomplete class type.
10377 virtual SemaDiagnosticBuilder
10378 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
10379
10380 /// Emits a diagnostic when the only matching conversion function
10381 /// is explicit.
10382 virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S,
10383 SourceLocation Loc,
10384 QualType T,
10385 QualType ConvTy) = 0;
10386
10387 /// Emits a note for the explicit conversion function.
10388 virtual SemaDiagnosticBuilder
10389 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10390
10391 /// Emits a diagnostic when there are multiple possible conversion
10392 /// functions.
10393 virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10394 QualType T) = 0;
10395
10396 /// Emits a note for one of the candidate conversions.
10397 virtual SemaDiagnosticBuilder
10398 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10399
10400 /// Emits a diagnostic when we picked a conversion function
10401 /// (for cases when we are not allowed to pick a conversion function).
10402 virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S,
10403 SourceLocation Loc,
10404 QualType T,
10405 QualType ConvTy) = 0;
10406
10407 virtual ~ContextualImplicitConverter() {}
10408 };
10409
10410 class ICEConvertDiagnoser : public ContextualImplicitConverter {
10411 bool AllowScopedEnumerations;
10412
10413 public:
10414 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10415 bool SuppressConversion)
10416 : ContextualImplicitConverter(Suppress, SuppressConversion),
10417 AllowScopedEnumerations(AllowScopedEnumerations) {}
10418
10419 /// Match an integral or (possibly scoped) enumeration type.
10420 bool match(QualType T) override;
10421
10422 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10423 QualType T) override {
10424 return diagnoseNotInt(S, Loc, T);
10425 }
10426
10427 /// Emits a diagnostic complaining that the expression does not have
10428 /// integral or enumeration type.
10429 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10430 QualType T) = 0;
10431 };
10432
10433 /// Perform a contextual implicit conversion.
10434 ExprResult
10435 PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE,
10436 ContextualImplicitConverter &Converter);
10437
10438 /// ReferenceCompareResult - Expresses the result of comparing two
10439 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10440 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10441 enum ReferenceCompareResult {
10442 /// Ref_Incompatible - The two types are incompatible, so direct
10443 /// reference binding is not possible.
10444 Ref_Incompatible = 0,
10445 /// Ref_Related - The two types are reference-related, which means
10446 /// that their unqualified forms (T1 and T2) are either the same
10447 /// or T1 is a base class of T2.
10448 Ref_Related,
10449 /// Ref_Compatible - The two types are reference-compatible.
10450 Ref_Compatible
10451 };
10452
10453 // Fake up a scoped enumeration that still contextually converts to bool.
10454 struct ReferenceConversionsScope {
10455 /// The conversions that would be performed on an lvalue of type T2 when
10456 /// binding a reference of type T1 to it, as determined when evaluating
10457 /// whether T1 is reference-compatible with T2.
10458 enum ReferenceConversions {
10459 Qualification = 0x1,
10460 NestedQualification = 0x2,
10461 Function = 0x4,
10462 DerivedToBase = 0x8,
10463 ObjC = 0x10,
10464 ObjCLifetime = 0x20,
10465
10466 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
10467 };
10468 };
10469 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
10470
10471 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10472 /// determine whether they are reference-compatible,
10473 /// reference-related, or incompatible, for use in C++ initialization by
10474 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10475 /// type, and the first type (T1) is the pointee type of the reference
10476 /// type being initialized.
10477 ReferenceCompareResult
10478 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
10479 ReferenceConversions *Conv = nullptr);
10480
10481 /// AddOverloadCandidate - Adds the given function to the set of
10482 /// candidate functions, using the given function call arguments. If
10483 /// @p SuppressUserConversions, then don't allow user-defined
10484 /// conversions via constructors or conversion operators.
10485 ///
10486 /// \param PartialOverloading true if we are performing "partial" overloading
10487 /// based on an incomplete set of function arguments. This feature is used by
10488 /// code completion.
10489 void AddOverloadCandidate(
10490 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
10491 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10492 bool PartialOverloading = false, bool AllowExplicit = true,
10493 bool AllowExplicitConversion = false,
10494 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10495 ConversionSequenceList EarlyConversions = {},
10496 OverloadCandidateParamOrder PO = {},
10497 bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10498
10499 /// Add all of the function declarations in the given function set to
10500 /// the overload candidate set.
10501 void AddFunctionCandidates(
10502 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10503 OverloadCandidateSet &CandidateSet,
10504 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10505 bool SuppressUserConversions = false, bool PartialOverloading = false,
10506 bool FirstArgumentIsBase = false);
10507
10508 /// AddMethodCandidate - Adds a named decl (which is some kind of
10509 /// method) as a method candidate to the given overload set.
10510 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10511 Expr::Classification ObjectClassification,
10512 ArrayRef<Expr *> Args,
10513 OverloadCandidateSet &CandidateSet,
10514 bool SuppressUserConversion = false,
10515 OverloadCandidateParamOrder PO = {});
10516
10517 /// AddMethodCandidate - Adds the given C++ member function to the set
10518 /// of candidate functions, using the given function call arguments
10519 /// and the object argument (@c Object). For example, in a call
10520 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10521 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10522 /// allow user-defined conversions via constructors or conversion
10523 /// operators.
10524 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10525 CXXRecordDecl *ActingContext, QualType ObjectType,
10526 Expr::Classification ObjectClassification,
10527 ArrayRef<Expr *> Args,
10528 OverloadCandidateSet &CandidateSet,
10529 bool SuppressUserConversions = false,
10530 bool PartialOverloading = false,
10531 ConversionSequenceList EarlyConversions = {},
10532 OverloadCandidateParamOrder PO = {},
10533 bool StrictPackMatch = false);
10534
10535 /// Add a C++ member function template as a candidate to the candidate
10536 /// set, using template argument deduction to produce an appropriate member
10537 /// function template specialization.
10538 void AddMethodTemplateCandidate(
10539 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10540 CXXRecordDecl *ActingContext,
10541 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10542 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10543 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10544 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10545
10546 /// Add a C++ function template specialization as a candidate
10547 /// in the candidate set, using template argument deduction to produce
10548 /// an appropriate function template specialization.
10549 void AddTemplateOverloadCandidate(
10550 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10551 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10552 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10553 bool PartialOverloading = false, bool AllowExplicit = true,
10554 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10555 OverloadCandidateParamOrder PO = {},
10556 bool AggregateCandidateDeduction = false);
10557
10558 struct CheckNonDependentConversionsFlag {
10559 /// Do not consider any user-defined conversions when constructing the
10560 /// initializing sequence.
10561 bool SuppressUserConversions;
10562
10563 /// Before constructing the initializing sequence, we check whether the
10564 /// parameter type and argument type contain any user defined conversions.
10565 /// If so, do not initialize them. This effectively bypasses some undesired
10566 /// instantiation before checking constaints, which might otherwise result
10567 /// in non-SFINAE errors e.g. recursive constraints.
10568 bool OnlyInitializeNonUserDefinedConversions;
10569
10570 CheckNonDependentConversionsFlag(
10571 bool SuppressUserConversions,
10572 bool OnlyInitializeNonUserDefinedConversions)
10573 : SuppressUserConversions(SuppressUserConversions),
10574 OnlyInitializeNonUserDefinedConversions(
10575 OnlyInitializeNonUserDefinedConversions) {}
10576 };
10577
10578 /// Check that implicit conversion sequences can be formed for each argument
10579 /// whose corresponding parameter has a non-dependent type, per DR1391's
10580 /// [temp.deduct.call]p10.
10581 bool CheckNonDependentConversions(
10582 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
10583 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10584 ConversionSequenceList &Conversions,
10585 CheckNonDependentConversionsFlag UserConversionFlag,
10586 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10587 Expr::Classification ObjectClassification = {},
10588 OverloadCandidateParamOrder PO = {});
10589
10590 /// AddConversionCandidate - Add a C++ conversion function as a
10591 /// candidate in the candidate set (C++ [over.match.conv],
10592 /// C++ [over.match.copy]). From is the expression we're converting from,
10593 /// and ToType is the type that we're eventually trying to convert to
10594 /// (which may or may not be the same type as the type that the
10595 /// conversion function produces).
10596 void AddConversionCandidate(
10597 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10598 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10599 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10600 bool AllowExplicit, bool AllowResultConversion = true,
10601 bool StrictPackMatch = false);
10602
10603 /// Adds a conversion function template specialization
10604 /// candidate to the overload set, using template argument deduction
10605 /// to deduce the template arguments of the conversion function
10606 /// template from the type that we are converting to (C++
10607 /// [temp.deduct.conv]).
10608 void AddTemplateConversionCandidate(
10609 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10610 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10611 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10612 bool AllowExplicit, bool AllowResultConversion = true);
10613
10614 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10615 /// converts the given @c Object to a function pointer via the
10616 /// conversion function @c Conversion, and then attempts to call it
10617 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10618 /// the type of function that we'll eventually be calling.
10619 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10620 DeclAccessPair FoundDecl,
10621 CXXRecordDecl *ActingContext,
10622 const FunctionProtoType *Proto, Expr *Object,
10623 ArrayRef<Expr *> Args,
10624 OverloadCandidateSet &CandidateSet);
10625
10626 /// Add all of the non-member operator function declarations in the given
10627 /// function set to the overload candidate set.
10628 void AddNonMemberOperatorCandidates(
10629 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10630 OverloadCandidateSet &CandidateSet,
10631 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10632
10633 /// Add overload candidates for overloaded operators that are
10634 /// member functions.
10635 ///
10636 /// Add the overloaded operator candidates that are member functions
10637 /// for the operator Op that was used in an operator expression such
10638 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10639 /// CandidateSet will store the added overload candidates. (C++
10640 /// [over.match.oper]).
10641 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
10642 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10643 OverloadCandidateSet &CandidateSet,
10644 OverloadCandidateParamOrder PO = {});
10645
10646 /// AddBuiltinCandidate - Add a candidate for a built-in
10647 /// operator. ResultTy and ParamTys are the result and parameter types
10648 /// of the built-in candidate, respectively. Args and NumArgs are the
10649 /// arguments being passed to the candidate. IsAssignmentOperator
10650 /// should be true when this built-in candidate is an assignment
10651 /// operator. NumContextualBoolArguments is the number of arguments
10652 /// (at the beginning of the argument list) that will be contextually
10653 /// converted to bool.
10654 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10655 OverloadCandidateSet &CandidateSet,
10656 bool IsAssignmentOperator = false,
10657 unsigned NumContextualBoolArguments = 0);
10658
10659 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10660 /// operator overloads to the candidate set (C++ [over.built]), based
10661 /// on the operator @p Op and the arguments given. For example, if the
10662 /// operator is a binary '+', this routine might add "int
10663 /// operator+(int, int)" to cover integer addition.
10664 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10665 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10666 OverloadCandidateSet &CandidateSet);
10667
10668 /// Add function candidates found via argument-dependent lookup
10669 /// to the set of overloading candidates.
10670 ///
10671 /// This routine performs argument-dependent name lookup based on the
10672 /// given function name (which may also be an operator name) and adds
10673 /// all of the overload candidates found by ADL to the overload
10674 /// candidate set (C++ [basic.lookup.argdep]).
10675 void AddArgumentDependentLookupCandidates(
10676 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10677 TemplateArgumentListInfo *ExplicitTemplateArgs,
10678 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10679
10680 /// Check the enable_if expressions on the given function. Returns the first
10681 /// failing attribute, or NULL if they were all successful.
10682 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10683 ArrayRef<Expr *> Args,
10684 bool MissingImplicitThis = false);
10685
10686 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10687 /// non-ArgDependent DiagnoseIfAttrs.
10688 ///
10689 /// Argument-dependent diagnose_if attributes should be checked each time a
10690 /// function is used as a direct callee of a function call.
10691 ///
10692 /// Returns true if any errors were emitted.
10693 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10694 const Expr *ThisArg,
10695 ArrayRef<const Expr *> Args,
10696 SourceLocation Loc);
10697
10698 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10699 /// ArgDependent DiagnoseIfAttrs.
10700 ///
10701 /// Argument-independent diagnose_if attributes should be checked on every use
10702 /// of a function.
10703 ///
10704 /// Returns true if any errors were emitted.
10705 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10706 SourceLocation Loc);
10707
10708 /// Determine if \p A and \p B are equivalent internal linkage declarations
10709 /// from different modules, and thus an ambiguity error can be downgraded to
10710 /// an extension warning.
10711 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10712 const NamedDecl *B);
10713 void diagnoseEquivalentInternalLinkageDeclarations(
10714 SourceLocation Loc, const NamedDecl *D,
10715 ArrayRef<const NamedDecl *> Equiv);
10716
10717 // Emit as a 'note' the specific overload candidate
10718 void NoteOverloadCandidate(
10719 const NamedDecl *Found, const FunctionDecl *Fn,
10720 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
10721 QualType DestType = QualType(), bool TakingAddress = false);
10722
10723 // Emit as a series of 'note's all template and non-templates identified by
10724 // the expression Expr
10725 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10726 bool TakingAddress = false);
10727
10728 /// Returns whether the given function's address can be taken or not,
10729 /// optionally emitting a diagnostic if the address can't be taken.
10730 ///
10731 /// Returns false if taking the address of the function is illegal.
10732 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10733 bool Complain = false,
10734 SourceLocation Loc = SourceLocation());
10735
10736 // [PossiblyAFunctionType] --> [Return]
10737 // NonFunctionType --> NonFunctionType
10738 // R (A) --> R(A)
10739 // R (*)(A) --> R (A)
10740 // R (&)(A) --> R (A)
10741 // R (S::*)(A) --> R (A)
10742 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10743
10744 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10745 /// an overloaded function (C++ [over.over]), where @p From is an
10746 /// expression with overloaded function type and @p ToType is the type
10747 /// we're trying to resolve to. For example:
10748 ///
10749 /// @code
10750 /// int f(double);
10751 /// int f(int);
10752 ///
10753 /// int (*pfd)(double) = f; // selects f(double)
10754 /// @endcode
10755 ///
10756 /// This routine returns the resulting FunctionDecl if it could be
10757 /// resolved, and NULL otherwise. When @p Complain is true, this
10758 /// routine will emit diagnostics if there is an error.
10759 FunctionDecl *
10760 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10761 bool Complain, DeclAccessPair &Found,
10762 bool *pHadMultipleCandidates = nullptr);
10763
10764 /// Given an expression that refers to an overloaded function, try to
10765 /// resolve that function to a single function that can have its address
10766 /// taken. This will modify `Pair` iff it returns non-null.
10767 ///
10768 /// This routine can only succeed if from all of the candidates in the
10769 /// overload set for SrcExpr that can have their addresses taken, there is one
10770 /// candidate that is more constrained than the rest.
10771 FunctionDecl *
10772 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10773
10774 /// Given an overloaded function, tries to turn it into a non-overloaded
10775 /// function reference using resolveAddressOfSingleOverloadCandidate. This
10776 /// will perform access checks, diagnose the use of the resultant decl, and,
10777 /// if requested, potentially perform a function-to-pointer decay.
10778 ///
10779 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10780 /// Otherwise, returns true. This may emit diagnostics and return true.
10781 bool resolveAndFixAddressOfSingleOverloadCandidate(
10782 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10783
10784 /// Given an expression that refers to an overloaded function, try to
10785 /// resolve that overloaded function expression down to a single function.
10786 ///
10787 /// This routine can only resolve template-ids that refer to a single function
10788 /// template, where that template-id refers to a single template whose
10789 /// template arguments are either provided by the template-id or have
10790 /// defaults, as described in C++0x [temp.arg.explicit]p3.
10791 ///
10792 /// If no template-ids are found, no diagnostics are emitted and NULL is
10793 /// returned.
10794 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(
10795 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10796 TemplateSpecCandidateSet *FailedTSC = nullptr,
10797 bool ForTypeDeduction = false);
10798
10799 // Resolve and fix an overloaded expression that can be resolved
10800 // because it identifies a single function template specialization.
10801 //
10802 // Last three arguments should only be supplied if Complain = true
10803 //
10804 // Return true if it was logically possible to so resolve the
10805 // expression, regardless of whether or not it succeeded. Always
10806 // returns true if 'complain' is set.
10807 bool ResolveAndFixSingleFunctionTemplateSpecialization(
10808 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10809 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10810 QualType DestTypeForComplaining = QualType(),
10811 unsigned DiagIDForComplaining = 0);
10812
10813 /// Add the overload candidates named by callee and/or found by argument
10814 /// dependent lookup to the given overload set.
10815 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10816 ArrayRef<Expr *> Args,
10817 OverloadCandidateSet &CandidateSet,
10818 bool PartialOverloading = false);
10819
10820 /// Add the call candidates from the given set of lookup results to the given
10821 /// overload set. Non-function lookup results are ignored.
10822 void AddOverloadedCallCandidates(
10823 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
10824 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
10825
10826 // An enum used to represent the different possible results of building a
10827 // range-based for loop.
10828 enum ForRangeStatus {
10829 FRS_Success,
10830 FRS_NoViableFunction,
10831 FRS_DiagnosticIssued
10832 };
10833
10834 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
10835 /// given LookupResult is non-empty, it is assumed to describe a member which
10836 /// will be invoked. Otherwise, the function will be found via argument
10837 /// dependent lookup.
10838 /// CallExpr is set to a valid expression and FRS_Success returned on success,
10839 /// otherwise CallExpr is set to ExprError() and some non-success value
10840 /// is returned.
10841 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
10842 SourceLocation RangeLoc,
10843 const DeclarationNameInfo &NameInfo,
10844 LookupResult &MemberLookup,
10845 OverloadCandidateSet *CandidateSet,
10846 Expr *Range, ExprResult *CallExpr);
10847
10848 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10849 /// (which eventually refers to the declaration Func) and the call
10850 /// arguments Args/NumArgs, attempt to resolve the function call down
10851 /// to a specific function. If overload resolution succeeds, returns
10852 /// the call expression produced by overload resolution.
10853 /// Otherwise, emits diagnostics and returns ExprError.
10854 ExprResult BuildOverloadedCallExpr(
10855 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
10856 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
10857 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
10858
10859 /// Constructs and populates an OverloadedCandidateSet from
10860 /// the given function.
10861 /// \returns true when an the ExprResult output parameter has been set.
10862 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
10863 MultiExprArg Args, SourceLocation RParenLoc,
10864 OverloadCandidateSet *CandidateSet,
10865 ExprResult *Result);
10866
10867 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
10868 NestedNameSpecifierLoc NNSLoc,
10869 DeclarationNameInfo DNI,
10870 const UnresolvedSetImpl &Fns,
10871 bool PerformADL = true);
10872
10873 /// Perform lookup for an overloaded unary operator.
10874 void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet,
10875 OverloadedOperatorKind Op,
10876 const UnresolvedSetImpl &Fns,
10877 ArrayRef<Expr *> Args, bool RequiresADL = true);
10878
10879 /// Create a unary operation that may resolve to an overloaded
10880 /// operator.
10881 ///
10882 /// \param OpLoc The location of the operator itself (e.g., '*').
10883 ///
10884 /// \param Opc The UnaryOperatorKind that describes this operator.
10885 ///
10886 /// \param Fns The set of non-member functions that will be
10887 /// considered by overload resolution. The caller needs to build this
10888 /// set based on the context using, e.g.,
10889 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10890 /// set should not contain any member functions; those will be added
10891 /// by CreateOverloadedUnaryOp().
10892 ///
10893 /// \param Input The input argument.
10894 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
10895 UnaryOperatorKind Opc,
10896 const UnresolvedSetImpl &Fns, Expr *input,
10897 bool RequiresADL = true);
10898
10899 /// Perform lookup for an overloaded binary operator.
10900 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
10901 OverloadedOperatorKind Op,
10902 const UnresolvedSetImpl &Fns,
10903 ArrayRef<Expr *> Args, bool RequiresADL = true);
10904
10905 /// Create a binary operation that may resolve to an overloaded
10906 /// operator.
10907 ///
10908 /// \param OpLoc The location of the operator itself (e.g., '+').
10909 ///
10910 /// \param Opc The BinaryOperatorKind that describes this operator.
10911 ///
10912 /// \param Fns The set of non-member functions that will be
10913 /// considered by overload resolution. The caller needs to build this
10914 /// set based on the context using, e.g.,
10915 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10916 /// set should not contain any member functions; those will be added
10917 /// by CreateOverloadedBinOp().
10918 ///
10919 /// \param LHS Left-hand argument.
10920 /// \param RHS Right-hand argument.
10921 /// \param PerformADL Whether to consider operator candidates found by ADL.
10922 /// \param AllowRewrittenCandidates Whether to consider candidates found by
10923 /// C++20 operator rewrites.
10924 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
10925 /// the function in question. Such a function is never a candidate in
10926 /// our overload resolution. This also enables synthesizing a three-way
10927 /// comparison from < and == as described in C++20 [class.spaceship]p1.
10928 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
10929 const UnresolvedSetImpl &Fns, Expr *LHS,
10930 Expr *RHS, bool RequiresADL = true,
10931 bool AllowRewrittenCandidates = true,
10932 FunctionDecl *DefaultedFn = nullptr);
10933 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
10934 const UnresolvedSetImpl &Fns,
10935 Expr *LHS, Expr *RHS,
10936 FunctionDecl *DefaultedFn);
10937
10938 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10939 SourceLocation RLoc, Expr *Base,
10940 MultiExprArg Args);
10941
10942 /// BuildCallToMemberFunction - Build a call to a member
10943 /// function. MemExpr is the expression that refers to the member
10944 /// function (and includes the object parameter), Args/NumArgs are the
10945 /// arguments to the function call (not including the object
10946 /// parameter). The caller needs to validate that the member
10947 /// expression refers to a non-static member function or an overloaded
10948 /// member function.
10949 ExprResult BuildCallToMemberFunction(
10950 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
10951 SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
10952 bool IsExecConfig = false, bool AllowRecovery = false);
10953
10954 /// BuildCallToObjectOfClassType - Build a call to an object of class
10955 /// type (C++ [over.call.object]), which can end up invoking an
10956 /// overloaded function call operator (@c operator()) or performing a
10957 /// user-defined conversion on the object argument.
10958 ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object,
10959 SourceLocation LParenLoc,
10960 MultiExprArg Args,
10961 SourceLocation RParenLoc);
10962
10963 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
10964 /// (if one exists), where @c Base is an expression of class type and
10965 /// @c Member is the name of the member we're trying to find.
10966 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
10967 SourceLocation OpLoc,
10968 bool *NoArrowOperatorFound = nullptr);
10969
10970 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
10971 CXXConversionDecl *Method,
10972 bool HadMultipleCandidates);
10973
10974 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
10975 /// to a literal operator described by the provided lookup results.
10976 ExprResult BuildLiteralOperatorCall(
10977 LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args,
10978 SourceLocation LitEndLoc,
10979 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10980
10981 /// FixOverloadedFunctionReference - E is an expression that refers to
10982 /// a C++ overloaded function (possibly with some parentheses and
10983 /// perhaps a '&' around it). We have resolved the overloaded function
10984 /// to the function declaration Fn, so patch up the expression E to
10985 /// refer (possibly indirectly) to Fn. Returns the new expr.
10986 ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl,
10987 FunctionDecl *Fn);
10988 ExprResult FixOverloadedFunctionReference(ExprResult,
10989 DeclAccessPair FoundDecl,
10990 FunctionDecl *Fn);
10991
10992 /// - Returns a selector which best matches given argument list or
10993 /// nullptr if none could be found
10994 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
10995 bool IsInstance,
10996 SmallVectorImpl<ObjCMethodDecl *> &Methods);
10997
10998 ///@}
10999
11000 //
11001 //
11002 // -------------------------------------------------------------------------
11003 //
11004 //
11005
11006 /// \name Statements
11007 /// Implementations are in SemaStmt.cpp
11008 ///@{
11009
11010public:
11011 /// Stack of active SEH __finally scopes. Can be empty.
11012 SmallVector<Scope *, 2> CurrentSEHFinally;
11013
11014 /// Stack of '_Defer' statements that are currently being parsed, as well
11015 /// as the locations of their '_Defer' keywords. Can be empty.
11016 SmallVector<std::pair<Scope *, SourceLocation>, 2> CurrentDefer;
11017
11018 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
11019 StmtResult ActOnExprStmtError();
11020
11021 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
11022 bool HasLeadingEmptyMacro = false);
11023
11024 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc,
11025 SourceLocation EndLoc);
11026 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
11027
11028 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
11029 /// whose result is unused, warn.
11030 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
11031
11032 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
11033 void ActOnAfterCompoundStatementLeadingPragmas();
11034 void ActOnFinishOfCompoundStmt();
11035 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
11036 ArrayRef<Stmt *> Elts, bool isStmtExpr);
11037
11038 sema::CompoundScopeInfo &getCurCompoundScope() const;
11039
11040 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
11041 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
11042 SourceLocation DotDotDotLoc, ExprResult RHS,
11043 SourceLocation ColonLoc);
11044
11045 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
11046 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
11047
11048 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
11049 SourceLocation ColonLoc, Stmt *SubStmt,
11050 Scope *CurScope);
11051 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
11052 SourceLocation ColonLoc, Stmt *SubStmt);
11053
11054 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
11055 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
11056 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
11057 Stmt *SubStmt);
11058
11059 /// Check whether the given statement can have musttail applied to it,
11060 /// issuing a diagnostic and returning false if not. In the success case,
11061 /// the statement is rewritten to remove implicit nodes from the return
11062 /// value.
11063 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11064
11065 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11066 SourceLocation LParenLoc, Stmt *InitStmt,
11067 ConditionResult Cond, SourceLocation RParenLoc,
11068 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11069 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11070 SourceLocation LParenLoc, Stmt *InitStmt,
11071 ConditionResult Cond, SourceLocation RParenLoc,
11072 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11073
11074 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11075
11076 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
11077 SourceLocation LParenLoc, Stmt *InitStmt,
11078 ConditionResult Cond,
11079 SourceLocation RParenLoc);
11080 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
11081 Stmt *Body);
11082
11083 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11084 /// integer not in the range of enum values.
11085 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11086 Expr *SrcExpr);
11087
11088 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
11089 ConditionResult Cond, SourceLocation RParenLoc,
11090 Stmt *Body);
11091 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
11092 SourceLocation WhileLoc, SourceLocation CondLParen,
11093 Expr *Cond, SourceLocation CondRParen);
11094
11095 StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
11096 Stmt *First, ConditionResult Second,
11097 FullExprArg Third, SourceLocation RParenLoc,
11098 Stmt *Body);
11099
11100 /// In an Objective C collection iteration statement:
11101 /// for (x in y)
11102 /// x can be an arbitrary l-value expression. Bind it up as a
11103 /// full-expression.
11104 StmtResult ActOnForEachLValueExpr(Expr *E);
11105
11106 enum BuildForRangeKind {
11107 /// Initial building of a for-range statement.
11108 BFRK_Build,
11109 /// Instantiation or recovery rebuild of a for-range statement. Don't
11110 /// attempt any typo-correction.
11111 BFRK_Rebuild,
11112 /// Determining whether a for-range statement could be built. Avoid any
11113 /// unnecessary or irreversible actions.
11114 BFRK_Check
11115 };
11116
11117 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
11118 ///
11119 /// C++11 [stmt.ranged]:
11120 /// A range-based for statement is equivalent to
11121 ///
11122 /// {
11123 /// auto && __range = range-init;
11124 /// for ( auto __begin = begin-expr,
11125 /// __end = end-expr;
11126 /// __begin != __end;
11127 /// ++__begin ) {
11128 /// for-range-declaration = *__begin;
11129 /// statement
11130 /// }
11131 /// }
11132 ///
11133 /// The body of the loop is not available yet, since it cannot be analysed
11134 /// until we have determined the type of the for-range-declaration.
11135 StmtResult ActOnCXXForRangeStmt(
11136 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11137 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11138 SourceLocation RParenLoc, BuildForRangeKind Kind,
11139 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11140
11141 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11142 StmtResult BuildCXXForRangeStmt(
11143 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11144 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11145 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11146 BuildForRangeKind Kind,
11147 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11148
11149 /// Set the type of a for-range declaration whose for-range or expansion
11150 /// initialiser is dependent.
11151 void ActOnDependentForRangeInitializer(VarDecl *LoopVar,
11152 BuildForRangeKind BFRK);
11153
11154 /// Holds the 'begin' and 'end' variables of a range-based for loop or
11155 /// expansion statement; begin-expr and end-expr are also provided; the
11156 /// latter are used in some diagnostics.
11157 struct ForRangeBeginEndInfo {
11158 VarDecl *BeginVar = nullptr;
11159 VarDecl *EndVar = nullptr;
11160 Expr *BeginExpr = nullptr;
11161 Expr *EndExpr = nullptr;
11162 bool isValid() const { return BeginVar != nullptr && EndVar != nullptr; }
11163 };
11164
11165 /// Determine begin-expr and end-expr and build variable declarations for
11166 /// them as per [stmt.ranged].
11167 ForRangeBeginEndInfo BuildCXXForRangeBeginEndVars(
11168 Scope *S, VarDecl *RangeVar, SourceLocation ColonLoc,
11169 SourceLocation CoawaitLoc,
11170 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps,
11171 BuildForRangeKind Kind, bool IsConstexpr,
11172 StmtResult *RebuildResult = nullptr,
11173 llvm::function_ref<StmtResult()> RebuildWithDereference = {},
11174 IdentifierInfo *BeginName = nullptr, IdentifierInfo *EndName = nullptr);
11175
11176 /// Helper used by the expansion statements and for-range code to build
11177 /// a variable declaration for e.g. 'begin' and 'end'.
11178 VarDecl *BuildForRangeVarDecl(SourceLocation Loc, QualType Type,
11179 IdentifierInfo *Name, bool IsConstexpr);
11180
11181 /// Build the range variable of a range-based for loop or iterating
11182 /// expansion statement and return its DeclStmt.
11183 StmtResult BuildCXXForRangeRangeVar(Scope *S, Expr *Range, QualType Type,
11184 bool IsConstexpr = false);
11185
11186 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11187 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11188 /// body cannot be performed until after the type of the range variable is
11189 /// determined.
11190 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11191
11192 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11193 LabelDecl *TheDecl);
11194 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11195 SourceLocation StarLoc, Expr *DestExp);
11196 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
11197 LabelDecl *Label, SourceLocation LabelLoc);
11198 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
11199 LabelDecl *Label, SourceLocation LabelLoc);
11200
11201 void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope);
11202 void ActOnDeferStmtError(Scope *CurScope);
11203 StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope);
11204
11205 struct NamedReturnInfo {
11206 const VarDecl *Candidate;
11207
11208 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
11209 Status S;
11210
11211 bool isMoveEligible() const { return S != None; };
11212 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
11213 };
11214 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
11215
11216 /// Determine whether the given expression might be move-eligible or
11217 /// copy-elidable in either a (co_)return statement or throw expression,
11218 /// without considering function return type, if applicable.
11219 ///
11220 /// \param E The expression being returned from the function or block,
11221 /// being thrown, or being co_returned from a coroutine. This expression
11222 /// might be modified by the implementation.
11223 ///
11224 /// \param Mode Overrides detection of current language mode
11225 /// and uses the rules for C++23.
11226 ///
11227 /// \returns An aggregate which contains the Candidate and isMoveEligible
11228 /// and isCopyElidable methods. If Candidate is non-null, it means
11229 /// isMoveEligible() would be true under the most permissive language
11230 /// standard.
11231 NamedReturnInfo getNamedReturnInfo(
11232 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
11233
11234 /// Determine whether the given NRVO candidate variable is move-eligible or
11235 /// copy-elidable, without considering function return type.
11236 ///
11237 /// \param VD The NRVO candidate variable.
11238 ///
11239 /// \returns An aggregate which contains the Candidate and isMoveEligible
11240 /// and isCopyElidable methods. If Candidate is non-null, it means
11241 /// isMoveEligible() would be true under the most permissive language
11242 /// standard.
11243 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11244
11245 /// Updates given NamedReturnInfo's move-eligible and
11246 /// copy-elidable statuses, considering the function
11247 /// return type criteria as applicable to return statements.
11248 ///
11249 /// \param Info The NamedReturnInfo object to update.
11250 ///
11251 /// \param ReturnType This is the return type of the function.
11252 /// \returns The copy elision candidate, in case the initial return expression
11253 /// was copy elidable, or nullptr otherwise.
11254 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11255 QualType ReturnType);
11256
11257 /// Perform the initialization of a potentially-movable value, which
11258 /// is the result of return value.
11259 ///
11260 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11261 /// treat returned lvalues as rvalues in certain cases (to prefer move
11262 /// construction), then falls back to treating them as lvalues if that failed.
11263 ExprResult
11264 PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
11265 const NamedReturnInfo &NRInfo, Expr *Value,
11266 bool SupressSimplerImplicitMoves = false);
11267
11268 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
11269
11270 /// Deduce the return type for a function from a returned expression, per
11271 /// C++1y [dcl.spec.auto]p6.
11272 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
11273 SourceLocation ReturnLoc, Expr *RetExpr,
11274 const AutoType *AT);
11275
11276 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11277 Scope *CurScope);
11278 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11279 bool AllowRecovery = false);
11280
11281 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11282 /// for capturing scopes.
11283 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11284 NamedReturnInfo &NRInfo,
11285 bool SupressSimplerImplicitMoves);
11286
11287 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11288 /// and creates a proper catch handler from them.
11289 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
11290 Stmt *HandlerBlock);
11291
11292 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11293 /// handlers and creates a try statement from them.
11294 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
11295 ArrayRef<Stmt *> Handlers);
11296
11297 void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11298
11299 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11300 SourceLocation TryLoc, Stmt *TryBlock,
11301 Stmt *Handler);
11302 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
11303 Stmt *Block);
11304 void ActOnStartSEHFinallyBlock();
11305 void ActOnAbortSEHFinallyBlock();
11306 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
11307 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
11308
11309 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
11310 bool IsIfExists,
11311 NestedNameSpecifierLoc QualifierLoc,
11312 DeclarationNameInfo NameInfo,
11313 Stmt *Nested);
11314 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
11315 bool IsIfExists, CXXScopeSpec &SS,
11316 UnqualifiedId &Name, Stmt *Nested);
11317
11318 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11319 CapturedRegionKind Kind, unsigned NumParams);
11320 typedef std::pair<StringRef, QualType> CapturedParamNameType;
11321 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11322 CapturedRegionKind Kind,
11323 ArrayRef<CapturedParamNameType> Params,
11324 unsigned OpenMPCaptureLevel = 0);
11325 StmtResult ActOnCapturedRegionEnd(Stmt *S);
11326 void ActOnCapturedRegionError();
11327 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
11328 SourceLocation Loc,
11329 unsigned NumParams);
11330
11331 void ApplyForRangeOrExpansionStatementLifetimeExtension(
11332 VarDecl *RangeVar, ArrayRef<MaterializeTemporaryExpr *> Temporaries);
11333
11334private:
11335 /// Check whether the given statement can have musttail applied to it,
11336 /// issuing a diagnostic and returning false if not.
11337 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11338
11339 ///@}
11340
11341 //
11342 //
11343 // -------------------------------------------------------------------------
11344 //
11345 //
11346
11347 /// \name `inline asm` Statement
11348 /// Implementations are in SemaStmtAsm.cpp
11349 ///@{
11350
11351public:
11352 ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel);
11353 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11354 bool IsVolatile, unsigned NumOutputs,
11355 unsigned NumInputs, IdentifierInfo **Names,
11356 MultiExprArg Constraints, MultiExprArg Exprs,
11357 Expr *AsmString, MultiExprArg Clobbers,
11358 unsigned NumLabels, SourceLocation RParenLoc);
11359
11360 void FillInlineAsmIdentifierInfo(Expr *Res,
11361 llvm::InlineAsmIdentifierInfo &Info);
11362 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
11363 SourceLocation TemplateKWLoc,
11364 UnqualifiedId &Id,
11365 bool IsUnevaluatedContext);
11366 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11367 SourceLocation AsmLoc);
11368 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
11369 SourceLocation AsmLoc);
11370 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
11371 ArrayRef<Token> AsmToks, StringRef AsmString,
11372 unsigned NumOutputs, unsigned NumInputs,
11373 ArrayRef<StringRef> Constraints,
11374 ArrayRef<StringRef> Clobbers,
11375 ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11376 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11377 SourceLocation Location, bool AlwaysCreate);
11378
11379 ///@}
11380
11381 //
11382 //
11383 // -------------------------------------------------------------------------
11384 //
11385 //
11386
11387 /// \name Statement Attribute Handling
11388 /// Implementations are in SemaStmtAttr.cpp
11389 ///@{
11390
11391public:
11392 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11393 const AttributeCommonInfo &A);
11394 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11395 const AttributeCommonInfo &A);
11396
11397 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11398 bool CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs);
11399
11400 /// Process the attributes before creating an attributed statement. Returns
11401 /// the semantic attributes that have been processed.
11402 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11403 SmallVectorImpl<const Attr *> &OutAttrs);
11404
11405 ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A,
11406 SourceRange Range);
11407 ExprResult BuildCXXAssumeExpr(Expr *Assumption,
11408 const IdentifierInfo *AttrName,
11409 SourceRange Range);
11410
11411 ///@}
11412
11413 //
11414 //
11415 // -------------------------------------------------------------------------
11416 //
11417 //
11418
11419 /// \name C++ Templates
11420 /// Implementations are in SemaTemplate.cpp
11421 ///@{
11422
11423public:
11424 // Saves the current floating-point pragma stack and clear it in this Sema.
11425 class FpPragmaStackSaveRAII {
11426 public:
11427 FpPragmaStackSaveRAII(Sema &S)
11428 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11429 S.FpPragmaStack.Stack.clear();
11430 }
11431 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11432 FpPragmaStackSaveRAII(const FpPragmaStackSaveRAII &) = delete;
11433 FpPragmaStackSaveRAII &operator=(const FpPragmaStackSaveRAII &) = delete;
11434
11435 private:
11436 Sema &S;
11437 PragmaStack<FPOptionsOverride> SavedStack;
11438 };
11439
11440 void resetFPOptions(FPOptions FPO) {
11441 CurFPFeatures = FPO;
11442 FpPragmaStack.CurrentValue = FPO.getChangesFrom(Base: FPOptions(LangOpts));
11443 }
11444
11445 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
11446 return llvm::ArrayRef(InventedParameterInfos.begin() +
11447 InventedParameterInfosStart,
11448 InventedParameterInfos.end());
11449 }
11450
11451 ArrayRef<sema::FunctionScopeInfo *> getFunctionScopes() const {
11452 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
11453 FunctionScopes.end());
11454 }
11455
11456 typedef llvm::MapVector<const FunctionDecl *,
11457 std::unique_ptr<LateParsedTemplate>>
11458 LateParsedTemplateMapT;
11459 LateParsedTemplateMapT LateParsedTemplateMap;
11460
11461 /// Determine the number of levels of enclosing template parameters. This is
11462 /// only usable while parsing. Note that this does not include dependent
11463 /// contexts in which no template parameters have yet been declared, such as
11464 /// in a terse function template or generic lambda before the first 'auto' is
11465 /// encountered.
11466 unsigned getTemplateDepth(Scope *S) const;
11467
11468 void FilterAcceptableTemplateNames(LookupResult &R,
11469 bool AllowFunctionTemplates = true,
11470 bool AllowDependent = true);
11471 bool hasAnyAcceptableTemplateNames(LookupResult &R,
11472 bool AllowFunctionTemplates = true,
11473 bool AllowDependent = true,
11474 bool AllowNonTemplateFunctions = false);
11475 /// Try to interpret the lookup result D as a template-name.
11476 ///
11477 /// \param D A declaration found by name lookup.
11478 /// \param AllowFunctionTemplates Whether function templates should be
11479 /// considered valid results.
11480 /// \param AllowDependent Whether unresolved using declarations (that might
11481 /// name templates) should be considered valid results.
11482 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
11483 bool AllowFunctionTemplates = true,
11484 bool AllowDependent = true);
11485
11486 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
11487 /// Whether and why a template name is required in this lookup.
11488 class RequiredTemplateKind {
11489 public:
11490 /// Template name is required if TemplateKWLoc is valid.
11491 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
11492 : TemplateKW(TemplateKWLoc) {}
11493 /// Template name is unconditionally required.
11494 RequiredTemplateKind(TemplateNameIsRequiredTag) {}
11495
11496 SourceLocation getTemplateKeywordLoc() const {
11497 return TemplateKW.value_or(u: SourceLocation());
11498 }
11499 bool hasTemplateKeyword() const {
11500 return getTemplateKeywordLoc().isValid();
11501 }
11502 bool isRequired() const { return TemplateKW != SourceLocation(); }
11503 explicit operator bool() const { return isRequired(); }
11504
11505 private:
11506 std::optional<SourceLocation> TemplateKW;
11507 };
11508
11509 enum class AssumedTemplateKind {
11510 /// This is not assumed to be a template name.
11511 None,
11512 /// This is assumed to be a template name because lookup found nothing.
11513 FoundNothing,
11514 /// This is assumed to be a template name because lookup found one or more
11515 /// functions (but no function templates).
11516 FoundFunctions,
11517 };
11518
11519 bool
11520 LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
11521 QualType ObjectType, bool EnteringContext,
11522 RequiredTemplateKind RequiredTemplate = SourceLocation(),
11523 AssumedTemplateKind *ATK = nullptr,
11524 bool AllowTypoCorrection = true);
11525
11526 TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS,
11527 bool hasTemplateKeyword,
11528 const UnqualifiedId &Name,
11529 ParsedType ObjectType, bool EnteringContext,
11530 TemplateTy &Template,
11531 bool &MemberOfUnknownSpecialization,
11532 bool AllowTypoCorrection = true);
11533
11534 /// Try to resolve an undeclared template name as a type template.
11535 ///
11536 /// Sets II to the identifier corresponding to the template name, and updates
11537 /// Name to a corresponding (typo-corrected) type template name and TNK to
11538 /// the corresponding kind, if possible.
11539 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
11540 TemplateNameKind &TNK,
11541 SourceLocation NameLoc,
11542 IdentifierInfo *&II);
11543
11544 /// Determine whether a particular identifier might be the name in a C++1z
11545 /// deduction-guide declaration.
11546 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11547 SourceLocation NameLoc, CXXScopeSpec &SS,
11548 ParsedTemplateTy *Template = nullptr);
11549
11550 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
11551 SourceLocation IILoc, Scope *S,
11552 const CXXScopeSpec *SS,
11553 TemplateTy &SuggestedTemplate,
11554 TemplateNameKind &SuggestedKind);
11555
11556 /// Determine whether we would be unable to instantiate this template (because
11557 /// it either has no definition, or is in the process of being instantiated).
11558 bool DiagnoseUninstantiableTemplate(
11559 SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11560 bool InstantiatedFromMember, const NamedDecl *Pattern,
11561 const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11562 bool Complain = true, bool *Unreachable = nullptr);
11563
11564 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11565 /// that the template parameter 'PrevDecl' is being shadowed by a new
11566 /// declaration at location Loc. Returns true to indicate that this is
11567 /// an error, and false otherwise.
11568 ///
11569 /// \param Loc The location of the declaration that shadows a template
11570 /// parameter.
11571 ///
11572 /// \param PrevDecl The template parameter that the declaration shadows.
11573 ///
11574 /// \param SupportedForCompatibility Whether to issue the diagnostic as
11575 /// a warning for compatibility with older versions of clang.
11576 /// Ignored when MSVC compatibility is enabled.
11577 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
11578 bool SupportedForCompatibility = false);
11579
11580 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11581 /// the parameter D to reference the templated declaration and return a
11582 /// pointer to the template declaration. Otherwise, do nothing to D and return
11583 /// null.
11584 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
11585
11586 /// ActOnTypeParameter - Called when a C++ template type parameter
11587 /// (e.g., "typename T") has been parsed. Typename specifies whether
11588 /// the keyword "typename" was used to declare the type parameter
11589 /// (otherwise, "class" was used), and KeyLoc is the location of the
11590 /// "class" or "typename" keyword. ParamName is the name of the
11591 /// parameter (NULL indicates an unnamed template parameter) and
11592 /// ParamNameLoc is the location of the parameter name (if any).
11593 /// If the type parameter has a default argument, it will be added
11594 /// later via ActOnTypeParameterDefault.
11595 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
11596 SourceLocation EllipsisLoc,
11597 SourceLocation KeyLoc,
11598 IdentifierInfo *ParamName,
11599 SourceLocation ParamNameLoc, unsigned Depth,
11600 unsigned Position, SourceLocation EqualLoc,
11601 ParsedType DefaultArg, bool HasTypeConstraint);
11602
11603 bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint);
11604
11605 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11606 TemplateIdAnnotation *TypeConstraint,
11607 TemplateTypeParmDecl *ConstrainedParameter,
11608 SourceLocation EllipsisLoc);
11609 bool BuildTypeConstraint(const CXXScopeSpec &SS,
11610 TemplateIdAnnotation *TypeConstraint,
11611 TemplateTypeParmDecl *ConstrainedParameter,
11612 SourceLocation EllipsisLoc,
11613 bool AllowUnexpandedPack);
11614
11615 /// Attach a type-constraint to a template parameter.
11616 /// \returns true if an error occurred. This can happen if the
11617 /// immediately-declared constraint could not be formed (e.g. incorrect number
11618 /// of arguments for the named concept).
11619 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
11620 DeclarationNameInfo NameInfo,
11621 TemplateName NamedConcept, NamedDecl *FoundDecl,
11622 const TemplateArgumentListInfo *TemplateArgs,
11623 TemplateTypeParmDecl *ConstrainedParameter,
11624 SourceLocation EllipsisLoc);
11625
11626 bool AttachTypeConstraint(AutoTypeLoc TL,
11627 NonTypeTemplateParmDecl *NewConstrainedParm,
11628 NonTypeTemplateParmDecl *OrigConstrainedParm,
11629 SourceLocation EllipsisLoc);
11630
11631 /// Require the given type to be a structural type, and diagnose if it is not.
11632 ///
11633 /// \return \c true if an error was produced.
11634 bool RequireStructuralType(QualType T, SourceLocation Loc);
11635
11636 /// Check that the type of a non-type template parameter is
11637 /// well-formed.
11638 ///
11639 /// \returns the (possibly-promoted) parameter type if valid;
11640 /// otherwise, produces a diagnostic and returns a NULL type.
11641 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
11642 SourceLocation Loc);
11643 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
11644
11645 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
11646 unsigned Depth, unsigned Position,
11647 SourceLocation EqualLoc,
11648 Expr *DefaultArg);
11649
11650 /// ActOnTemplateTemplateParameter - Called when a C++ template template
11651 /// parameter (e.g. T in template <template \<typename> class T> class array)
11652 /// has been parsed. S is the current scope.
11653 NamedDecl *ActOnTemplateTemplateParameter(
11654 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind,
11655 bool TypenameKeyword, TemplateParameterList *Params,
11656 SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11657 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11658 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11659
11660 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11661 /// constrained by RequiresClause, that contains the template parameters in
11662 /// Params.
11663 TemplateParameterList *ActOnTemplateParameterList(
11664 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11665 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11666 SourceLocation RAngleLoc, Expr *RequiresClause);
11667
11668 /// The context in which we are checking a template parameter list.
11669 enum TemplateParamListContext {
11670 // For this context, Class, Variable, TypeAlias, and non-pack Template
11671 // Template Parameters are treated uniformly.
11672 TPC_Other,
11673
11674 TPC_FunctionTemplate,
11675 TPC_ClassTemplateMember,
11676 TPC_FriendClassTemplate,
11677 TPC_FriendFunctionTemplate,
11678 TPC_FriendFunctionTemplateDefinition,
11679 TPC_TemplateTemplateParameterPack,
11680 };
11681
11682 /// Checks the validity of a template parameter list, possibly
11683 /// considering the template parameter list from a previous
11684 /// declaration.
11685 ///
11686 /// If an "old" template parameter list is provided, it must be
11687 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11688 /// template parameter list.
11689 ///
11690 /// \param NewParams Template parameter list for a new template
11691 /// declaration. This template parameter list will be updated with any
11692 /// default arguments that are carried through from the previous
11693 /// template parameter list.
11694 ///
11695 /// \param OldParams If provided, template parameter list from a
11696 /// previous declaration of the same template. Default template
11697 /// arguments will be merged from the old template parameter list to
11698 /// the new template parameter list.
11699 ///
11700 /// \param TPC Describes the context in which we are checking the given
11701 /// template parameter list.
11702 ///
11703 /// \param SkipBody If we might have already made a prior merged definition
11704 /// of this template visible, the corresponding body-skipping information.
11705 /// Default argument redefinition is not an error when skipping such a body,
11706 /// because (under the ODR) we can assume the default arguments are the same
11707 /// as the prior merged definition.
11708 ///
11709 /// \returns true if an error occurred, false otherwise.
11710 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
11711 TemplateParameterList *OldParams,
11712 TemplateParamListContext TPC,
11713 SkipBodyInfo *SkipBody = nullptr);
11714
11715 /// Match the given template parameter lists to the given scope
11716 /// specifier, returning the template parameter list that applies to the
11717 /// name.
11718 ///
11719 /// \param DeclStartLoc the start of the declaration that has a scope
11720 /// specifier or a template parameter list.
11721 ///
11722 /// \param DeclLoc The location of the declaration itself.
11723 ///
11724 /// \param SS the scope specifier that will be matched to the given template
11725 /// parameter lists. This scope specifier precedes a qualified name that is
11726 /// being declared.
11727 ///
11728 /// \param TemplateId The template-id following the scope specifier, if there
11729 /// is one. Used to check for a missing 'template<>'.
11730 ///
11731 /// \param ParamLists the template parameter lists, from the outermost to the
11732 /// innermost template parameter lists.
11733 ///
11734 /// \param IsFriend Whether to apply the slightly different rules for
11735 /// matching template parameters to scope specifiers in friend
11736 /// declarations.
11737 ///
11738 /// \param IsMemberSpecialization will be set true if the scope specifier
11739 /// denotes a fully-specialized type, and therefore this is a declaration of
11740 /// a member specialization.
11741 ///
11742 /// \returns the template parameter list, if any, that corresponds to the
11743 /// name that is preceded by the scope specifier @p SS. This template
11744 /// parameter list may have template parameters (if we're declaring a
11745 /// template) or may have no template parameters (if we're declaring a
11746 /// template specialization), or may be NULL (if what we're declaring isn't
11747 /// itself a template).
11748 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
11749 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11750 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11751 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11752 bool &IsMemberSpecialization, bool &Invalid,
11753 bool SuppressDiagnostic = false);
11754
11755 /// Returns the template parameter list with all default template argument
11756 /// information.
11757 TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD);
11758
11759 DeclResult CheckClassTemplate(
11760 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11761 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11762 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11763 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11764 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11765 TemplateParameterList **OuterTemplateParamLists,
11766 bool IsMemberSpecialization, SkipBodyInfo *SkipBody = nullptr);
11767
11768 /// Translates template arguments as provided by the parser
11769 /// into template arguments used by semantic analysis.
11770 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
11771 TemplateArgumentListInfo &Out);
11772
11773 /// Convert a parsed type into a parsed template argument. This is mostly
11774 /// trivial, except that we may have parsed a C++17 deduced class template
11775 /// specialization type, in which case we should form a template template
11776 /// argument instead of a type template argument.
11777 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
11778
11779 void NoteAllFoundTemplates(TemplateName Name);
11780
11781 QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
11782 TemplateName Template,
11783 SourceLocation TemplateLoc,
11784 TemplateArgumentListInfo &TemplateArgs,
11785 Scope *Scope, bool ForNestedNameSpecifier);
11786
11787 TypeResult
11788 ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
11789 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
11790 SourceLocation TemplateKWLoc, TemplateTy Template,
11791 const IdentifierInfo *TemplateII,
11792 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11793 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11794 bool IsCtorOrDtorName = false, bool IsClassName = false,
11795 ImplicitTypenameContext AllowImplicitTypename =
11796 ImplicitTypenameContext::No);
11797
11798 /// Parsed an elaborated-type-specifier that refers to a template-id,
11799 /// such as \c class T::template apply<U>.
11800 TypeResult ActOnTagTemplateIdType(
11801 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11802 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11803 SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11804 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11805
11806 DeclResult ActOnVarTemplateSpecialization(
11807 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
11808 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11809 StorageClass SC, bool IsPartialSpecialization);
11810
11811 /// Get the specialization of the given variable template corresponding to
11812 /// the specified argument list, or a null-but-valid result if the arguments
11813 /// are dependent.
11814 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
11815 SourceLocation TemplateLoc,
11816 SourceLocation TemplateNameLoc,
11817 const TemplateArgumentListInfo &TemplateArgs,
11818 bool SetWrittenArgs);
11819
11820 /// Form a reference to the specialization of the given variable template
11821 /// corresponding to the specified argument list, or a null-but-valid result
11822 /// if the arguments are dependent.
11823 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
11824 const DeclarationNameInfo &NameInfo,
11825 VarTemplateDecl *Template, NamedDecl *FoundD,
11826 SourceLocation TemplateLoc,
11827 const TemplateArgumentListInfo *TemplateArgs);
11828
11829 ExprResult CheckVarOrConceptTemplateTemplateId(
11830 const DeclarationNameInfo &NameInfo, TemplateName Template,
11831 const TemplateArgumentListInfo *TemplateArgs);
11832
11833 ExprResult
11834 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11835 const DeclarationNameInfo &ConceptNameInfo,
11836 NamedDecl *FoundDecl, TemplateDecl *NamedConcept,
11837 const TemplateArgumentListInfo *TemplateArgs,
11838 bool DoCheckConstraintSatisfaction = true);
11839
11840 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
11841 void diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
11842 bool TemplateKeyword, TemplateDecl *TD,
11843 SourceLocation Loc);
11844
11845 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
11846 SourceLocation TemplateKWLoc, LookupResult &R,
11847 bool RequiresADL,
11848 const TemplateArgumentListInfo *TemplateArgs);
11849
11850 // We actually only call this from template instantiation.
11851 ExprResult
11852 BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11853 const DeclarationNameInfo &NameInfo,
11854 const TemplateArgumentListInfo *TemplateArgs,
11855 bool IsAddressOfOperand);
11856
11857 UnsignedOrNone getPackIndex(TemplateArgument Pack) const {
11858 return Pack.pack_size() - 1 - *ArgPackSubstIndex;
11859 }
11860
11861 TemplateArgument
11862 getPackSubstitutedTemplateArgument(TemplateArgument Arg) const {
11863 Arg = Arg.pack_elements()[*ArgPackSubstIndex];
11864 if (Arg.isPackExpansion())
11865 Arg = Arg.getPackExpansionPattern();
11866 return Arg;
11867 }
11868
11869 ExprResult
11870 BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
11871 QualType ParamType, SourceLocation loc,
11872 TemplateArgument Replacement,
11873 UnsignedOrNone PackIndex, bool Final);
11874
11875 /// Form a template name from a name that is syntactically required to name a
11876 /// template, either due to use of the 'template' keyword or because a name in
11877 /// this syntactic context is assumed to name a template (C++
11878 /// [temp.names]p2-4).
11879 ///
11880 /// This action forms a template name given the name of the template and its
11881 /// optional scope specifier. This is used when the 'template' keyword is used
11882 /// or when the parsing context unambiguously treats a following '<' as
11883 /// introducing a template argument list. Note that this may produce a
11884 /// non-dependent template name if we can perform the lookup now and identify
11885 /// the named template.
11886 ///
11887 /// For example, given "x.MetaFun::template apply", the scope specifier
11888 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
11889 /// of the "template" keyword, and "apply" is the \p Name.
11890 TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS,
11891 SourceLocation TemplateKWLoc,
11892 const UnqualifiedId &Name,
11893 ParsedType ObjectType,
11894 bool EnteringContext, TemplateTy &Template,
11895 bool AllowInjectedClassName = false);
11896
11897 DeclResult ActOnClassTemplateSpecialization(
11898 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11899 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
11900 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
11901 MultiTemplateParamsArg TemplateParameterLists,
11902 SkipBodyInfo *SkipBody = nullptr);
11903
11904 /// Check the non-type template arguments of a class template
11905 /// partial specialization according to C++ [temp.class.spec]p9.
11906 ///
11907 /// \param TemplateNameLoc the location of the template name.
11908 /// \param PrimaryTemplate the template parameters of the primary class
11909 /// template.
11910 /// \param NumExplicit the number of explicitly-specified template arguments.
11911 /// \param TemplateArgs the template arguments of the class template
11912 /// partial specialization.
11913 ///
11914 /// \returns \c true if there was an error, \c false otherwise.
11915 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
11916 TemplateDecl *PrimaryTemplate,
11917 unsigned NumExplicitArgs,
11918 ArrayRef<TemplateArgument> Args);
11919 void CheckTemplatePartialSpecialization(
11920 ClassTemplatePartialSpecializationDecl *Partial);
11921 void CheckTemplatePartialSpecialization(
11922 VarTemplatePartialSpecializationDecl *Partial);
11923
11924 Decl *ActOnTemplateDeclarator(Scope *S,
11925 MultiTemplateParamsArg TemplateParameterLists,
11926 Declarator &D);
11927
11928 /// Diagnose cases where we have an explicit template specialization
11929 /// before/after an explicit template instantiation, producing diagnostics
11930 /// for those cases where they are required and determining whether the
11931 /// new specialization/instantiation will have any effect.
11932 ///
11933 /// \param NewLoc the location of the new explicit specialization or
11934 /// instantiation.
11935 ///
11936 /// \param NewTSK the kind of the new explicit specialization or
11937 /// instantiation.
11938 ///
11939 /// \param PrevDecl the previous declaration of the entity.
11940 ///
11941 /// \param PrevTSK the kind of the old explicit specialization or
11942 /// instantiatin.
11943 ///
11944 /// \param PrevPointOfInstantiation if valid, indicates where the previous
11945 /// declaration was instantiated (either implicitly or explicitly).
11946 ///
11947 /// \param HasNoEffect will be set to true to indicate that the new
11948 /// specialization or instantiation has no effect and should be ignored.
11949 ///
11950 /// \returns true if there was an error that should prevent the introduction
11951 /// of the new declaration into the AST, false otherwise.
11952 bool CheckSpecializationInstantiationRedecl(
11953 SourceLocation NewLoc,
11954 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
11955 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
11956 SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
11957
11958 /// Perform semantic analysis for the given dependent function
11959 /// template specialization.
11960 ///
11961 /// The only possible way to get a dependent function template specialization
11962 /// is with a friend declaration, like so:
11963 ///
11964 /// \code
11965 /// template \<class T> void foo(T);
11966 /// template \<class T> class A {
11967 /// friend void foo<>(T);
11968 /// };
11969 /// \endcode
11970 ///
11971 /// There really isn't any useful analysis we can do here, so we
11972 /// just store the information.
11973 bool CheckDependentFunctionTemplateSpecialization(
11974 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
11975 LookupResult &Previous);
11976
11977 /// Perform semantic analysis for the given function template
11978 /// specialization.
11979 ///
11980 /// This routine performs all of the semantic analysis required for an
11981 /// explicit function template specialization. On successful completion,
11982 /// the function declaration \p FD will become a function template
11983 /// specialization.
11984 ///
11985 /// \param FD the function declaration, which will be updated to become a
11986 /// function template specialization.
11987 ///
11988 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
11989 /// if any. Note that this may be valid info even when 0 arguments are
11990 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
11991 /// as it anyway contains info on the angle brackets locations.
11992 ///
11993 /// \param Previous the set of declarations that may be specialized by
11994 /// this function specialization.
11995 ///
11996 /// \param QualifiedFriend whether this is a lookup for a qualified friend
11997 /// declaration with no explicit template argument list that might be
11998 /// befriending a function template specialization.
11999 bool CheckFunctionTemplateSpecialization(
12000 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
12001 LookupResult &Previous, bool QualifiedFriend = false);
12002
12003 /// Perform semantic analysis for the given non-template member
12004 /// specialization.
12005 ///
12006 /// This routine performs all of the semantic analysis required for an
12007 /// explicit member function specialization. On successful completion,
12008 /// the function declaration \p FD will become a member function
12009 /// specialization.
12010 ///
12011 /// \param Member the member declaration, which will be updated to become a
12012 /// specialization.
12013 ///
12014 /// \param Previous the set of declarations, one of which may be specialized
12015 /// by this function specialization; the set will be modified to contain the
12016 /// redeclared member.
12017 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12018 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12019
12020 // Explicit instantiation of a class template specialization
12021 DeclResult ActOnExplicitInstantiation(
12022 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
12023 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
12024 TemplateTy Template, SourceLocation TemplateNameLoc,
12025 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
12026 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
12027
12028 // Explicit instantiation of a member class of a class template.
12029 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12030 SourceLocation TemplateLoc,
12031 unsigned TagSpec, SourceLocation KWLoc,
12032 CXXScopeSpec &SS, IdentifierInfo *Name,
12033 SourceLocation NameLoc,
12034 const ParsedAttributesView &Attr);
12035
12036 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12037 SourceLocation TemplateLoc,
12038 Declarator &D);
12039
12040 /// If the given template parameter has a default template
12041 /// argument, substitute into that default template argument and
12042 /// return the corresponding template argument.
12043 TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(
12044 TemplateDecl *Template, SourceLocation TemplateKWLoc,
12045 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
12046 ArrayRef<TemplateArgument> SugaredConverted,
12047 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
12048
12049 /// Returns the top most location responsible for the definition of \p N.
12050 /// If \p N is a a template specialization, this is the location
12051 /// of the top of the instantiation stack.
12052 /// Otherwise, the location of \p N is returned.
12053 SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const;
12054
12055 /// Specifies the context in which a particular template
12056 /// argument is being checked.
12057 enum CheckTemplateArgumentKind {
12058 /// The template argument was specified in the code or was
12059 /// instantiated with some deduced template arguments.
12060 CTAK_Specified,
12061
12062 /// The template argument was deduced via template argument
12063 /// deduction.
12064 CTAK_Deduced,
12065
12066 /// The template argument was deduced from an array bound
12067 /// via template argument deduction.
12068 CTAK_DeducedFromArrayBound
12069 };
12070
12071 struct CheckTemplateArgumentInfo {
12072 explicit CheckTemplateArgumentInfo(bool PartialOrdering = false,
12073 bool MatchingTTP = false)
12074 : PartialOrdering(PartialOrdering), MatchingTTP(MatchingTTP) {}
12075 CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &) = delete;
12076 CheckTemplateArgumentInfo &
12077 operator=(const CheckTemplateArgumentInfo &) = delete;
12078
12079 /// The checked, converted argument will be added to the
12080 /// end of these vectors.
12081 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
12082
12083 /// The check is being performed in the context of partial ordering.
12084 bool PartialOrdering;
12085
12086 /// If true, assume these template arguments are
12087 /// the injected template arguments for a template template parameter.
12088 /// This will relax the requirement that all its possible uses are valid:
12089 /// TTP checking is loose, and assumes that invalid uses will be diagnosed
12090 /// during instantiation.
12091 bool MatchingTTP;
12092
12093 /// Is set to true when, in the context of TTP matching, a pack parameter
12094 /// matches non-pack arguments.
12095 bool StrictPackMatch = false;
12096 };
12097
12098 /// Check that the given template argument corresponds to the given
12099 /// template parameter.
12100 ///
12101 /// \param Param The template parameter against which the argument will be
12102 /// checked.
12103 ///
12104 /// \param Arg The template argument, which may be updated due to conversions.
12105 ///
12106 /// \param Template The template in which the template argument resides.
12107 ///
12108 /// \param TemplateLoc The location of the template name for the template
12109 /// whose argument list we're matching.
12110 ///
12111 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
12112 /// the template argument list.
12113 ///
12114 /// \param ArgumentPackIndex The index into the argument pack where this
12115 /// argument will be placed. Only valid if the parameter is a parameter pack.
12116 ///
12117 /// \param CTAK Describes how we arrived at this particular template argument:
12118 /// explicitly written, deduced, etc.
12119 ///
12120 /// \returns true on error, false otherwise.
12121 bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
12122 NamedDecl *Template, SourceLocation TemplateLoc,
12123 SourceLocation RAngleLoc,
12124 unsigned ArgumentPackIndex,
12125 CheckTemplateArgumentInfo &CTAI,
12126 CheckTemplateArgumentKind CTAK);
12127
12128 /// Check that the given template arguments can be provided to
12129 /// the given template, converting the arguments along the way.
12130 ///
12131 /// \param Template The template to which the template arguments are being
12132 /// provided.
12133 ///
12134 /// \param TemplateLoc The location of the template name in the source.
12135 ///
12136 /// \param TemplateArgs The list of template arguments. If the template is
12137 /// a template template parameter, this function may extend the set of
12138 /// template arguments to also include substituted, defaulted template
12139 /// arguments.
12140 ///
12141 /// \param PartialTemplateArgs True if the list of template arguments is
12142 /// intentionally partial, e.g., because we're checking just the initial
12143 /// set of template arguments.
12144 ///
12145 /// \param Converted Will receive the converted, canonicalized template
12146 /// arguments.
12147 ///
12148 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
12149 /// contain the converted forms of the template arguments as written.
12150 /// Otherwise, \p TemplateArgs will not be modified.
12151 ///
12152 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
12153 /// receive true if the cause for the error is the associated constraints of
12154 /// the template not being satisfied by the template arguments.
12155 ///
12156 /// \param DefaultArgs any default arguments from template specialization
12157 /// deduction.
12158 ///
12159 /// \returns true if an error occurred, false otherwise.
12160 bool CheckTemplateArgumentList(TemplateDecl *Template,
12161 SourceLocation TemplateLoc,
12162 TemplateArgumentListInfo &TemplateArgs,
12163 const DefaultArguments &DefaultArgs,
12164 bool PartialTemplateArgs,
12165 CheckTemplateArgumentInfo &CTAI,
12166 bool UpdateArgsWithConversions = true,
12167 bool *ConstraintsNotSatisfied = nullptr);
12168
12169 bool CheckTemplateArgumentList(
12170 TemplateDecl *Template, TemplateParameterList *Params,
12171 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
12172 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
12173 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions = true,
12174 bool *ConstraintsNotSatisfied = nullptr);
12175
12176 bool CheckTemplateTypeArgument(
12177 TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
12178 SmallVectorImpl<TemplateArgument> &SugaredConverted,
12179 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
12180
12181 /// Check a template argument against its corresponding
12182 /// template type parameter.
12183 ///
12184 /// This routine implements the semantics of C++ [temp.arg.type]. It
12185 /// returns true if an error occurred, and false otherwise.
12186 bool CheckTemplateArgument(TypeSourceInfo *Arg);
12187
12188 /// Check a template argument against its corresponding
12189 /// non-type template parameter.
12190 ///
12191 /// This routine implements the semantics of C++ [temp.arg.nontype].
12192 /// If an error occurred, it returns ExprError(); otherwise, it
12193 /// returns the converted template argument. \p ParamType is the
12194 /// type of the non-type template parameter after it has been instantiated.
12195 ExprResult CheckTemplateArgument(NamedDecl *Param,
12196 QualType InstantiatedParamType, Expr *Arg,
12197 TemplateArgument &SugaredConverted,
12198 TemplateArgument &CanonicalConverted,
12199 bool StrictCheck,
12200 CheckTemplateArgumentKind CTAK);
12201
12202 /// Check a template argument against its corresponding
12203 /// template template parameter.
12204 ///
12205 /// This routine implements the semantics of C++ [temp.arg.template].
12206 /// It returns true if an error occurred, and false otherwise.
12207 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
12208 TemplateParameterList *Params,
12209 TemplateArgumentLoc &Arg,
12210 bool PartialOrdering,
12211 bool *StrictPackMatch);
12212
12213 bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template,
12214 TemplateTemplateParmDecl *Param,
12215 const TemplateArgumentLoc &Arg);
12216
12217 void NoteTemplateLocation(const NamedDecl &Decl,
12218 std::optional<SourceRange> ParamRange = {});
12219 void NoteTemplateParameterLocation(const NamedDecl &Decl);
12220
12221 /// Given a non-type template argument that refers to a
12222 /// declaration and the type of its corresponding non-type template
12223 /// parameter, produce an expression that properly refers to that
12224 /// declaration.
12225 /// FIXME: This is used in some contexts where the resulting expression
12226 /// doesn't need to live too long. It would be useful if this function
12227 /// could return a temporary expression.
12228 ExprResult BuildExpressionFromDeclTemplateArgument(
12229 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc);
12230 ExprResult
12231 BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
12232 SourceLocation Loc);
12233
12234 /// Enumeration describing how template parameter lists are compared
12235 /// for equality.
12236 enum TemplateParameterListEqualKind {
12237 /// We are matching the template parameter lists of two templates
12238 /// that might be redeclarations.
12239 ///
12240 /// \code
12241 /// template<typename T> struct X;
12242 /// template<typename T> struct X;
12243 /// \endcode
12244 TPL_TemplateMatch,
12245
12246 /// We are matching the template parameter lists of two template
12247 /// template parameters as part of matching the template parameter lists
12248 /// of two templates that might be redeclarations.
12249 ///
12250 /// \code
12251 /// template<template<int I> class TT> struct X;
12252 /// template<template<int Value> class Other> struct X;
12253 /// \endcode
12254 TPL_TemplateTemplateParmMatch,
12255
12256 /// We are determining whether the template-parameters are equivalent
12257 /// according to C++ [temp.over.link]/6. This comparison does not consider
12258 /// constraints.
12259 ///
12260 /// \code
12261 /// template<C1 T> void f(T);
12262 /// template<C2 T> void f(T);
12263 /// \endcode
12264 TPL_TemplateParamsEquivalent,
12265 };
12266
12267 // A struct to represent the 'new' declaration, which is either itself just
12268 // the named decl, or the important information we need about it in order to
12269 // do constraint comparisons.
12270 class TemplateCompareNewDeclInfo {
12271 const NamedDecl *ND = nullptr;
12272 const DeclContext *DC = nullptr;
12273 const DeclContext *LexicalDC = nullptr;
12274 SourceLocation Loc;
12275
12276 public:
12277 TemplateCompareNewDeclInfo(const NamedDecl *ND) : ND(ND) {}
12278 TemplateCompareNewDeclInfo(const DeclContext *DeclCtx,
12279 const DeclContext *LexicalDeclCtx,
12280 SourceLocation Loc)
12281
12282 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12283 assert(DC && LexicalDC &&
12284 "Constructor only for cases where we have the information to put "
12285 "in here");
12286 }
12287
12288 // If this was constructed with no information, we cannot do substitution
12289 // for constraint comparison, so make sure we can check that.
12290 bool isInvalid() const { return !ND && !DC; }
12291
12292 const NamedDecl *getDecl() const { return ND; }
12293
12294 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12295
12296 const DeclContext *getLexicalDeclContext() const {
12297 return ND ? ND->getLexicalDeclContext() : LexicalDC;
12298 }
12299
12300 const DeclContext *getDeclContext() const {
12301 return ND ? ND->getDeclContext() : DC;
12302 }
12303
12304 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12305 };
12306
12307 /// Determine whether the given template parameter lists are
12308 /// equivalent.
12309 ///
12310 /// \param New The new template parameter list, typically written in the
12311 /// source code as part of a new template declaration.
12312 ///
12313 /// \param Old The old template parameter list, typically found via
12314 /// name lookup of the template declared with this template parameter
12315 /// list.
12316 ///
12317 /// \param Complain If true, this routine will produce a diagnostic if
12318 /// the template parameter lists are not equivalent.
12319 ///
12320 /// \param Kind describes how we are to match the template parameter lists.
12321 ///
12322 /// \param TemplateArgLoc If this source location is valid, then we
12323 /// are actually checking the template parameter list of a template
12324 /// argument (New) against the template parameter list of its
12325 /// corresponding template template parameter (Old). We produce
12326 /// slightly different diagnostics in this scenario.
12327 ///
12328 /// \returns True if the template parameter lists are equal, false
12329 /// otherwise.
12330 bool TemplateParameterListsAreEqual(
12331 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12332 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12333 TemplateParameterListEqualKind Kind,
12334 SourceLocation TemplateArgLoc = SourceLocation());
12335
12336 bool TemplateParameterListsAreEqual(
12337 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12338 TemplateParameterListEqualKind Kind,
12339 SourceLocation TemplateArgLoc = SourceLocation()) {
12340 return TemplateParameterListsAreEqual(NewInstFrom: nullptr, New, OldInstFrom: nullptr, Old, Complain,
12341 Kind, TemplateArgLoc);
12342 }
12343
12344 /// Check whether a template can be declared within this scope.
12345 ///
12346 /// If the template declaration is valid in this scope, returns
12347 /// false. Otherwise, issues a diagnostic and returns true.
12348 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12349
12350 /// Called when the parser has parsed a C++ typename
12351 /// specifier, e.g., "typename T::type".
12352 ///
12353 /// \param S The scope in which this typename type occurs.
12354 /// \param TypenameLoc the location of the 'typename' keyword
12355 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12356 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12357 /// \param IdLoc the location of the identifier.
12358 /// \param IsImplicitTypename context where T::type refers to a type.
12359 TypeResult ActOnTypenameType(
12360 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12361 const IdentifierInfo &II, SourceLocation IdLoc,
12362 ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No);
12363
12364 /// Called when the parser has parsed a C++ typename
12365 /// specifier that ends in a template-id, e.g.,
12366 /// "typename MetaFun::template apply<T1, T2>".
12367 ///
12368 /// \param S The scope in which this typename type occurs.
12369 /// \param TypenameLoc the location of the 'typename' keyword
12370 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12371 /// \param TemplateLoc the location of the 'template' keyword, if any.
12372 /// \param TemplateName The template name.
12373 /// \param TemplateII The identifier used to name the template.
12374 /// \param TemplateIILoc The location of the template name.
12375 /// \param LAngleLoc The location of the opening angle bracket ('<').
12376 /// \param TemplateArgs The template arguments.
12377 /// \param RAngleLoc The location of the closing angle bracket ('>').
12378 TypeResult
12379 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12380 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12381 TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12382 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12383 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12384
12385 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12386 SourceLocation KeywordLoc,
12387 NestedNameSpecifierLoc QualifierLoc,
12388 const IdentifierInfo &II, SourceLocation IILoc,
12389 TypeSourceInfo **TSI, bool DeducedTSTContext);
12390
12391 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12392 SourceLocation KeywordLoc,
12393 NestedNameSpecifierLoc QualifierLoc,
12394 const IdentifierInfo &II, SourceLocation IILoc,
12395 bool DeducedTSTContext = true);
12396
12397 /// Rebuilds a type within the context of the current instantiation.
12398 ///
12399 /// The type \p T is part of the type of an out-of-line member definition of
12400 /// a class template (or class template partial specialization) that was
12401 /// parsed and constructed before we entered the scope of the class template
12402 /// (or partial specialization thereof). This routine will rebuild that type
12403 /// now that we have entered the declarator's scope, which may produce
12404 /// different canonical types, e.g.,
12405 ///
12406 /// \code
12407 /// template<typename T>
12408 /// struct X {
12409 /// typedef T* pointer;
12410 /// pointer data();
12411 /// };
12412 ///
12413 /// template<typename T>
12414 /// typename X<T>::pointer X<T>::data() { ... }
12415 /// \endcode
12416 ///
12417 /// Here, the type "typename X<T>::pointer" will be created as a
12418 /// DependentNameType, since we do not know that we can look into X<T> when we
12419 /// parsed the type. This function will rebuild the type, performing the
12420 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12421 /// canonical type is the same as the canonical type of T*, allowing the
12422 /// return types of the out-of-line definition and the declaration to match.
12423 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
12424 SourceLocation Loc,
12425 DeclarationName Name);
12426 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
12427
12428 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
12429
12430 /// Rebuild the template parameters now that we know we're in a current
12431 /// instantiation.
12432 bool
12433 RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params);
12434
12435 /// Produces a formatted string that describes the binding of
12436 /// template parameters to template arguments.
12437 std::string
12438 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12439 const TemplateArgumentList &Args);
12440
12441 std::string
12442 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12443 const TemplateArgument *Args,
12444 unsigned NumArgs);
12445
12446 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
12447 SourceLocation Less,
12448 SourceLocation Greater);
12449
12450 /// ActOnDependentIdExpression - Handle a dependent id-expression that
12451 /// was just parsed. This is only possible with an explicit scope
12452 /// specifier naming a dependent type.
12453 ExprResult ActOnDependentIdExpression(
12454 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12455 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12456 const TemplateArgumentListInfo *TemplateArgs);
12457
12458 ExprResult
12459 BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
12460 SourceLocation TemplateKWLoc,
12461 const DeclarationNameInfo &NameInfo,
12462 const TemplateArgumentListInfo *TemplateArgs);
12463
12464 // Calculates whether the expression Constraint depends on an enclosing
12465 // template, for the purposes of [temp.friend] p9.
12466 // TemplateDepth is the 'depth' of the friend function, which is used to
12467 // compare whether a declaration reference is referring to a containing
12468 // template, or just the current friend function. A 'lower' TemplateDepth in
12469 // the AST refers to a 'containing' template. As the constraint is
12470 // uninstantiated, this is relative to the 'top' of the TU.
12471 bool
12472 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
12473 unsigned TemplateDepth,
12474 const Expr *Constraint);
12475
12476 /// Find the failed Boolean condition within a given Boolean
12477 /// constant expression, and describe it with a string.
12478 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12479
12480 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
12481
12482 ConceptDecl *ActOnStartConceptDefinition(
12483 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12484 const IdentifierInfo *Name, SourceLocation NameLoc);
12485
12486 ConceptDecl *ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
12487 Expr *ConstraintExpr,
12488 const ParsedAttributesView &Attrs);
12489
12490 void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
12491 bool &AddToScope);
12492 bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc);
12493
12494 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12495 const CXXScopeSpec &SS,
12496 const IdentifierInfo *Name,
12497 SourceLocation TagLoc, SourceLocation NameLoc);
12498
12499 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
12500 CachedTokens &Toks);
12501 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
12502 bool IsInsideALocalClassWithinATemplateFunction();
12503
12504 /// We've found a use of a templated declaration that would trigger an
12505 /// implicit instantiation. Check that any relevant explicit specializations
12506 /// and partial specializations are visible/reachable, and diagnose if not.
12507 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
12508 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
12509
12510 ///@}
12511
12512 //
12513 //
12514 // -------------------------------------------------------------------------
12515 //
12516 //
12517
12518 /// \name C++ Template Argument Deduction
12519 /// Implementations are in SemaTemplateDeduction.cpp
12520 ///@{
12521
12522public:
12523 class SFINAETrap;
12524
12525 struct SFINAEContextBase {
12526 SFINAEContextBase(Sema &S, SFINAETrap *Cur)
12527 : S(S), Prev(std::exchange(obj&: S.CurrentSFINAEContext, new_val&: Cur)) {}
12528
12529 protected:
12530 Sema &S;
12531 ~SFINAEContextBase() { S.CurrentSFINAEContext = Prev; }
12532 SFINAEContextBase(const SFINAEContextBase &) = delete;
12533 SFINAEContextBase &operator=(const SFINAEContextBase &) = delete;
12534
12535 private:
12536 SFINAETrap *Prev;
12537 };
12538
12539 struct NonSFINAEContext : SFINAEContextBase {
12540 NonSFINAEContext(Sema &S) : SFINAEContextBase(S, nullptr) {}
12541 };
12542
12543 /// RAII class used to determine whether SFINAE has
12544 /// trapped any errors that occur during template argument
12545 /// deduction.
12546 class SFINAETrap : SFINAEContextBase {
12547 bool HasErrorOcurred = false;
12548 bool WithAccessChecking = false;
12549 bool PrevLastDiagnosticIgnored =
12550 S.getDiagnostics().isLastDiagnosticIgnored();
12551 sema::TemplateDeductionInfo *DeductionInfo = nullptr;
12552
12553 SFINAETrap(Sema &S, sema::TemplateDeductionInfo *Info,
12554 bool WithAccessChecking)
12555 : SFINAEContextBase(S, this), WithAccessChecking(WithAccessChecking),
12556 DeductionInfo(Info) {}
12557
12558 public:
12559 /// \param WithAccessChecking If true, discard all diagnostics (from the
12560 /// immediate context) instead of adding them to the currently active
12561 /// \ref TemplateDeductionInfo.
12562 explicit SFINAETrap(Sema &S, bool WithAccessChecking = false)
12563 : SFINAETrap(S, /*Info=*/nullptr, WithAccessChecking) {}
12564
12565 SFINAETrap(Sema &S, sema::TemplateDeductionInfo &Info)
12566 : SFINAETrap(S, &Info, /*WithAccessChecking=*/false) {}
12567
12568 ~SFINAETrap() {
12569 S.getDiagnostics().setLastDiagnosticIgnored(PrevLastDiagnosticIgnored);
12570 }
12571
12572 SFINAETrap(const SFINAETrap &) = delete;
12573 SFINAETrap &operator=(const SFINAETrap &) = delete;
12574
12575 sema::TemplateDeductionInfo *getDeductionInfo() const {
12576 return DeductionInfo;
12577 }
12578
12579 /// Determine whether any SFINAE errors have been trapped.
12580 bool hasErrorOccurred() const { return HasErrorOcurred; }
12581 void setErrorOccurred() { HasErrorOcurred = true; }
12582
12583 bool withAccessChecking() const { return WithAccessChecking; }
12584 };
12585
12586 /// RAII class used to indicate that we are performing provisional
12587 /// semantic analysis to determine the validity of a construct, so
12588 /// typo-correction and diagnostics in the immediate context (not within
12589 /// implicitly-instantiated templates) should be suppressed.
12590 class TentativeAnalysisScope {
12591 Sema &SemaRef;
12592 // FIXME: Using a SFINAETrap for this is a hack.
12593 SFINAETrap Trap;
12594 bool PrevDisableTypoCorrection;
12595
12596 public:
12597 explicit TentativeAnalysisScope(Sema &SemaRef)
12598 : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12599 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12600 SemaRef.DisableTypoCorrection = true;
12601 }
12602 ~TentativeAnalysisScope() {
12603 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12604 }
12605
12606 TentativeAnalysisScope(const TentativeAnalysisScope &) = delete;
12607 TentativeAnalysisScope &operator=(const TentativeAnalysisScope &) = delete;
12608 };
12609
12610 /// For each declaration that involved template argument deduction, the
12611 /// set of diagnostics that were suppressed during that template argument
12612 /// deduction.
12613 ///
12614 /// FIXME: Serialize this structure to the AST file.
12615 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12616 SuppressedDiagnosticsMap;
12617 SuppressedDiagnosticsMap SuppressedDiagnostics;
12618
12619 /// Compare types for equality with respect to possibly compatible
12620 /// function types (noreturn adjustment, implicit calling conventions). If any
12621 /// of parameter and argument is not a function, just perform type comparison.
12622 ///
12623 /// \param P the template parameter type.
12624 ///
12625 /// \param A the argument type.
12626 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
12627
12628 /// Allocate a TemplateArgumentLoc where all locations have
12629 /// been initialized to the given location.
12630 ///
12631 /// \param Arg The template argument we are producing template argument
12632 /// location information for.
12633 ///
12634 /// \param NTTPType For a declaration template argument, the type of
12635 /// the non-type template parameter that corresponds to this template
12636 /// argument. Can be null if no type sugar is available to add to the
12637 /// type from the template argument.
12638 ///
12639 /// \param Loc The source location to use for the resulting template
12640 /// argument.
12641 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
12642 QualType NTTPType,
12643 SourceLocation Loc);
12644
12645 /// Get a template argument mapping the given template parameter to itself,
12646 /// e.g. for X in \c template<int X>, this would return an expression template
12647 /// argument referencing X.
12648 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
12649 SourceLocation Location);
12650
12651 /// Adjust the type \p ArgFunctionType to match the calling convention,
12652 /// noreturn, and optionally the exception specification of \p FunctionType.
12653 /// Deduction often wants to ignore these properties when matching function
12654 /// types.
12655 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
12656 bool AdjustExceptionSpec = false);
12657
12658 TemplateDeductionResult
12659 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
12660 ArrayRef<TemplateArgument> TemplateArgs,
12661 sema::TemplateDeductionInfo &Info);
12662
12663 TemplateDeductionResult
12664 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
12665 ArrayRef<TemplateArgument> TemplateArgs,
12666 sema::TemplateDeductionInfo &Info);
12667
12668 /// Deduce the template arguments of the given template from \p FromType.
12669 /// Used to implement the IsDeducible constraint for alias CTAD per C++
12670 /// [over.match.class.deduct]p4.
12671 ///
12672 /// It only supports class or type alias templates.
12673 TemplateDeductionResult
12674 DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType,
12675 sema::TemplateDeductionInfo &Info);
12676
12677 TemplateDeductionResult DeduceTemplateArguments(
12678 TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps,
12679 ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info,
12680 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12681 bool NumberOfArgumentsMustMatch);
12682
12683 /// Substitute the explicitly-provided template arguments into the
12684 /// given function template according to C++ [temp.arg.explicit].
12685 ///
12686 /// \param FunctionTemplate the function template into which the explicit
12687 /// template arguments will be substituted.
12688 ///
12689 /// \param ExplicitTemplateArgs the explicitly-specified template
12690 /// arguments.
12691 ///
12692 /// \param Deduced the deduced template arguments, which will be populated
12693 /// with the converted and checked explicit template arguments.
12694 ///
12695 /// \param ParamTypes will be populated with the instantiated function
12696 /// parameters.
12697 ///
12698 /// \param FunctionType if non-NULL, the result type of the function template
12699 /// will also be instantiated and the pointed-to value will be updated with
12700 /// the instantiated function type.
12701 ///
12702 /// \param Info if substitution fails for any reason, this object will be
12703 /// populated with more information about the failure.
12704 ///
12705 /// \returns TemplateDeductionResult::Success if substitution was successful,
12706 /// or some failure condition.
12707 TemplateDeductionResult SubstituteExplicitTemplateArguments(
12708 FunctionTemplateDecl *FunctionTemplate,
12709 TemplateArgumentListInfo &ExplicitTemplateArgs,
12710 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12711 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
12712 sema::TemplateDeductionInfo &Info);
12713
12714 /// brief A function argument from which we performed template argument
12715 // deduction for a call.
12716 struct OriginalCallArg {
12717 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
12718 unsigned ArgIdx, QualType OriginalArgType)
12719 : OriginalParamType(OriginalParamType),
12720 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
12721 OriginalArgType(OriginalArgType) {}
12722
12723 QualType OriginalParamType;
12724 bool DecomposedParam;
12725 unsigned ArgIdx;
12726 QualType OriginalArgType;
12727 };
12728
12729 /// Finish template argument deduction for a function template,
12730 /// checking the deduced template arguments for completeness and forming
12731 /// the function template specialization.
12732 ///
12733 /// \param OriginalCallArgs If non-NULL, the original call arguments against
12734 /// which the deduced argument types should be compared.
12735 /// \param CheckNonDependent Callback before substituting into the declaration
12736 /// with the deduced template arguments.
12737 /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12738 /// some breakages introduced by CWG2369, where non-user-defined conversions
12739 /// are checked first before the constraints.
12740 TemplateDeductionResult FinishTemplateArgumentDeduction(
12741 FunctionTemplateDecl *FunctionTemplate,
12742 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12743 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12744 sema::TemplateDeductionInfo &Info,
12745 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12746 bool PartialOverloading, bool PartialOrdering,
12747 bool ForOverloadSetAddressResolution,
12748 llvm::function_ref<bool(bool)> CheckNonDependent =
12749 [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12750 return false;
12751 });
12752
12753 /// Perform [temp.friend] p5 template argument deduction for a dependent
12754 /// friend declaration and a candidate class template specialization.
12755 bool DeduceTemplateArguments(FriendTemplateDecl *FTD,
12756 ClassTemplateDecl *PatternCTD,
12757 ClassTemplateDecl *CandidateCTD,
12758 ArrayRef<TemplateParameterList *> TPLs,
12759 ArrayRef<TemplateArgument> PatternArgs,
12760 ArrayRef<TemplateArgument> CandidateArgs,
12761 SourceLocation Loc,
12762 TemplateSpecCandidateSet *FailedTSC,
12763 MultiLevelTemplateArgumentList &DeducedArgs);
12764
12765 /// Perform template argument deduction from a function call
12766 /// (C++ [temp.deduct.call]).
12767 ///
12768 /// \param FunctionTemplate the function template for which we are performing
12769 /// template argument deduction.
12770 ///
12771 /// \param ExplicitTemplateArgs the explicit template arguments provided
12772 /// for this call.
12773 ///
12774 /// \param Args the function call arguments
12775 ///
12776 /// \param Specialization if template argument deduction was successful,
12777 /// this will be set to the function template specialization produced by
12778 /// template argument deduction.
12779 ///
12780 /// \param Info the argument will be updated to provide additional information
12781 /// about template argument deduction.
12782 ///
12783 /// \param CheckNonDependent A callback to invoke to check conversions for
12784 /// non-dependent parameters, between deduction and substitution, per DR1391.
12785 /// If this returns true, substitution will be skipped and we return
12786 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12787 /// passed the parameter types (after substituting explicit template
12788 /// arguments).
12789 ///
12790 /// \returns the result of template argument deduction.
12791 TemplateDeductionResult DeduceTemplateArguments(
12792 FunctionTemplateDecl *FunctionTemplate,
12793 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12794 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12795 bool PartialOverloading, bool AggregateDeductionCandidate,
12796 bool PartialOrdering, QualType ObjectType,
12797 Expr::Classification ObjectClassification,
12798 bool ForOverloadSetAddressResolution,
12799 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12800
12801 /// Deduce template arguments when taking the address of a function
12802 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12803 /// a template.
12804 ///
12805 /// \param FunctionTemplate the function template for which we are performing
12806 /// template argument deduction.
12807 ///
12808 /// \param ExplicitTemplateArgs the explicitly-specified template
12809 /// arguments.
12810 ///
12811 /// \param ArgFunctionType the function type that will be used as the
12812 /// "argument" type (A) when performing template argument deduction from the
12813 /// function template's function type. This type may be NULL, if there is no
12814 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
12815 ///
12816 /// \param Specialization if template argument deduction was successful,
12817 /// this will be set to the function template specialization produced by
12818 /// template argument deduction.
12819 ///
12820 /// \param Info the argument will be updated to provide additional information
12821 /// about template argument deduction.
12822 ///
12823 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12824 /// the address of a function template per [temp.deduct.funcaddr] and
12825 /// [over.over]. If \c false, we are looking up a function template
12826 /// specialization based on its signature, per [temp.deduct.decl].
12827 ///
12828 /// \returns the result of template argument deduction.
12829 TemplateDeductionResult DeduceTemplateArguments(
12830 FunctionTemplateDecl *FunctionTemplate,
12831 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
12832 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12833 bool IsAddressOfFunction = false);
12834
12835 /// Deduce template arguments for a templated conversion
12836 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
12837 /// conversion function template specialization.
12838 TemplateDeductionResult DeduceTemplateArguments(
12839 FunctionTemplateDecl *FunctionTemplate, QualType ObjectType,
12840 Expr::Classification ObjectClassification, QualType ToType,
12841 CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info);
12842
12843 /// Deduce template arguments for a function template when there is
12844 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
12845 ///
12846 /// \param FunctionTemplate the function template for which we are performing
12847 /// template argument deduction.
12848 ///
12849 /// \param ExplicitTemplateArgs the explicitly-specified template
12850 /// arguments.
12851 ///
12852 /// \param Specialization if template argument deduction was successful,
12853 /// this will be set to the function template specialization produced by
12854 /// template argument deduction.
12855 ///
12856 /// \param Info the argument will be updated to provide additional information
12857 /// about template argument deduction.
12858 ///
12859 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12860 /// the address of a function template in a context where we do not have a
12861 /// target type, per [over.over]. If \c false, we are looking up a function
12862 /// template specialization based on its signature, which only happens when
12863 /// deducing a function parameter type from an argument that is a template-id
12864 /// naming a function template specialization.
12865 ///
12866 /// \returns the result of template argument deduction.
12867 TemplateDeductionResult
12868 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
12869 TemplateArgumentListInfo *ExplicitTemplateArgs,
12870 FunctionDecl *&Specialization,
12871 sema::TemplateDeductionInfo &Info,
12872 bool IsAddressOfFunction = false);
12873
12874 /// Substitute Replacement for \p auto in \p TypeWithAuto
12875 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
12876 /// Substitute Replacement for auto in TypeWithAuto
12877 TypeSourceInfo *SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12878 QualType Replacement);
12879
12880 // Substitute auto in TypeWithAuto for a Dependent auto type
12881 QualType SubstAutoTypeDependent(QualType TypeWithAuto);
12882
12883 // Substitute auto in TypeWithAuto for a Dependent auto type
12884 TypeSourceInfo *
12885 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
12886
12887 /// Completely replace the \c auto in \p TypeWithAuto by
12888 /// \p Replacement. This does not retain any \c auto type sugar.
12889 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
12890 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12891 QualType Replacement);
12892
12893 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
12894 ///
12895 /// Note that this is done even if the initializer is dependent. (This is
12896 /// necessary to support partial ordering of templates using 'auto'.)
12897 /// A dependent type will be produced when deducing from a dependent type.
12898 ///
12899 /// \param Type the type pattern using the auto type-specifier.
12900 /// \param Init the initializer for the variable whose type is to be deduced.
12901 /// \param Result if type deduction was successful, this will be set to the
12902 /// deduced type.
12903 /// \param Info the argument will be updated to provide additional information
12904 /// about template argument deduction.
12905 /// \param DependentDeduction Set if we should permit deduction in
12906 /// dependent cases. This is necessary for template partial ordering
12907 /// with 'auto' template parameters. The template parameter depth to be
12908 /// used should be specified in the 'Info' parameter.
12909 /// \param IgnoreConstraints Set if we should not fail if the deduced type
12910 /// does not satisfy the type-constraint in the auto
12911 /// type.
12912 TemplateDeductionResult
12913 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result,
12914 sema::TemplateDeductionInfo &Info,
12915 bool DependentDeduction = false,
12916 bool IgnoreConstraints = false,
12917 TemplateSpecCandidateSet *FailedTSC = nullptr);
12918 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
12919 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
12920 bool Diagnose = true);
12921
12922 bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD,
12923 SourceLocation Loc);
12924
12925 /// Returns the more specialized class template partial specialization
12926 /// according to the rules of partial ordering of class template partial
12927 /// specializations (C++ [temp.class.order]).
12928 ///
12929 /// \param PS1 the first class template partial specialization
12930 ///
12931 /// \param PS2 the second class template partial specialization
12932 ///
12933 /// \returns the more specialized class template partial specialization. If
12934 /// neither partial specialization is more specialized, returns NULL.
12935 ClassTemplatePartialSpecializationDecl *
12936 getMoreSpecializedPartialSpecialization(
12937 ClassTemplatePartialSpecializationDecl *PS1,
12938 ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
12939
12940 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
12941 sema::TemplateDeductionInfo &Info);
12942
12943 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
12944 VarTemplatePartialSpecializationDecl *PS1,
12945 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
12946
12947 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
12948 sema::TemplateDeductionInfo &Info);
12949
12950 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
12951 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
12952 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
12953 bool PartialOrdering, bool *StrictPackMatch);
12954
12955 /// Mark which template parameters are used in a given expression.
12956 ///
12957 /// \param E the expression from which template parameters will be deduced.
12958 ///
12959 /// \param Used a bit vector whose elements will be set to \c true
12960 /// to indicate when the corresponding template parameter will be
12961 /// deduced.
12962 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
12963 unsigned Depth, llvm::SmallBitVector &Used);
12964
12965 /// Mark which template parameters are named in a given expression.
12966 ///
12967 /// Unlike MarkUsedTemplateParameters, this excludes parameter that
12968 /// are used but not directly named by an expression - i.e. it excludes
12969 /// any template parameter that denotes the type of a referenced NTTP.
12970 ///
12971 /// \param Used a bit vector whose elements will be set to \c true
12972 /// to indicate when the corresponding template parameter will be
12973 /// deduced.
12974 void MarkUsedTemplateParametersForSubsumptionParameterMapping(
12975 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used);
12976
12977 /// Mark which template parameters can be deduced from a given
12978 /// template argument list.
12979 ///
12980 /// \param TemplateArgs the template argument list from which template
12981 /// parameters will be deduced.
12982 ///
12983 /// \param Used a bit vector whose elements will be set to \c true
12984 /// to indicate when the corresponding template parameter will be
12985 /// deduced.
12986 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
12987 bool OnlyDeduced, unsigned Depth,
12988 llvm::SmallBitVector &Used);
12989
12990 void MarkUsedTemplateParameters(ArrayRef<TemplateArgument> TemplateArgs,
12991 bool OnlyDeduced, unsigned Depth,
12992 llvm::SmallBitVector &Used);
12993
12994 void MarkUsedTemplateParameters(ArrayRef<TemplateArgumentLoc> TemplateArgs,
12995 unsigned Depth, llvm::SmallBitVector &Used);
12996
12997 void
12998 MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate,
12999 llvm::SmallBitVector &Deduced) {
13000 return MarkDeducedTemplateParameters(Ctx&: Context, FunctionTemplate, Deduced);
13001 }
13002
13003 /// Marks all of the template parameters that will be deduced by a
13004 /// call to the given function template.
13005 static void
13006 MarkDeducedTemplateParameters(ASTContext &Ctx,
13007 const FunctionTemplateDecl *FunctionTemplate,
13008 llvm::SmallBitVector &Deduced);
13009
13010 /// Returns the more specialized function template according
13011 /// to the rules of function template partial ordering (C++
13012 /// [temp.func.order]).
13013 ///
13014 /// \param FT1 the first function template
13015 ///
13016 /// \param FT2 the second function template
13017 ///
13018 /// \param TPOC the context in which we are performing partial ordering of
13019 /// function templates.
13020 ///
13021 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
13022 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
13023 /// when calling a member function.
13024 ///
13025 /// \param RawObj1Ty The type of the object parameter of FT1 if a member
13026 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
13027 /// template from a member function
13028 ///
13029 /// \param RawObj2Ty The type of the object parameter of FT2 if a member
13030 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
13031 /// template from a member function
13032 ///
13033 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
13034 /// candidate with a reversed parameter order. In this case, the corresponding
13035 /// P/A pairs between FT1 and FT2 are reversed.
13036 ///
13037 /// \returns the more specialized function template. If neither
13038 /// template is more specialized, returns NULL.
13039 FunctionTemplateDecl *getMoreSpecializedTemplate(
13040 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
13041 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
13042 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
13043 bool PartialOverloading = false);
13044
13045 /// Retrieve the most specialized of the given function template
13046 /// specializations.
13047 ///
13048 /// \param SpecBegin the start iterator of the function template
13049 /// specializations that we will be comparing.
13050 ///
13051 /// \param SpecEnd the end iterator of the function template
13052 /// specializations, paired with \p SpecBegin.
13053 ///
13054 /// \param Loc the location where the ambiguity or no-specializations
13055 /// diagnostic should occur.
13056 ///
13057 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
13058 /// no matching candidates.
13059 ///
13060 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
13061 /// occurs.
13062 ///
13063 /// \param CandidateDiag partial diagnostic used for each function template
13064 /// specialization that is a candidate in the ambiguous ordering. One
13065 /// parameter in this diagnostic should be unbound, which will correspond to
13066 /// the string describing the template arguments for the function template
13067 /// specialization.
13068 ///
13069 /// \returns the most specialized function template specialization, if
13070 /// found. Otherwise, returns SpecEnd.
13071 UnresolvedSetIterator
13072 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
13073 TemplateSpecCandidateSet &FailedCandidates,
13074 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
13075 const PartialDiagnostic &AmbigDiag,
13076 const PartialDiagnostic &CandidateDiag,
13077 bool Complain = true, QualType TargetType = QualType());
13078
13079 /// Returns the more constrained function according to the rules of
13080 /// partial ordering by constraints (C++ [temp.constr.order]).
13081 ///
13082 /// \param FD1 the first function
13083 ///
13084 /// \param FD2 the second function
13085 ///
13086 /// \returns the more constrained function. If neither function is
13087 /// more constrained, returns NULL.
13088 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
13089 FunctionDecl *FD2);
13090
13091 ///@}
13092
13093 //
13094 //
13095 // -------------------------------------------------------------------------
13096 //
13097 //
13098
13099 /// \name C++ Template Deduction Guide
13100 /// Implementations are in SemaTemplateDeductionGuide.cpp
13101 ///@{
13102
13103 /// Declare implicit deduction guides for a class template if we've
13104 /// not already done so.
13105 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
13106 SourceLocation Loc);
13107
13108 CXXDeductionGuideDecl *DeclareAggregateDeductionGuideFromInitList(
13109 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
13110 SourceLocation Loc);
13111
13112 ///@}
13113
13114 //
13115 //
13116 // -------------------------------------------------------------------------
13117 //
13118 //
13119
13120 /// \name C++ Template Instantiation
13121 /// Implementations are in SemaTemplateInstantiate.cpp
13122 ///@{
13123
13124public:
13125 /// A helper class for building up ExtParameterInfos.
13126 class ExtParameterInfoBuilder {
13127 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
13128 bool HasInteresting = false;
13129
13130 public:
13131 /// Set the ExtParameterInfo for the parameter at the given index,
13132 ///
13133 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
13134 assert(Infos.size() <= index);
13135 Infos.resize(N: index);
13136 Infos.push_back(Elt: info);
13137
13138 if (!HasInteresting)
13139 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
13140 }
13141
13142 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
13143 /// ExtParameterInfo array we've built up.
13144 const FunctionProtoType::ExtParameterInfo *
13145 getPointerOrNull(unsigned numParams) {
13146 if (!HasInteresting)
13147 return nullptr;
13148 Infos.resize(N: numParams);
13149 return Infos.data();
13150 }
13151 };
13152
13153 /// The current instantiation scope used to store local
13154 /// variables.
13155 LocalInstantiationScope *CurrentInstantiationScope;
13156
13157 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
13158 UnparsedDefaultArgInstantiationsMap;
13159
13160 /// A mapping from parameters with unparsed default arguments to the
13161 /// set of instantiations of each parameter.
13162 ///
13163 /// This mapping is a temporary data structure used when parsing
13164 /// nested class templates or nested classes of class templates,
13165 /// where we might end up instantiating an inner class before the
13166 /// default arguments of its methods have been parsed.
13167 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
13168
13169 using InstantiatingSpecializationsKey = llvm::PointerIntPair<Decl *, 2>;
13170
13171 struct RecursiveInstGuard {
13172 enum class Kind {
13173 Template,
13174 DefaultArgument,
13175 ExceptionSpec,
13176 };
13177
13178 RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
13179 : S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
13180 auto [_, Created] = S.InstantiatingSpecializations.insert(V: Key);
13181 if (!Created)
13182 Key = {};
13183 }
13184
13185 ~RecursiveInstGuard() {
13186 if (Key.getOpaqueValue()) {
13187 [[maybe_unused]] bool Erased =
13188 S.InstantiatingSpecializations.erase(V: Key);
13189 assert(Erased);
13190 }
13191 }
13192
13193 RecursiveInstGuard(const RecursiveInstGuard &) = delete;
13194 RecursiveInstGuard &operator=(const RecursiveInstGuard &) = delete;
13195
13196 operator bool() const { return Key.getOpaqueValue() == nullptr; }
13197
13198 private:
13199 Sema &S;
13200 Sema::InstantiatingSpecializationsKey Key;
13201 };
13202
13203 /// A context in which code is being synthesized (where a source location
13204 /// alone is not sufficient to identify the context). This covers template
13205 /// instantiation and various forms of implicitly-generated functions.
13206 struct CodeSynthesisContext {
13207 /// The kind of template instantiation we are performing
13208 enum SynthesisKind {
13209 /// We are instantiating a template declaration. The entity is
13210 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
13211 TemplateInstantiation,
13212
13213 /// We are instantiating a default argument for a template
13214 /// parameter. The Entity is the template parameter whose argument is
13215 /// being instantiated, the Template is the template, and the
13216 /// TemplateArgs/NumTemplateArguments provide the template arguments as
13217 /// specified.
13218 DefaultTemplateArgumentInstantiation,
13219
13220 /// We are instantiating a default argument for a function.
13221 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
13222 /// provides the template arguments as specified.
13223 DefaultFunctionArgumentInstantiation,
13224
13225 /// We are substituting explicit template arguments provided for
13226 /// a function template. The entity is a FunctionTemplateDecl.
13227 ExplicitTemplateArgumentSubstitution,
13228
13229 /// We are substituting template argument determined as part of
13230 /// template argument deduction for either a class template
13231 /// partial specialization or a function template. The
13232 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
13233 /// a TemplateDecl.
13234 DeducedTemplateArgumentSubstitution,
13235
13236 /// We are substituting into a lambda expression.
13237 LambdaExpressionSubstitution,
13238
13239 /// We are substituting prior template arguments into a new
13240 /// template parameter. The template parameter itself is either a
13241 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
13242 PriorTemplateArgumentSubstitution,
13243
13244 /// We are checking the validity of a default template argument that
13245 /// has been used when naming a template-id.
13246 DefaultTemplateArgumentChecking,
13247
13248 /// We are computing the exception specification for a defaulted special
13249 /// member function.
13250 ExceptionSpecEvaluation,
13251
13252 /// We are instantiating the exception specification for a function
13253 /// template which was deferred until it was needed.
13254 ExceptionSpecInstantiation,
13255
13256 /// We are instantiating a requirement of a requires expression.
13257 RequirementInstantiation,
13258
13259 /// We are checking the satisfaction of a nested requirement of a requires
13260 /// expression.
13261 NestedRequirementConstraintsCheck,
13262
13263 /// We are declaring an implicit special member function.
13264 DeclaringSpecialMember,
13265
13266 /// We are declaring an implicit 'operator==' for a defaulted
13267 /// 'operator<=>'.
13268 DeclaringImplicitEqualityComparison,
13269
13270 /// We are defining a synthesized function (such as a defaulted special
13271 /// member).
13272 DefiningSynthesizedFunction,
13273
13274 // We are checking the constraints associated with a constrained entity or
13275 // the constraint expression of a concept. This includes the checks that
13276 // atomic constraints have the type 'bool' and that they can be constant
13277 // evaluated.
13278 ConstraintsCheck,
13279
13280 // We are substituting template arguments into a constraint expression.
13281 ConstraintSubstitution,
13282
13283 // Instantiating a Requires Expression parameter clause.
13284 RequirementParameterInstantiation,
13285
13286 // We are substituting into the parameter mapping of an atomic constraint
13287 // during normalization.
13288 ParameterMappingSubstitution,
13289
13290 /// We are rewriting a comparison operator in terms of an operator<=>.
13291 RewritingOperatorAsSpaceship,
13292
13293 /// We are initializing a structured binding.
13294 InitializingStructuredBinding,
13295
13296 /// We are marking a class as __dllexport.
13297 MarkingClassDllexported,
13298
13299 /// We are building an implied call from __builtin_dump_struct. The
13300 /// arguments are in CallArgs.
13301 BuildingBuiltinDumpStructCall,
13302
13303 /// Added for Template instantiation observation.
13304 /// Memoization means we are _not_ instantiating a template because
13305 /// it is already instantiated (but we entered a context where we
13306 /// would have had to if it was not already instantiated).
13307 Memoization,
13308
13309 /// We are building deduction guides for a class.
13310 BuildingDeductionGuides,
13311
13312 /// We are instantiating a type alias template declaration.
13313 TypeAliasTemplateInstantiation,
13314
13315 /// We are performing partial ordering for template template parameters.
13316 PartialOrderingTTP,
13317
13318 /// We are performing name lookup for a function template or variable
13319 /// template named 'sycl_kernel_launch'.
13320 SYCLKernelLaunchLookup,
13321
13322 /// We are performing overload resolution for a call to a function
13323 /// template or variable template named 'sycl_kernel_launch'.
13324 SYCLKernelLaunchOverloadResolution,
13325
13326 /// We are instantiating an expansion statement.
13327 ExpansionStmtInstantiation,
13328 } Kind;
13329
13330 /// Whether we're substituting into constraints.
13331 bool InConstraintSubstitution;
13332
13333 /// Whether we're substituting into the parameter mapping of a constraint.
13334 bool InParameterMappingSubstitution;
13335
13336 /// The point of instantiation or synthesis within the source code.
13337 SourceLocation PointOfInstantiation;
13338
13339 /// The entity that is being synthesized.
13340 Decl *Entity;
13341
13342 /// The template (or partial specialization) in which we are
13343 /// performing the instantiation, for substitutions of prior template
13344 /// arguments.
13345 NamedDecl *Template;
13346
13347 union {
13348 /// The list of template arguments we are substituting, if they
13349 /// are not part of the entity.
13350 const TemplateArgument *TemplateArgs;
13351
13352 /// The list of argument expressions in a synthesized call.
13353 const Expr *const *CallArgs;
13354 };
13355
13356 // FIXME: Wrap this union around more members, or perhaps store the
13357 // kind-specific members in the RAII object owning the context.
13358 union {
13359 /// The number of template arguments in TemplateArgs.
13360 unsigned NumTemplateArgs;
13361
13362 /// The number of expressions in CallArgs.
13363 unsigned NumCallArgs;
13364
13365 /// The special member being declared or defined.
13366 CXXSpecialMemberKind SpecialMember;
13367 };
13368
13369 ArrayRef<TemplateArgument> template_arguments() const {
13370 assert(Kind != DeclaringSpecialMember);
13371 return {TemplateArgs, NumTemplateArgs};
13372 }
13373
13374 /// The source range that covers the construct that cause
13375 /// the instantiation, e.g., the template-id that causes a class
13376 /// template instantiation.
13377 SourceRange InstantiationRange;
13378
13379 CodeSynthesisContext()
13380 : Kind(TemplateInstantiation), InConstraintSubstitution(false),
13381 InParameterMappingSubstitution(false), Entity(nullptr),
13382 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0) {}
13383
13384 /// Determines whether this template is an actual instantiation
13385 /// that should be counted toward the maximum instantiation depth.
13386 bool isInstantiationRecord() const;
13387 };
13388
13389 /// A stack object to be created when performing template
13390 /// instantiation.
13391 ///
13392 /// Construction of an object of type \c InstantiatingTemplate
13393 /// pushes the current instantiation onto the stack of active
13394 /// instantiations. If the size of this stack exceeds the maximum
13395 /// number of recursive template instantiations, construction
13396 /// produces an error and evaluates true.
13397 ///
13398 /// Destruction of this object will pop the named instantiation off
13399 /// the stack.
13400 struct InstantiatingTemplate {
13401 /// Note that we are instantiating a class template,
13402 /// function template, variable template, alias template,
13403 /// or a member thereof.
13404 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13405 Decl *Entity,
13406 SourceRange InstantiationRange = SourceRange());
13407
13408 struct ExceptionSpecification {};
13409 /// Note that we are instantiating an exception specification
13410 /// of a function template.
13411 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13412 FunctionDecl *Entity, ExceptionSpecification,
13413 SourceRange InstantiationRange = SourceRange());
13414
13415 /// Note that we are instantiating a type alias template declaration.
13416 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13417 TypeAliasTemplateDecl *Entity,
13418 ArrayRef<TemplateArgument> TemplateArgs,
13419 SourceRange InstantiationRange = SourceRange());
13420
13421 /// Note that we are instantiating a default argument in a
13422 /// template-id.
13423 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13424 TemplateParameter Param, TemplateDecl *Template,
13425 ArrayRef<TemplateArgument> TemplateArgs,
13426 SourceRange InstantiationRange = SourceRange());
13427
13428 /// Note that we are substituting either explicitly-specified or
13429 /// deduced template arguments during function template argument deduction.
13430 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13431 FunctionTemplateDecl *FunctionTemplate,
13432 ArrayRef<TemplateArgument> TemplateArgs,
13433 CodeSynthesisContext::SynthesisKind Kind,
13434 SourceRange InstantiationRange = SourceRange());
13435
13436 /// Note that we are instantiating as part of template
13437 /// argument deduction for a class template declaration.
13438 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13439 TemplateDecl *Template,
13440 ArrayRef<TemplateArgument> TemplateArgs,
13441 SourceRange InstantiationRange = SourceRange());
13442
13443 /// Note that we are instantiating as part of template
13444 /// argument deduction for a class template partial
13445 /// specialization.
13446 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13447 ClassTemplatePartialSpecializationDecl *PartialSpec,
13448 ArrayRef<TemplateArgument> TemplateArgs,
13449 SourceRange InstantiationRange = SourceRange());
13450
13451 /// Note that we are instantiating as part of template
13452 /// argument deduction for a variable template partial
13453 /// specialization.
13454 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13455 VarTemplatePartialSpecializationDecl *PartialSpec,
13456 ArrayRef<TemplateArgument> TemplateArgs,
13457 SourceRange InstantiationRange = SourceRange());
13458
13459 /// Note that we are instantiating a default argument for a function
13460 /// parameter.
13461 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13462 ParmVarDecl *Param,
13463 ArrayRef<TemplateArgument> TemplateArgs,
13464 SourceRange InstantiationRange = SourceRange());
13465
13466 /// Note that we are substituting prior template arguments into a
13467 /// non-type parameter.
13468 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13469 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
13470 ArrayRef<TemplateArgument> TemplateArgs,
13471 SourceRange InstantiationRange);
13472
13473 /// Note that we are substituting prior template arguments into a
13474 /// template template parameter.
13475 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13476 NamedDecl *Template, TemplateTemplateParmDecl *Param,
13477 ArrayRef<TemplateArgument> TemplateArgs,
13478 SourceRange InstantiationRange);
13479
13480 /// Note that we are checking the default template argument
13481 /// against the template parameter for a given template-id.
13482 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13483 TemplateDecl *Template, NamedDecl *Param,
13484 ArrayRef<TemplateArgument> TemplateArgs,
13485 SourceRange InstantiationRange);
13486
13487 struct ConstraintsCheck {};
13488 /// \brief Note that we are checking the constraints associated with some
13489 /// constrained entity (a concept declaration or a template with associated
13490 /// constraints).
13491 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13492 ConstraintsCheck, NamedDecl *Template,
13493 ArrayRef<TemplateArgument> TemplateArgs,
13494 SourceRange InstantiationRange);
13495
13496 struct ConstraintSubstitution {};
13497 /// \brief Note that we are checking a constraint expression associated
13498 /// with a template declaration or as part of the satisfaction check of a
13499 /// concept.
13500 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13501 ConstraintSubstitution, NamedDecl *Template,
13502 SourceRange InstantiationRange);
13503
13504 struct ParameterMappingSubstitution {};
13505 /// \brief Note that we are subtituting into the parameter mapping of an
13506 /// atomic constraint during constraint normalization.
13507 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13508 ParameterMappingSubstitution, NamedDecl *Template,
13509 SourceRange InstantiationRange);
13510
13511 /// \brief Note that we are substituting template arguments into a part of
13512 /// a requirement of a requires expression.
13513 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13514 concepts::Requirement *Req,
13515 SourceRange InstantiationRange = SourceRange());
13516
13517 /// \brief Note that we are substituting the body of an expansion statement.
13518 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13519 CXXExpansionStmtPattern *ExpansionStmt,
13520 ArrayRef<TemplateArgument> TArgs,
13521 SourceRange InstantiationRange);
13522
13523 /// \brief Note that we are checking the satisfaction of the constraint
13524 /// expression inside of a nested requirement.
13525 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13526 concepts::NestedRequirement *Req, ConstraintsCheck,
13527 SourceRange InstantiationRange = SourceRange());
13528
13529 /// \brief Note that we are checking a requires clause.
13530 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13531 const RequiresExpr *E,
13532 SourceRange InstantiationRange);
13533
13534 struct BuildingDeductionGuidesTag {};
13535 /// \brief Note that we are building deduction guides.
13536 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13537 TemplateDecl *Entity, BuildingDeductionGuidesTag,
13538 SourceRange InstantiationRange = SourceRange());
13539
13540 struct PartialOrderingTTP {};
13541 /// \brief Note that we are partial ordering template template parameters.
13542 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13543 PartialOrderingTTP, TemplateDecl *PArg,
13544 SourceRange InstantiationRange = SourceRange());
13545
13546 /// Note that we have finished instantiating this template.
13547 void Clear();
13548
13549 ~InstantiatingTemplate() { Clear(); }
13550
13551 /// Determines whether we have exceeded the maximum
13552 /// recursive template instantiations.
13553 bool isInvalid() const { return Invalid; }
13554
13555 private:
13556 Sema &SemaRef;
13557 bool Invalid;
13558
13559 InstantiatingTemplate(Sema &SemaRef,
13560 CodeSynthesisContext::SynthesisKind Kind,
13561 SourceLocation PointOfInstantiation,
13562 SourceRange InstantiationRange, Decl *Entity,
13563 NamedDecl *Template = nullptr,
13564 ArrayRef<TemplateArgument> TemplateArgs = {});
13565
13566 InstantiatingTemplate(const InstantiatingTemplate &) = delete;
13567
13568 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13569 };
13570
13571 bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13572 const MultiLevelTemplateArgumentList &TemplateArgs,
13573 TemplateArgumentLoc &Output,
13574 SourceLocation Loc = {},
13575 const DeclarationName &Entity = {});
13576 bool
13577 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13578 const MultiLevelTemplateArgumentList &TemplateArgs,
13579 TemplateArgumentListInfo &Outputs);
13580
13581 /// Substitute concept template arguments in the constraint expression
13582 /// of a concept-id. This is used to implement [temp.constr.normal].
13583 ExprResult
13584 SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE,
13585 const Expr *ConstraintExpr,
13586 const MultiLevelTemplateArgumentList &MLTAL);
13587
13588 bool SubstTemplateArgumentsInParameterMapping(
13589 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
13590 const MultiLevelTemplateArgumentList &TemplateArgs,
13591 TemplateArgumentListInfo &Out);
13592
13593 /// Retrieve the template argument list(s) that should be used to
13594 /// instantiate the definition of the given declaration.
13595 ///
13596 /// \param ND the declaration for which we are computing template
13597 /// instantiation arguments.
13598 ///
13599 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13600 /// the decl context where it will be created. In this case, the `Innermost`
13601 /// should likely be provided. If ND is non-null, this is ignored.
13602 ///
13603 /// \param Innermost if non-NULL, specifies a template argument list for the
13604 /// template declaration passed as ND.
13605 ///
13606 /// \param RelativeToPrimary true if we should get the template
13607 /// arguments relative to the primary template, even when we're
13608 /// dealing with a specialization. This is only relevant for function
13609 /// template specializations.
13610 ///
13611 /// \param Pattern If non-NULL, indicates the pattern from which we will be
13612 /// instantiating the definition of the given declaration, \p ND. This is
13613 /// used to determine the proper set of template instantiation arguments for
13614 /// friend function template specializations.
13615 ///
13616 /// \param ForConstraintInstantiation when collecting arguments,
13617 /// ForConstraintInstantiation indicates we should continue looking when
13618 /// encountering a lambda generic call operator, and continue looking for
13619 /// arguments on an enclosing class template.
13620 ///
13621 /// \param SkipForSpecialization when specified, any template specializations
13622 /// in a traversal would be ignored.
13623 ///
13624 /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13625 /// when encountering a specialized member function template, rather than
13626 /// returning immediately.
13627 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13628 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13629 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13630 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13631 bool ForConstraintInstantiation = false,
13632 bool SkipForSpecialization = false,
13633 bool ForDefaultArgumentSubstitution = false);
13634
13635 /// RAII object to handle the state changes required to synthesize
13636 /// a function body.
13637 class SynthesizedFunctionScope {
13638 Sema &S;
13639 Sema::ContextRAII SavedContext;
13640 bool PushedCodeSynthesisContext = false;
13641
13642 public:
13643 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
13644 : S(S), SavedContext(S, DC) {
13645 auto *FD = dyn_cast<FunctionDecl>(Val: DC);
13646 S.PushFunctionScope();
13647 S.PushExpressionEvaluationContextForFunction(
13648 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, FD);
13649 if (FD)
13650 FD->setWillHaveBody(true);
13651 else
13652 assert(isa<ObjCMethodDecl>(DC));
13653 }
13654
13655 void addContextNote(SourceLocation UseLoc) {
13656 assert(!PushedCodeSynthesisContext);
13657
13658 Sema::CodeSynthesisContext Ctx;
13659 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
13660 Ctx.PointOfInstantiation = UseLoc;
13661 Ctx.Entity = cast<Decl>(Val: S.CurContext);
13662 S.pushCodeSynthesisContext(Ctx);
13663
13664 PushedCodeSynthesisContext = true;
13665 }
13666
13667 ~SynthesizedFunctionScope() {
13668 if (PushedCodeSynthesisContext)
13669 S.popCodeSynthesisContext();
13670 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
13671 FD->setWillHaveBody(false);
13672 S.CheckImmediateEscalatingFunctionDefinition(FD, FSI: S.getCurFunction());
13673 }
13674 S.PopExpressionEvaluationContext();
13675 S.PopFunctionScopeInfo();
13676 }
13677
13678 SynthesizedFunctionScope(const SynthesizedFunctionScope &) = delete;
13679 SynthesizedFunctionScope &
13680 operator=(const SynthesizedFunctionScope &) = delete;
13681 };
13682
13683 /// RAII object to ensure that a code synthesis context is popped on scope
13684 /// exit.
13685 class ScopedCodeSynthesisContext {
13686 Sema &S;
13687
13688 public:
13689 ScopedCodeSynthesisContext(Sema &S, const CodeSynthesisContext &Ctx)
13690 : S(S) {
13691 S.pushCodeSynthesisContext(Ctx);
13692 }
13693
13694 ~ScopedCodeSynthesisContext() { S.popCodeSynthesisContext(); }
13695 ScopedCodeSynthesisContext(const ScopedCodeSynthesisContext &) = delete;
13696 ScopedCodeSynthesisContext &
13697 operator=(const ScopedCodeSynthesisContext &) = delete;
13698 };
13699
13700 /// List of active code synthesis contexts.
13701 ///
13702 /// This vector is treated as a stack. As synthesis of one entity requires
13703 /// synthesis of another, additional contexts are pushed onto the stack.
13704 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
13705
13706 /// Specializations whose definitions are currently being instantiated.
13707 llvm::DenseSet<InstantiatingSpecializationsKey> InstantiatingSpecializations;
13708
13709 /// Non-dependent types used in templates that have already been instantiated
13710 /// by some template instantiation.
13711 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13712
13713 /// Extra modules inspected when performing a lookup during a template
13714 /// instantiation. Computed lazily.
13715 SmallVector<Module *, 16> CodeSynthesisContextLookupModules;
13716
13717 /// Cache of additional modules that should be used for name lookup
13718 /// within the current template instantiation. Computed lazily; use
13719 /// getLookupModules() to get a complete set.
13720 llvm::DenseSet<Module *> LookupModulesCache;
13721
13722 /// Map from the most recent declaration of a namespace to the most
13723 /// recent visible declaration of that namespace.
13724 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13725
13726 SFINAETrap *CurrentSFINAEContext = nullptr;
13727
13728 /// The number of \p CodeSynthesisContexts that are not template
13729 /// instantiations and, therefore, should not be counted as part of the
13730 /// instantiation depth.
13731 ///
13732 /// When the instantiation depth reaches the user-configurable limit
13733 /// \p LangOptions::InstantiationDepth we will abort instantiation.
13734 // FIXME: Should we have a similar limit for other forms of synthesis?
13735 unsigned NonInstantiationEntries;
13736
13737 /// The depth of the context stack at the point when the most recent
13738 /// error or warning was produced.
13739 ///
13740 /// This value is used to suppress printing of redundant context stacks
13741 /// when there are multiple errors or warnings in the same instantiation.
13742 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13743 unsigned LastEmittedCodeSynthesisContextDepth = 0;
13744
13745 /// The current index into pack expansion arguments that will be
13746 /// used for substitution of parameter packs.
13747 ///
13748 /// The pack expansion index will be none to indicate that parameter packs
13749 /// should be instantiated as themselves. Otherwise, the index specifies
13750 /// which argument within the parameter pack will be used for substitution.
13751 UnsignedOrNone ArgPackSubstIndex;
13752
13753 /// RAII object used to change the argument pack substitution index
13754 /// within a \c Sema object.
13755 ///
13756 /// See \c ArgPackSubstIndex for more information.
13757 class ArgPackSubstIndexRAII {
13758 Sema &Self;
13759 UnsignedOrNone OldSubstIndex;
13760
13761 public:
13762 ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
13763 : Self(Self),
13764 OldSubstIndex(std::exchange(obj&: Self.ArgPackSubstIndex, new_val&: NewSubstIndex)) {}
13765
13766 ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13767 ArgPackSubstIndexRAII(const ArgPackSubstIndexRAII &) = delete;
13768 ArgPackSubstIndexRAII &operator=(const ArgPackSubstIndexRAII &) = delete;
13769 };
13770
13771 bool pushCodeSynthesisContext(CodeSynthesisContext Ctx);
13772 void popCodeSynthesisContext();
13773
13774 void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc) {
13775 if (!CodeSynthesisContexts.empty() &&
13776 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
13777 PrintInstantiationStack(DiagFunc);
13778 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
13779 }
13780 if (PragmaAttributeCurrentTargetDecl)
13781 PrintPragmaAttributeInstantiationPoint(DiagFunc);
13782 }
13783 void PrintContextStack() { PrintContextStack(DiagFunc: getDefaultDiagFunc()); }
13784 /// Prints the current instantiation stack through a series of
13785 /// notes.
13786 void PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc);
13787 void PrintInstantiationStack() {
13788 PrintInstantiationStack(DiagFunc: getDefaultDiagFunc());
13789 }
13790
13791 /// Returns a pointer to the current SFINAE context, if any.
13792 [[nodiscard]] SFINAETrap *getSFINAEContext() const {
13793 return CurrentSFINAEContext;
13794 }
13795 [[nodiscard]] bool isSFINAEContext() const {
13796 return CurrentSFINAEContext != nullptr;
13797 }
13798
13799 /// Perform substitution on the type T with a given set of template
13800 /// arguments.
13801 ///
13802 /// This routine substitutes the given template arguments into the
13803 /// type T and produces the instantiated type.
13804 ///
13805 /// \param T the type into which the template arguments will be
13806 /// substituted. If this type is not dependent, it will be returned
13807 /// immediately.
13808 ///
13809 /// \param Args the template arguments that will be
13810 /// substituted for the top-level template parameters within T.
13811 ///
13812 /// \param Loc the location in the source code where this substitution
13813 /// is being performed. It will typically be the location of the
13814 /// declarator (if we're instantiating the type of some declaration)
13815 /// or the location of the type in the source code (if, e.g., we're
13816 /// instantiating the type of a cast expression).
13817 ///
13818 /// \param Entity the name of the entity associated with a declaration
13819 /// being instantiated (if any). May be empty to indicate that there
13820 /// is no such entity (if, e.g., this is a type that occurs as part of
13821 /// a cast expression) or that the entity has no name (e.g., an
13822 /// unnamed function parameter).
13823 ///
13824 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
13825 /// acceptable as the top level type of the result.
13826 ///
13827 /// \param IsIncompleteSubstitution If provided, the pointee will be set
13828 /// whenever substitution would perform a replacement with a null or
13829 /// non-existent template argument.
13830 ///
13831 /// \returns If the instantiation succeeds, the instantiated
13832 /// type. Otherwise, produces diagnostics and returns a NULL type.
13833 TypeSourceInfo *SubstType(TypeSourceInfo *T,
13834 const MultiLevelTemplateArgumentList &TemplateArgs,
13835 SourceLocation Loc, DeclarationName Entity,
13836 bool AllowDeducedTST = false);
13837
13838 QualType SubstType(QualType T,
13839 const MultiLevelTemplateArgumentList &TemplateArgs,
13840 SourceLocation Loc, DeclarationName Entity,
13841 bool *IsIncompleteSubstitution = nullptr);
13842
13843 TypeSourceInfo *SubstType(TypeLoc TL,
13844 const MultiLevelTemplateArgumentList &TemplateArgs,
13845 SourceLocation Loc, DeclarationName Entity);
13846
13847 TypeSourceInfo *
13848 SubstFriendType(TypeSourceInfo *TSI,
13849 const MultiLevelTemplateArgumentList &TemplateArgs,
13850 SourceLocation Loc, DeclarationName Entity);
13851
13852 /// A form of SubstType intended specifically for instantiating the
13853 /// type of a FunctionDecl. Its purpose is solely to force the
13854 /// instantiation of default-argument expressions and to avoid
13855 /// instantiating an exception-specification.
13856 TypeSourceInfo *SubstFunctionDeclType(
13857 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
13858 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
13859 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
13860 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
13861 const MultiLevelTemplateArgumentList &Args);
13862 bool SubstExceptionSpec(SourceLocation Loc,
13863 FunctionProtoType::ExceptionSpecInfo &ESI,
13864 SmallVectorImpl<QualType> &ExceptionStorage,
13865 const MultiLevelTemplateArgumentList &Args);
13866 ParmVarDecl *
13867 SubstParmVarDecl(ParmVarDecl *D,
13868 const MultiLevelTemplateArgumentList &TemplateArgs,
13869 int indexAdjustment, UnsignedOrNone NumExpansions,
13870 bool ExpectParameterPack, bool EvaluateConstraints = true);
13871
13872 /// Substitute the given template arguments into the given set of
13873 /// parameters, producing the set of parameter types that would be generated
13874 /// from such a substitution.
13875 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
13876 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
13877 const MultiLevelTemplateArgumentList &TemplateArgs,
13878 SmallVectorImpl<QualType> &ParamTypes,
13879 SmallVectorImpl<ParmVarDecl *> *OutParams,
13880 ExtParameterInfoBuilder &ParamInfos);
13881
13882 /// Substitute the given template arguments into the default argument.
13883 bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param,
13884 const MultiLevelTemplateArgumentList &TemplateArgs,
13885 bool ForCallExpr = false);
13886 ExprResult SubstExpr(Expr *E,
13887 const MultiLevelTemplateArgumentList &TemplateArgs);
13888 /// Substitute an expression as if it is a address-of-operand, which makes it
13889 /// act like a CXXIdExpression rather than an attempt to call.
13890 ExprResult SubstCXXIdExpr(Expr *E,
13891 const MultiLevelTemplateArgumentList &TemplateArgs);
13892
13893 // Must be used instead of SubstExpr at 'constraint checking' time.
13894 ExprResult
13895 SubstConstraintExpr(Expr *E,
13896 const MultiLevelTemplateArgumentList &TemplateArgs);
13897 // Unlike the above, this does not evaluate constraints.
13898 ExprResult SubstConstraintExprWithoutSatisfaction(
13899 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
13900
13901 /// Substitute the given template arguments into a list of
13902 /// expressions, expanding pack expansions if required.
13903 ///
13904 /// \param Exprs The list of expressions to substitute into.
13905 ///
13906 /// \param IsCall Whether this is some form of call, in which case
13907 /// default arguments will be dropped.
13908 ///
13909 /// \param TemplateArgs The set of template arguments to substitute.
13910 ///
13911 /// \param Outputs Will receive all of the substituted arguments.
13912 ///
13913 /// \returns true if an error occurred, false otherwise.
13914 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
13915 const MultiLevelTemplateArgumentList &TemplateArgs,
13916 SmallVectorImpl<Expr *> &Outputs);
13917
13918 StmtResult SubstStmt(Stmt *S,
13919 const MultiLevelTemplateArgumentList &TemplateArgs);
13920
13921 ExprResult
13922 SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs,
13923 bool CXXDirectInit);
13924
13925 /// Perform substitution on the base class specifiers of the
13926 /// given class template specialization.
13927 ///
13928 /// Produces a diagnostic and returns true on error, returns false and
13929 /// attaches the instantiated base classes to the class template
13930 /// specialization if successful.
13931 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13932 const MultiLevelTemplateArgumentList &TemplateArgs);
13933
13934 /// Instantiate the definition of a class from a given pattern.
13935 ///
13936 /// \param PointOfInstantiation The point of instantiation within the
13937 /// source code.
13938 ///
13939 /// \param Instantiation is the declaration whose definition is being
13940 /// instantiated. This will be either a class template specialization
13941 /// or a member class of a class template specialization.
13942 ///
13943 /// \param Pattern is the pattern from which the instantiation
13944 /// occurs. This will be either the declaration of a class template or
13945 /// the declaration of a member class of a class template.
13946 ///
13947 /// \param TemplateArgs The template arguments to be substituted into
13948 /// the pattern.
13949 ///
13950 /// \param TSK the kind of implicit or explicit instantiation to perform.
13951 ///
13952 /// \param Complain whether to complain if the class cannot be instantiated
13953 /// due to the lack of a definition.
13954 ///
13955 /// \returns true if an error occurred, false otherwise.
13956 bool InstantiateClass(SourceLocation PointOfInstantiation,
13957 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13958 const MultiLevelTemplateArgumentList &TemplateArgs,
13959 TemplateSpecializationKind TSK, bool Complain = true);
13960
13961private:
13962 bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
13963 CXXRecordDecl *Instantiation,
13964 CXXRecordDecl *Pattern,
13965 const MultiLevelTemplateArgumentList &TemplateArgs,
13966 TemplateSpecializationKind TSK, bool Complain);
13967
13968public:
13969 /// Instantiate the definition of an enum from a given pattern.
13970 ///
13971 /// \param PointOfInstantiation The point of instantiation within the
13972 /// source code.
13973 /// \param Instantiation is the declaration whose definition is being
13974 /// instantiated. This will be a member enumeration of a class
13975 /// temploid specialization, or a local enumeration within a
13976 /// function temploid specialization.
13977 /// \param Pattern The templated declaration from which the instantiation
13978 /// occurs.
13979 /// \param TemplateArgs The template arguments to be substituted into
13980 /// the pattern.
13981 /// \param TSK The kind of implicit or explicit instantiation to perform.
13982 ///
13983 /// \return \c true if an error occurred, \c false otherwise.
13984 bool InstantiateEnum(SourceLocation PointOfInstantiation,
13985 EnumDecl *Instantiation, EnumDecl *Pattern,
13986 const MultiLevelTemplateArgumentList &TemplateArgs,
13987 TemplateSpecializationKind TSK);
13988
13989 /// Instantiate the definition of a field from the given pattern.
13990 ///
13991 /// \param PointOfInstantiation The point of instantiation within the
13992 /// source code.
13993 /// \param Instantiation is the declaration whose definition is being
13994 /// instantiated. This will be a class of a class temploid
13995 /// specialization, or a local enumeration within a function temploid
13996 /// specialization.
13997 /// \param Pattern The templated declaration from which the instantiation
13998 /// occurs.
13999 /// \param TemplateArgs The template arguments to be substituted into
14000 /// the pattern.
14001 ///
14002 /// \return \c true if an error occurred, \c false otherwise.
14003 bool InstantiateInClassInitializer(
14004 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
14005 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
14006
14007 bool usesPartialOrExplicitSpecialization(
14008 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
14009
14010 bool InstantiateClassTemplateSpecialization(
14011 SourceLocation PointOfInstantiation,
14012 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14013 TemplateSpecializationKind TSK, bool Complain,
14014 bool PrimaryStrictPackMatch);
14015
14016 /// Instantiates the definitions of all of the member
14017 /// of the given class, which is an instantiation of a class template
14018 /// or a member class of a template.
14019 void
14020 InstantiateClassMembers(SourceLocation PointOfInstantiation,
14021 CXXRecordDecl *Instantiation,
14022 const MultiLevelTemplateArgumentList &TemplateArgs,
14023 TemplateSpecializationKind TSK);
14024
14025 /// Instantiate the definitions of all of the members of the
14026 /// given class template specialization, which was named as part of an
14027 /// explicit instantiation.
14028 void InstantiateClassTemplateSpecializationMembers(
14029 SourceLocation PointOfInstantiation,
14030 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14031 TemplateSpecializationKind TSK);
14032
14033 NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(
14034 NestedNameSpecifierLoc NNS,
14035 const MultiLevelTemplateArgumentList &TemplateArgs);
14036
14037 /// Do template substitution on declaration name info.
14038 DeclarationNameInfo
14039 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
14040 const MultiLevelTemplateArgumentList &TemplateArgs);
14041 TemplateName
14042 SubstTemplateName(SourceLocation TemplateKWLoc,
14043 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
14044 SourceLocation NameLoc,
14045 const MultiLevelTemplateArgumentList &TemplateArgs);
14046
14047 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
14048 const MultiLevelTemplateArgumentList &TemplateArgs,
14049 bool EvaluateConstraint);
14050
14051 /// Determine whether we are currently performing template instantiation.
14052 bool inTemplateInstantiation() const {
14053 return CodeSynthesisContexts.size() > NonInstantiationEntries;
14054 }
14055
14056 /// Determine whether we are currently performing constraint substitution.
14057 bool inConstraintSubstitution() const {
14058 return !CodeSynthesisContexts.empty() &&
14059 CodeSynthesisContexts.back().InConstraintSubstitution;
14060 }
14061
14062 bool inParameterMappingSubstitution() const {
14063 return !CodeSynthesisContexts.empty() &&
14064 CodeSynthesisContexts.back().InParameterMappingSubstitution &&
14065 !inConstraintSubstitution();
14066 }
14067
14068 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
14069
14070 /// \brief create a Requirement::SubstitutionDiagnostic with only a
14071 /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
14072 concepts::Requirement::SubstitutionDiagnostic *
14073 createSubstDiagAt(SourceLocation Location, EntityPrinter Printer);
14074
14075 ///@}
14076
14077 //
14078 //
14079 // -------------------------------------------------------------------------
14080 //
14081 //
14082
14083 /// \name C++ Template Declaration Instantiation
14084 /// Implementations are in SemaTemplateInstantiateDecl.cpp
14085 ///@{
14086
14087public:
14088 /// An entity for which implicit template instantiation is required.
14089 ///
14090 /// The source location associated with the declaration is the first place in
14091 /// the source code where the declaration was "used". It is not necessarily
14092 /// the point of instantiation (which will be either before or after the
14093 /// namespace-scope declaration that triggered this implicit instantiation),
14094 /// However, it is the location that diagnostics should generally refer to,
14095 /// because users will need to know what code triggered the instantiation.
14096 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
14097
14098 /// The queue of implicit template instantiations that are required
14099 /// but have not yet been performed.
14100 std::deque<PendingImplicitInstantiation> PendingInstantiations;
14101
14102 /// Queue of implicit template instantiations that cannot be performed
14103 /// eagerly.
14104 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
14105
14106 SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses;
14107 SmallVector<std::deque<PendingImplicitInstantiation>, 8>
14108 SavedPendingInstantiations;
14109
14110 /// The queue of implicit template instantiations that are required
14111 /// and must be performed within the current local scope.
14112 ///
14113 /// This queue is only used for member functions of local classes in
14114 /// templates, which must be instantiated in the same scope as their
14115 /// enclosing function, so that they can reference function-local
14116 /// types, static variables, enumerators, etc.
14117 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
14118
14119 class LocalEagerInstantiationScope {
14120 public:
14121 LocalEagerInstantiationScope(Sema &S, bool AtEndOfTU)
14122 : S(S), AtEndOfTU(AtEndOfTU) {
14123 SavedPendingLocalImplicitInstantiations.swap(
14124 x&: S.PendingLocalImplicitInstantiations);
14125 }
14126
14127 void perform() {
14128 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: true,
14129 /*AtEndOfTU=*/AtEndOfTU);
14130 }
14131
14132 ~LocalEagerInstantiationScope() {
14133 assert(S.PendingLocalImplicitInstantiations.empty() &&
14134 "there shouldn't be any pending local implicit instantiations");
14135 SavedPendingLocalImplicitInstantiations.swap(
14136 x&: S.PendingLocalImplicitInstantiations);
14137 }
14138
14139 LocalEagerInstantiationScope(const LocalEagerInstantiationScope &) = delete;
14140 LocalEagerInstantiationScope &
14141 operator=(const LocalEagerInstantiationScope &) = delete;
14142
14143 private:
14144 Sema &S;
14145 bool AtEndOfTU;
14146 std::deque<PendingImplicitInstantiation>
14147 SavedPendingLocalImplicitInstantiations;
14148 };
14149
14150 /// Records and restores the CurFPFeatures state on entry/exit of compound
14151 /// statements.
14152 class FPFeaturesStateRAII {
14153 public:
14154 FPFeaturesStateRAII(Sema &S);
14155 ~FPFeaturesStateRAII();
14156 FPFeaturesStateRAII(const FPFeaturesStateRAII &) = delete;
14157 FPFeaturesStateRAII &operator=(const FPFeaturesStateRAII &) = delete;
14158 FPOptionsOverride getOverrides() { return OldOverrides; }
14159
14160 private:
14161 Sema &S;
14162 FPOptions OldFPFeaturesState;
14163 FPOptionsOverride OldOverrides;
14164 LangOptions::FPEvalMethodKind OldEvalMethod;
14165 SourceLocation OldFPPragmaLocation;
14166 };
14167
14168 class GlobalEagerInstantiationScope {
14169 public:
14170 GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
14171 : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
14172 if (!Enabled)
14173 return;
14174
14175 S.SavedPendingInstantiations.emplace_back();
14176 S.SavedPendingInstantiations.back().swap(x&: S.PendingInstantiations);
14177
14178 S.SavedVTableUses.emplace_back();
14179 S.SavedVTableUses.back().swap(RHS&: S.VTableUses);
14180 }
14181
14182 void perform() {
14183 if (Enabled) {
14184 S.DefineUsedVTables();
14185 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: false,
14186 /*AtEndOfTU=*/AtEndOfTU);
14187 }
14188 }
14189
14190 ~GlobalEagerInstantiationScope() {
14191 if (!Enabled)
14192 return;
14193
14194 // Restore the set of pending vtables.
14195 assert(S.VTableUses.empty() &&
14196 "VTableUses should be empty before it is discarded.");
14197 S.VTableUses.swap(RHS&: S.SavedVTableUses.back());
14198 S.SavedVTableUses.pop_back();
14199
14200 // Restore the set of pending implicit instantiations.
14201 if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
14202 AtEndOfTU) {
14203 assert(S.PendingInstantiations.empty() &&
14204 "PendingInstantiations should be empty before it is discarded.");
14205 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14206 S.SavedPendingInstantiations.pop_back();
14207 } else {
14208 // Template instantiations in the PCH may be delayed until the TU.
14209 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14210 S.PendingInstantiations.insert(
14211 position: S.PendingInstantiations.end(),
14212 first: S.SavedPendingInstantiations.back().begin(),
14213 last: S.SavedPendingInstantiations.back().end());
14214 S.SavedPendingInstantiations.pop_back();
14215 }
14216 }
14217
14218 GlobalEagerInstantiationScope(const GlobalEagerInstantiationScope &) =
14219 delete;
14220 GlobalEagerInstantiationScope &
14221 operator=(const GlobalEagerInstantiationScope &) = delete;
14222
14223 private:
14224 Sema &S;
14225 bool Enabled;
14226 bool AtEndOfTU;
14227 };
14228
14229 ExplicitSpecifier instantiateExplicitSpecifier(
14230 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
14231
14232 struct LateInstantiatedAttribute {
14233 const Attr *TmplAttr;
14234 LocalInstantiationScope *Scope;
14235 Decl *NewDecl;
14236
14237 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
14238 Decl *D)
14239 : TmplAttr(A), Scope(S), NewDecl(D) {}
14240 };
14241 typedef SmallVector<LateInstantiatedAttribute, 1> LateInstantiatedAttrVec;
14242
14243 /// Recheck instantiated thread-safety attributes that could not be validated
14244 /// on the dependent pattern declaration.
14245 bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A);
14246
14247 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14248 const Decl *Pattern, Decl *Inst,
14249 LateInstantiatedAttrVec *LateAttrs = nullptr,
14250 LocalInstantiationScope *OuterMostScope = nullptr);
14251
14252 /// Update instantiation attributes after template was late parsed.
14253 ///
14254 /// Some attributes are evaluated based on the body of template. If it is
14255 /// late parsed, such attributes cannot be evaluated when declaration is
14256 /// instantiated. This function is used to update instantiation attributes
14257 /// when template definition is ready.
14258 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
14259
14260 void
14261 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
14262 const Decl *Pattern, Decl *Inst,
14263 LateInstantiatedAttrVec *LateAttrs = nullptr,
14264 LocalInstantiationScope *OuterMostScope = nullptr);
14265
14266 bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor,
14267 bool IsCopy = false);
14268
14269 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
14270 ParmVarDecl *Param);
14271 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
14272 FunctionDecl *Function);
14273
14274 /// Instantiate (or find existing instantiation of) a function template with a
14275 /// given set of template arguments.
14276 ///
14277 /// Usually this should not be used, and template argument deduction should be
14278 /// used in its place.
14279 FunctionDecl *InstantiateFunctionDeclaration(
14280 FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
14281 SourceLocation Loc,
14282 CodeSynthesisContext::SynthesisKind CSC =
14283 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution);
14284
14285 /// Instantiate the definition of the given function from its
14286 /// template.
14287 ///
14288 /// \param PointOfInstantiation the point at which the instantiation was
14289 /// required. Note that this is not precisely a "point of instantiation"
14290 /// for the function, but it's close.
14291 ///
14292 /// \param Function the already-instantiated declaration of a
14293 /// function template specialization or member function of a class template
14294 /// specialization.
14295 ///
14296 /// \param Recursive if true, recursively instantiates any functions that
14297 /// are required by this instantiation.
14298 ///
14299 /// \param DefinitionRequired if true, then we are performing an explicit
14300 /// instantiation where the body of the function is required. Complain if
14301 /// there is no such body.
14302 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
14303 FunctionDecl *Function,
14304 bool Recursive = false,
14305 bool DefinitionRequired = false,
14306 bool AtEndOfTU = false);
14307 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
14308 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
14309 const TemplateArgumentList *PartialSpecArgs,
14310 SmallVectorImpl<TemplateArgument> &Converted,
14311 SourceLocation PointOfInstantiation,
14312 LateInstantiatedAttrVec *LateAttrs = nullptr,
14313 LocalInstantiationScope *StartingScope = nullptr);
14314
14315 /// Instantiates a variable template specialization by completing it
14316 /// with appropriate type information and initializer.
14317 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
14318 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14319 const MultiLevelTemplateArgumentList &TemplateArgs);
14320
14321 /// BuildVariableInstantiation - Used after a new variable has been created.
14322 /// Sets basic variable data and decides whether to postpone the
14323 /// variable instantiation.
14324 void
14325 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
14326 const MultiLevelTemplateArgumentList &TemplateArgs,
14327 LateInstantiatedAttrVec *LateAttrs,
14328 DeclContext *Owner,
14329 LocalInstantiationScope *StartingScope,
14330 bool InstantiatingVarTemplate = false,
14331 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14332
14333 /// Instantiate the initializer of a variable.
14334 void InstantiateVariableInitializer(
14335 VarDecl *Var, VarDecl *OldVar,
14336 const MultiLevelTemplateArgumentList &TemplateArgs);
14337
14338 /// Instantiate the definition of the given variable from its
14339 /// template.
14340 ///
14341 /// \param PointOfInstantiation the point at which the instantiation was
14342 /// required. Note that this is not precisely a "point of instantiation"
14343 /// for the variable, but it's close.
14344 ///
14345 /// \param Var the already-instantiated declaration of a templated variable.
14346 ///
14347 /// \param Recursive if true, recursively instantiates any functions that
14348 /// are required by this instantiation.
14349 ///
14350 /// \param DefinitionRequired if true, then we are performing an explicit
14351 /// instantiation where a definition of the variable is required. Complain
14352 /// if there is no such definition.
14353 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14354 VarDecl *Var, bool Recursive = false,
14355 bool DefinitionRequired = false,
14356 bool AtEndOfTU = false);
14357
14358 void InstantiateMemInitializers(
14359 CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl,
14360 const MultiLevelTemplateArgumentList &TemplateArgs);
14361
14362 /// Find the instantiation of the given declaration within the
14363 /// current instantiation.
14364 ///
14365 /// This routine is intended to be used when \p D is a declaration
14366 /// referenced from within a template, that needs to mapped into the
14367 /// corresponding declaration within an instantiation. For example,
14368 /// given:
14369 ///
14370 /// \code
14371 /// template<typename T>
14372 /// struct X {
14373 /// enum Kind {
14374 /// KnownValue = sizeof(T)
14375 /// };
14376 ///
14377 /// bool getKind() const { return KnownValue; }
14378 /// };
14379 ///
14380 /// template struct X<int>;
14381 /// \endcode
14382 ///
14383 /// In the instantiation of X<int>::getKind(), we need to map the \p
14384 /// EnumConstantDecl for \p KnownValue (which refers to
14385 /// X<T>::<Kind>::KnownValue) to its instantiation
14386 /// (X<int>::<Kind>::KnownValue).
14387 /// \p FindInstantiatedDecl performs this mapping from within the
14388 /// instantiation of X<int>.
14389 NamedDecl *
14390 FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
14391 const MultiLevelTemplateArgumentList &TemplateArgs,
14392 bool FindingInstantiatedContext = false);
14393
14394 /// Finds the instantiation of the given declaration context
14395 /// within the current instantiation.
14396 ///
14397 /// \returns NULL if there was an error
14398 DeclContext *
14399 FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
14400 const MultiLevelTemplateArgumentList &TemplateArgs);
14401
14402 Decl *SubstDecl(Decl *D, DeclContext *Owner,
14403 const MultiLevelTemplateArgumentList &TemplateArgs);
14404
14405 /// Substitute the name and return type of a defaulted 'operator<=>' to form
14406 /// an implicit 'operator=='.
14407 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
14408 FunctionDecl *Spaceship);
14409
14410 /// Performs template instantiation for all implicit template
14411 /// instantiations we have seen until this point.
14412 void PerformPendingInstantiations(bool LocalOnly = false,
14413 bool AtEndOfTU = true);
14414
14415 TemplateParameterList *
14416 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
14417 const MultiLevelTemplateArgumentList &TemplateArgs,
14418 bool EvaluateConstraints = true);
14419
14420 void PerformDependentDiagnostics(
14421 const DeclContext *Pattern,
14422 const MultiLevelTemplateArgumentList &TemplateArgs);
14423
14424private:
14425 /// Introduce the instantiated local variables into the local
14426 /// instantiation scope.
14427 void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14428 const FunctionDecl *PatternDecl,
14429 LocalInstantiationScope &Scope);
14430 /// Introduce the instantiated function parameters into the local
14431 /// instantiation scope, and set the parameter names to those used
14432 /// in the template.
14433 bool addInstantiatedParametersToScope(
14434 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14435 LocalInstantiationScope &Scope,
14436 const MultiLevelTemplateArgumentList &TemplateArgs);
14437
14438 /// Introduce the instantiated captures of the lambda into the local
14439 /// instantiation scope.
14440 bool addInstantiatedCapturesToScope(
14441 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14442 LocalInstantiationScope &Scope,
14443 const MultiLevelTemplateArgumentList &TemplateArgs);
14444
14445 int ParsingClassDepth = 0;
14446
14447 class SavePendingParsedClassStateRAII {
14448 public:
14449 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14450
14451 ~SavePendingParsedClassStateRAII() {
14452 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14453 "there shouldn't be any pending delayed exception spec checks");
14454 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14455 "there shouldn't be any pending delayed exception spec checks");
14456 swapSavedState();
14457 }
14458
14459 SavePendingParsedClassStateRAII(const SavePendingParsedClassStateRAII &) =
14460 delete;
14461 SavePendingParsedClassStateRAII &
14462 operator=(const SavePendingParsedClassStateRAII &) = delete;
14463
14464 private:
14465 Sema &S;
14466 decltype(DelayedOverridingExceptionSpecChecks)
14467 SavedOverridingExceptionSpecChecks;
14468 decltype(DelayedEquivalentExceptionSpecChecks)
14469 SavedEquivalentExceptionSpecChecks;
14470
14471 void swapSavedState() {
14472 SavedOverridingExceptionSpecChecks.swap(
14473 RHS&: S.DelayedOverridingExceptionSpecChecks);
14474 SavedEquivalentExceptionSpecChecks.swap(
14475 RHS&: S.DelayedEquivalentExceptionSpecChecks);
14476 }
14477 };
14478
14479 ///@}
14480
14481 //
14482 //
14483 // -------------------------------------------------------------------------
14484 //
14485 //
14486
14487 /// \name C++ Variadic Templates
14488 /// Implementations are in SemaTemplateVariadic.cpp
14489 ///@{
14490
14491public:
14492 /// Determine whether an unexpanded parameter pack might be permitted in this
14493 /// location. Useful for error recovery.
14494 bool isUnexpandedParameterPackPermitted();
14495
14496 /// The context in which an unexpanded parameter pack is
14497 /// being diagnosed.
14498 ///
14499 /// Note that the values of this enumeration line up with the first
14500 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14501 enum UnexpandedParameterPackContext {
14502 /// An arbitrary expression.
14503 UPPC_Expression = 0,
14504
14505 /// The base type of a class type.
14506 UPPC_BaseType,
14507
14508 /// The type of an arbitrary declaration.
14509 UPPC_DeclarationType,
14510
14511 /// The type of a data member.
14512 UPPC_DataMemberType,
14513
14514 /// The size of a bit-field.
14515 UPPC_BitFieldWidth,
14516
14517 /// The expression in a static assertion.
14518 UPPC_StaticAssertExpression,
14519
14520 /// The fixed underlying type of an enumeration.
14521 UPPC_FixedUnderlyingType,
14522
14523 /// The enumerator value.
14524 UPPC_EnumeratorValue,
14525
14526 /// A using declaration.
14527 UPPC_UsingDeclaration,
14528
14529 /// A friend declaration.
14530 UPPC_FriendDeclaration,
14531
14532 /// A declaration qualifier.
14533 UPPC_DeclarationQualifier,
14534
14535 /// An initializer.
14536 UPPC_Initializer,
14537
14538 /// A default argument.
14539 UPPC_DefaultArgument,
14540
14541 /// The type of a non-type template parameter.
14542 UPPC_NonTypeTemplateParameterType,
14543
14544 /// The type of an exception.
14545 UPPC_ExceptionType,
14546
14547 /// Explicit specialization.
14548 UPPC_ExplicitSpecialization,
14549
14550 /// Partial specialization.
14551 UPPC_PartialSpecialization,
14552
14553 /// Microsoft __if_exists.
14554 UPPC_IfExists,
14555
14556 /// Microsoft __if_not_exists.
14557 UPPC_IfNotExists,
14558
14559 /// Lambda expression.
14560 UPPC_Lambda,
14561
14562 /// Block expression.
14563 UPPC_Block,
14564
14565 /// A type constraint.
14566 UPPC_TypeConstraint,
14567
14568 // A requirement in a requires-expression.
14569 UPPC_Requirement,
14570
14571 // A requires-clause.
14572 UPPC_RequiresClause,
14573 };
14574
14575 /// Diagnose unexpanded parameter packs.
14576 ///
14577 /// \param Loc The location at which we should emit the diagnostic.
14578 ///
14579 /// \param UPPC The context in which we are diagnosing unexpanded
14580 /// parameter packs.
14581 ///
14582 /// \param Unexpanded the set of unexpanded parameter packs.
14583 ///
14584 /// \returns true if an error occurred, false otherwise.
14585 bool DiagnoseUnexpandedParameterPacks(
14586 SourceLocation Loc, UnexpandedParameterPackContext UPPC,
14587 ArrayRef<UnexpandedParameterPack> Unexpanded);
14588
14589 /// If the given type contains an unexpanded parameter pack,
14590 /// diagnose the error.
14591 ///
14592 /// \param Loc The source location where a diagnostc should be emitted.
14593 ///
14594 /// \param T The type that is being checked for unexpanded parameter
14595 /// packs.
14596 ///
14597 /// \returns true if an error occurred, false otherwise.
14598 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
14599 UnexpandedParameterPackContext UPPC);
14600
14601 /// If the given expression contains an unexpanded parameter
14602 /// pack, diagnose the error.
14603 ///
14604 /// \param E The expression that is being checked for unexpanded
14605 /// parameter packs.
14606 ///
14607 /// \returns true if an error occurred, false otherwise.
14608 bool DiagnoseUnexpandedParameterPack(
14609 Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression);
14610
14611 /// If the given requirees-expression contains an unexpanded reference to one
14612 /// of its own parameter packs, diagnose the error.
14613 ///
14614 /// \param RE The requiress-expression that is being checked for unexpanded
14615 /// parameter packs.
14616 ///
14617 /// \returns true if an error occurred, false otherwise.
14618 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
14619
14620 /// If the given nested-name-specifier contains an unexpanded
14621 /// parameter pack, diagnose the error.
14622 ///
14623 /// \param SS The nested-name-specifier that is being checked for
14624 /// unexpanded parameter packs.
14625 ///
14626 /// \returns true if an error occurred, false otherwise.
14627 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
14628 UnexpandedParameterPackContext UPPC);
14629
14630 /// If the given name contains an unexpanded parameter pack,
14631 /// diagnose the error.
14632 ///
14633 /// \param NameInfo The name (with source location information) that
14634 /// is being checked for unexpanded parameter packs.
14635 ///
14636 /// \returns true if an error occurred, false otherwise.
14637 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
14638 UnexpandedParameterPackContext UPPC);
14639
14640 /// If the given template name contains an unexpanded parameter pack,
14641 /// diagnose the error.
14642 ///
14643 /// \param Loc The location of the template name.
14644 ///
14645 /// \param Template The template name that is being checked for unexpanded
14646 /// parameter packs.
14647 ///
14648 /// \returns true if an error occurred, false otherwise.
14649 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
14650 TemplateName Template,
14651 UnexpandedParameterPackContext UPPC);
14652
14653 /// If the given template argument contains an unexpanded parameter
14654 /// pack, diagnose the error.
14655 ///
14656 /// \param Arg The template argument that is being checked for unexpanded
14657 /// parameter packs.
14658 ///
14659 /// \returns true if an error occurred, false otherwise.
14660 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
14661 UnexpandedParameterPackContext UPPC);
14662
14663 /// Collect the set of unexpanded parameter packs within the given
14664 /// template argument.
14665 ///
14666 /// \param Arg The template argument that will be traversed to find
14667 /// unexpanded parameter packs.
14668 void collectUnexpandedParameterPacks(
14669 TemplateArgument Arg,
14670 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14671
14672 /// Collect the set of unexpanded parameter packs within the given
14673 /// template argument.
14674 ///
14675 /// \param Arg The template argument that will be traversed to find
14676 /// unexpanded parameter packs.
14677 void collectUnexpandedParameterPacks(
14678 TemplateArgumentLoc Arg,
14679 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14680
14681 /// Collect the set of unexpanded parameter packs within the given
14682 /// type.
14683 ///
14684 /// \param T The type that will be traversed to find
14685 /// unexpanded parameter packs.
14686 void collectUnexpandedParameterPacks(
14687 QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14688
14689 /// Collect the set of unexpanded parameter packs within the given
14690 /// template name.
14691 ///
14692 /// \param Template The template name that will be traversed to find
14693 /// unexpanded parameter packs.
14694 void collectUnexpandedParameterPacks(
14695 TemplateName Template,
14696 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14697
14698 /// Collect the set of unexpanded parameter packs within the given
14699 /// type.
14700 ///
14701 /// \param TL The type that will be traversed to find
14702 /// unexpanded parameter packs.
14703 void collectUnexpandedParameterPacks(
14704 TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14705
14706 /// Collect the set of unexpanded parameter packs within the given
14707 /// nested-name-specifier.
14708 ///
14709 /// \param NNS The nested-name-specifier that will be traversed to find
14710 /// unexpanded parameter packs.
14711 void collectUnexpandedParameterPacks(
14712 NestedNameSpecifierLoc NNS,
14713 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14714
14715 /// Collect the set of unexpanded parameter packs within the given
14716 /// name.
14717 ///
14718 /// \param NameInfo The name that will be traversed to find
14719 /// unexpanded parameter packs.
14720 void collectUnexpandedParameterPacks(
14721 const DeclarationNameInfo &NameInfo,
14722 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14723
14724 /// Collect the set of unexpanded parameter packs within the given
14725 /// expression.
14726 static void collectUnexpandedParameterPacks(
14727 Expr *E, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14728
14729 /// Invoked when parsing a template argument.
14730 ///
14731 /// \param Arg the template argument, which may already be invalid.
14732 ///
14733 /// If it is followed by ellipsis, this function is called before
14734 /// `ActOnPackExpansion`.
14735 ParsedTemplateArgument
14736 ActOnTemplateTemplateArgument(const ParsedTemplateArgument &Arg);
14737
14738 /// Invoked when parsing a template argument followed by an
14739 /// ellipsis, which creates a pack expansion.
14740 ///
14741 /// \param Arg The template argument preceding the ellipsis, which
14742 /// may already be invalid.
14743 ///
14744 /// \param EllipsisLoc The location of the ellipsis.
14745 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
14746 SourceLocation EllipsisLoc);
14747
14748 /// Invoked when parsing a type followed by an ellipsis, which
14749 /// creates a pack expansion.
14750 ///
14751 /// \param Type The type preceding the ellipsis, which will become
14752 /// the pattern of the pack expansion.
14753 ///
14754 /// \param EllipsisLoc The location of the ellipsis.
14755 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
14756
14757 /// Construct a pack expansion type from the pattern of the pack
14758 /// expansion.
14759 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
14760 SourceLocation EllipsisLoc,
14761 UnsignedOrNone NumExpansions);
14762
14763 /// Construct a pack expansion type from the pattern of the pack
14764 /// expansion.
14765 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14766 SourceLocation EllipsisLoc,
14767 UnsignedOrNone NumExpansions);
14768
14769 /// Invoked when parsing an expression followed by an ellipsis, which
14770 /// creates a pack expansion.
14771 ///
14772 /// \param Pattern The expression preceding the ellipsis, which will become
14773 /// the pattern of the pack expansion.
14774 ///
14775 /// \param EllipsisLoc The location of the ellipsis.
14776 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14777
14778 /// Invoked when parsing an expression followed by an ellipsis, which
14779 /// creates a pack expansion.
14780 ///
14781 /// \param Pattern The expression preceding the ellipsis, which will become
14782 /// the pattern of the pack expansion.
14783 ///
14784 /// \param EllipsisLoc The location of the ellipsis.
14785 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14786 UnsignedOrNone NumExpansions);
14787
14788 /// Determine whether we could expand a pack expansion with the
14789 /// given set of parameter packs into separate arguments by repeatedly
14790 /// transforming the pattern.
14791 ///
14792 /// \param EllipsisLoc The location of the ellipsis that identifies the
14793 /// pack expansion.
14794 ///
14795 /// \param PatternRange The source range that covers the entire pattern of
14796 /// the pack expansion.
14797 ///
14798 /// \param Unexpanded The set of unexpanded parameter packs within the
14799 /// pattern.
14800 ///
14801 /// \param ShouldExpand Will be set to \c true if the transformer should
14802 /// expand the corresponding pack expansions into separate arguments. When
14803 /// set, \c NumExpansions must also be set.
14804 ///
14805 /// \param RetainExpansion Whether the caller should add an unexpanded
14806 /// pack expansion after all of the expanded arguments. This is used
14807 /// when extending explicitly-specified template argument packs per
14808 /// C++0x [temp.arg.explicit]p9.
14809 ///
14810 /// \param NumExpansions The number of separate arguments that will be in
14811 /// the expanded form of the corresponding pack expansion. This is both an
14812 /// input and an output parameter, which can be set by the caller if the
14813 /// number of expansions is known a priori (e.g., due to a prior substitution)
14814 /// and will be set by the callee when the number of expansions is known.
14815 /// The callee must set this value when \c ShouldExpand is \c true; it may
14816 /// set this value in other cases.
14817 ///
14818 /// \returns true if an error occurred (e.g., because the parameter packs
14819 /// are to be instantiated with arguments of different lengths), false
14820 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
14821 /// must be set.
14822 bool CheckParameterPacksForExpansion(
14823 SourceLocation EllipsisLoc, SourceRange PatternRange,
14824 ArrayRef<UnexpandedParameterPack> Unexpanded,
14825 const MultiLevelTemplateArgumentList &TemplateArgs,
14826 bool FailOnPackProducingTemplates, bool &ShouldExpand,
14827 bool &RetainExpansion, UnsignedOrNone &NumExpansions,
14828 bool Diagnose = true);
14829
14830 /// Determine the number of arguments in the given pack expansion
14831 /// type.
14832 ///
14833 /// This routine assumes that the number of arguments in the expansion is
14834 /// consistent across all of the unexpanded parameter packs in its pattern.
14835 ///
14836 /// Returns an empty Optional if the type can't be expanded.
14837 UnsignedOrNone getNumArgumentsInExpansion(
14838 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
14839
14840 UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(
14841 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
14842 const MultiLevelTemplateArgumentList &TemplateArgs);
14843
14844 /// Determine whether the given declarator contains any unexpanded
14845 /// parameter packs.
14846 ///
14847 /// This routine is used by the parser to disambiguate function declarators
14848 /// with an ellipsis prior to the ')', e.g.,
14849 ///
14850 /// \code
14851 /// void f(T...);
14852 /// \endcode
14853 ///
14854 /// To determine whether we have an (unnamed) function parameter pack or
14855 /// a variadic function.
14856 ///
14857 /// \returns true if the declarator contains any unexpanded parameter packs,
14858 /// false otherwise.
14859 bool containsUnexpandedParameterPacks(Declarator &D);
14860
14861 /// Returns the pattern of the pack expansion for a template argument.
14862 ///
14863 /// \param OrigLoc The template argument to expand.
14864 ///
14865 /// \param Ellipsis Will be set to the location of the ellipsis.
14866 ///
14867 /// \param NumExpansions Will be set to the number of expansions that will
14868 /// be generated from this pack expansion, if known a priori.
14869 TemplateArgumentLoc
14870 getTemplateArgumentPackExpansionPattern(TemplateArgumentLoc OrigLoc,
14871 SourceLocation &Ellipsis,
14872 UnsignedOrNone &NumExpansions) const;
14873
14874 /// Given a template argument that contains an unexpanded parameter pack, but
14875 /// which has already been substituted, attempt to determine the number of
14876 /// elements that will be produced once this argument is fully-expanded.
14877 ///
14878 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
14879 /// avoid actually expanding the pack where possible.
14880 UnsignedOrNone getFullyPackExpandedSize(TemplateArgument Arg);
14881
14882 /// Called when an expression computing the size of a parameter pack
14883 /// is parsed.
14884 ///
14885 /// \code
14886 /// template<typename ...Types> struct count {
14887 /// static const unsigned value = sizeof...(Types);
14888 /// };
14889 /// \endcode
14890 ///
14891 //
14892 /// \param OpLoc The location of the "sizeof" keyword.
14893 /// \param Name The name of the parameter pack whose size will be determined.
14894 /// \param NameLoc The source location of the name of the parameter pack.
14895 /// \param RParenLoc The location of the closing parentheses.
14896 ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc,
14897 IdentifierInfo &Name,
14898 SourceLocation NameLoc,
14899 SourceLocation RParenLoc);
14900
14901 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
14902 SourceLocation EllipsisLoc,
14903 SourceLocation LSquareLoc, Expr *IndexExpr,
14904 SourceLocation RSquareLoc);
14905
14906 ExprResult BuildPackIndexingExpr(Expr *PackExpression,
14907 SourceLocation EllipsisLoc, Expr *IndexExpr,
14908 SourceLocation RSquareLoc,
14909 ArrayRef<Expr *> ExpandedExprs = {},
14910 bool FullySubstituted = false);
14911
14912 TemplateName ActOnPackIndexingTemplateName(TemplateName Pattern,
14913 SourceLocation NameLoc,
14914 Expr *IndexExpr);
14915
14916 TemplateName
14917 BuildPackIndexingTemplateName(TemplateName Pattern, Expr *IndexExpr,
14918 bool FullySubstituted = false,
14919 ArrayRef<TemplateName> Expansions = {});
14920
14921 TypeResult
14922 ActOnPackIndexingDeducedTemplateSpecializationType(TemplateName Name,
14923 SourceLocation NameLoc);
14924
14925 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
14926 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
14927 tok::TokenKind Operator,
14928 SourceLocation EllipsisLoc, Expr *RHS,
14929 SourceLocation RParenLoc);
14930 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
14931 SourceLocation LParenLoc, Expr *LHS,
14932 BinaryOperatorKind Operator,
14933 SourceLocation EllipsisLoc, Expr *RHS,
14934 SourceLocation RParenLoc,
14935 UnsignedOrNone NumExpansions);
14936 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
14937 BinaryOperatorKind Operator);
14938
14939 ///@}
14940
14941 //
14942 //
14943 // -------------------------------------------------------------------------
14944 //
14945 //
14946
14947 /// \name Constraints and Concepts
14948 /// Implementations are in SemaConcept.cpp
14949 ///@{
14950
14951public:
14952 ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI);
14953
14954 ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc,
14955 TypeSourceInfo *TSI);
14956
14957public:
14958 void PushSatisfactionStackEntry(const NamedDecl *D,
14959 const llvm::FoldingSetNodeID &ID) {
14960 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
14961 SatisfactionStack.emplace_back(Args&: Can, Args: ID);
14962 }
14963
14964 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
14965
14966 bool SatisfactionStackContains(const NamedDecl *D,
14967 const llvm::FoldingSetNodeID &ID) const {
14968 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
14969 return llvm::is_contained(Range: SatisfactionStack,
14970 Element: SatisfactionStackEntryTy{Can, ID});
14971 }
14972
14973 using SatisfactionStackEntryTy =
14974 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
14975
14976 // Resets the current SatisfactionStack for cases where we are instantiating
14977 // constraints as a 'side effect' of normal instantiation in a way that is not
14978 // indicative of recursive definition.
14979 class SatisfactionStackResetRAII {
14980 llvm::SmallVector<SatisfactionStackEntryTy, 10> BackupSatisfactionStack;
14981 Sema &SemaRef;
14982
14983 public:
14984 SatisfactionStackResetRAII(Sema &S) : SemaRef(S) {
14985 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
14986 }
14987
14988 ~SatisfactionStackResetRAII() {
14989 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
14990 }
14991
14992 SatisfactionStackResetRAII(const SatisfactionStackResetRAII &) = delete;
14993 SatisfactionStackResetRAII &
14994 operator=(const SatisfactionStackResetRAII &) = delete;
14995 };
14996
14997 void SwapSatisfactionStack(
14998 llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) {
14999 SatisfactionStack.swap(RHS&: NewSS);
15000 }
15001
15002 using ConstrainedDeclOrNestedRequirement =
15003 llvm::PointerUnion<const NamedDecl *,
15004 const concepts::NestedRequirement *>;
15005
15006 /// Check whether the given expression is a valid constraint expression.
15007 /// A diagnostic is emitted if it is not, false is returned, and
15008 /// PossibleNonPrimary will be set to true if the failure might be due to a
15009 /// non-primary expression being used as an atomic constraint.
15010 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
15011 bool *PossibleNonPrimary = nullptr,
15012 bool IsTrailingRequiresClause = false);
15013
15014 /// \brief Check whether the given list of constraint expressions are
15015 /// satisfied (as if in a 'conjunction') given template arguments.
15016 /// \param Template the template-like entity that triggered the constraints
15017 /// check (either a concept or a constrained entity).
15018 /// \param ConstraintExprs a list of constraint expressions, treated as if
15019 /// they were 'AND'ed together.
15020 /// \param TemplateArgLists the list of template arguments to substitute into
15021 /// the constraint expression.
15022 /// \param TemplateIDRange The source range of the template id that
15023 /// caused the constraints check.
15024 /// \param Satisfaction if true is returned, will contain details of the
15025 /// satisfaction, with enough information to diagnose an unsatisfied
15026 /// expression.
15027 /// \returns true if an error occurred and satisfaction could not be checked,
15028 /// false otherwise.
15029 bool CheckConstraintSatisfaction(
15030 ConstrainedDeclOrNestedRequirement Entity,
15031 ArrayRef<AssociatedConstraint> AssociatedConstraints,
15032 const MultiLevelTemplateArgumentList &TemplateArgLists,
15033 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
15034 const ConceptReference *TopLevelConceptId = nullptr,
15035 Expr **ConvertedExpr = nullptr);
15036
15037 /// Check whether the given function decl's trailing requires clause is
15038 /// satisfied, if any. Returns false and updates Satisfaction with the
15039 /// satisfaction verdict if successful, emits a diagnostic and returns true if
15040 /// an error occurred and satisfaction could not be determined.
15041 ///
15042 /// \returns true if an error occurred, false otherwise.
15043 bool CheckFunctionConstraints(const FunctionDecl *FD,
15044 ConstraintSatisfaction &Satisfaction,
15045 SourceLocation UsageLoc = SourceLocation(),
15046 bool ForOverloadResolution = false);
15047
15048 // Calculates whether two constraint expressions are equal irrespective of a
15049 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
15050 // 'New', which are the "source" of the constraint, since this is necessary
15051 // for figuring out the relative 'depth' of the constraint. The depth of the
15052 // 'primary template' and the 'instantiated from' templates aren't necessarily
15053 // the same, such as a case when one is a 'friend' defined in a class.
15054 bool AreConstraintExpressionsEqual(const NamedDecl *Old,
15055 const Expr *OldConstr,
15056 const TemplateCompareNewDeclInfo &New,
15057 const Expr *NewConstr);
15058
15059 // Calculates whether the friend function depends on an enclosing template for
15060 // the purposes of [temp.friend] p9.
15061 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
15062
15063 /// \brief Ensure that the given template arguments satisfy the constraints
15064 /// associated with the given template, emitting a diagnostic if they do not.
15065 ///
15066 /// \param Template The template to which the template arguments are being
15067 /// provided.
15068 ///
15069 /// \param TemplateArgs The converted, canonicalized template arguments.
15070 ///
15071 /// \param TemplateIDRange The source range of the template id that
15072 /// caused the constraints check.
15073 ///
15074 /// \returns true if the constrains are not satisfied or could not be checked
15075 /// for satisfaction, false if the constraints are satisfied.
15076 bool EnsureTemplateArgumentListConstraints(
15077 TemplateDecl *Template,
15078 const MultiLevelTemplateArgumentList &TemplateArgs,
15079 SourceRange TemplateIDRange);
15080
15081 bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
15082 FunctionDecl *Decl,
15083 ArrayRef<TemplateArgument> TemplateArgs,
15084 ConstraintSatisfaction &Satisfaction);
15085
15086 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15087 /// unsatisfied.
15088 /// \param First whether this is the first time an unsatisfied constraint is
15089 /// diagnosed for this error.
15090 void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
15091 SourceLocation Loc = {},
15092 bool First = true);
15093
15094 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15095 /// unsatisfied.
15096 void
15097 DiagnoseUnsatisfiedConstraint(const ConceptSpecializationExpr *ConstraintExpr,
15098 bool First = true);
15099
15100 void DiagnoseUnsatisfiedRequiresExpr(const RequiresExpr *RequiresExpr,
15101 bool First = true);
15102
15103 const NormalizedConstraint *getNormalizedAssociatedConstraints(
15104 ConstrainedDeclOrNestedRequirement Entity,
15105 ArrayRef<AssociatedConstraint> AssociatedConstraints);
15106
15107 /// \brief Check whether the given declaration's associated constraints are
15108 /// at least as constrained than another declaration's according to the
15109 /// partial ordering of constraints.
15110 ///
15111 /// \param Result If no error occurred, receives the result of true if D1 is
15112 /// at least constrained than D2, and false otherwise.
15113 ///
15114 /// \returns true if an error occurred, false otherwise.
15115 bool IsAtLeastAsConstrained(const NamedDecl *D1,
15116 MutableArrayRef<AssociatedConstraint> AC1,
15117 const NamedDecl *D2,
15118 MutableArrayRef<AssociatedConstraint> AC2,
15119 bool &Result);
15120
15121 /// If D1 was not at least as constrained as D2, but would've been if a pair
15122 /// of atomic constraints involved had been declared in a concept and not
15123 /// repeated in two separate places in code.
15124 /// \returns true if such a diagnostic was emitted, false otherwise.
15125 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(
15126 const NamedDecl *D1, ArrayRef<AssociatedConstraint> AC1,
15127 const NamedDecl *D2, ArrayRef<AssociatedConstraint> AC2);
15128
15129 /// Cache the satisfaction of an atomic constraint.
15130 /// The key is based on the unsubstituted expression and the parameter
15131 /// mapping. This lets us not substituting the mapping more than once,
15132 /// which is (very!) expensive.
15133 /// FIXME: this should be private.
15134 llvm::DenseMap<llvm::FoldingSetNodeID,
15135 UnsubstitutedConstraintSatisfactionCacheResult>
15136 UnsubstitutedConstraintSatisfactionCache;
15137
15138 /// Cache the instantiation results of template parameter mappings within
15139 /// concepts. Substituting into normalized concepts can be extremely expensive
15140 /// due to the redundancy of template parameters. This cache is intended for
15141 /// use by TemplateInstantiator to avoid redundant semantic checking.
15142 llvm::DenseMap<llvm::FoldingSetNodeID, TemplateArgumentLoc>
15143 *CurrentCachedTemplateArgs = nullptr;
15144
15145private:
15146 /// Caches pairs of template-like decls whose associated constraints were
15147 /// checked for subsumption and whether or not the first's constraints did in
15148 /// fact subsume the second's.
15149 llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
15150 SubsumptionCache;
15151 /// Caches the normalized associated constraints of declarations (concepts or
15152 /// constrained declarations). If an error occurred while normalizing the
15153 /// associated constraints of the template or concept, nullptr will be cached
15154 /// here.
15155 llvm::DenseMap<ConstrainedDeclOrNestedRequirement, NormalizedConstraint *>
15156 NormalizationCache;
15157
15158 /// Cache whether the associated constraint of a declaration
15159 /// is satisfied.
15160 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
15161 SatisfactionCache;
15162
15163 // The current stack of constraint satisfactions, so we can exit-early.
15164 llvm::SmallVector<SatisfactionStackEntryTy, 10> SatisfactionStack;
15165
15166 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
15167 /// LocalInstantiationScope of the current non-lambda function. For lambdas,
15168 /// use LambdaScopeForCallOperatorInstantiationRAII.
15169 bool
15170 SetupConstraintScope(FunctionDecl *FD,
15171 std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15172 const MultiLevelTemplateArgumentList &MLTAL,
15173 LocalInstantiationScope &Scope);
15174
15175 /// Used during constraint checking, sets up the constraint template argument
15176 /// lists, and calls SetupConstraintScope to set up the
15177 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
15178 std::optional<MultiLevelTemplateArgumentList>
15179 SetupConstraintCheckingTemplateArgumentsAndScope(
15180 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15181 LocalInstantiationScope &Scope);
15182
15183 ///@}
15184
15185 //
15186 //
15187 // -------------------------------------------------------------------------
15188 //
15189 //
15190
15191 /// \name Types
15192 /// Implementations are in SemaType.cpp
15193 ///@{
15194
15195public:
15196 /// A mapping that describes the nullability we've seen in each header file.
15197 FileNullabilityMap NullabilityMap;
15198
15199 static int getPrintable(int I) { return I; }
15200 static unsigned getPrintable(unsigned I) { return I; }
15201 static bool getPrintable(bool B) { return B; }
15202 static const char *getPrintable(const char *S) { return S; }
15203 static StringRef getPrintable(StringRef S) { return S; }
15204 static const std::string &getPrintable(const std::string &S) { return S; }
15205 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
15206 return II;
15207 }
15208 static DeclarationName getPrintable(DeclarationName N) { return N; }
15209 static QualType getPrintable(QualType T) { return T; }
15210 static SourceRange getPrintable(SourceRange R) { return R; }
15211 static SourceRange getPrintable(SourceLocation L) { return L; }
15212 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
15213 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange(); }
15214
15215 enum class CompleteTypeKind {
15216 /// Apply the normal rules for complete types. In particular,
15217 /// treat all sizeless types as incomplete.
15218 Normal,
15219
15220 /// Relax the normal rules for complete types so that they include
15221 /// sizeless built-in types.
15222 AcceptSizeless,
15223
15224 // FIXME: Eventually we should flip the default to Normal and opt in
15225 // to AcceptSizeless rather than opt out of it.
15226 Default = AcceptSizeless
15227 };
15228
15229 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
15230 const DeclSpec *DS = nullptr);
15231 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
15232 const DeclSpec *DS = nullptr);
15233
15234 /// Build a pointer type.
15235 ///
15236 /// \param T The type to which we'll be building a pointer.
15237 ///
15238 /// \param Loc The location of the entity whose type involves this
15239 /// pointer type or, if there is no such entity, the location of the
15240 /// type that will have pointer type.
15241 ///
15242 /// \param Entity The name of the entity that involves the pointer
15243 /// type, if known.
15244 ///
15245 /// \returns A suitable pointer type, if there are no
15246 /// errors. Otherwise, returns a NULL type.
15247 QualType BuildPointerType(QualType T, SourceLocation Loc,
15248 DeclarationName Entity);
15249
15250 /// Build a reference type.
15251 ///
15252 /// \param T The type to which we'll be building a reference.
15253 ///
15254 /// \param Loc The location of the entity whose type involves this
15255 /// reference type or, if there is no such entity, the location of the
15256 /// type that will have reference type.
15257 ///
15258 /// \param Entity The name of the entity that involves the reference
15259 /// type, if known.
15260 ///
15261 /// \returns A suitable reference type, if there are no
15262 /// errors. Otherwise, returns a NULL type.
15263 QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc,
15264 DeclarationName Entity);
15265
15266 /// Build an array type.
15267 ///
15268 /// \param T The type of each element in the array.
15269 ///
15270 /// \param ASM C99 array size modifier (e.g., '*', 'static').
15271 ///
15272 /// \param ArraySize Expression describing the size of the array.
15273 ///
15274 /// \param Brackets The range from the opening '[' to the closing ']'.
15275 ///
15276 /// \param Entity The name of the entity that involves the array
15277 /// type, if known.
15278 ///
15279 /// \returns A suitable array type, if there are no errors. Otherwise,
15280 /// returns a NULL type.
15281 QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize,
15282 unsigned Quals, SourceRange Brackets,
15283 DeclarationName Entity);
15284 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
15285
15286 /// Build an ext-vector type.
15287 ///
15288 /// Run the required checks for the extended vector type.
15289 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
15290 SourceLocation AttrLoc);
15291 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
15292 SourceLocation AttrLoc);
15293
15294 QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy,
15295 Expr *CountExpr,
15296 bool CountInBytes,
15297 bool OrNull);
15298
15299 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
15300 /// expression is uninstantiated. If instantiated it will apply the
15301 /// appropriate address space to the type. This function allows dependent
15302 /// template variables to be used in conjunction with the address_space
15303 /// attribute
15304 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
15305 SourceLocation AttrLoc);
15306
15307 /// Same as above, but constructs the AddressSpace index if not provided.
15308 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
15309 SourceLocation AttrLoc);
15310
15311 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
15312
15313 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
15314
15315 /// Build a function type.
15316 ///
15317 /// This routine checks the function type according to C++ rules and
15318 /// under the assumption that the result type and parameter types have
15319 /// just been instantiated from a template. It therefore duplicates
15320 /// some of the behavior of GetTypeForDeclarator, but in a much
15321 /// simpler form that is only suitable for this narrow use case.
15322 ///
15323 /// \param T The return type of the function.
15324 ///
15325 /// \param ParamTypes The parameter types of the function. This array
15326 /// will be modified to account for adjustments to the types of the
15327 /// function parameters.
15328 ///
15329 /// \param Loc The location of the entity whose type involves this
15330 /// function type or, if there is no such entity, the location of the
15331 /// type that will have function type.
15332 ///
15333 /// \param Entity The name of the entity that involves the function
15334 /// type, if known.
15335 ///
15336 /// \param EPI Extra information about the function type. Usually this will
15337 /// be taken from an existing function with the same prototype.
15338 ///
15339 /// \returns A suitable function type, if there are no errors. The
15340 /// unqualified type will always be a FunctionProtoType.
15341 /// Otherwise, returns a NULL type.
15342 QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes,
15343 SourceLocation Loc, DeclarationName Entity,
15344 const FunctionProtoType::ExtProtoInfo &EPI);
15345
15346 /// Build a member pointer type \c T Class::*.
15347 ///
15348 /// \param T the type to which the member pointer refers.
15349 /// \param Class the class type into which the member pointer points.
15350 /// \param Loc the location where this type begins
15351 /// \param Entity the name of the entity that will have this member pointer
15352 /// type
15353 ///
15354 /// \returns a member pointer type, if successful, or a NULL type if there was
15355 /// an error.
15356 QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS,
15357 CXXRecordDecl *Cls, SourceLocation Loc,
15358 DeclarationName Entity);
15359
15360 /// Build a block pointer type.
15361 ///
15362 /// \param T The type to which we'll be building a block pointer.
15363 ///
15364 /// \param Loc The source location, used for diagnostics.
15365 ///
15366 /// \param Entity The name of the entity that involves the block pointer
15367 /// type, if known.
15368 ///
15369 /// \returns A suitable block pointer type, if there are no
15370 /// errors. Otherwise, returns a NULL type.
15371 QualType BuildBlockPointerType(QualType T, SourceLocation Loc,
15372 DeclarationName Entity);
15373
15374 /// Build a paren type including \p T.
15375 QualType BuildParenType(QualType T);
15376 QualType BuildAtomicType(QualType T, SourceLocation Loc);
15377
15378 /// Build a Read-only Pipe type.
15379 ///
15380 /// \param T The type to which we'll be building a Pipe.
15381 ///
15382 /// \param Loc We do not use it for now.
15383 ///
15384 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15385 /// a NULL type.
15386 QualType BuildReadPipeType(QualType T, SourceLocation Loc);
15387
15388 /// Build a Write-only Pipe type.
15389 ///
15390 /// \param T The type to which we'll be building a Pipe.
15391 ///
15392 /// \param Loc We do not use it for now.
15393 ///
15394 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15395 /// a NULL type.
15396 QualType BuildWritePipeType(QualType T, SourceLocation Loc);
15397
15398 /// Build a bit-precise integer type.
15399 ///
15400 /// \param IsUnsigned Boolean representing the signedness of the type.
15401 ///
15402 /// \param BitWidth Size of this int type in bits, or an expression
15403 /// representing that.
15404 ///
15405 /// \param Loc Location of the keyword.
15406 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15407
15408 /// GetTypeForDeclarator - Convert the type for the specified
15409 /// declarator to Type instances.
15410 ///
15411 /// The result of this call will never be null, but the associated
15412 /// type may be a null type if there's an unrecoverable error.
15413 TypeSourceInfo *GetTypeForDeclarator(Declarator &D);
15414 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
15415
15416 /// Package the given type and TSI into a ParsedType.
15417 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
15418 static QualType GetTypeFromParser(ParsedType Ty,
15419 TypeSourceInfo **TInfo = nullptr);
15420
15421 TypeResult ActOnTypeName(Declarator &D);
15422
15423 // Check whether the size of array element of type \p EltTy is a multiple of
15424 // its alignment and return false if it isn't.
15425 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
15426
15427 void
15428 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15429 SourceLocation FallbackLoc,
15430 SourceLocation ConstQualLoc = SourceLocation(),
15431 SourceLocation VolatileQualLoc = SourceLocation(),
15432 SourceLocation RestrictQualLoc = SourceLocation(),
15433 SourceLocation AtomicQualLoc = SourceLocation(),
15434 SourceLocation UnalignedQualLoc = SourceLocation());
15435
15436 /// Retrieve the keyword associated
15437 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
15438
15439 /// Adjust the calling convention of a method to be the ABI default if it
15440 /// wasn't specified explicitly. This handles method types formed from
15441 /// function type typedefs and typename template arguments.
15442 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15443 bool IsCtorOrDtor, SourceLocation Loc);
15444
15445 // Check if there is an explicit attribute, but only look through parens.
15446 // The intent is to look for an attribute on the current declarator, but not
15447 // one that came from a typedef.
15448 bool hasExplicitCallingConv(QualType T);
15449
15450 /// Check whether a nullability type specifier can be added to the given
15451 /// type through some means not written in source (e.g. API notes).
15452 ///
15453 /// \param Type The type to which the nullability specifier will be
15454 /// added. On success, this type will be updated appropriately.
15455 ///
15456 /// \param Nullability The nullability specifier to add.
15457 ///
15458 /// \param DiagLoc The location to use for diagnostics.
15459 ///
15460 /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15461 /// array type (e.g., because it will decay to a pointer).
15462 ///
15463 /// \param OverrideExisting Whether to override an existing, locally-specified
15464 /// nullability specifier rather than complaining about the conflict.
15465 ///
15466 /// \returns true if nullability cannot be applied, false otherwise.
15467 bool CheckImplicitNullabilityTypeSpecifier(QualType &Type,
15468 NullabilityKind Nullability,
15469 SourceLocation DiagLoc,
15470 bool AllowArrayTypes,
15471 bool OverrideExisting);
15472
15473 /// Check whether the given variable declaration has a size that fits within
15474 /// the address space it is declared in. This issues a diagnostic if not.
15475 ///
15476 /// \param VD The variable declaration to check the size of.
15477 ///
15478 /// \param AS The address space to check the size of \p VD against.
15479 ///
15480 /// \returns true if the variable's size fits within the address space, false
15481 /// otherwise.
15482 bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS);
15483
15484 /// Get the type of expression E, triggering instantiation to complete the
15485 /// type if necessary -- that is, if the expression refers to a templated
15486 /// static data member of incomplete array type.
15487 ///
15488 /// May still return an incomplete type if instantiation was not possible or
15489 /// if the type is incomplete for a different reason. Use
15490 /// RequireCompleteExprType instead if a diagnostic is expected for an
15491 /// incomplete expression type.
15492 QualType getCompletedType(Expr *E);
15493
15494 void completeExprArrayBound(Expr *E);
15495
15496 /// Ensure that the type of the given expression is complete.
15497 ///
15498 /// This routine checks whether the expression \p E has a complete type. If
15499 /// the expression refers to an instantiable construct, that instantiation is
15500 /// performed as needed to complete its type. Furthermore
15501 /// Sema::RequireCompleteType is called for the expression's type (or in the
15502 /// case of a reference type, the referred-to type).
15503 ///
15504 /// \param E The expression whose type is required to be complete.
15505 /// \param Kind Selects which completeness rules should be applied.
15506 /// \param Diagnoser The object that will emit a diagnostic if the type is
15507 /// incomplete.
15508 ///
15509 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15510 /// otherwise.
15511 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
15512 TypeDiagnoser &Diagnoser);
15513 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15514
15515 template <typename... Ts>
15516 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15517 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15518 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
15519 }
15520
15521 // Returns the underlying type of a decltype with the given expression.
15522 QualType getDecltypeForExpr(Expr *E);
15523
15524 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
15525 /// If AsUnevaluated is false, E is treated as though it were an evaluated
15526 /// context, such as when building a type for decltype(auto).
15527 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15528
15529 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15530 SourceLocation Loc,
15531 SourceLocation EllipsisLoc);
15532 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15533 SourceLocation Loc, SourceLocation EllipsisLoc,
15534 bool FullySubstituted = false,
15535 ArrayRef<QualType> Expansions = {});
15536
15537 using UTTKind = UnaryTransformType::UTTKind;
15538 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
15539 SourceLocation Loc);
15540 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
15541 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
15542 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
15543 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
15544 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
15545 SourceLocation Loc);
15546 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
15547 SourceLocation Loc);
15548 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
15549 SourceLocation Loc);
15550
15551 QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc) {
15552 return BuiltinRemoveReference(BaseType, UKind: UTTKind::RemoveCVRef, Loc);
15553 }
15554
15555 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
15556 SourceLocation Loc);
15557 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
15558 SourceLocation Loc);
15559
15560 bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15561
15562 /// Ensure that the type T is a literal type.
15563 ///
15564 /// This routine checks whether the type @p T is a literal type. If @p T is an
15565 /// incomplete type, an attempt is made to complete it. If @p T is a literal
15566 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15567 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15568 /// it the type @p T), along with notes explaining why the type is not a
15569 /// literal type, and returns true.
15570 ///
15571 /// @param Loc The location in the source that the non-literal type
15572 /// diagnostic should refer to.
15573 ///
15574 /// @param T The type that this routine is examining for literalness.
15575 ///
15576 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15577 ///
15578 /// @returns @c true if @p T is not a literal type and a diagnostic was
15579 /// emitted, @c false otherwise.
15580 bool RequireLiteralType(SourceLocation Loc, QualType T,
15581 TypeDiagnoser &Diagnoser);
15582 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15583
15584 template <typename... Ts>
15585 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15586 const Ts &...Args) {
15587 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15588 return RequireLiteralType(Loc, T, Diagnoser);
15589 }
15590
15591 bool isCompleteType(SourceLocation Loc, QualType T,
15592 CompleteTypeKind Kind = CompleteTypeKind::Default) {
15593 return !RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser: nullptr);
15594 }
15595
15596 /// Ensure that the type T is a complete type.
15597 ///
15598 /// This routine checks whether the type @p T is complete in any
15599 /// context where a complete type is required. If @p T is a complete
15600 /// type, returns false. If @p T is a class template specialization,
15601 /// this routine then attempts to perform class template
15602 /// instantiation. If instantiation fails, or if @p T is incomplete
15603 /// and cannot be completed, issues the diagnostic @p diag (giving it
15604 /// the type @p T) and returns true.
15605 ///
15606 /// @param Loc The location in the source that the incomplete type
15607 /// diagnostic should refer to.
15608 ///
15609 /// @param T The type that this routine is examining for completeness.
15610 ///
15611 /// @param Kind Selects which completeness rules should be applied.
15612 ///
15613 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15614 /// @c false otherwise.
15615 bool RequireCompleteType(SourceLocation Loc, QualType T,
15616 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15617 bool RequireCompleteType(SourceLocation Loc, QualType T,
15618 CompleteTypeKind Kind, unsigned DiagID);
15619
15620 bool RequireCompleteType(SourceLocation Loc, QualType T,
15621 TypeDiagnoser &Diagnoser) {
15622 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, Diagnoser);
15623 }
15624 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15625 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, DiagID);
15626 }
15627
15628 template <typename... Ts>
15629 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15630 const Ts &...Args) {
15631 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15632 return RequireCompleteType(Loc, T, Diagnoser);
15633 }
15634
15635 /// Determine whether a declaration is visible to name lookup.
15636 bool isVisible(const NamedDecl *D) {
15637 return D->isUnconditionallyVisible() ||
15638 isAcceptableSlow(D, Kind: AcceptableKind::Visible);
15639 }
15640
15641 /// Determine whether a declaration is reachable.
15642 bool isReachable(const NamedDecl *D) {
15643 // All visible declarations are reachable.
15644 return D->isUnconditionallyVisible() ||
15645 isAcceptableSlow(D, Kind: AcceptableKind::Reachable);
15646 }
15647
15648 /// Determine whether a declaration is acceptable (visible/reachable).
15649 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
15650 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15651 }
15652
15653 /// Determine if \p D and \p Suggested have a structurally compatible
15654 /// layout as described in C11 6.2.7/1.
15655 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15656
15657 /// Determine if \p D has a visible definition. If not, suggest a declaration
15658 /// that should be made visible to expose the definition.
15659 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15660 bool OnlyNeedComplete = false);
15661 bool hasVisibleDefinition(const NamedDecl *D) {
15662 NamedDecl *Hidden;
15663 return hasVisibleDefinition(D: const_cast<NamedDecl *>(D), Suggested: &Hidden);
15664 }
15665 /// Determine if \p D has a definition which allows we redefine it in current
15666 /// TU. \p Suggested is the definition that should be made visible to expose
15667 /// the definition.
15668 bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
15669 bool &Visible);
15670 bool isRedefinitionAllowedFor(const NamedDecl *D, bool &Visible) {
15671 NamedDecl *Hidden;
15672 return isRedefinitionAllowedFor(D: const_cast<NamedDecl *>(D), Suggested: &Hidden,
15673 Visible);
15674 }
15675
15676 /// Determine if \p D has a reachable definition. If not, suggest a
15677 /// declaration that should be made reachable to expose the definition.
15678 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15679 bool OnlyNeedComplete = false);
15680 bool hasReachableDefinition(NamedDecl *D) {
15681 NamedDecl *Hidden;
15682 return hasReachableDefinition(D, Suggested: &Hidden);
15683 }
15684
15685 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15686 AcceptableKind Kind,
15687 bool OnlyNeedComplete = false);
15688 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
15689 NamedDecl *Hidden;
15690 return hasAcceptableDefinition(D, Suggested: &Hidden, Kind);
15691 }
15692
15693 /// Try to parse the conditional expression attached to an effect attribute
15694 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15695 /// optional on error.
15696 std::optional<FunctionEffectMode>
15697 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15698
15699 void ActOnCleanupAttr(Decl *D, const Attr *A);
15700 void ActOnInitPriorityAttr(Decl *D, const Attr *A);
15701
15702private:
15703 /// The implementation of RequireCompleteType
15704 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15705 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15706
15707 /// Nullability type specifiers.
15708 IdentifierInfo *Ident__Nonnull = nullptr;
15709 IdentifierInfo *Ident__Nullable = nullptr;
15710 IdentifierInfo *Ident__Nullable_result = nullptr;
15711 IdentifierInfo *Ident__Null_unspecified = nullptr;
15712
15713 ///@}
15714
15715 //
15716 //
15717 // -------------------------------------------------------------------------
15718 //
15719 //
15720
15721 /// \name FixIt Helpers
15722 /// Implementations are in SemaFixItUtils.cpp
15723 ///@{
15724
15725public:
15726 /// Get a string to suggest for zero-initialization of a type.
15727 std::string getFixItZeroInitializerForType(QualType T,
15728 SourceLocation Loc) const;
15729 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15730
15731 ///@}
15732
15733 //
15734 //
15735 // -------------------------------------------------------------------------
15736 //
15737 //
15738
15739 /// \name Function Effects
15740 /// Implementations are in SemaFunctionEffects.cpp
15741 ///@{
15742public:
15743 struct FunctionEffectDiff {
15744 enum class Kind { Added, Removed, ConditionMismatch };
15745
15746 FunctionEffect::Kind EffectKind;
15747 Kind DiffKind;
15748 std::optional<FunctionEffectWithCondition>
15749 Old; // Invalid when 'Kind' is 'Added'.
15750 std::optional<FunctionEffectWithCondition>
15751 New; // Invalid when 'Kind' is 'Removed'.
15752
15753 StringRef effectName() const {
15754 if (Old)
15755 return Old.value().Effect.name();
15756 return New.value().Effect.name();
15757 }
15758
15759 /// Describes the result of effects differing between a base class's virtual
15760 /// method and an overriding method in a subclass.
15761 enum class OverrideResult {
15762 NoAction,
15763 Warn,
15764 Merge // Merge missing effect from base to derived.
15765 };
15766
15767 /// Return true if adding or removing the effect as part of a type
15768 /// conversion should generate a diagnostic.
15769 bool shouldDiagnoseConversion(QualType SrcType,
15770 const FunctionEffectsRef &SrcFX,
15771 QualType DstType,
15772 const FunctionEffectsRef &DstFX) const;
15773
15774 /// Return true if adding or removing the effect in a redeclaration should
15775 /// generate a diagnostic.
15776 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
15777 const FunctionEffectsRef &OldFX,
15778 const FunctionDecl &NewFunction,
15779 const FunctionEffectsRef &NewFX) const;
15780
15781 /// Return true if adding or removing the effect in a C++ virtual method
15782 /// override should generate a diagnostic.
15783 OverrideResult shouldDiagnoseMethodOverride(
15784 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
15785 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
15786 };
15787
15788 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
15789 /// Caller should short-circuit by checking for equality first.
15790 FunctionEffectDiffVector(const FunctionEffectsRef &Old,
15791 const FunctionEffectsRef &New);
15792 };
15793
15794 /// All functions/lambdas/blocks which have bodies and which have a non-empty
15795 /// FunctionEffectsRef to be verified.
15796 SmallVector<const Decl *> DeclsWithEffectsToVerify;
15797
15798 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
15799 /// are all null.
15800 FunctionEffectKindSet AllEffectsToVerify;
15801
15802public:
15803 /// Warn and return true if adding a function effect to a set would create a
15804 /// conflict.
15805 bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX,
15806 const FunctionEffectWithCondition &EC,
15807 SourceLocation NewAttrLoc);
15808
15809 // Report a failure to merge function effects between declarations due to a
15810 // conflict.
15811 void
15812 diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs,
15813 SourceLocation NewLoc,
15814 SourceLocation OldLoc);
15815
15816 /// Inline checks from the start of maybeAddDeclWithEffects, to
15817 /// minimize performance impact on code not using effects.
15818 template <class FuncOrBlockDecl>
15819 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
15820 if (Context.hasAnyFunctionEffects())
15821 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
15822 maybeAddDeclWithEffects(D, FX);
15823 }
15824
15825 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
15826 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15827
15828 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
15829 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15830
15831 void performFunctionEffectAnalysis(TranslationUnitDecl *TU);
15832
15833 ///@}
15834
15835 //
15836 //
15837 // -------------------------------------------------------------------------
15838 //
15839 //
15840
15841 /// \name Expansion Statements
15842 /// Implementations are in SemaExpand.cpp
15843 ///@{
15844public:
15845 CXXExpansionStmtDecl *ActOnCXXExpansionStmtDecl(unsigned TemplateDepth,
15846 SourceLocation TemplateKWLoc);
15847
15848 CXXExpansionStmtDecl *
15849 BuildCXXExpansionStmtDecl(DeclContext *Ctx, SourceLocation TemplateKWLoc,
15850 NonTypeTemplateParmDecl *NTTP);
15851
15852 ExprResult ActOnCXXExpansionInitList(MultiExprArg SubExprs,
15853 SourceLocation LBraceLoc,
15854 SourceLocation RBraceLoc);
15855
15856 StmtResult ActOnCXXExpansionStmtPattern(
15857 CXXExpansionStmtDecl *ESD, Stmt *Init, Stmt *ExpansionVarStmt,
15858 Expr *ExpansionInitializer, SourceLocation LParenLoc,
15859 SourceLocation ColonLoc, SourceLocation RParenLoc,
15860 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps);
15861
15862 StmtResult FinishCXXExpansionStmt(Stmt *Expansion, Stmt *Body);
15863
15864 StmtResult BuildCXXEnumeratingExpansionStmtPattern(Decl *ESD, Stmt *Init,
15865 Stmt *ExpansionVar,
15866 SourceLocation LParenLoc,
15867 SourceLocation ColonLoc,
15868 SourceLocation RParenLoc);
15869
15870 StmtResult BuildNonEnumeratingCXXExpansionStmtPattern(
15871 CXXExpansionStmtDecl *ESD, Stmt *Init, DeclStmt *ExpansionVarStmt,
15872 Expr *ExpansionInitializer, SourceLocation LParenLoc,
15873 SourceLocation ColonLoc, SourceLocation RParenLoc,
15874 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
15875
15876 ExprResult BuildCXXExpansionSelectExpr(InitListExpr *Range, Expr *Idx);
15877
15878 std::optional<uint64_t>
15879 ComputeExpansionSize(CXXExpansionStmtPattern *Expansion);
15880 ///@}
15881};
15882
15883DeductionFailureInfo
15884MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK,
15885 sema::TemplateDeductionInfo &Info);
15886
15887/// Contains a late templated function.
15888/// Will be parsed at the end of the translation unit, used by Sema & Parser.
15889struct LateParsedTemplate {
15890 CachedTokens Toks;
15891 /// The template function declaration to be late parsed.
15892 Decl *D;
15893 /// Floating-point options in the point of definition.
15894 FPOptions FPO;
15895};
15896
15897template <>
15898void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
15899 PragmaMsStackAction Action,
15900 llvm::StringRef StackSlotLabel,
15901 AlignPackInfo Value);
15902
15903} // end namespace clang
15904
15905#endif
15906