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 /// Returns true if any of the documentation warnings is enabled at \p Loc.
1130 bool areDocumentationDiagsEnabled(SourceLocation Loc);
1131
1132 /// Discard the areDocumentationDiagsEnabled() cache, for when a
1133 /// `#pragma clang diagnostic` has changed diagnostic severities.
1134 void clearDocumentationDiagsCache();
1135
1136private:
1137 /// The uncached answer for both documentation groups at \p Loc.
1138 bool computeDocumentationDiagsAt(SourceLocation Loc) const;
1139
1140 /// Caches results for areDocumentationDiagsEnabled().
1141 /// Flushed whenever a diagnostic pragma changes severities.
1142 /// Level one is keyed on the diagnostic state alone.
1143 const void *DocDiagsStateKey = nullptr;
1144 bool DocDiagsEnabledIgnoringSystem = false;
1145
1146 /// Level two, for when the location does matter. Bit i of each mask is a
1147 /// DiagStateSystemClass value; bit 0 is unused.
1148 uint8_t DocDiagsExactComputed = 0;
1149 uint8_t DocDiagsExactEnabled = 0;
1150
1151public:
1152 /// Returns true if a comment at \p Loc should be retained in the AST
1153 /// (some consumer such as -Wdocumentation, -fparse-all-comments, code
1154 /// completion, or AST-file serialization may read it back).
1155 bool shouldRetainCommentsInAST(SourceLocation Loc);
1156
1157 /// Retrieve the parser's current scope.
1158 ///
1159 /// This routine must only be used when it is certain that semantic analysis
1160 /// and the parser are in precisely the same context, which is not the case
1161 /// when, e.g., we are performing any kind of template instantiation.
1162 /// Therefore, the only safe places to use this scope are in the parser
1163 /// itself and in routines directly invoked from the parser and *never* from
1164 /// template substitution or instantiation.
1165 Scope *getCurScope() const { return CurScope; }
1166
1167 IdentifierInfo *getSuperIdentifier() const;
1168
1169 DeclContext *getCurLexicalContext() const {
1170 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
1171 }
1172
1173 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1174 const FunctionDecl *FD = nullptr);
1175 SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
1176 const PartialDiagnostic &PD,
1177 const FunctionDecl *FD = nullptr) {
1178 return targetDiag(Loc, DiagID: PD.getDiagID(), FD) << PD;
1179 }
1180
1181 /// Check if the type is allowed to be used for the current target.
1182 void checkTypeSupport(QualType Ty, SourceLocation Loc,
1183 ValueDecl *D = nullptr);
1184
1185 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1186 /// cast. If there is already an implicit cast, merge into the existing one.
1187 /// If isLvalue, the result of the cast is an lvalue.
1188 ExprResult ImpCastExprToType(
1189 Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue,
1190 const CXXCastPath *BasePath = nullptr,
1191 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
1192
1193 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1194 /// to the conversion from scalar type ScalarTy to the Boolean type.
1195 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
1196
1197 /// If \p AllowLambda is true, treat lambda as function.
1198 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1199
1200 /// Returns a pointer to the innermost enclosing function, or nullptr if the
1201 /// current context is not inside a function. If \p AllowLambda is true,
1202 /// this can return the call operator of an enclosing lambda, otherwise
1203 /// lambdas are skipped when looking for an enclosing function.
1204 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1205
1206 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1207 /// the method decl for the method being parsed. If we're currently
1208 /// in a 'block', this returns the containing context.
1209 ObjCMethodDecl *getCurMethodDecl();
1210
1211 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1212 /// or C function we're in, otherwise return null. If we're currently
1213 /// in a 'block', this returns the containing context.
1214 NamedDecl *getCurFunctionOrMethodDecl() const;
1215
1216 /// Warn if we're implicitly casting from a _Nullable pointer type to a
1217 /// _Nonnull one.
1218 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
1219 SourceLocation Loc);
1220
1221 /// Warn when implicitly casting 0 to nullptr.
1222 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1223
1224 /// Warn when implicitly changing function effects.
1225 void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType,
1226 SourceLocation Loc);
1227
1228 /// makeUnavailableInSystemHeader - There is an error in the current
1229 /// context. If we're still in a system header, and we can plausibly
1230 /// make the relevant declaration unavailable instead of erroring, do
1231 /// so and return true.
1232 bool makeUnavailableInSystemHeader(SourceLocation loc,
1233 UnavailableAttr::ImplicitReason reason);
1234
1235 /// Retrieve a suitable printing policy for diagnostics.
1236 PrintingPolicy getPrintingPolicy() const {
1237 return getPrintingPolicy(Ctx: Context, PP);
1238 }
1239
1240 /// Retrieve a suitable printing policy for diagnostics.
1241 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1242 const Preprocessor &PP);
1243
1244 /// Scope actions.
1245 void ActOnTranslationUnitScope(Scope *S);
1246
1247 /// Determine whether \param D is function like (function or function
1248 /// template) for parsing.
1249 bool isDeclaratorFunctionLike(Declarator &D);
1250
1251 /// The maximum alignment, same as in llvm::Value. We duplicate them here
1252 /// because that allows us not to duplicate the constants in clang code,
1253 /// which we must to since we can't directly use the llvm constants.
1254 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1255 ///
1256 /// This is the greatest alignment value supported by load, store, and alloca
1257 /// instructions, and global values.
1258 static const unsigned MaxAlignmentExponent = 32;
1259 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1260
1261 /// Flag indicating whether or not to collect detailed statistics.
1262 bool CollectStats;
1263
1264 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1265
1266 /// Stack containing information about each of the nested
1267 /// function, block, and method scopes that are currently active.
1268 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
1269
1270 /// The index of the first FunctionScope that corresponds to the current
1271 /// context.
1272 unsigned FunctionScopesStart = 0;
1273
1274 /// Track the number of currently active capturing scopes.
1275 unsigned CapturingFunctionScopes = 0;
1276
1277 llvm::BumpPtrAllocator BumpAlloc;
1278
1279 /// The kind of translation unit we are processing.
1280 ///
1281 /// When we're processing a complete translation unit, Sema will perform
1282 /// end-of-translation-unit semantic tasks (such as creating
1283 /// initializers for tentative definitions in C) once parsing has
1284 /// completed. Modules and precompiled headers perform different kinds of
1285 /// checks.
1286 const TranslationUnitKind TUKind;
1287
1288 /// Translation Unit Scope - useful to Objective-C actions that need
1289 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1290 /// For example, user-defined classes, built-in "id" type, etc.
1291 Scope *TUScope;
1292
1293 void incrementMSManglingNumber() const {
1294 return CurScope->incrementMSManglingNumber();
1295 }
1296
1297 /// Try to recover by turning the given expression into a
1298 /// call. Returns true if recovery was attempted or an error was
1299 /// emitted; this may also leave the ExprResult invalid.
1300 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1301 bool ForceComplain = false,
1302 bool (*IsPlausibleResult)(QualType) = nullptr);
1303
1304 // Adds implicit lifetime bound attribute for implicit this to its
1305 // TypeSourceInfo.
1306 void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD);
1307
1308 /// Figure out if an expression could be turned into a call.
1309 ///
1310 /// Use this when trying to recover from an error where the programmer may
1311 /// have written just the name of a function instead of actually calling it.
1312 ///
1313 /// \param E - The expression to examine.
1314 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1315 /// with no arguments, this parameter is set to the type returned by such a
1316 /// call; otherwise, it is set to an empty QualType.
1317 /// \param OverloadSet - If the expression is an overloaded function
1318 /// name, this parameter is populated with the decls of the various
1319 /// overloads.
1320 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1321 UnresolvedSetImpl &NonTemplateOverloads);
1322
1323 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
1324 typedef OpaquePtr<TemplateName> TemplateTy;
1325 typedef OpaquePtr<QualType> TypeTy;
1326
1327 OpenCLOptions OpenCLFeatures;
1328 FPOptions CurFPFeatures;
1329
1330 const LangOptions &LangOpts;
1331 Preprocessor &PP;
1332 ASTContext &Context;
1333 ASTConsumer &Consumer;
1334 DiagnosticsEngine &Diags;
1335 SourceManager &SourceMgr;
1336 api_notes::APINotesManager APINotes;
1337
1338 std::unique_ptr<APINotesSelectorDiagnosticState> APINotesSelectorDiagnostics;
1339
1340 /// A RAII object to enter scope of a compound statement.
1341 class CompoundScopeRAII {
1342 public:
1343 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1344 S.ActOnStartOfCompoundStmt(IsStmtExpr);
1345 }
1346
1347 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1348 CompoundScopeRAII(const CompoundScopeRAII &) = delete;
1349 CompoundScopeRAII &operator=(const CompoundScopeRAII &) = delete;
1350
1351 private:
1352 Sema &S;
1353 };
1354
1355 /// An RAII helper that pops function a function scope on exit.
1356 struct FunctionScopeRAII {
1357 Sema &S;
1358 bool Active;
1359 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
1360 ~FunctionScopeRAII() {
1361 if (Active)
1362 S.PopFunctionScopeInfo();
1363 }
1364 void disable() { Active = false; }
1365 };
1366
1367 sema::FunctionScopeInfo *getCurFunction() const {
1368 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1369 }
1370
1371 /// Worker object for performing CFG-based warnings.
1372 sema::AnalysisBasedWarnings AnalysisWarnings;
1373 threadSafety::BeforeSet *ThreadSafetyDeclCache;
1374
1375 /// Callback to the parser to parse templated functions when needed.
1376 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1377 LateTemplateParserCB *LateTemplateParser;
1378 void *OpaqueParser;
1379
1380 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
1381 LateTemplateParser = LTP;
1382 OpaqueParser = P;
1383 }
1384
1385 /// Callback to the parser to parse a type expressed as a string.
1386 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1387 ParseTypeFromStringCallback;
1388
1389 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1390 /// This is used as part of a hack to omit that class from ADL results.
1391 DeclarationName VAListTagName;
1392
1393 /// Is the last error level diagnostic immediate. This is used to determined
1394 /// whether the next info diagnostic should be immediate.
1395 bool IsLastErrorImmediate = true;
1396
1397 /// Track if we're currently analyzing overflow behavior types in assignment
1398 /// context.
1399 bool InOverflowBehaviorAssignmentContext = false;
1400
1401 class DelayedDiagnostics;
1402
1403 class DelayedDiagnosticsState {
1404 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1405 friend class Sema::DelayedDiagnostics;
1406 };
1407 typedef DelayedDiagnosticsState ParsingDeclState;
1408 typedef DelayedDiagnosticsState ProcessingContextState;
1409
1410 /// A class which encapsulates the logic for delaying diagnostics
1411 /// during parsing and other processing.
1412 class DelayedDiagnostics {
1413 /// The current pool of diagnostics into which delayed
1414 /// diagnostics should go.
1415 sema::DelayedDiagnosticPool *CurPool = nullptr;
1416
1417 public:
1418 DelayedDiagnostics() = default;
1419
1420 /// Adds a delayed diagnostic.
1421 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1422
1423 /// Determines whether diagnostics should be delayed.
1424 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1425
1426 /// Returns the current delayed-diagnostics pool.
1427 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1428
1429 /// Enter a new scope. Access and deprecation diagnostics will be
1430 /// collected in this pool.
1431 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
1432 DelayedDiagnosticsState state;
1433 state.SavedPool = CurPool;
1434 CurPool = &pool;
1435 return state;
1436 }
1437
1438 /// Leave a delayed-diagnostic state that was previously pushed.
1439 /// Do not emit any of the diagnostics. This is performed as part
1440 /// of the bookkeeping of popping a pool "properly".
1441 void popWithoutEmitting(DelayedDiagnosticsState state) {
1442 CurPool = state.SavedPool;
1443 }
1444
1445 /// Enter a new scope where access and deprecation diagnostics are
1446 /// not delayed.
1447 DelayedDiagnosticsState pushUndelayed() {
1448 DelayedDiagnosticsState state;
1449 state.SavedPool = CurPool;
1450 CurPool = nullptr;
1451 return state;
1452 }
1453
1454 /// Undo a previous pushUndelayed().
1455 void popUndelayed(DelayedDiagnosticsState state) {
1456 assert(CurPool == nullptr);
1457 CurPool = state.SavedPool;
1458 }
1459 } DelayedDiagnostics;
1460
1461 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
1462 return DelayedDiagnostics.push(pool);
1463 }
1464
1465 /// Diagnostics that are emitted only if we discover that the given function
1466 /// must be codegen'ed. Because handling these correctly adds overhead to
1467 /// compilation, this is currently only used for offload languages like CUDA,
1468 /// OpenMP, and SYCL.
1469 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1470
1471 /// CurContext - This is the current declaration context of parsing.
1472 DeclContext *CurContext;
1473
1474 SemaAMDGPU &AMDGPU() {
1475 assert(AMDGPUPtr);
1476 return *AMDGPUPtr;
1477 }
1478
1479 SemaARM &ARM() {
1480 assert(ARMPtr);
1481 return *ARMPtr;
1482 }
1483
1484 SemaAVR &AVR() {
1485 assert(AVRPtr);
1486 return *AVRPtr;
1487 }
1488
1489 SemaBPF &BPF() {
1490 assert(BPFPtr);
1491 return *BPFPtr;
1492 }
1493
1494 SemaCodeCompletion &CodeCompletion() {
1495 assert(CodeCompletionPtr);
1496 return *CodeCompletionPtr;
1497 }
1498
1499 SemaCUDA &CUDA() {
1500 assert(CUDAPtr);
1501 return *CUDAPtr;
1502 }
1503
1504 SemaDirectX &DirectX() {
1505 assert(DirectXPtr);
1506 return *DirectXPtr;
1507 }
1508
1509 SemaHLSL &HLSL() {
1510 assert(HLSLPtr);
1511 return *HLSLPtr;
1512 }
1513
1514 SemaHexagon &Hexagon() {
1515 assert(HexagonPtr);
1516 return *HexagonPtr;
1517 }
1518
1519 SemaLoongArch &LoongArch() {
1520 assert(LoongArchPtr);
1521 return *LoongArchPtr;
1522 }
1523
1524 SemaM68k &M68k() {
1525 assert(M68kPtr);
1526 return *M68kPtr;
1527 }
1528
1529 SemaMIPS &MIPS() {
1530 assert(MIPSPtr);
1531 return *MIPSPtr;
1532 }
1533
1534 SemaMSP430 &MSP430() {
1535 assert(MSP430Ptr);
1536 return *MSP430Ptr;
1537 }
1538
1539 SemaNVPTX &NVPTX() {
1540 assert(NVPTXPtr);
1541 return *NVPTXPtr;
1542 }
1543
1544 SemaObjC &ObjC() {
1545 assert(ObjCPtr);
1546 return *ObjCPtr;
1547 }
1548
1549 SemaOpenACC &OpenACC() {
1550 assert(OpenACCPtr);
1551 return *OpenACCPtr;
1552 }
1553
1554 SemaOpenCL &OpenCL() {
1555 assert(OpenCLPtr);
1556 return *OpenCLPtr;
1557 }
1558
1559 SemaOpenMP &OpenMP() {
1560 assert(OpenMPPtr && "SemaOpenMP is dead");
1561 return *OpenMPPtr;
1562 }
1563
1564 SemaPPC &PPC() {
1565 assert(PPCPtr);
1566 return *PPCPtr;
1567 }
1568
1569 SemaPseudoObject &PseudoObject() {
1570 assert(PseudoObjectPtr);
1571 return *PseudoObjectPtr;
1572 }
1573
1574 SemaRISCV &RISCV() {
1575 assert(RISCVPtr);
1576 return *RISCVPtr;
1577 }
1578
1579 SemaSPIRV &SPIRV() {
1580 assert(SPIRVPtr);
1581 return *SPIRVPtr;
1582 }
1583
1584 SemaSYCL &SYCL() {
1585 assert(SYCLPtr);
1586 return *SYCLPtr;
1587 }
1588
1589 SemaSwift &Swift() {
1590 assert(SwiftPtr);
1591 return *SwiftPtr;
1592 }
1593
1594 SemaSystemZ &SystemZ() {
1595 assert(SystemZPtr);
1596 return *SystemZPtr;
1597 }
1598
1599 SemaWasm &Wasm() {
1600 assert(WasmPtr);
1601 return *WasmPtr;
1602 }
1603
1604 SemaX86 &X86() {
1605 assert(X86Ptr);
1606 return *X86Ptr;
1607 }
1608
1609 /// Source of additional semantic information.
1610 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
1611
1612protected:
1613 friend class Parser;
1614 friend class InitializationSequence;
1615 friend class ASTReader;
1616 friend class ASTDeclReader;
1617 friend class ASTWriter;
1618
1619private:
1620 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1621 bool WarnedDarwinSDKInfoMissing = false;
1622
1623 StackExhaustionHandler StackHandler;
1624
1625 Sema(const Sema &) = delete;
1626 void operator=(const Sema &) = delete;
1627
1628 /// The handler for the FileChanged preprocessor events.
1629 ///
1630 /// Used for diagnostics that implement custom semantic analysis for #include
1631 /// directives, like -Wpragma-pack.
1632 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1633
1634 /// The parser's current scope.
1635 ///
1636 /// The parser maintains this state here.
1637 Scope *CurScope;
1638
1639 mutable IdentifierInfo *Ident_super;
1640
1641 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1642 std::unique_ptr<SemaARM> ARMPtr;
1643 std::unique_ptr<SemaAVR> AVRPtr;
1644 std::unique_ptr<SemaBPF> BPFPtr;
1645 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1646 std::unique_ptr<SemaCUDA> CUDAPtr;
1647 std::unique_ptr<SemaDirectX> DirectXPtr;
1648 std::unique_ptr<SemaHLSL> HLSLPtr;
1649 std::unique_ptr<SemaHexagon> HexagonPtr;
1650 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1651 std::unique_ptr<SemaM68k> M68kPtr;
1652 std::unique_ptr<SemaMIPS> MIPSPtr;
1653 std::unique_ptr<SemaMSP430> MSP430Ptr;
1654 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1655 std::unique_ptr<SemaObjC> ObjCPtr;
1656 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1657 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1658 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1659 std::unique_ptr<SemaPPC> PPCPtr;
1660 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1661 std::unique_ptr<SemaRISCV> RISCVPtr;
1662 std::unique_ptr<SemaSPIRV> SPIRVPtr;
1663 std::unique_ptr<SemaSYCL> SYCLPtr;
1664 std::unique_ptr<SemaSwift> SwiftPtr;
1665 std::unique_ptr<SemaSystemZ> SystemZPtr;
1666 std::unique_ptr<SemaWasm> WasmPtr;
1667 std::unique_ptr<SemaX86> X86Ptr;
1668
1669 ///@}
1670
1671 //
1672 //
1673 // -------------------------------------------------------------------------
1674 //
1675 //
1676
1677 /// \name API Notes
1678 /// Implementations are in SemaAPINotes.cpp
1679 ///@{
1680
1681public:
1682 /// Map any API notes provided for this declaration to attributes on the
1683 /// declaration.
1684 ///
1685 /// Triggered by declaration-attribute processing.
1686 void ProcessAPINotes(Decl *D);
1687 /// Apply the 'Nullability:' annotation to the specified declaration
1688 void ApplyNullability(Decl *D, NullabilityKind Nullability);
1689 /// Apply the 'Type:' annotation to the specified declaration
1690 void ApplyAPINotesType(Decl *D, StringRef TypeString);
1691
1692 /// Diagnose exact API notes selectors that were not matched by any
1693 /// declaration processed in this translation unit.
1694 void DiagnoseUnusedAPINotesSelectors();
1695
1696 /// Whether APINotes should be gathered for all applicable Swift language
1697 /// versions, without being applied. Leaving clients of the current module
1698 /// to select and apply the correct version.
1699 bool captureSwiftVersionIndependentAPINotes() {
1700 return APINotes.captureVersionIndependentSwift();
1701 }
1702 ///@}
1703
1704 //
1705 //
1706 // -------------------------------------------------------------------------
1707 //
1708 //
1709
1710 /// \name C++ Access Control
1711 /// Implementations are in SemaAccess.cpp
1712 ///@{
1713
1714public:
1715 enum AccessResult {
1716 AR_accessible,
1717 AR_inaccessible,
1718 AR_dependent,
1719 AR_delayed
1720 };
1721
1722 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1723 /// Returns true on error (when the previous member decl access specifier
1724 /// is different from the new member decl access specifier).
1725 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1726 NamedDecl *PrevMemberDecl,
1727 AccessSpecifier LexicalAS);
1728
1729 /// Perform access-control checking on a previously-unresolved member
1730 /// access which has now been resolved to a member.
1731 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
1732 DeclAccessPair FoundDecl);
1733 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
1734 DeclAccessPair FoundDecl);
1735
1736 /// Checks access to an overloaded operator new or delete.
1737 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
1738 SourceRange PlacementRange,
1739 CXXRecordDecl *NamingClass,
1740 DeclAccessPair FoundDecl,
1741 bool Diagnose = true);
1742
1743 /// Checks access to a constructor.
1744 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1745 DeclAccessPair FoundDecl,
1746 const InitializedEntity &Entity,
1747 bool IsCopyBindingRefToTemp = false);
1748
1749 /// Checks access to a constructor.
1750 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1751 DeclAccessPair FoundDecl,
1752 const InitializedEntity &Entity,
1753 const PartialDiagnostic &PDiag);
1754 AccessResult CheckDestructorAccess(SourceLocation Loc,
1755 CXXDestructorDecl *Dtor,
1756 const PartialDiagnostic &PDiag,
1757 QualType objectType = QualType());
1758
1759 /// Checks access to the target of a friend declaration.
1760 AccessResult CheckFriendAccess(NamedDecl *D);
1761
1762 /// Checks access to a member.
1763 AccessResult CheckMemberAccess(SourceLocation UseLoc,
1764 CXXRecordDecl *NamingClass,
1765 DeclAccessPair Found);
1766
1767 /// Checks implicit access to a member in a structured binding.
1768 AccessResult
1769 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
1770 CXXRecordDecl *DecomposedClass,
1771 DeclAccessPair Field);
1772 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1773 const SourceRange &,
1774 DeclAccessPair FoundDecl);
1775
1776 /// Checks access to an overloaded member operator, including
1777 /// conversion operators.
1778 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1779 Expr *ArgExpr,
1780 DeclAccessPair FoundDecl);
1781 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1782 ArrayRef<Expr *> ArgExprs,
1783 DeclAccessPair FoundDecl);
1784 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
1785 DeclAccessPair FoundDecl);
1786
1787 /// Checks access for a hierarchy conversion.
1788 ///
1789 /// \param ForceCheck true if this check should be performed even if access
1790 /// control is disabled; some things rely on this for semantics
1791 /// \param ForceUnprivileged true if this check should proceed as if the
1792 /// context had no special privileges
1793 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base,
1794 QualType Derived, const CXXBasePath &Path,
1795 unsigned DiagID, bool ForceCheck = false,
1796 bool ForceUnprivileged = false);
1797
1798 AccessResult CheckBaseClassAccess(
1799 SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1800 const CXXBasePath &Path, unsigned DiagID,
1801 llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1802 bool ForceCheck = false, bool ForceUnprivileged = false);
1803
1804 /// Checks access to all the declarations in the given result set.
1805 void CheckLookupAccess(const LookupResult &R);
1806
1807 /// Checks access to Target from the given class. The check will take access
1808 /// specifiers into account, but no member access expressions and such.
1809 ///
1810 /// \param Target the declaration to check if it can be accessed
1811 /// \param NamingClass the class in which the lookup was started.
1812 /// \param BaseType type of the left side of member access expression.
1813 /// \p BaseType and \p NamingClass are used for C++ access control.
1814 /// Depending on the lookup case, they should be set to the following:
1815 /// - lhs.target (member access without a qualifier):
1816 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1817 /// - lhs.X::target (member access with a qualifier):
1818 /// BaseType is the type of 'lhs', NamingClass is 'X'
1819 /// - X::target (qualified lookup without member access):
1820 /// BaseType is null, NamingClass is 'X'.
1821 /// - target (unqualified lookup).
1822 /// BaseType is null, NamingClass is the parent class of 'target'.
1823 /// \return true if the Target is accessible from the Class, false otherwise.
1824 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1825 QualType BaseType);
1826
1827 /// Is the given member accessible for the purposes of deciding whether to
1828 /// define a special member function as deleted?
1829 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1830 DeclAccessPair Found, QualType ObjectType,
1831 SourceLocation Loc,
1832 const PartialDiagnostic &Diag);
1833 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1834 DeclAccessPair Found,
1835 QualType ObjectType) {
1836 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1837 Loc: SourceLocation(), Diag: PDiag());
1838 }
1839
1840 void HandleDependentAccessCheck(
1841 const DependentDiagnostic &DD,
1842 const MultiLevelTemplateArgumentList &TemplateArgs);
1843 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
1844
1845 ///@}
1846
1847 //
1848 //
1849 // -------------------------------------------------------------------------
1850 //
1851 //
1852
1853 /// \name Attributes
1854 /// Implementations are in SemaAttr.cpp
1855 ///@{
1856
1857public:
1858 /// Controls member pointer representation format under the MS ABI.
1859 LangOptions::PragmaMSPointersToMembersKind
1860 MSPointerToMemberRepresentationMethod;
1861
1862 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1863
1864 /// Source location for newly created implicit MSInheritanceAttrs
1865 SourceLocation ImplicitMSInheritanceAttrLoc;
1866
1867 struct PragmaClangSection {
1868 std::string SectionName;
1869 bool Valid = false;
1870 SourceLocation PragmaLocation;
1871 };
1872
1873 PragmaClangSection PragmaClangBSSSection;
1874 PragmaClangSection PragmaClangDataSection;
1875 PragmaClangSection PragmaClangRodataSection;
1876 PragmaClangSection PragmaClangRelroSection;
1877 PragmaClangSection PragmaClangTextSection;
1878
1879 enum PragmaMsStackAction {
1880 PSK_Reset = 0x0, // #pragma ()
1881 PSK_Set = 0x1, // #pragma (value)
1882 PSK_Push = 0x2, // #pragma (push[, id])
1883 PSK_Pop = 0x4, // #pragma (pop[, id])
1884 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1885 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1886 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1887 };
1888
1889 struct PragmaPackInfo {
1890 PragmaMsStackAction Action;
1891 StringRef SlotLabel;
1892 Token Alignment;
1893 };
1894
1895 // #pragma pack and align.
1896 class AlignPackInfo {
1897 public:
1898 // `Native` represents default align mode, which may vary based on the
1899 // platform.
1900 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1901
1902 // #pragma pack info constructor
1903 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1904 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1905 assert(Num == PackNumber && "The pack number has been truncated.");
1906 }
1907
1908 // #pragma align info constructor
1909 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
1910 : PackAttr(false), AlignMode(M),
1911 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1912
1913 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1914
1915 AlignPackInfo() : AlignPackInfo(Native, false) {}
1916
1917 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1918 // integer encoding for it. This should only be passed to
1919 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1920 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
1921 std::uint32_t Encoding{};
1922 if (Info.IsXLStack())
1923 Encoding |= IsXLMask;
1924
1925 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1926
1927 if (Info.IsPackAttr())
1928 Encoding |= PackAttrMask;
1929
1930 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1931
1932 return Encoding;
1933 }
1934
1935 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1936 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1937 AlignPackInfo::Mode M =
1938 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1939 int PackNumber = (Encoding & PackNumMask) >> 4;
1940
1941 if (Encoding & PackAttrMask)
1942 return AlignPackInfo(M, PackNumber, IsXL);
1943
1944 return AlignPackInfo(M, IsXL);
1945 }
1946
1947 bool IsPackAttr() const { return PackAttr; }
1948
1949 bool IsAlignAttr() const { return !PackAttr; }
1950
1951 Mode getAlignMode() const { return AlignMode; }
1952
1953 unsigned getPackNumber() const { return PackNumber; }
1954
1955 bool IsPackSet() const {
1956 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1957 // attriute on a decl.
1958 return PackNumber != UninitPackVal && PackNumber != 0;
1959 }
1960
1961 bool IsXLStack() const { return XLStack; }
1962
1963 bool operator==(const AlignPackInfo &Info) const {
1964 return std::tie(args: AlignMode, args: PackNumber, args: PackAttr, args: XLStack) ==
1965 std::tie(args: Info.AlignMode, args: Info.PackNumber, args: Info.PackAttr,
1966 args: Info.XLStack);
1967 }
1968
1969 bool operator!=(const AlignPackInfo &Info) const {
1970 return !(*this == Info);
1971 }
1972
1973 private:
1974 /// \brief True if this is a pragma pack attribute,
1975 /// not a pragma align attribute.
1976 bool PackAttr;
1977
1978 /// \brief The alignment mode that is in effect.
1979 Mode AlignMode;
1980
1981 /// \brief The pack number of the stack.
1982 unsigned char PackNumber;
1983
1984 /// \brief True if it is a XL #pragma align/pack stack.
1985 bool XLStack;
1986
1987 /// \brief Uninitialized pack value.
1988 static constexpr unsigned char UninitPackVal = -1;
1989
1990 // Masks to encode and decode an AlignPackInfo.
1991 static constexpr uint32_t IsXLMask{0x0000'0001};
1992 static constexpr uint32_t AlignModeMask{0x0000'0006};
1993 static constexpr uint32_t PackAttrMask{0x00000'0008};
1994 static constexpr uint32_t PackNumMask{0x0000'01F0};
1995 };
1996
1997 template <typename ValueType> struct PragmaStack {
1998 struct Slot {
1999 llvm::StringRef StackSlotLabel;
2000 ValueType Value;
2001 SourceLocation PragmaLocation;
2002 SourceLocation PragmaPushLocation;
2003 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
2004 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
2005 : StackSlotLabel(StackSlotLabel), Value(Value),
2006 PragmaLocation(PragmaLocation),
2007 PragmaPushLocation(PragmaPushLocation) {}
2008 };
2009
2010 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
2011 llvm::StringRef StackSlotLabel, ValueType Value) {
2012 if (Action == PSK_Reset) {
2013 CurrentValue = DefaultValue;
2014 CurrentPragmaLocation = PragmaLocation;
2015 return;
2016 }
2017 if (Action & PSK_Push)
2018 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
2019 PragmaLocation);
2020 else if (Action & PSK_Pop) {
2021 if (!StackSlotLabel.empty()) {
2022 // If we've got a label, try to find it and jump there.
2023 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
2024 return x.StackSlotLabel == StackSlotLabel;
2025 });
2026 // If we found the label so pop from there.
2027 if (I != Stack.rend()) {
2028 CurrentValue = I->Value;
2029 CurrentPragmaLocation = I->PragmaLocation;
2030 Stack.erase(std::prev(I.base()), Stack.end());
2031 }
2032 } else if (!Stack.empty()) {
2033 // We do not have a label, just pop the last entry.
2034 CurrentValue = Stack.back().Value;
2035 CurrentPragmaLocation = Stack.back().PragmaLocation;
2036 Stack.pop_back();
2037 }
2038 }
2039 if (Action & PSK_Set) {
2040 CurrentValue = Value;
2041 CurrentPragmaLocation = PragmaLocation;
2042 }
2043 }
2044
2045 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
2046 // method body to restore the stacks on exit, so it works like this:
2047 //
2048 // struct S {
2049 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
2050 // void Method {}
2051 // #pragma <name>(pop, InternalPragmaSlot)
2052 // };
2053 //
2054 // It works even with #pragma vtordisp, although MSVC doesn't support
2055 // #pragma vtordisp(push [, id], n)
2056 // syntax.
2057 //
2058 // Push / pop a named sentinel slot.
2059 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
2060 assert((Action == PSK_Push || Action == PSK_Pop) &&
2061 "Can only push / pop #pragma stack sentinels!");
2062 Act(PragmaLocation: CurrentPragmaLocation, Action, StackSlotLabel: Label, Value: CurrentValue);
2063 }
2064
2065 // Constructors.
2066 explicit PragmaStack(const ValueType &Default)
2067 : DefaultValue(Default), CurrentValue(Default) {}
2068
2069 bool hasValue() const { return CurrentValue != DefaultValue; }
2070
2071 SmallVector<Slot, 2> Stack;
2072 ValueType DefaultValue; // Value used for PSK_Reset action.
2073 ValueType CurrentValue;
2074 SourceLocation CurrentPragmaLocation;
2075 };
2076 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2077 // we shouldn't do so if they're in a module).
2078
2079 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2080 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
2081 ///
2082 /// 0: Suppress all vtordisps
2083 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2084 /// structors
2085 /// 2: Always insert vtordisps to support RTTI on partially constructed
2086 /// objects
2087 PragmaStack<MSVtorDispMode> VtorDispStack;
2088 PragmaStack<AlignPackInfo> AlignPackStack;
2089 // The current #pragma align/pack values and locations at each #include.
2090 struct AlignPackIncludeState {
2091 AlignPackInfo CurrentValue;
2092 SourceLocation CurrentPragmaLocation;
2093 bool HasNonDefaultValue, ShouldWarnOnInclude;
2094 };
2095 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
2096 // Segment #pragmas.
2097 PragmaStack<StringLiteral *> DataSegStack;
2098 PragmaStack<StringLiteral *> BSSSegStack;
2099 PragmaStack<StringLiteral *> ConstSegStack;
2100 PragmaStack<StringLiteral *> CodeSegStack;
2101
2102 // #pragma strict_gs_check.
2103 PragmaStack<bool> StrictGuardStackCheckStack;
2104
2105 // This stack tracks the current state of Sema.CurFPFeatures.
2106 PragmaStack<FPOptionsOverride> FpPragmaStack;
2107 FPOptionsOverride CurFPFeatureOverrides() {
2108 FPOptionsOverride result;
2109 if (!FpPragmaStack.hasValue()) {
2110 result = FPOptionsOverride();
2111 } else {
2112 result = FpPragmaStack.CurrentValue;
2113 }
2114 return result;
2115 }
2116
2117 enum PragmaSectionKind {
2118 PSK_DataSeg,
2119 PSK_BSSSeg,
2120 PSK_ConstSeg,
2121 PSK_CodeSeg,
2122 };
2123
2124 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2125 // Actions should be performed only if we enter / exit a C++ method body.
2126 class PragmaStackSentinelRAII {
2127 public:
2128 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2129 ~PragmaStackSentinelRAII();
2130 PragmaStackSentinelRAII(const PragmaStackSentinelRAII &) = delete;
2131 PragmaStackSentinelRAII &
2132 operator=(const PragmaStackSentinelRAII &) = delete;
2133
2134 private:
2135 Sema &S;
2136 StringRef SlotLabel;
2137 bool ShouldAct;
2138 };
2139
2140 /// Last section used with #pragma init_seg.
2141 StringLiteral *CurInitSeg;
2142 SourceLocation CurInitSegLoc;
2143
2144 /// Sections used with #pragma alloc_text.
2145 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2146
2147 /// VisContext - Manages the stack for \#pragma GCC visibility.
2148 void *VisContext; // Really a "PragmaVisStack*"
2149
2150 /// This an attribute introduced by \#pragma clang attribute.
2151 struct PragmaAttributeEntry {
2152 SourceLocation Loc;
2153 ParsedAttr *Attribute;
2154 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
2155 bool IsUsed;
2156 };
2157
2158 /// A push'd group of PragmaAttributeEntries.
2159 struct PragmaAttributeGroup {
2160 /// The location of the push attribute.
2161 SourceLocation Loc;
2162 /// The namespace of this push group.
2163 const IdentifierInfo *Namespace;
2164 SmallVector<PragmaAttributeEntry, 2> Entries;
2165 };
2166
2167 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
2168
2169 /// The declaration that is currently receiving an attribute from the
2170 /// #pragma attribute stack.
2171 const Decl *PragmaAttributeCurrentTargetDecl;
2172
2173 /// This represents the last location of a "#pragma clang optimize off"
2174 /// directive if such a directive has not been closed by an "on" yet. If
2175 /// optimizations are currently "on", this is set to an invalid location.
2176 SourceLocation OptimizeOffPragmaLocation;
2177
2178 /// Get the location for the currently active "\#pragma clang optimize
2179 /// off". If this location is invalid, then the state of the pragma is "on".
2180 SourceLocation getOptimizeOffPragmaLocation() const {
2181 return OptimizeOffPragmaLocation;
2182 }
2183
2184 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2185 /// whether the optimizations in the list passed to the pragma should be
2186 /// turned off or on. This boolean is true by default because command line
2187 /// options are honored when `#pragma optimize("", on)`.
2188 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2189 bool MSPragmaOptimizeIsOn = true;
2190
2191 /// Set of no-builtin functions listed by \#pragma function.
2192 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
2193
2194 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2195 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2196 void AddAlignmentAttributesForRecord(RecordDecl *RD);
2197
2198 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2199 void AddMsStructLayoutForRecord(RecordDecl *RD);
2200
2201 /// Add gsl::Pointer attribute to std::container::iterator
2202 /// \param ND The declaration that introduces the name
2203 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2204 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2205
2206 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2207 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
2208
2209 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2210 void inferLifetimeBoundAttribute(FunctionDecl *FD);
2211
2212 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2213 void inferLifetimeCaptureByAttribute(FunctionDecl *FD);
2214
2215 /// Add [[gsl::Pointer]] attributes for std:: types.
2216 void inferGslPointerAttribute(TypedefNameDecl *TD);
2217
2218 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2219 StringRef ParamName);
2220 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2221 // can be the name of a function parameter, we need to parse the function
2222 // declaration and rest of the parameters before processesing 'X'. Therefore
2223 // do this lazily instead of processing while parsing the annotation itself.
2224 void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD);
2225
2226 /// Add _Nullable attributes for std:: types.
2227 void inferNullableClassAttribute(CXXRecordDecl *CRD);
2228
2229 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2230 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
2231 PragmaClangSectionAction Action,
2232 PragmaClangSectionKind SecKind,
2233 StringRef SecName);
2234
2235 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2236 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
2237 SourceLocation PragmaLoc);
2238
2239 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2240 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2241 StringRef SlotLabel, Expr *Alignment);
2242
2243 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2244 /// (unless they are value dependent or type dependent). Returns false
2245 /// and emits a diagnostic if one or more of the arguments could not be
2246 /// folded into a constant.
2247 bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
2248 MutableArrayRef<Expr *> Args);
2249
2250 enum class PragmaAlignPackDiagnoseKind {
2251 NonDefaultStateAtInclude,
2252 ChangedStateAtExit
2253 };
2254
2255 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
2256 SourceLocation IncludeLoc);
2257 void DiagnoseUnterminatedPragmaAlignPack();
2258
2259 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2260 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
2261
2262 /// ActOnPragmaMSComment - Called on well formed
2263 /// \#pragma comment(kind, "arg").
2264 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
2265 StringRef Arg);
2266
2267 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2268 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2269 StringRef Value);
2270
2271 /// Are precise floating point semantics currently enabled?
2272 bool isPreciseFPEnabled() {
2273 return !CurFPFeatures.getAllowFPReassociate() &&
2274 !CurFPFeatures.getNoSignedZero() &&
2275 !CurFPFeatures.getAllowReciprocal() &&
2276 !CurFPFeatures.getAllowApproxFunc();
2277 }
2278
2279 void ActOnPragmaFPEvalMethod(SourceLocation Loc,
2280 LangOptions::FPEvalMethodKind Value);
2281
2282 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2283 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2284 PragmaFloatControlKind Value);
2285
2286 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2287 /// pointers_to_members(representation method[, general purpose
2288 /// representation]).
2289 void ActOnPragmaMSPointersToMembers(
2290 LangOptions::PragmaMSPointersToMembersKind Kind,
2291 SourceLocation PragmaLoc);
2292
2293 /// Called on well formed \#pragma vtordisp().
2294 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2295 SourceLocation PragmaLoc, MSVtorDispMode Value);
2296
2297 bool UnifySection(StringRef SectionName, int SectionFlags,
2298 NamedDecl *TheDecl);
2299 bool UnifySection(StringRef SectionName, int SectionFlags,
2300 SourceLocation PragmaSectionLocation);
2301
2302 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2303 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2304 PragmaMsStackAction Action,
2305 llvm::StringRef StackSlotLabel,
2306 StringLiteral *SegmentName, llvm::StringRef PragmaName);
2307
2308 /// Called on well formed \#pragma section().
2309 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2310 StringLiteral *SegmentName);
2311
2312 /// Called on well-formed \#pragma init_seg().
2313 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2314 StringLiteral *SegmentName);
2315
2316 /// Called on well-formed \#pragma alloc_text().
2317 void ActOnPragmaMSAllocText(
2318 SourceLocation PragmaLocation, StringRef Section,
2319 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2320 &Functions);
2321
2322 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2323 /// strict_gs_check.
2324 void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
2325 PragmaMsStackAction Action,
2326 bool Value);
2327
2328 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2329 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2330 SourceLocation PragmaLoc);
2331
2332 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
2333 SourceLocation PragmaLoc,
2334 attr::ParsedSubjectMatchRuleSet Rules);
2335 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
2336 const IdentifierInfo *Namespace);
2337
2338 /// Called on well-formed '\#pragma clang attribute pop'.
2339 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
2340 const IdentifierInfo *Namespace);
2341
2342 /// Adds the attributes that have been specified using the
2343 /// '\#pragma clang attribute push' directives to the given declaration.
2344 void AddPragmaAttributes(Scope *S, Decl *D);
2345
2346 using InstantiationContextDiagFuncRef =
2347 llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
2348 auto getDefaultDiagFunc() {
2349 return [this](SourceLocation Loc, PartialDiagnostic PD) {
2350 // This bypasses a lot of the filters in the diag engine, as it's
2351 // to be used to attach notes to diagnostics which have already
2352 // been filtered through.
2353 DiagnosticBuilder Builder(Diags.Report(Loc, DiagID: PD.getDiagID()));
2354 PD.Emit(DB: Builder);
2355 };
2356 }
2357
2358 void PrintPragmaAttributeInstantiationPoint(
2359 InstantiationContextDiagFuncRef DiagFunc);
2360 void PrintPragmaAttributeInstantiationPoint() {
2361 PrintPragmaAttributeInstantiationPoint(DiagFunc: getDefaultDiagFunc());
2362 }
2363
2364 void DiagnoseUnterminatedPragmaAttribute();
2365
2366 /// Called on well formed \#pragma clang optimize.
2367 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2368
2369 /// #pragma optimize("[optimization-list]", on | off).
2370 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2371
2372 /// Call on well formed \#pragma function.
2373 void
2374 ActOnPragmaMSFunction(SourceLocation Loc,
2375 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2376
2377 NamedDecl *lookupExternCFunctionOrVariable(IdentifierInfo *IdentId,
2378 SourceLocation NameLoc,
2379 Scope *curScope);
2380
2381 /// Information from a C++ #pragma export, for a symbol that we
2382 /// haven't seen the declaration for yet.
2383 struct PendingPragmaInfo {
2384 SourceLocation NameLoc;
2385 bool Used;
2386 };
2387
2388 llvm::DenseMap<IdentifierInfo *, PendingPragmaInfo> PendingExportedNames;
2389
2390 /// ActonPragmaExport - called on well-formed '\#pragma export'.
2391 void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc,
2392 Scope *curScope);
2393
2394 /// Only called on function definitions; if there is a pragma in scope
2395 /// with the effect of a range-based optnone, consider marking the function
2396 /// with attribute optnone.
2397 void AddRangeBasedOptnone(FunctionDecl *FD);
2398
2399 /// Only called on function definitions; if there is a `#pragma alloc_text`
2400 /// that decides which code section the function should be in, add
2401 /// attribute section to the function.
2402 void AddSectionMSAllocText(FunctionDecl *FD);
2403
2404 /// Adds the 'optnone' attribute to the function declaration if there
2405 /// are no conflicts; Loc represents the location causing the 'optnone'
2406 /// attribute to be added (usually because of a pragma).
2407 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
2408
2409 /// Only called on function definitions; if there is a MSVC #pragma optimize
2410 /// in scope, consider changing the function's attributes based on the
2411 /// optimization list passed to the pragma.
2412 void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
2413
2414 /// Only called on function definitions; if there is a pragma in scope
2415 /// with the effect of a range-based no_builtin, consider marking the function
2416 /// with attribute no_builtin.
2417 void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
2418
2419 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2420 /// add an appropriate visibility attribute.
2421 void AddPushedVisibilityAttribute(Decl *RD);
2422
2423 /// FreeVisContext - Deallocate and null out VisContext.
2424 void FreeVisContext();
2425
2426 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2427 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2428 SourceLocation PragmaLoc);
2429
2430 /// ActOnPragmaFPContract - Called on well formed
2431 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2432 /// \#pragma clang fp contract
2433 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
2434
2435 /// Called on well formed
2436 /// \#pragma clang fp reassociate
2437 /// or
2438 /// \#pragma clang fp reciprocal
2439 void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind,
2440 bool IsEnabled);
2441
2442 /// ActOnPragmaFenvAccess - Called on well formed
2443 /// \#pragma STDC FENV_ACCESS
2444 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2445
2446 /// ActOnPragmaCXLimitedRange - Called on well formed
2447 /// \#pragma STDC CX_LIMITED_RANGE
2448 void ActOnPragmaCXLimitedRange(SourceLocation Loc,
2449 LangOptions::ComplexRangeKind Range);
2450
2451 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2452 void ActOnPragmaFPExceptions(SourceLocation Loc,
2453 LangOptions::FPExceptionModeKind);
2454
2455 /// Called to set constant rounding mode for floating point operations.
2456 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2457
2458 /// Called to set exception behavior for floating point operations.
2459 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
2460
2461 /// PushNamespaceVisibilityAttr - Note that we've entered a
2462 /// namespace with a visibility attribute.
2463 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2464 SourceLocation Loc);
2465
2466 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2467 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2468 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2469
2470 /// Handles semantic checking for features that are common to all attributes,
2471 /// such as checking whether a parameter was properly specified, or the
2472 /// correct number of arguments were passed, etc. Returns true if the
2473 /// attribute has been diagnosed.
2474 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2475 bool SkipArgCountCheck = false);
2476 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2477 bool SkipArgCountCheck = false);
2478
2479 ///@}
2480
2481 //
2482 //
2483 // -------------------------------------------------------------------------
2484 //
2485 //
2486
2487 /// \name Availability Attribute Handling
2488 /// Implementations are in SemaAvailability.cpp
2489 ///@{
2490
2491public:
2492 /// Issue any -Wunguarded-availability warnings in \c FD
2493 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
2494
2495 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2496
2497 /// Retrieve the current function, if any, that should be analyzed for
2498 /// potential availability violations.
2499 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2500
2501 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
2502 const ObjCInterfaceDecl *UnknownObjCClass,
2503 bool ObjCPropertyAccess,
2504 bool AvoidPartialAvailabilityChecks,
2505 ObjCInterfaceDecl *ClassReceiver);
2506
2507 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs);
2508
2509 std::pair<AvailabilityResult, const NamedDecl *>
2510 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2511 ObjCInterfaceDecl *ClassReceiver);
2512 ///@}
2513
2514 //
2515 //
2516 // -------------------------------------------------------------------------
2517 //
2518 //
2519
2520 /// \name Bounds Safety
2521 /// Implementations are in SemaBoundsSafety.cpp
2522 ///@{
2523public:
2524 struct BoundsAttrFlags {
2525 bool CountInBytes = false;
2526 bool OrNull = false;
2527 bool IsEndedBy = false;
2528
2529 /// Return the flags for a bounds attribute of kind \p K.
2530 static BoundsAttrFlags get(AttributeCommonInfo::Kind K);
2531 };
2532 static BoundsAttributedType::BoundsAttrKind
2533 getBoundsAttrKind(const BoundsAttrFlags &);
2534
2535 /// Check the type shape for counted_by, sized_by and their _or_null variants.
2536 /// The caller checks declaration context, count expressions, flexible array
2537 /// member eligibility and nesting.
2538 ///
2539 /// \p Flags selects the attribute variant. For void pointers, counted_by is
2540 /// treated as a byte count outside the -fbounds-safety attribute model. Set
2541 /// \c Flags.CountInBytes in this case if \p UpdateFlags is true.
2542 /// \p AttrSpelling, \p AllowRedecl and \p AttrArg are reserved for that model
2543 /// (see LangOptions::hasBoundsSafetyAttributes).
2544 ///
2545 /// \returns false after diagnosing an attribute that must be dropped. Returns
2546 /// true if the shape is valid, after the warning for an array of structs with
2547 /// flexible array members, and, under the -fbounds-safety attribute model,
2548 /// after an error on a pointer, with \c Flags.CountInBytes set so that type
2549 /// construction can recover.
2550 bool ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc,
2551 SourceRange AttrRange,
2552 BoundsAttrFlags &Flags,
2553 StringRef AttrSpelling = {},
2554 bool AllowRedecl = false,
2555 Expr *AttrArg = nullptr,
2556 bool UpdateFlags = true);
2557
2558 /// Check a counted_by-family attribute in type position and initialize
2559 /// \p Flags from \p AttrKind. \p PointerNestLevel counts the pointer, array
2560 /// and function declarator chunks enclosing the attribute.
2561 ///
2562 /// \returns false after diagnosing an attribute that must be dropped (see
2563 /// ValidateBoundsAttrTypeShape).
2564 bool ValidateBoundsAttrTypeForTypePosition(
2565 QualType Ty, AttributeCommonInfo::Kind AttrKind, SourceLocation AttrLoc,
2566 SourceRange AttrRange, unsigned PointerNestLevel, BoundsAttrFlags &Flags);
2567
2568 /// Check if applying the specified attribute variant from the "counted by"
2569 /// family of attributes to FieldDecl \p FD is semantically valid. If
2570 /// semantically invalid diagnostics will be emitted explaining the problems.
2571 ///
2572 /// \param FD The FieldDecl to apply the attribute to
2573 /// \param E The count expression on the attribute
2574 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2575 /// attributes. If the false the attribute is from
2576 /// "counted_by" family of attributes.
2577 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2578 /// of attributes. If false the attribute does not have the
2579 /// suffix.
2580 ///
2581 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2582 /// \p CountInBytes and \p OrNull both being true indicates the
2583 /// `counted_by_or_null` attribute.
2584 ///
2585 /// \returns false iff semantically valid.
2586 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2587 bool OrNull);
2588
2589 /// Late-parsed bounds types dropped while their declarator was built. The
2590 /// attribute has already been diagnosed and its node is no longer part of
2591 /// any type, so the completion pass must skip it rather than parse its
2592 /// argument and complete it.
2593 llvm::SmallPtrSet<const BoundsAttributedType *, 1>
2594 RejectedLateParsedBoundsTypes;
2595
2596 void markLateParsedBoundsTypeRejected(const BoundsAttributedType *BATy) {
2597 RejectedLateParsedBoundsTypes.insert(Ptr: BATy);
2598 }
2599
2600 bool isLateParsedBoundsTypeRejected(const BoundsAttributedType *BATy) const {
2601 return RejectedLateParsedBoundsTypes.contains(Ptr: BATy);
2602 }
2603
2604 /// Supply the parsed argument of a late-parsed bounds attribute to the type
2605 /// built for it by ActOnLateParsedTypeAttr, and run the checks that need the
2606 /// owning declaration. \p FD is the field the type belongs to. Returns false
2607 /// if the attribute was rejected.
2608 bool ActOnLateParsedTypeAttrArgument(BoundsAttributedType *BATy,
2609 FieldDecl *FD, Expr *Arg);
2610
2611 /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2612 /// `__counted_by_or_null` pointer type \param LHSTy.
2613 ///
2614 /// \param LHSTy The type being assigned to. Checks will only be performed if
2615 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2616 /// \param RHSExpr The expression being assigned from.
2617 /// \param Action The type assignment being performed
2618 /// \param Loc The SourceLocation to use for error diagnostics
2619 /// \param Assignee The ValueDecl being assigned. This is used to compute
2620 /// the name of the assignee. If the assignee isn't known this can
2621 /// be set to nullptr.
2622 /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2623 /// Assignee to compute the name of the assignee use the fully
2624 /// qualified name, otherwise use the unqualified name.
2625 ///
2626 /// \returns True iff no diagnostic where emitted, false otherwise.
2627 bool BoundsSafetyCheckAssignmentToCountAttrPtr(
2628 QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2629 SourceLocation Loc, const ValueDecl *Assignee,
2630 bool ShowFullyQualifiedAssigneeName);
2631
2632 /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2633 /// pointer.
2634 ///
2635 /// \param Entity The entity being initialized
2636 /// \param Kind The kind of initialization being performed
2637 /// \param Action The type assignment being performed
2638 /// \param LHSTy The type being assigned to. Checks will only be performed if
2639 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2640 /// \param RHSExpr The expression being used for initialization.
2641 ///
2642 /// \returns True iff no diagnostic where emitted, false otherwise.
2643 bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity,
2644 const InitializationKind &Kind,
2645 AssignmentAction Action,
2646 QualType LHSType, Expr *RHSExpr);
2647
2648 /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2649 /// or counted_by_or_null pointers in \param E.
2650 ///
2651 /// \param E the expression to check
2652 ///
2653 /// \returns True iff no diagnostic where emitted, false otherwise.
2654 bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E);
2655 ///@}
2656
2657 //
2658 //
2659 // -------------------------------------------------------------------------
2660 //
2661 //
2662
2663 /// \name Casts
2664 /// Implementations are in SemaCast.cpp
2665 ///@{
2666
2667public:
2668 static bool isCast(CheckedConversionKind CCK) {
2669 return CCK == CheckedConversionKind::CStyleCast ||
2670 CCK == CheckedConversionKind::FunctionalCast ||
2671 CCK == CheckedConversionKind::OtherCast;
2672 }
2673
2674 /// ActOnCXXNamedCast - Parse
2675 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2676 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2677 SourceLocation LAngleBracketLoc, Declarator &D,
2678 SourceLocation RAngleBracketLoc,
2679 SourceLocation LParenLoc, Expr *E,
2680 SourceLocation RParenLoc);
2681
2682 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2683 TypeSourceInfo *Ty, Expr *E,
2684 SourceRange AngleBrackets, SourceRange Parens);
2685
2686 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
2687 ExprResult Operand,
2688 SourceLocation RParenLoc);
2689
2690 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
2691 Expr *Operand, SourceLocation RParenLoc);
2692
2693 // Checks that reinterpret casts don't have undefined behavior.
2694 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2695 bool IsDereference, SourceRange Range);
2696
2697 // Checks that the vector type should be initialized from a scalar
2698 // by splatting the value rather than populating a single element.
2699 // This is the case for AltiVecVector types as well as with
2700 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2701 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2702
2703 // Checks if the -faltivec-src-compat=gcc option is specified.
2704 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2705 // treated the same way as they are when trying to initialize
2706 // these vectors on gcc (an error is emitted).
2707 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
2708 QualType SrcTy);
2709
2710 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
2711 SourceLocation RParenLoc, Expr *Op);
2712
2713 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
2714 SourceLocation LParenLoc,
2715 Expr *CastExpr,
2716 SourceLocation RParenLoc);
2717
2718 ///@}
2719
2720 //
2721 //
2722 // -------------------------------------------------------------------------
2723 //
2724 //
2725
2726 /// \name Extra Semantic Checking
2727 /// Implementations are in SemaChecking.cpp
2728 ///@{
2729
2730public:
2731 /// Used to change context to isConstantEvaluated without pushing a heavy
2732 /// ExpressionEvaluationContextRecord object.
2733 bool isConstantEvaluatedOverride = false;
2734
2735 bool isConstantEvaluatedContext() const {
2736 return currentEvaluationContext().isConstantEvaluated() ||
2737 isConstantEvaluatedOverride;
2738 }
2739
2740 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
2741 unsigned ByteNo) const;
2742
2743 enum FormatArgumentPassingKind {
2744 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2745 FAPK_Variadic, // values to format are passed as variadic arguments
2746 FAPK_VAList, // values to format are passed in a va_list
2747 FAPK_Elsewhere, // values to format are not passed to this function
2748 };
2749
2750 // Used to grab the relevant information from a FormatAttr and a
2751 // FunctionDeclaration.
2752 struct FormatStringInfo {
2753 unsigned FormatIdx;
2754 unsigned FirstDataArg;
2755 FormatArgumentPassingKind ArgPassingKind;
2756 };
2757
2758 /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2759 /// populate the FormatStringInfo parameter with the attribute's correct
2760 /// format_idx and firstDataArg. Returns true when the format fits the
2761 /// function and the FormatStringInfo has been populated.
2762 static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2763 unsigned FirstArg, FormatStringInfo *FSI);
2764 static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2765 bool HasImplicitThisParam, bool IsVariadic,
2766 FormatStringInfo *FSI);
2767
2768 // Used by C++ template instantiation.
2769 ExprResult BuiltinShuffleVector(CallExpr *TheCall);
2770
2771 /// ConvertVectorExpr - Handle __builtin_convertvector
2772 ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2773 SourceLocation BuiltinLoc,
2774 SourceLocation RParenLoc);
2775
2776 static StringRef GetFormatStringTypeName(FormatStringType FST);
2777 static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2778 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2779 static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2780
2781 bool FormatStringHasSArg(const StringLiteral *FExpr);
2782
2783 /// Check for comparisons of floating-point values using == and !=. Issue a
2784 /// warning if the comparison is not likely to do what the programmer
2785 /// intended.
2786 void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2787 const Expr *RHS, BinaryOperatorKind Opcode);
2788
2789 /// Register a magic integral constant to be used as a type tag.
2790 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2791 uint64_t MagicValue, QualType Type,
2792 bool LayoutCompatible, bool MustBeNull);
2793
2794 struct TypeTagData {
2795 TypeTagData() {}
2796
2797 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
2798 : Type(Type), LayoutCompatible(LayoutCompatible),
2799 MustBeNull(MustBeNull) {}
2800
2801 QualType Type;
2802
2803 /// If true, \c Type should be compared with other expression's types for
2804 /// layout-compatibility.
2805 LLVM_PREFERRED_TYPE(bool)
2806 unsigned LayoutCompatible : 1;
2807 LLVM_PREFERRED_TYPE(bool)
2808 unsigned MustBeNull : 1;
2809 };
2810
2811 /// A pair of ArgumentKind identifier and magic value. This uniquely
2812 /// identifies the magic value.
2813 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2814
2815 /// Diagnoses the current set of gathered accesses. This happens at the end of
2816 /// each expression evaluation context. Diagnostics are emitted only for
2817 /// accesses gathered in the current evaluation context.
2818 void DiagnoseMisalignedMembers();
2819
2820 /// This function checks if the expression is in the sef of potentially
2821 /// misaligned members and it is converted to some pointer type T with lower
2822 /// or equal alignment requirements. If so it removes it. This is used when
2823 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2824 /// void*).
2825 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2826
2827 /// Returns true if `From` is a function or pointer to a function with the
2828 /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2829 /// function without this attribute.
2830 bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2831
2832 /// This function calls Action when it determines that E designates a
2833 /// misaligned member due to the packed attribute. This is used to emit
2834 /// local diagnostics like in reference binding.
2835 void RefersToMemberWithReducedAlignment(
2836 Expr *E,
2837 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2838 Action);
2839
2840 enum class AtomicArgumentOrder { API, AST };
2841 ExprResult
2842 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2843 SourceLocation RParenLoc, MultiExprArg Args,
2844 AtomicExpr::AtomicOp Op,
2845 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
2846
2847 /// Check to see if a given expression could have '.c_str()' called on it.
2848 bool hasCStrMethod(const Expr *E);
2849
2850 /// Diagnose pointers that are always non-null.
2851 /// \param E the expression containing the pointer
2852 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2853 /// compared to a null pointer
2854 /// \param IsEqual True when the comparison is equal to a null pointer
2855 /// \param Range Extra SourceRange to highlight in the diagnostic
2856 void DiagnoseAlwaysNonNullPointer(Expr *E,
2857 Expr::NullPointerConstantKind NullType,
2858 bool IsEqual, SourceRange Range);
2859
2860 /// CheckParmsForFunctionDef - Check that the parameters of the given
2861 /// function are appropriate for the definition of a function. This
2862 /// takes care of any checks that cannot be performed on the
2863 /// declaration itself, e.g., that the types of each of the function
2864 /// parameters are complete.
2865 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2866 bool CheckParameterNames);
2867
2868 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2869 /// pointer cast increases the alignment requirements.
2870 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2871
2872 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2873 /// to weak/__unsafe_unretained type.
2874 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2875
2876 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2877 /// to weak/__unsafe_unretained expression.
2878 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2879
2880 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2881 /// statement as a \p Body, and it is located on the same line.
2882 ///
2883 /// This helps prevent bugs due to typos, such as:
2884 /// if (condition);
2885 /// do_stuff();
2886 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2887 unsigned DiagID);
2888
2889 /// Warn if a for/while loop statement \p S, which is followed by
2890 /// \p PossibleBody, has a suspicious null statement as a body.
2891 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2892
2893 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2894 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2895 SourceLocation OpLoc);
2896
2897 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2898 bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
2899 const TypeSourceInfo *Derived);
2900
2901 /// CheckFunctionCall - Check a direct function call for various correctness
2902 /// and safety properties not strictly enforced by the C type system.
2903 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2904 const FunctionProtoType *Proto);
2905
2906 enum class EltwiseBuiltinArgTyRestriction {
2907 None,
2908 FloatTy,
2909 IntegerTy,
2910 SignedIntOrFloatTy,
2911 };
2912
2913 /// \param FPOnly restricts the arguments to floating-point types.
2914 std::optional<QualType>
2915 BuiltinVectorMath(CallExpr *TheCall,
2916 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2917 EltwiseBuiltinArgTyRestriction::None);
2918 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2919
2920 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2921 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2922
2923 /// Handles the checks for format strings, non-POD arguments to vararg
2924 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2925 /// attributes and AArch64 SME attributes.
2926 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2927 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2928 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2929 VariadicCallType CallType);
2930
2931 /// Verify that two format strings (as understood by attribute(format) and
2932 /// attribute(format_matches) are compatible. If they are incompatible,
2933 /// diagnostics are emitted with the assumption that \c
2934 /// AuthoritativeFormatString is correct and
2935 /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2936 /// diagnostics will point to it and a note will refer to \c
2937 /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2938 bool
2939 CheckFormatStringsCompatible(FormatStringType FST,
2940 const StringLiteral *AuthoritativeFormatString,
2941 const StringLiteral *TestedFormatString,
2942 const Expr *FunctionCallArg = nullptr);
2943
2944 /// Verify that one format string (as understood by attribute(format)) is
2945 /// self-consistent; for instance, that it doesn't have multiple positional
2946 /// arguments referring to the same argument in incompatible ways. Diagnose
2947 /// if it isn't.
2948 bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str);
2949
2950 /// \brief Enforce the bounds of a TCB
2951 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2952 /// directly calls other functions in the same TCB as marked by the
2953 /// enforce_tcb and enforce_tcb_leaf attributes.
2954 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2955 const NamedDecl *Callee);
2956
2957 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2958
2959 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2960 /// TheCall is a constant expression.
2961 bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
2962 llvm::APSInt &Result);
2963
2964 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2965 /// TheCall is a constant expression in the range [Low, High].
2966 bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
2967 int High, bool RangeIsError = true);
2968
2969 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2970 /// TheCall is a constant expression is a multiple of Num..
2971 bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
2972 unsigned Multiple);
2973
2974 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2975 /// constant expression representing a power of 2.
2976 bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum);
2977
2978 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2979 /// a constant expression representing an arbitrary byte value shifted left by
2980 /// a multiple of 8 bits.
2981 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
2982 unsigned ArgBits);
2983
2984 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2985 /// TheCall is a constant expression representing either a shifted byte value,
2986 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2987 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2988 /// Arm MVE intrinsics.
2989 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum,
2990 unsigned ArgBits);
2991
2992 /// Checks that a call expression's argument count is at least the desired
2993 /// number. This is useful when doing custom type-checking on a variadic
2994 /// function. Returns true on error.
2995 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2996
2997 /// Checks that a call expression's argument count is at most the desired
2998 /// number. This is useful when doing custom type-checking on a variadic
2999 /// function. Returns true on error.
3000 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
3001
3002 /// Checks that a call expression's argument count is in the desired range.
3003 /// This is useful when doing custom type-checking on a variadic function.
3004 /// Returns true on error.
3005 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
3006 unsigned MaxArgCount);
3007
3008 /// Checks that a call expression's argument count is the desired number.
3009 /// This is useful when doing custom type-checking. Returns true on error.
3010 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
3011
3012 bool convertArgumentToType(Expr *&Value, QualType Ty);
3013
3014 /// Returns true if the argument consists of one contiguous run of 1s with any
3015 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
3016 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3017 /// since all 1s are not contiguous.
3018 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
3019
3020 void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
3021 bool *ICContext = nullptr,
3022 bool IsListInit = false);
3023
3024 /// Check for overflow behavior type related implicit conversion diagnostics.
3025 /// Returns true if OBT-related diagnostic was issued, false otherwise.
3026 bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
3027 SourceLocation CC);
3028
3029 bool
3030 BuiltinElementwiseTernaryMath(CallExpr *TheCall,
3031 EltwiseBuiltinArgTyRestriction ArgTyRestr =
3032 EltwiseBuiltinArgTyRestriction::FloatTy);
3033 bool PrepareBuiltinElementwiseMathOneArgCall(
3034 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
3035 EltwiseBuiltinArgTyRestriction::None);
3036
3037private:
3038 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3039 const ArraySubscriptExpr *ASE = nullptr,
3040 bool AllowOnePastEnd = true, bool IndexNegated = false);
3041 void CheckArrayAccess(const Expr *E);
3042
3043 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3044 const FunctionProtoType *Proto);
3045
3046 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3047 /// such as function pointers returned from functions.
3048 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
3049
3050 /// CheckConstructorCall - Check a constructor call for correctness and safety
3051 /// properties not enforced by the C type system.
3052 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
3053 ArrayRef<const Expr *> Args,
3054 const FunctionProtoType *Proto, SourceLocation Loc);
3055
3056 /// Warn if a pointer or reference argument passed to a function points to an
3057 /// object that is less aligned than the parameter. This can happen when
3058 /// creating a typedef with a lower alignment than the original type and then
3059 /// calling functions defined in terms of the original type.
3060 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3061 StringRef ParamName, QualType ArgTy, QualType ParamTy);
3062
3063 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
3064
3065 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3066 CallExpr *TheCall);
3067
3068 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3069 CallExpr *TheCall);
3070
3071 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
3072
3073 /// Argument-value fortify checks for libc functions that are not builtins,
3074 /// dispatched by name (e.g. umask). Diagnostics belong to -Wfortify-source.
3075 void checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall);
3076
3077 /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
3078 /// or '__builtin_c23_va_start' for validity. Emit an error and return true
3079 /// on failure; return false on success.
3080 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
3081 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
3082
3083 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3084 /// friends. This is declared to take (...), so we have to check everything.
3085 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
3086
3087 /// BuiltinSemaBuiltinFPClassification - Handle functions like
3088 /// __builtin_isnan and friends. This is declared to take (...), so we have
3089 /// to check everything.
3090 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
3091 unsigned BuiltinID);
3092
3093 /// Perform semantic analysis for a call to __builtin_complex.
3094 bool BuiltinComplex(CallExpr *TheCall);
3095 bool BuiltinOSLogFormat(CallExpr *TheCall);
3096
3097 /// BuiltinPrefetch - Handle __builtin_prefetch.
3098 /// This is declared to take (const void*, ...) and can take two
3099 /// optional constant int args.
3100 bool BuiltinPrefetch(CallExpr *TheCall);
3101
3102 /// Handle __builtin_alloca_with_align. This is declared
3103 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3104 /// than 8.
3105 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
3106
3107 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
3108 bool BuiltinArithmeticFence(CallExpr *TheCall);
3109
3110 /// BuiltinAssume - Handle __assume (MS Extension).
3111 /// __assume does not evaluate its arguments, and should warn if its argument
3112 /// has side effects.
3113 bool BuiltinAssume(CallExpr *TheCall);
3114
3115 /// Handle __builtin_assume_aligned. This is declared
3116 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3117 bool BuiltinAssumeAligned(CallExpr *TheCall);
3118
3119 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3120 /// This checks that the target supports __builtin_longjmp and
3121 /// that val is a constant 1.
3122 bool BuiltinLongjmp(CallExpr *TheCall);
3123
3124 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3125 /// This checks that the target supports __builtin_setjmp.
3126 bool BuiltinSetjmp(CallExpr *TheCall);
3127
3128 /// We have a call to a function like __sync_fetch_and_add, which is an
3129 /// overloaded function based on the pointer type of its first argument.
3130 /// The main BuildCallExpr routines have already promoted the types of
3131 /// arguments because all of these calls are prototyped as void(...).
3132 ///
3133 /// This function goes through and does final semantic checking for these
3134 /// builtins, as well as generating any warnings.
3135 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
3136
3137 /// BuiltinNontemporalOverloaded - We have a call to
3138 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3139 /// overloaded function based on the pointer type of its last argument.
3140 ///
3141 /// This function goes through and does final semantic checking for these
3142 /// builtins.
3143 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
3144 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
3145 AtomicExpr::AtomicOp Op);
3146
3147 /// \param FPOnly restricts the arguments to floating-point types.
3148 bool BuiltinElementwiseMath(CallExpr *TheCall,
3149 EltwiseBuiltinArgTyRestriction ArgTyRestr =
3150 EltwiseBuiltinArgTyRestriction::None);
3151 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
3152
3153 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
3154
3155 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
3156 BuiltinCountedByRefKind K);
3157 bool BuiltinCountedByRef(CallExpr *TheCall);
3158
3159 // Matrix builtin handling.
3160 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
3161 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
3162 ExprResult CallResult);
3163 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
3164 ExprResult CallResult);
3165
3166 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3167 /// functions) for correct use of format strings.
3168 /// Returns true if a format string has been fully checked.
3169 bool CheckFormatArguments(const FormatAttr *Format,
3170 ArrayRef<const Expr *> Args, bool IsCXXMember,
3171 VariadicCallType CallType, SourceLocation Loc,
3172 SourceRange Range,
3173 llvm::SmallBitVector &CheckedVarArgs);
3174 bool CheckFormatString(const FormatMatchesAttr *Format,
3175 ArrayRef<const Expr *> Args, bool IsCXXMember,
3176 VariadicCallType CallType, SourceLocation Loc,
3177 SourceRange Range,
3178 llvm::SmallBitVector &CheckedVarArgs);
3179 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3180 FormatArgumentPassingKind FAPK,
3181 StringLiteral *ReferenceFormatString,
3182 unsigned format_idx, unsigned firstDataArg,
3183 FormatStringType Type, VariadicCallType CallType,
3184 SourceLocation Loc, SourceRange range,
3185 llvm::SmallBitVector &CheckedVarArgs);
3186
3187 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3188
3189 /// Warn when using the wrong abs() function.
3190 void CheckAbsoluteValueFunction(const CallExpr *Call,
3191 const FunctionDecl *FDecl);
3192
3193 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3194
3195 /// Check for dangerous or invalid arguments to memset().
3196 ///
3197 /// This issues warnings on known problematic, dangerous or unspecified
3198 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3199 /// function calls.
3200 ///
3201 /// \param Call The call expression to diagnose.
3202 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3203 IdentifierInfo *FnName);
3204
3205 bool CheckSizeofMemaccessArgument(const Expr *SizeOfArg, const Expr *Dest,
3206 IdentifierInfo *FnName);
3207 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3208 // be the size of the source, instead of the destination.
3209 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3210
3211 // Warn on anti-patterns as the 'size' argument to strncat.
3212 // The correct size argument should look like following:
3213 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3214 void CheckStrncatArguments(const CallExpr *Call,
3215 const IdentifierInfo *FnName);
3216
3217 /// Alerts the user that they are attempting to free a non-malloc'd object.
3218 void CheckFreeArguments(const CallExpr *E);
3219
3220 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3221 SourceLocation ReturnLoc, bool isObjCMethod = false,
3222 const AttrVec *Attrs = nullptr,
3223 const FunctionDecl *FD = nullptr);
3224
3225 /// Diagnoses "dangerous" implicit conversions within the given
3226 /// expression (which is a full expression). Implements -Wconversion
3227 /// and -Wsign-compare.
3228 ///
3229 /// \param CC the "context" location of the implicit conversion, i.e.
3230 /// the most location of the syntactic entity requiring the implicit
3231 /// conversion
3232 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3233
3234 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3235 /// Input argument E is a logical expression.
3236 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
3237
3238 /// Diagnose when expression is an integer constant expression and its
3239 /// evaluation results in integer overflow
3240 void CheckForIntOverflow(const Expr *E);
3241 void CheckUnsequencedOperations(const Expr *E);
3242
3243 /// Perform semantic checks on a completed expression. This will either
3244 /// be a full-expression or a default argument expression.
3245 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3246 bool IsConstexpr = false);
3247
3248 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3249 Expr *Init);
3250
3251 /// A map from magic value to type information.
3252 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3253 TypeTagForDatatypeMagicValues;
3254
3255 /// Peform checks on a call of a function with argument_with_type_tag
3256 /// or pointer_with_type_tag attributes.
3257 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3258 const ArrayRef<const Expr *> ExprArgs,
3259 SourceLocation CallSiteLoc);
3260
3261 /// Check if we are taking the address of a packed field
3262 /// as this may be a problem if the pointer value is dereferenced.
3263 void CheckAddressOfPackedMember(Expr *rhs);
3264
3265 /// Helper class that collects misaligned member designations and
3266 /// their location info for delayed diagnostics.
3267 struct MisalignedMember {
3268 Expr *E;
3269 RecordDecl *RD;
3270 ValueDecl *MD;
3271 CharUnits Alignment;
3272
3273 MisalignedMember() : E(), RD(), MD() {}
3274 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3275 CharUnits Alignment)
3276 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
3277 explicit MisalignedMember(Expr *E)
3278 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3279
3280 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3281 };
3282
3283 /// Adds an expression to the set of gathered misaligned members.
3284 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3285 CharUnits Alignment);
3286 ///@}
3287
3288 //
3289 //
3290 // -------------------------------------------------------------------------
3291 //
3292 //
3293
3294 /// \name C++ Coroutines
3295 /// Implementations are in SemaCoroutine.cpp
3296 ///@{
3297
3298public:
3299 /// The C++ "std::coroutine_traits" template, which is defined in
3300 /// \<coroutine_traits>
3301 ClassTemplateDecl *StdCoroutineTraitsCache;
3302
3303 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
3304 StringRef Keyword);
3305 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3306 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3307 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
3308
3309 ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
3310 ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
3311 UnresolvedLookupExpr *Lookup);
3312 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3313 Expr *Awaiter, bool IsImplicit = false);
3314 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3315 UnresolvedLookupExpr *Lookup);
3316 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
3317 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
3318 bool IsImplicit = false);
3319 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
3320 bool buildCoroutineParameterMoves(SourceLocation Loc);
3321 VarDecl *buildCoroutinePromise(SourceLocation Loc);
3322 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
3323
3324 // As a clang extension, enforces that a non-coroutine function must be marked
3325 // with [[clang::coro_wrapper]] if it returns a type marked with
3326 // [[clang::coro_return_type]].
3327 // Expects that FD is not a coroutine.
3328 void CheckCoroutineWrapper(FunctionDecl *FD);
3329 /// Lookup 'coroutine_traits' in std namespace and std::experimental
3330 /// namespace. The namespace found is recorded in Namespace.
3331 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
3332 SourceLocation FuncLoc);
3333 /// Check that the expression co_await promise.final_suspend() shall not be
3334 /// potentially-throwing.
3335 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3336
3337 ///@}
3338
3339 //
3340 //
3341 // -------------------------------------------------------------------------
3342 //
3343 //
3344
3345 /// \name C++ Scope Specifiers
3346 /// Implementations are in SemaCXXScopeSpec.cpp
3347 ///@{
3348
3349public:
3350 // Marks SS invalid if it represents an incomplete type.
3351 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
3352 // Complete an enum decl, maybe without a scope spec.
3353 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
3354 CXXScopeSpec *SS = nullptr);
3355
3356 /// Compute the DeclContext that is associated with the given type.
3357 ///
3358 /// \param T the type for which we are attempting to find a DeclContext.
3359 ///
3360 /// \returns the declaration context represented by the type T,
3361 /// or NULL if the declaration context cannot be computed (e.g., because it is
3362 /// dependent and not the current instantiation).
3363 DeclContext *computeDeclContext(QualType T);
3364
3365 /// Compute the DeclContext that is associated with the given
3366 /// scope specifier.
3367 ///
3368 /// \param SS the C++ scope specifier as it appears in the source
3369 ///
3370 /// \param EnteringContext when true, we will be entering the context of
3371 /// this scope specifier, so we can retrieve the declaration context of a
3372 /// class template or class template partial specialization even if it is
3373 /// not the current instantiation.
3374 ///
3375 /// \returns the declaration context represented by the scope specifier @p SS,
3376 /// or NULL if the declaration context cannot be computed (e.g., because it is
3377 /// dependent and not the current instantiation).
3378 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
3379 bool EnteringContext = false);
3380 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
3381
3382 /// If the given nested name specifier refers to the current
3383 /// instantiation, return the declaration that corresponds to that
3384 /// current instantiation (C++0x [temp.dep.type]p1).
3385 ///
3386 /// \param NNS a dependent nested name specifier.
3387 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier NNS);
3388
3389 /// The parser has parsed a global nested-name-specifier '::'.
3390 ///
3391 /// \param CCLoc The location of the '::'.
3392 ///
3393 /// \param SS The nested-name-specifier, which will be updated in-place
3394 /// to reflect the parsed nested-name-specifier.
3395 ///
3396 /// \returns true if an error occurred, false otherwise.
3397 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
3398
3399 /// The parser has parsed a '__super' nested-name-specifier.
3400 ///
3401 /// \param SuperLoc The location of the '__super' keyword.
3402 ///
3403 /// \param ColonColonLoc The location of the '::'.
3404 ///
3405 /// \param SS The nested-name-specifier, which will be updated in-place
3406 /// to reflect the parsed nested-name-specifier.
3407 ///
3408 /// \returns true if an error occurred, false otherwise.
3409 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
3410 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3411
3412 /// Determines whether the given declaration is an valid acceptable
3413 /// result for name lookup of a nested-name-specifier.
3414 /// \param SD Declaration checked for nested-name-specifier.
3415 /// \param IsExtension If not null and the declaration is accepted as an
3416 /// extension, the pointed variable is assigned true.
3417 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
3418 bool *CanCorrect = nullptr);
3419
3420 /// If the given nested-name-specifier begins with a bare identifier
3421 /// (e.g., Base::), perform name lookup for that identifier as a
3422 /// nested-name-specifier within the given scope, and return the result of
3423 /// that name lookup.
3424 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier NNS);
3425
3426 /// Keeps information about an identifier in a nested-name-spec.
3427 ///
3428 struct NestedNameSpecInfo {
3429 /// The type of the object, if we're parsing nested-name-specifier in
3430 /// a member access expression.
3431 ParsedType ObjectType;
3432
3433 /// The identifier preceding the '::'.
3434 IdentifierInfo *Identifier;
3435
3436 /// The location of the identifier.
3437 SourceLocation IdentifierLoc;
3438
3439 /// The location of the '::'.
3440 SourceLocation CCLoc;
3441
3442 /// Creates info object for the most typical case.
3443 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3444 SourceLocation ColonColonLoc,
3445 ParsedType ObjectType = ParsedType())
3446 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
3447 CCLoc(ColonColonLoc) {}
3448
3449 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3450 SourceLocation ColonColonLoc, QualType ObjectType)
3451 : ObjectType(ParsedType::make(P: ObjectType)), Identifier(II),
3452 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3453 };
3454
3455 /// Build a new nested-name-specifier for "identifier::", as described
3456 /// by ActOnCXXNestedNameSpecifier.
3457 ///
3458 /// \param S Scope in which the nested-name-specifier occurs.
3459 /// \param IdInfo Parser information about an identifier in the
3460 /// nested-name-spec.
3461 /// \param EnteringContext If true, enter the context specified by the
3462 /// nested-name-specifier.
3463 /// \param SS Optional nested name specifier preceding the identifier.
3464 /// \param ScopeLookupResult Provides the result of name lookup within the
3465 /// scope of the nested-name-specifier that was computed at template
3466 /// definition time.
3467 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3468 /// error recovery and what kind of recovery is performed.
3469 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3470 /// are allowed. The bool value pointed by this parameter is set to
3471 /// 'true' if the identifier is treated as if it was followed by ':',
3472 /// not '::'.
3473 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3474 ///
3475 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3476 /// that it contains an extra parameter \p ScopeLookupResult, which provides
3477 /// the result of name lookup within the scope of the nested-name-specifier
3478 /// that was computed at template definition time.
3479 ///
3480 /// If ErrorRecoveryLookup is true, then this call is used to improve error
3481 /// recovery. This means that it should not emit diagnostics, it should
3482 /// just return true on failure. It also means it should only return a valid
3483 /// scope if it *knows* that the result is correct. It should not return in a
3484 /// dependent context, for example. Nor will it extend \p SS with the scope
3485 /// specifier.
3486 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3487 bool EnteringContext, CXXScopeSpec &SS,
3488 NamedDecl *ScopeLookupResult,
3489 bool ErrorRecoveryLookup,
3490 bool *IsCorrectedToColon = nullptr,
3491 bool OnlyNamespace = false);
3492
3493 /// The parser has parsed a nested-name-specifier 'identifier::'.
3494 ///
3495 /// \param S The scope in which this nested-name-specifier occurs.
3496 ///
3497 /// \param IdInfo Parser information about an identifier in the
3498 /// nested-name-spec.
3499 ///
3500 /// \param EnteringContext Whether we're entering the context nominated by
3501 /// this nested-name-specifier.
3502 ///
3503 /// \param SS The nested-name-specifier, which is both an input
3504 /// parameter (the nested-name-specifier before this type) and an
3505 /// output parameter (containing the full nested-name-specifier,
3506 /// including this new type).
3507 ///
3508 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3509 /// are allowed. The bool value pointed by this parameter is set to 'true'
3510 /// if the identifier is treated as if it was followed by ':', not '::'.
3511 ///
3512 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3513 ///
3514 /// \returns true if an error occurred, false otherwise.
3515 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3516 bool EnteringContext, CXXScopeSpec &SS,
3517 bool *IsCorrectedToColon = nullptr,
3518 bool OnlyNamespace = false);
3519
3520 /// The parser has parsed a nested-name-specifier
3521 /// 'template[opt] template-name < template-args >::'.
3522 ///
3523 /// \param S The scope in which this nested-name-specifier occurs.
3524 ///
3525 /// \param SS The nested-name-specifier, which is both an input
3526 /// parameter (the nested-name-specifier before this type) and an
3527 /// output parameter (containing the full nested-name-specifier,
3528 /// including this new type).
3529 ///
3530 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3531 /// \param TemplateName the template name.
3532 /// \param TemplateNameLoc The location of the template name.
3533 /// \param LAngleLoc The location of the opening angle bracket ('<').
3534 /// \param TemplateArgs The template arguments.
3535 /// \param RAngleLoc The location of the closing angle bracket ('>').
3536 /// \param CCLoc The location of the '::'.
3537 ///
3538 /// \param EnteringContext Whether we're entering the context of the
3539 /// nested-name-specifier.
3540 ///
3541 ///
3542 /// \returns true if an error occurred, false otherwise.
3543 bool ActOnCXXNestedNameSpecifier(
3544 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3545 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3546 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3547 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3548
3549 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS,
3550 SourceLocation ColonColonLoc);
3551
3552 ParsedType ActOnCXXNestedNameSpecifierIndexedPack(
3553 CXXScopeSpec &SS, const DeclSpec &DS, TypeSourceInfo *PatternLoc,
3554 SourceLocation ColonColonLoc, QualType Type);
3555
3556 /// IsInvalidUnlessNestedName - This method is used for error recovery
3557 /// purposes to determine whether the specified identifier is only valid as
3558 /// a nested name specifier, for example a namespace name. It is
3559 /// conservatively correct to always return false from this method.
3560 ///
3561 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3562 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3563 NestedNameSpecInfo &IdInfo,
3564 bool EnteringContext);
3565
3566 /// Given a C++ nested-name-specifier, produce an annotation value
3567 /// that the parser can use later to reconstruct the given
3568 /// nested-name-specifier.
3569 ///
3570 /// \param SS A nested-name-specifier.
3571 ///
3572 /// \returns A pointer containing all of the information in the
3573 /// nested-name-specifier \p SS.
3574 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3575
3576 /// Given an annotation pointer for a nested-name-specifier, restore
3577 /// the nested-name-specifier structure.
3578 ///
3579 /// \param Annotation The annotation pointer, produced by
3580 /// \c SaveNestedNameSpecifierAnnotation().
3581 ///
3582 /// \param AnnotationRange The source range corresponding to the annotation.
3583 ///
3584 /// \param SS The nested-name-specifier that will be updated with the contents
3585 /// of the annotation pointer.
3586 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3587 SourceRange AnnotationRange,
3588 CXXScopeSpec &SS);
3589
3590 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3591
3592 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3593 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3594 /// After this method is called, according to [C++ 3.4.3p3], names should be
3595 /// looked up in the declarator-id's scope, until the declarator is parsed and
3596 /// ActOnCXXExitDeclaratorScope is called.
3597 /// The 'SS' should be a non-empty valid CXXScopeSpec.
3598 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
3599
3600 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3601 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3602 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3603 /// Used to indicate that names should revert to being looked up in the
3604 /// defining scope.
3605 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3606
3607 ///@}
3608
3609 //
3610 //
3611 // -------------------------------------------------------------------------
3612 //
3613 //
3614
3615 /// \name Declarations
3616 /// Implementations are in SemaDecl.cpp
3617 ///@{
3618
3619public:
3620 IdentifierResolver IdResolver;
3621
3622 /// The index of the first InventedParameterInfo that refers to the current
3623 /// context.
3624 unsigned InventedParameterInfosStart = 0;
3625
3626 /// A RAII object to temporarily push a declaration context.
3627 class ContextRAII {
3628 private:
3629 Sema &S;
3630 DeclContext *SavedContext;
3631 ProcessingContextState SavedContextState;
3632 QualType SavedCXXThisTypeOverride;
3633 unsigned SavedFunctionScopesStart;
3634 unsigned SavedInventedParameterInfosStart;
3635
3636 public:
3637 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3638 : S(S), SavedContext(S.CurContext),
3639 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3640 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3641 SavedFunctionScopesStart(S.FunctionScopesStart),
3642 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3643 assert(ContextToPush && "pushing null context");
3644 S.CurContext = ContextToPush;
3645 if (NewThisContext)
3646 S.CXXThisTypeOverride = QualType();
3647 // Any saved FunctionScopes do not refer to this context.
3648 S.FunctionScopesStart = S.FunctionScopes.size();
3649 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3650 }
3651
3652 void pop() {
3653 if (!SavedContext)
3654 return;
3655 S.CurContext = SavedContext;
3656 S.DelayedDiagnostics.popUndelayed(state: SavedContextState);
3657 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3658 S.FunctionScopesStart = SavedFunctionScopesStart;
3659 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3660 SavedContext = nullptr;
3661 }
3662
3663 ~ContextRAII() { pop(); }
3664 ContextRAII(const ContextRAII &) = delete;
3665 ContextRAII &operator=(const ContextRAII &) = delete;
3666 };
3667
3668 void DiagnoseInvalidJumps(Stmt *Body);
3669
3670 /// The function definitions which were renamed as part of typo-correction
3671 /// to match their respective declarations. We want to keep track of them
3672 /// to ensure that we don't emit a "redefinition" error if we encounter a
3673 /// correctly named definition after the renamed definition.
3674 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
3675
3676 /// A cache of the flags available in enumerations with the flag_enum
3677 /// attribute.
3678 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3679
3680 /// A cache of enumerator values for enums checked by -Wassign-enum.
3681 llvm::DenseMap<const EnumDecl *, llvm::SmallVector<llvm::APSInt>>
3682 AssignEnumCache;
3683
3684 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3685 /// declared. Rare. May alias another identifier, declared or undeclared.
3686 ///
3687 /// For aliases, the target identifier is used as a key for eventual
3688 /// processing when the target is declared. For the single-identifier form,
3689 /// the sole identifier is used as the key. Each entry is a `SetVector`
3690 /// (ordered by parse order) of aliases (identified by the alias name) in case
3691 /// of multiple aliases to the same undeclared identifier.
3692 llvm::MapVector<
3693 IdentifierInfo *,
3694 llvm::SetVector<
3695 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
3696 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3697 WeakUndeclaredIdentifiers;
3698
3699 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3700 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3701 /// to define functions that occur in multiple standards to call the version
3702 /// in the currently selected standard.
3703 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>
3704 ExtnameUndeclaredIdentifiers;
3705
3706 /// Set containing all typedefs that are likely unused.
3707 llvm::SmallPtrSet<const TypedefNameDecl *, 4>
3708 UnusedLocalTypedefNameCandidates;
3709
3710 /// Store UnusedLocalTypedefNameCandidates in \p Sorted in a deterministic
3711 /// order.
3712 void getSortedUnusedLocalTypedefNameCandidates(
3713 SmallVectorImpl<const TypedefNameDecl *> &Sorted) const;
3714
3715 typedef LazyVector<const DeclaratorDecl *,
3716 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
3717 UnusedFileScopedDeclsType;
3718
3719 /// The set of file scoped decls seen so far that have not been used
3720 /// and must warn if not used. Only contains the first declaration.
3721 UnusedFileScopedDeclsType UnusedFileScopedDecls;
3722
3723 typedef LazyVector<VarDecl *, &ExternalSemaSource::ReadTentativeDefinitions,
3724 2, 2>
3725 TentativeDefinitionsType;
3726
3727 /// All the tentative definitions encountered in the TU.
3728 TentativeDefinitionsType TentativeDefinitions;
3729
3730 /// All the external declarations encoutered and used in the TU.
3731 SmallVector<DeclaratorDecl *, 4> ExternalDeclarations;
3732
3733 /// Generally null except when we temporarily switch decl contexts,
3734 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3735 DeclContext *OriginalLexicalContext;
3736
3737 /// Is the module scope we are in a C++ Header Unit?
3738 bool currentModuleIsHeaderUnit() const {
3739 return ModuleScopes.empty() ? false
3740 : ModuleScopes.back().Module->isHeaderUnit();
3741 }
3742
3743 /// Get the module owning an entity.
3744 Module *getOwningModule(const Decl *Entity) {
3745 return Entity->getOwningModule();
3746 }
3747
3748 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3749
3750 enum class DiagCtorKind { None, Implicit, Typename };
3751 /// Returns the TypeDeclType for the given type declaration,
3752 /// as ASTContext::getTypeDeclType would, but
3753 /// performs the required semantic checks for name lookup of said entity.
3754 void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD,
3755 SourceLocation NameLoc);
3756
3757 /// If the identifier refers to a type name within this scope,
3758 /// return the declaration of that type.
3759 ///
3760 /// This routine performs ordinary name lookup of the identifier II
3761 /// within the given scope, with optional C++ scope specifier SS, to
3762 /// determine whether the name refers to a type. If so, returns an
3763 /// opaque pointer (actually a QualType) corresponding to that
3764 /// type. Otherwise, returns NULL.
3765 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
3766 Scope *S, CXXScopeSpec *SS = nullptr,
3767 bool isClassName = false, bool HasTrailingDot = false,
3768 ParsedType ObjectType = nullptr,
3769 bool IsCtorOrDtorName = false,
3770 bool WantNontrivialTypeSourceInfo = false,
3771 bool IsClassTemplateDeductionContext = true,
3772 ImplicitTypenameContext AllowImplicitTypename =
3773 ImplicitTypenameContext::No,
3774 IdentifierInfo **CorrectedII = nullptr);
3775
3776 /// isTagName() - This method is called *for error recovery purposes only*
3777 /// to determine if the specified name is a valid tag name ("struct foo"). If
3778 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3779 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3780 /// diagnose cases in C where the user forgot to specify the tag.
3781 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
3782
3783 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3784 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3785 /// then downgrade the missing typename error to a warning.
3786 /// This is needed for MSVC compatibility; Example:
3787 /// @code
3788 /// template<class T> class A {
3789 /// public:
3790 /// typedef int TYPE;
3791 /// };
3792 /// template<class T> class B : public A<T> {
3793 /// public:
3794 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3795 /// };
3796 /// @endcode
3797 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3798 void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc,
3799 Scope *S, CXXScopeSpec *SS,
3800 ParsedType &SuggestedType,
3801 bool IsTemplateName = false);
3802
3803 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3804 /// type name has failed in a dependent context. In these situations, we
3805 /// automatically form a DependentTypeName that will retry lookup in a related
3806 /// scope during instantiation.
3807 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
3808 SourceLocation NameLoc,
3809 bool IsTemplateTypeArg);
3810
3811 class NameClassification {
3812 NameClassificationKind Kind;
3813 union {
3814 ExprResult Expr;
3815 NamedDecl *NonTypeDecl;
3816 TemplateName Template;
3817 ParsedType Type;
3818 };
3819
3820 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3821
3822 public:
3823 NameClassification(ParsedType Type)
3824 : Kind(NameClassificationKind::Type), Type(Type) {}
3825
3826 NameClassification(const IdentifierInfo *Keyword)
3827 : Kind(NameClassificationKind::Keyword) {}
3828
3829 static NameClassification Error() {
3830 return NameClassification(NameClassificationKind::Error);
3831 }
3832
3833 static NameClassification Unknown() {
3834 return NameClassification(NameClassificationKind::Unknown);
3835 }
3836
3837 static NameClassification OverloadSet(ExprResult E) {
3838 NameClassification Result(NameClassificationKind::OverloadSet);
3839 Result.Expr = E;
3840 return Result;
3841 }
3842
3843 static NameClassification NonType(NamedDecl *D) {
3844 NameClassification Result(NameClassificationKind::NonType);
3845 Result.NonTypeDecl = D;
3846 return Result;
3847 }
3848
3849 static NameClassification UndeclaredNonType() {
3850 return NameClassification(NameClassificationKind::UndeclaredNonType);
3851 }
3852
3853 static NameClassification DependentNonType() {
3854 return NameClassification(NameClassificationKind::DependentNonType);
3855 }
3856
3857 static NameClassification TypeTemplate(TemplateName Name) {
3858 NameClassification Result(NameClassificationKind::TypeTemplate);
3859 Result.Template = Name;
3860 return Result;
3861 }
3862
3863 static NameClassification VarTemplate(TemplateName Name) {
3864 NameClassification Result(NameClassificationKind::VarTemplate);
3865 Result.Template = Name;
3866 return Result;
3867 }
3868
3869 static NameClassification FunctionTemplate(TemplateName Name) {
3870 NameClassification Result(NameClassificationKind::FunctionTemplate);
3871 Result.Template = Name;
3872 return Result;
3873 }
3874
3875 static NameClassification Concept(TemplateName Name) {
3876 NameClassification Result(NameClassificationKind::Concept);
3877 Result.Template = Name;
3878 return Result;
3879 }
3880
3881 static NameClassification UndeclaredTemplate(TemplateName Name) {
3882 NameClassification Result(NameClassificationKind::UndeclaredTemplate);
3883 Result.Template = Name;
3884 return Result;
3885 }
3886
3887 NameClassificationKind getKind() const { return Kind; }
3888
3889 ExprResult getExpression() const {
3890 assert(Kind == NameClassificationKind::OverloadSet);
3891 return Expr;
3892 }
3893
3894 ParsedType getType() const {
3895 assert(Kind == NameClassificationKind::Type);
3896 return Type;
3897 }
3898
3899 NamedDecl *getNonTypeDecl() const {
3900 assert(Kind == NameClassificationKind::NonType);
3901 return NonTypeDecl;
3902 }
3903
3904 TemplateName getTemplateName() const {
3905 assert(Kind == NameClassificationKind::TypeTemplate ||
3906 Kind == NameClassificationKind::FunctionTemplate ||
3907 Kind == NameClassificationKind::VarTemplate ||
3908 Kind == NameClassificationKind::Concept ||
3909 Kind == NameClassificationKind::UndeclaredTemplate);
3910 return Template;
3911 }
3912
3913 TemplateNameKind getTemplateNameKind() const {
3914 switch (Kind) {
3915 case NameClassificationKind::TypeTemplate:
3916 return TNK_Type_template;
3917 case NameClassificationKind::FunctionTemplate:
3918 return TNK_Function_template;
3919 case NameClassificationKind::VarTemplate:
3920 return TNK_Var_template;
3921 case NameClassificationKind::Concept:
3922 return TNK_Concept_template;
3923 case NameClassificationKind::UndeclaredTemplate:
3924 return TNK_Undeclared_template;
3925 default:
3926 llvm_unreachable("unsupported name classification.");
3927 }
3928 }
3929 };
3930
3931 /// Perform name lookup on the given name, classifying it based on
3932 /// the results of name lookup and the following token.
3933 ///
3934 /// This routine is used by the parser to resolve identifiers and help direct
3935 /// parsing. When the identifier cannot be found, this routine will attempt
3936 /// to correct the typo and classify based on the resulting name.
3937 ///
3938 /// \param S The scope in which we're performing name lookup.
3939 ///
3940 /// \param SS The nested-name-specifier that precedes the name.
3941 ///
3942 /// \param Name The identifier. If typo correction finds an alternative name,
3943 /// this pointer parameter will be updated accordingly.
3944 ///
3945 /// \param NameLoc The location of the identifier.
3946 ///
3947 /// \param NextToken The token following the identifier. Used to help
3948 /// disambiguate the name.
3949 ///
3950 /// \param CCC The correction callback, if typo correction is desired.
3951 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3952 IdentifierInfo *&Name, SourceLocation NameLoc,
3953 const Token &NextToken,
3954 CorrectionCandidateCallback *CCC = nullptr);
3955
3956 /// Act on the result of classifying a name as an undeclared (ADL-only)
3957 /// non-type declaration.
3958 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
3959 SourceLocation NameLoc);
3960 /// Act on the result of classifying a name as an undeclared member of a
3961 /// dependent base class.
3962 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
3963 IdentifierInfo *Name,
3964 SourceLocation NameLoc,
3965 bool IsAddressOfOperand);
3966 /// Act on the result of classifying a name as a specific non-type
3967 /// declaration.
3968 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
3969 NamedDecl *Found,
3970 SourceLocation NameLoc,
3971 const Token &NextToken);
3972 /// Act on the result of classifying a name as an overload set.
3973 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
3974
3975 /// Describes the detailed kind of a template name. Used in diagnostics.
3976 enum class TemplateNameKindForDiagnostics {
3977 ClassTemplate,
3978 FunctionTemplate,
3979 VarTemplate,
3980 AliasTemplate,
3981 TemplateTemplateParam,
3982 Concept,
3983 DependentTemplate
3984 };
3985 TemplateNameKindForDiagnostics
3986 getTemplateNameKindForDiagnostics(TemplateName Name);
3987
3988 /// Determine whether it's plausible that E was intended to be a
3989 /// template-name.
3990 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
3991 if (!getLangOpts().CPlusPlus || E.isInvalid())
3992 return false;
3993 Dependent = false;
3994 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E.get()))
3995 return !DRE->hasExplicitTemplateArgs();
3996 if (auto *ME = dyn_cast<MemberExpr>(Val: E.get()))
3997 return !ME->hasExplicitTemplateArgs();
3998 Dependent = true;
3999 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(Val: E.get()))
4000 return !DSDRE->hasExplicitTemplateArgs();
4001 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(Val: E.get()))
4002 return !DSME->hasExplicitTemplateArgs();
4003 // Any additional cases recognized here should also be handled by
4004 // diagnoseExprIntendedAsTemplateName.
4005 return false;
4006 }
4007
4008 void warnOnReservedIdentifier(const NamedDecl *D);
4009 void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D);
4010
4011 void ProcessPragmaExport(DeclaratorDecl *newDecl);
4012
4013 Decl *ActOnDeclarator(Scope *S, Declarator &D);
4014
4015 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
4016 MultiTemplateParamsArg TemplateParameterLists);
4017
4018 /// Attempt to fold a variable-sized type to a constant-sized type, returning
4019 /// true if we were successful.
4020 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T,
4021 SourceLocation Loc,
4022 unsigned FailedFoldDiagID);
4023
4024 /// Register the given locally-scoped extern "C" declaration so
4025 /// that it can be found later for redeclarations. We include any extern "C"
4026 /// declaration that is not visible in the translation unit here, not just
4027 /// function-scope declarations.
4028 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
4029
4030 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4031 /// If T is the name of a class, then each of the following shall have a
4032 /// name different from T:
4033 /// - every static data member of class T;
4034 /// - every member function of class T
4035 /// - every member of class T that is itself a type;
4036 /// \returns true if the declaration name violates these rules.
4037 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
4038
4039 /// Diagnose a declaration whose declarator-id has the given
4040 /// nested-name-specifier.
4041 ///
4042 /// \param SS The nested-name-specifier of the declarator-id.
4043 ///
4044 /// \param DC The declaration context to which the nested-name-specifier
4045 /// resolves.
4046 ///
4047 /// \param Name The name of the entity being declared.
4048 ///
4049 /// \param Loc The location of the name of the entity being declared.
4050 ///
4051 /// \param IsMemberSpecialization Whether we are declaring a member
4052 /// specialization.
4053 ///
4054 /// \param TemplateId The template-id, if any.
4055 ///
4056 /// \returns true if we cannot safely recover from this error, false
4057 /// otherwise.
4058 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4059 DeclarationName Name, SourceLocation Loc,
4060 TemplateIdAnnotation *TemplateId,
4061 bool IsMemberSpecialization);
4062
4063 bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range);
4064
4065 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
4066
4067 bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind,
4068 unsigned &IntVal);
4069
4070 /// Diagnose function specifiers on a declaration of an identifier that
4071 /// does not identify a function.
4072 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
4073
4074 /// Return the declaration shadowed by the given typedef \p D, or null
4075 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
4076 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
4077 const LookupResult &R);
4078
4079 /// Return the declaration shadowed by the given variable \p D, or null
4080 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
4081 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
4082
4083 /// Return the declaration shadowed by the given variable \p D, or null
4084 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
4085 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
4086 const LookupResult &R);
4087 /// Diagnose variable or built-in function shadowing. Implements
4088 /// -Wshadow.
4089 ///
4090 /// This method is called whenever a VarDecl is added to a "useful"
4091 /// scope.
4092 ///
4093 /// \param ShadowedDecl the declaration that is shadowed by the given variable
4094 /// \param R the lookup of the name
4095 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
4096 const LookupResult &R);
4097
4098 /// Check -Wshadow without the advantage of a previous lookup.
4099 void CheckShadow(Scope *S, VarDecl *D);
4100
4101 /// Warn if 'E', which is an expression that is about to be modified, refers
4102 /// to a shadowing declaration.
4103 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
4104
4105 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
4106 /// when these variables are captured by the lambda.
4107 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
4108
4109 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
4110 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4111 TypedefNameDecl *NewTD);
4112 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
4113 NamedDecl *ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4114 TypeSourceInfo *TInfo,
4115 LookupResult &Previous);
4116
4117 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4118 /// declares a typedef-name, either using the 'typedef' type specifier or via
4119 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4120 NamedDecl *ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D,
4121 LookupResult &Previous, bool &Redeclaration);
4122 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4123 TypeSourceInfo *TInfo,
4124 LookupResult &Previous,
4125 MultiTemplateParamsArg TemplateParamLists,
4126 bool &AddToScope,
4127 ArrayRef<BindingDecl *> Bindings = {});
4128
4129private:
4130 // Perform a check on an AsmLabel to verify its consistency and emit
4131 // diagnostics in case of an error.
4132 void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
4133 TypeSourceInfo *TInfo, VarDecl *);
4134
4135public:
4136 /// Perform semantic checking on a newly-created variable
4137 /// declaration.
4138 ///
4139 /// This routine performs all of the type-checking required for a
4140 /// variable declaration once it has been built. It is used both to
4141 /// check variables after they have been parsed and their declarators
4142 /// have been translated into a declaration, and to check variables
4143 /// that have been instantiated from a template.
4144 ///
4145 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4146 ///
4147 /// Returns true if the variable declaration is a redeclaration.
4148 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
4149 void CheckVariableDeclarationType(VarDecl *NewVD);
4150 void CheckCompleteVariableDeclaration(VarDecl *VD);
4151
4152 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4153 TypeSourceInfo *TInfo,
4154 LookupResult &Previous,
4155 MultiTemplateParamsArg TemplateParamLists,
4156 bool &AddToScope);
4157
4158 /// Attach the ABI tag a standard calling convention variant requires, as an
4159 /// implicit abi_tag attribute. Call this once the function type is final.
4160 void addImplicitCallingConvAbiTag(FunctionDecl *FD);
4161
4162 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4163 /// and if so, check that it's a valid override and remember it.
4164 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
4165
4166 /// Perform semantic checking of a new function declaration.
4167 ///
4168 /// Performs semantic analysis of the new function declaration
4169 /// NewFD. This routine performs all semantic checking that does not
4170 /// require the actual declarator involved in the declaration, and is
4171 /// used both for the declaration of functions as they are parsed
4172 /// (called via ActOnDeclarator) and for the declaration of functions
4173 /// that have been instantiated via C++ template instantiation (called
4174 /// via InstantiateDecl).
4175 ///
4176 /// \param IsMemberSpecialization whether this new function declaration is
4177 /// a member specialization (that replaces any definition provided by the
4178 /// previous declaration).
4179 ///
4180 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4181 ///
4182 /// \returns true if the function declaration is a redeclaration.
4183 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4184 LookupResult &Previous,
4185 bool IsMemberSpecialization, bool DeclIsDefn);
4186
4187 /// Checks if the new declaration declared in dependent context must be
4188 /// put in the same redeclaration chain as the specified declaration.
4189 ///
4190 /// \param D Declaration that is checked.
4191 /// \param PrevDecl Previous declaration found with proper lookup method for
4192 /// the same declaration name.
4193 /// \returns True if D must be added to the redeclaration chain which PrevDecl
4194 /// belongs to.
4195 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4196
4197 /// Determines if we can perform a correct type check for \p D as a
4198 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4199 /// best-effort check.
4200 ///
4201 /// \param NewD The new declaration.
4202 /// \param OldD The old declaration.
4203 /// \param NewT The portion of the type of the new declaration to check.
4204 /// \param OldT The portion of the type of the old declaration to check.
4205 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4206 QualType NewT, QualType OldT);
4207 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4208 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4209
4210 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4211 /// containing class. Otherwise it will return implicit SectionAttr if the
4212 /// function is a definition and there is an active value on CodeSegStack
4213 /// (from the current #pragma code-seg value).
4214 ///
4215 /// \param FD Function being declared.
4216 /// \param IsDefinition Whether it is a definition or just a declaration.
4217 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4218 /// nullptr if no attribute should be added.
4219 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4220 bool IsDefinition);
4221
4222 /// Common checks for a parameter-declaration that should apply to both
4223 /// function parameters and non-type template parameters.
4224 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4225
4226 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4227 /// to introduce parameters into function prototype scope.
4228 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4229 SourceLocation ExplicitThisLoc = {});
4230
4231 /// Synthesizes a variable for a parameter arising from a
4232 /// typedef.
4233 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4234 QualType T);
4235 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4236 SourceLocation NameLoc,
4237 const IdentifierInfo *Name, QualType T,
4238 TypeSourceInfo *TSInfo, StorageClass SC);
4239
4240 /// Emit diagnostics if the initializer or any of its explicit or
4241 /// implicitly-generated subexpressions require copying or
4242 /// default-initializing a type that is or contains a C union type that is
4243 /// non-trivial to copy or default-initialize.
4244 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4245
4246 // These flags are passed to checkNonTrivialCUnion.
4247 enum NonTrivialCUnionKind {
4248 NTCUK_Init = 0x1,
4249 NTCUK_Destruct = 0x2,
4250 NTCUK_Copy = 0x4,
4251 };
4252
4253 /// Emit diagnostics if a non-trivial C union type or a struct that contains
4254 /// a non-trivial C union is used in an invalid context.
4255 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
4256 NonTrivialCUnionContext UseContext,
4257 unsigned NonTrivialKind);
4258
4259 /// Certain globally-unique variables might be accidentally duplicated if
4260 /// built into multiple shared libraries with hidden visibility. This can
4261 /// cause problems if the variable is mutable, its initialization is
4262 /// effectful, or its address is taken.
4263 bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl);
4264 void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl);
4265
4266 /// AddInitializerToDecl - Adds the initializer Init to the
4267 /// declaration dcl. If DirectInit is true, this is C++ direct
4268 /// initialization rather than copy initialization.
4269 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4270 void ActOnUninitializedDecl(Decl *dcl);
4271
4272 /// ActOnInitializerError - Given that there was an error parsing an
4273 /// initializer for the given declaration, try to at least re-establish
4274 /// invariants such as whether a variable's type is either dependent or
4275 /// complete.
4276 void ActOnInitializerError(Decl *Dcl);
4277
4278 void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt);
4279 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
4280 IdentifierInfo *Ident,
4281 ParsedAttributes &Attrs);
4282
4283 /// Check if VD needs to be dllexport/dllimport due to being in a
4284 /// dllexport/import function.
4285 void CheckStaticLocalForDllExport(VarDecl *VD);
4286 void CheckThreadLocalForLargeAlignment(VarDecl *VD);
4287
4288 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4289 /// any semantic actions necessary after any initializer has been attached.
4290 void FinalizeDeclaration(Decl *D);
4291 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4292 ArrayRef<Decl *> Group);
4293
4294 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4295 /// group, performing any necessary semantic checking.
4296 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
4297
4298 /// Should be called on all declarations that might have attached
4299 /// documentation comments.
4300 void ActOnDocumentableDecl(Decl *D);
4301 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
4302
4303 enum class FnBodyKind {
4304 /// C++26 [dcl.fct.def.general]p1
4305 /// function-body:
4306 /// ctor-initializer[opt] compound-statement
4307 /// function-try-block
4308 Other,
4309 /// = default ;
4310 Default,
4311 /// deleted-function-body
4312 ///
4313 /// deleted-function-body:
4314 /// = delete ;
4315 /// = delete ( unevaluated-string ) ;
4316 Delete
4317 };
4318
4319 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4320 SourceLocation LocAfterDecls);
4321 void CheckForFunctionRedefinition(
4322 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4323 SkipBodyInfo *SkipBody = nullptr);
4324 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
4325 MultiTemplateParamsArg TemplateParamLists,
4326 SkipBodyInfo *SkipBody = nullptr,
4327 FnBodyKind BodyKind = FnBodyKind::Other);
4328 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
4329 SkipBodyInfo *SkipBody = nullptr,
4330 FnBodyKind BodyKind = FnBodyKind::Other);
4331 void applyFunctionAttributesBeforeParsingBody(Decl *FD);
4332
4333 /// Determine whether we can delay parsing the body of a function or
4334 /// function template until it is used, assuming we don't care about emitting
4335 /// code for that function.
4336 ///
4337 /// This will be \c false if we may need the body of the function in the
4338 /// middle of parsing an expression (where it's impractical to switch to
4339 /// parsing a different function), for instance, if it's constexpr in C++11
4340 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4341 bool canDelayFunctionBody(const Declarator &D);
4342
4343 /// Determine whether we can skip parsing the body of a function
4344 /// definition, assuming we don't care about analyzing its body or emitting
4345 /// code for that function.
4346 ///
4347 /// This will be \c false only if we may need the body of the function in
4348 /// order to parse the rest of the program (for instance, if it is
4349 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4350 bool canSkipFunctionBody(Decl *D);
4351
4352 /// Given the set of return statements within a function body,
4353 /// compute the variables that are subject to the named return value
4354 /// optimization.
4355 ///
4356 /// Each of the variables that is subject to the named return value
4357 /// optimization will be marked as NRVO variables in the AST, and any
4358 /// return statement that has a marked NRVO variable as its NRVO candidate can
4359 /// use the named return value optimization.
4360 ///
4361 /// This function applies a very simplistic algorithm for NRVO: if every
4362 /// return statement in the scope of a variable has the same NRVO candidate,
4363 /// that candidate is an NRVO variable.
4364 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
4365
4366 /// Performs semantic analysis at the end of a function body.
4367 ///
4368 /// \param RetainFunctionScopeInfo If \c true, the client is responsible for
4369 /// releasing the associated \p FunctionScopeInfo. This is useful when
4370 /// building e.g. LambdaExprs.
4371 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body,
4372 bool IsInstantiation = false,
4373 bool RetainFunctionScopeInfo = false);
4374 Decl *ActOnSkippedFunctionBody(Decl *Decl);
4375 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
4376
4377 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4378 /// attribute for which parsing is delayed.
4379 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
4380
4381 /// Diagnose any unused parameters in the given sequence of
4382 /// ParmVarDecl pointers.
4383 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
4384
4385 /// Diagnose whether the size of parameters or return value of a
4386 /// function or obj-c method definition is pass-by-value and larger than a
4387 /// specified threshold.
4388 void
4389 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
4390 QualType ReturnTy, NamedDecl *D);
4391
4392 Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc,
4393 SourceLocation RParenLoc);
4394
4395 TopLevelStmtDecl *ActOnStartTopLevelStmtDecl(Scope *S);
4396 void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement);
4397
4398 void ActOnPopScope(SourceLocation Loc, Scope *S);
4399
4400 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4401 /// no declarator (e.g. "struct foo;") is parsed.
4402 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4403 const ParsedAttributesView &DeclAttrs,
4404 RecordDecl *&AnonRecord);
4405
4406 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4407 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4408 /// parameters to cope with template friend declarations.
4409 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4410 const ParsedAttributesView &DeclAttrs,
4411 MultiTemplateParamsArg TemplateParams,
4412 bool IsExplicitInstantiation,
4413 RecordDecl *&AnonRecord,
4414 SourceLocation EllipsisLoc = {});
4415
4416 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4417 /// anonymous structure or union. Anonymous unions are a C++ feature
4418 /// (C++ [class.union]) and a C11 feature; anonymous structures
4419 /// are a C11 feature and GNU C++ extension.
4420 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4421 RecordDecl *Record,
4422 const PrintingPolicy &Policy);
4423
4424 /// Called once it is known whether
4425 /// a tag declaration is an anonymous union or struct.
4426 void ActOnDefinedDeclarationSpecifier(Decl *D);
4427
4428 /// Emit diagnostic warnings for placeholder members.
4429 /// We can only do that after the class is fully constructed,
4430 /// as anonymous union/structs can insert placeholders
4431 /// in their parent scope (which might be a Record).
4432 void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record);
4433
4434 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4435 /// Microsoft C anonymous structure.
4436 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4437 /// Example:
4438 ///
4439 /// struct A { int a; };
4440 /// struct B { struct A; int b; };
4441 ///
4442 /// void foo() {
4443 /// B var;
4444 /// var.a = 3;
4445 /// }
4446 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4447 RecordDecl *Record);
4448
4449 /// Given a non-tag type declaration, returns an enum useful for indicating
4450 /// what kind of non-tag type this is.
4451 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4452
4453 /// Determine whether a tag with a given kind is acceptable
4454 /// as a redeclaration of the given tag declaration.
4455 ///
4456 /// \returns true if the new tag kind is acceptable, false otherwise.
4457 bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag,
4458 bool isDefinition, SourceLocation NewTagLoc,
4459 const IdentifierInfo *Name);
4460
4461 /// This is invoked when we see 'struct foo' or 'struct {'. In the
4462 /// former case, Name will be non-null. In the later case, Name will be null.
4463 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4464 /// a reference/declaration/definition of a tag.
4465 ///
4466 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4467 /// trailing-type-specifier) other than one in an alias-declaration.
4468 ///
4469 /// \param SkipBody If non-null, will be set to indicate if the caller should
4470 /// skip the definition of this tag and treat it as if it were a declaration.
4471 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4472 SourceLocation KWLoc, CXXScopeSpec &SS,
4473 IdentifierInfo *Name, SourceLocation NameLoc,
4474 const ParsedAttributesView &Attr, AccessSpecifier AS,
4475 SourceLocation ModulePrivateLoc,
4476 MultiTemplateParamsArg TemplateParameterLists,
4477 bool &OwnedDecl, bool &IsDependent,
4478 SourceLocation ScopedEnumKWLoc,
4479 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4480 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4481 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4482
4483 /// ActOnField - Each field of a C struct/union is passed into this in order
4484 /// to create a FieldDecl object for it.
4485 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4486 Declarator &D, Expr *BitfieldWidth);
4487
4488 /// HandleField - Analyze a field of a C struct or a C++ data member.
4489 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4490 Declarator &D, Expr *BitfieldWidth,
4491 InClassInitStyle InitStyle, AccessSpecifier AS);
4492
4493 /// Build a new FieldDecl and check its well-formedness.
4494 ///
4495 /// This routine builds a new FieldDecl given the fields name, type,
4496 /// record, etc. \p PrevDecl should refer to any previous declaration
4497 /// with the same name and in the same scope as the field to be
4498 /// created.
4499 ///
4500 /// \returns a new FieldDecl.
4501 ///
4502 /// \todo The Declarator argument is a hack. It will be removed once
4503 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4504 TypeSourceInfo *TInfo, RecordDecl *Record,
4505 SourceLocation Loc, bool Mutable,
4506 Expr *BitfieldWidth, InClassInitStyle InitStyle,
4507 SourceLocation TSSL, AccessSpecifier AS,
4508 NamedDecl *PrevDecl, Declarator *D = nullptr);
4509
4510 bool CheckNontrivialField(FieldDecl *FD);
4511
4512 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4513 /// class and class extensions. For every class \@interface and class
4514 /// extension \@interface, if the last ivar is a bitfield of any type,
4515 /// then add an implicit `char :0` ivar to the end of that interface.
4516 void ActOnLastBitfield(SourceLocation DeclStart,
4517 SmallVectorImpl<Decl *> &AllIvarDecls);
4518
4519 // This is used for both record definitions and ObjC interface declarations.
4520 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4521 ArrayRef<Decl *> Fields, SourceLocation LBrac,
4522 SourceLocation RBrac, const ParsedAttributesView &AttrList);
4523
4524 /// ActOnTagStartDefinition - Invoked when we have entered the
4525 /// scope of a tag's definition (e.g., for an enumeration, class,
4526 /// struct, or union).
4527 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4528
4529 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4530 /// Differently from C++, actually parse the body and reject / error out
4531 /// in case of a structural mismatch.
4532 bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4533
4534 typedef void *SkippedDefinitionContext;
4535
4536 /// Invoked when we enter a tag definition that we're skipping.
4537 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
4538
4539 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4540 /// C++ record definition's base-specifiers clause and are starting its
4541 /// member declarations.
4542 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
4543 SourceLocation FinalLoc,
4544 bool IsFinalSpelledSealed,
4545 bool IsAbstract,
4546 SourceLocation LBraceLoc);
4547
4548 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4549 /// the definition of a tag (enumeration, class, struct, or union).
4550 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
4551 SourceRange BraceRange);
4552
4553 ASTContext::CXXRecordDeclRelocationInfo
4554 CheckCXX2CRelocatable(const clang::CXXRecordDecl *D);
4555
4556 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
4557
4558 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4559 /// error parsing the definition of a tag.
4560 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
4561
4562 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
4563 EnumConstantDecl *LastEnumConst,
4564 SourceLocation IdLoc, IdentifierInfo *Id,
4565 Expr *val);
4566
4567 /// Check that this is a valid underlying type for an enum declaration.
4568 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
4569
4570 /// Check whether this is a valid redeclaration of a previous enumeration.
4571 /// \return true if the redeclaration was invalid.
4572 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4573 QualType EnumUnderlyingTy, bool IsFixed,
4574 const EnumDecl *Prev);
4575
4576 /// Determine whether the body of an anonymous enumeration should be skipped.
4577 /// \param II The name of the first enumerator.
4578 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
4579 SourceLocation IILoc);
4580
4581 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4582 SourceLocation IdLoc, IdentifierInfo *Id,
4583 const ParsedAttributesView &Attrs,
4584 SourceLocation EqualLoc, Expr *Val,
4585 SkipBodyInfo *SkipBody = nullptr);
4586 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4587 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4588 const ParsedAttributesView &Attr);
4589
4590 /// Set the current declaration context until it gets popped.
4591 void PushDeclContext(Scope *S, DeclContext *DC);
4592 void PopDeclContext();
4593
4594 /// EnterDeclaratorContext - Used when we must lookup names in the context
4595 /// of a declarator's nested name specifier.
4596 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
4597 void ExitDeclaratorContext(Scope *S);
4598
4599 /// Enter a template parameter scope, after it's been associated with a
4600 /// particular DeclContext. Causes lookup within the scope to chain through
4601 /// enclosing contexts in the correct order.
4602 void EnterTemplatedContext(Scope *S, DeclContext *DC);
4603
4604 /// Push the parameters of D, which must be a function, into scope.
4605 void ActOnReenterFunctionContext(Scope *S, Decl *D);
4606
4607 /// Add \p Params to scope, so a late-parsed attribute can name them.
4608 void ActOnReenterFunctionPrototypeParams(Scope *S,
4609 ArrayRef<ParmVarDecl *> Params);
4610 /// Undo the above, for when \p S outlives the attribute so no scope pop
4611 /// removes them.
4612 void ActOnExitFunctionPrototypeParams(Scope *S,
4613 ArrayRef<ParmVarDecl *> Params);
4614 void ActOnExitFunctionContext();
4615
4616 /// Add this decl to the scope shadowed decl chains.
4617 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4618
4619 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4620 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4621 /// true if 'D' belongs to the given declaration context.
4622 ///
4623 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4624 /// enclosing namespace set of the context, rather than contained
4625 /// directly within it.
4626 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4627 bool AllowInlineNamespace = false) const;
4628
4629 /// Determine whether a tag-like declaration found by lookup can be
4630 /// redeclared in the given scope. If lookup found a using-shadow, also
4631 /// consider the scope of the declaration named by the using-shadow.
4632 bool isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx,
4633 Scope *S = nullptr,
4634 bool AllowInlineNamespace = false) const;
4635
4636 /// Finds the scope corresponding to the given decl context, if it
4637 /// happens to be an enclosing scope. Otherwise return NULL.
4638 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
4639
4640 /// Subroutines of ActOnDeclarator().
4641 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4642 TypeSourceInfo *TInfo);
4643 bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New);
4644
4645 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4646 void mergeDeclAttributes(
4647 NamedDecl *New, Decl *Old,
4648 AvailabilityMergeKind AMK = AvailabilityMergeKind::Redeclaration);
4649
4650 /// CheckAttributesOnDeducedType - Calls Sema functions for attributes that
4651 /// requires the type to be deduced.
4652 void CheckAttributesOnDeducedType(Decl *D);
4653
4654 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4655 /// same name and scope as a previous declaration 'Old'. Figure out
4656 /// how to resolve this situation, merging decls or emitting
4657 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4658 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
4659 LookupResult &OldDecls);
4660
4661 /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4662 /// definition visible.
4663 /// This method performs any necessary cleanup on the parser state to discard
4664 /// child nodes from newly parsed decl we are retiring.
4665 void CleanupMergedEnum(Scope *S, Decl *New);
4666
4667 /// MergeFunctionDecl - We just parsed a function 'New' from
4668 /// declarator D which has the same name and scope as a previous
4669 /// declaration 'Old'. Figure out how to resolve this situation,
4670 /// merging decls or emitting diagnostics as appropriate.
4671 ///
4672 /// In C++, New and Old must be declarations that are not
4673 /// overloaded. Use IsOverload to determine whether New and Old are
4674 /// overloaded, and to select the Old declaration that New should be
4675 /// merged with.
4676 ///
4677 /// Returns true if there was an error, false otherwise.
4678 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
4679 bool MergeTypeWithOld, bool NewDeclIsDefn);
4680
4681 /// Completes the merge of two function declarations that are
4682 /// known to be compatible.
4683 ///
4684 /// This routine handles the merging of attributes and other
4685 /// properties of function declarations from the old declaration to
4686 /// the new declaration, once we know that New is in fact a
4687 /// redeclaration of Old.
4688 ///
4689 /// \returns false
4690 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4691 Scope *S, bool MergeTypeWithOld);
4692 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
4693
4694 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4695 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4696 /// situation, merging decls or emitting diagnostics as appropriate.
4697 ///
4698 /// Tentative definition rules (C99 6.9.2p2) are checked by
4699 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4700 /// definitions here, since the initializer hasn't been attached.
4701 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
4702
4703 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4704 /// scope as a previous declaration 'Old'. Figure out how to merge their
4705 /// types, emitting diagnostics as appropriate.
4706 ///
4707 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4708 /// back to here in AddInitializerToDecl. We can't check them before the
4709 /// initializer is attached.
4710 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4711
4712 /// We've just determined that \p Old and \p New both appear to be definitions
4713 /// of the same variable. Either diagnose or fix the problem.
4714 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4715 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
4716
4717 /// Filters out lookup results that don't fall within the given scope
4718 /// as determined by isDeclInScope.
4719 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4720 bool ConsiderLinkage, bool AllowInlineNamespace);
4721
4722 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4723 /// have compatible owning modules.
4724 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4725
4726 /// [module.interface]p6:
4727 /// A redeclaration of an entity X is implicitly exported if X was introduced
4728 /// by an exported declaration; otherwise it shall not be exported.
4729 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4730
4731 /// A wrapper function for checking the semantic restrictions of
4732 /// a redeclaration within a module.
4733 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4734
4735 /// Check the redefinition in C++20 Modules.
4736 ///
4737 /// [basic.def.odr]p14:
4738 /// For any definable item D with definitions in multiple translation units,
4739 /// - if D is a non-inline non-templated function or variable, or
4740 /// - if the definitions in different translation units do not satisfy the
4741 /// following requirements,
4742 /// the program is ill-formed; a diagnostic is required only if the
4743 /// definable item is attached to a named module and a prior definition is
4744 /// reachable at the point where a later definition occurs.
4745 /// - Each such definition shall not be attached to a named module
4746 /// ([module.unit]).
4747 /// - Each such definition shall consist of the same sequence of tokens, ...
4748 /// ...
4749 ///
4750 /// Return true if the redefinition is not allowed. Return false otherwise.
4751 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4752
4753 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4754
4755 /// If it's a file scoped decl that must warn if not used, keep track
4756 /// of it.
4757 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4758
4759 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4760 DiagReceiverTy;
4761
4762 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4763 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
4764 DiagReceiverTy DiagReceiver);
4765 void DiagnoseUnusedDecl(const NamedDecl *ND);
4766
4767 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4768 /// unless they are marked attr(unused).
4769 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4770
4771 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4772 /// variable.
4773 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4774
4775 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4776 /// from S, where a non-field would be declared. This routine copes
4777 /// with the difference between C and C++ scoping rules in structs and
4778 /// unions. For example, the following code is well-formed in C but
4779 /// ill-formed in C++:
4780 /// @code
4781 /// struct S6 {
4782 /// enum { BAR } e;
4783 /// };
4784 ///
4785 /// void test_S6() {
4786 /// struct S6 a;
4787 /// a.e = BAR;
4788 /// }
4789 /// @endcode
4790 /// For the declaration of BAR, this routine will return a different
4791 /// scope. The scope S will be the scope of the unnamed enumeration
4792 /// within S6. In C++, this routine will return the scope associated
4793 /// with S6, because the enumeration's scope is a transparent
4794 /// context but structures can contain non-field names. In C, this
4795 /// routine will return the translation unit scope, since the
4796 /// enumeration's scope is a transparent context and structures cannot
4797 /// contain non-field names.
4798 Scope *getNonFieldDeclScope(Scope *S);
4799
4800 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4801 SourceLocation Loc);
4802
4803 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4804 /// file scope. lazily create a decl for it. ForRedeclaration is true
4805 /// if we're creating this built-in in anticipation of redeclaring the
4806 /// built-in.
4807 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4808 bool ForRedeclaration, SourceLocation Loc);
4809
4810 /// Get the outermost AttributedType node that sets a calling convention.
4811 /// Valid types should not have multiple attributes with different CCs.
4812 const AttributedType *getCallingConvAttributedType(QualType T) const;
4813
4814 /// GetNameForDeclarator - Determine the full declaration name for the
4815 /// given Declarator.
4816 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
4817
4818 /// Retrieves the declaration name from a parsed unqualified-id.
4819 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
4820
4821 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4822 /// we are currently parsing the initializer.
4823 llvm::SmallPtrSet<const Decl *, 4> ParsingInitForAutoVars;
4824
4825 /// Look for a locally scoped extern "C" declaration by the given name.
4826 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
4827
4828 void deduceOpenCLAddressSpace(VarDecl *decl);
4829 void deduceHLSLAddressSpace(VarDecl *decl);
4830
4831 /// Adjust the \c DeclContext for a function or variable that might be a
4832 /// function-local external declaration.
4833 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
4834
4835 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4836
4837 /// Checks if the variant/multiversion functions are compatible.
4838 bool areMultiversionVariantFunctionsCompatible(
4839 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4840 const PartialDiagnostic &NoProtoDiagID,
4841 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4842 const PartialDiagnosticAt &NoSupportDiagIDAt,
4843 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4844 bool ConstexprSupported, bool CLinkageMayDiffer);
4845
4846 /// type checking declaration initializers (C99 6.7.8)
4847 bool CheckForConstantInitializer(
4848 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4849
4850 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
4851 QualType Type, TypeSourceInfo *TSI,
4852 SourceRange Range, bool DirectInit,
4853 Expr *Init);
4854
4855 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
4856 Expr *Init);
4857
4858 sema::LambdaScopeInfo *RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator);
4859
4860 // Heuristically tells if the function is `get_return_object` member of a
4861 // coroutine promise_type by matching the function name.
4862 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4863 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4864
4865 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4866 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4867 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4868 Scope *S);
4869
4870 /// If this function is a C++ replaceable global allocation function
4871 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4872 /// adds any function attributes that we know a priori based on the standard.
4873 ///
4874 /// We need to check for duplicate attributes both here and where user-written
4875 /// attributes are applied to declarations.
4876 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4877 FunctionDecl *FD);
4878
4879 /// Adds any function attributes that we know a priori based on
4880 /// the declaration of this function.
4881 ///
4882 /// These attributes can apply both to implicitly-declared builtins
4883 /// (like __builtin___printf_chk) or to library-declared functions
4884 /// like NSLog or printf.
4885 ///
4886 /// We need to check for duplicate attributes both here and where user-written
4887 /// attributes are applied to declarations.
4888 void AddKnownFunctionAttributes(FunctionDecl *FD);
4889
4890 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4891 /// the correct width, and that the field type is valid.
4892 /// Returns false on success.
4893 ExprResult VerifyBitField(SourceLocation FieldLoc,
4894 const IdentifierInfo *FieldName, QualType FieldTy,
4895 bool IsMsStruct, Expr *BitWidth);
4896
4897 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4898 /// enum. If AllowMask is true, then we also allow the complement of a valid
4899 /// value, to be used as a mask.
4900 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4901 bool AllowMask) const;
4902
4903 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4904 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4905 SourceLocation WeakNameLoc);
4906
4907 /// ActOnPragmaRedefineExtname - Called on well formed
4908 /// \#pragma redefine_extname oldname newname.
4909 void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName,
4910 IdentifierInfo *AliasName,
4911 SourceLocation PragmaLoc,
4912 SourceLocation WeakNameLoc,
4913 SourceLocation AliasNameLoc);
4914
4915 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4916 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4917 SourceLocation PragmaLoc,
4918 SourceLocation WeakNameLoc,
4919 SourceLocation AliasNameLoc);
4920
4921 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4922 enum class FunctionEmissionStatus {
4923 Emitted,
4924 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4925 OMPDiscarded, // Discarded due to OpenMP hostness
4926 TemplateDiscarded, // Discarded due to uninstantiated templates
4927 Unknown,
4928 };
4929 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4930 bool Final = false);
4931
4932 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4933 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4934
4935 /// Function or variable declarations to be checked for whether the deferred
4936 /// diagnostics should be emitted.
4937 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
4938
4939private:
4940 /// Map of current shadowing declarations to shadowed declarations. Warn if
4941 /// it looks like the user is trying to modify the shadowing declaration.
4942 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4943
4944 // We need this to handle
4945 //
4946 // typedef struct {
4947 // void *foo() { return 0; }
4948 // } A;
4949 //
4950 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4951 // for example. If 'A', foo will have external linkage. If we have '*A',
4952 // foo will have no linkage. Since we can't know until we get to the end
4953 // of the typedef, this function finds out if D might have non-external
4954 // linkage. Callers should verify at the end of the TU if it D has external
4955 // linkage or not.
4956 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4957
4958#include "clang/Sema/AttrIsTypeDependent.inc"
4959
4960 ///@}
4961
4962 //
4963 //
4964 // -------------------------------------------------------------------------
4965 //
4966 //
4967
4968 /// \name Declaration Attribute Handling
4969 /// Implementations are in SemaDeclAttr.cpp
4970 ///@{
4971
4972public:
4973 /// Describes the kind of priority given to an availability attribute.
4974 ///
4975 /// The sum of priorities deteremines the final priority of the attribute.
4976 /// The final priority determines how the attribute will be merged.
4977 /// An attribute with a lower priority will always remove higher priority
4978 /// attributes for the specified platform when it is being applied. An
4979 /// attribute with a higher priority will not be applied if the declaration
4980 /// already has an availability attribute with a lower priority for the
4981 /// specified platform. The final prirority values are not expected to match
4982 /// the values in this enumeration, but instead should be treated as a plain
4983 /// integer value. This enumeration just names the priority weights that are
4984 /// used to calculate that final vaue.
4985 enum AvailabilityPriority : int {
4986 /// The availability attribute was specified explicitly next to the
4987 /// declaration.
4988 AP_Explicit = 0,
4989
4990 /// The availability attribute was applied using '#pragma clang attribute'.
4991 AP_PragmaClangAttribute = 1,
4992
4993 /// The availability attribute for a specific platform was inferred from
4994 /// an availability attribute for another platform.
4995 AP_InferredFromOtherPlatform = 2,
4996
4997 /// The availability attribute was inferred from an 'anyAppleOS'
4998 /// availability attribute.
4999 AP_InferredFromAnyAppleOS = 3,
5000
5001 /// The availability attribute was inferred from an 'anyAppleOS'
5002 /// availability attribute that was applied using '#pragma clang attribute'.
5003 /// This has the lowest priority.
5004 AP_PragmaClangAttribute_InferredFromAnyAppleOS = 4
5005 };
5006
5007 /// Describes the reason a calling convention specification was ignored, used
5008 /// for diagnostics.
5009 enum class CallingConventionIgnoredReason {
5010 ForThisTarget = 0,
5011 VariadicFunction,
5012 ConstructorDestructor,
5013 BuiltinFunction
5014 };
5015
5016 /// A helper function to provide Attribute Location for the Attr types
5017 /// AND the ParsedAttr.
5018 template <typename AttrInfo>
5019 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
5020 getAttrLoc(const AttrInfo &AL) {
5021 return AL.getLocation();
5022 }
5023 SourceLocation getAttrLoc(const AttributeCommonInfo &CI);
5024
5025 /// If Expr is a valid integer constant, get the value of the integer
5026 /// expression and return success or failure. May output an error.
5027 ///
5028 /// Negative argument is implicitly converted to unsigned, unless
5029 /// \p StrictlyUnsigned is true.
5030 template <typename AttrInfo>
5031 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
5032 unsigned Idx = UINT_MAX,
5033 bool StrictlyUnsigned = false) {
5034 std::optional<llvm::APSInt> I = llvm::APSInt(32);
5035 if (Expr->isTypeDependent() ||
5036 !(I = Expr->getIntegerConstantExpr(Ctx: Context))) {
5037 if (Idx != UINT_MAX)
5038 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5039 << &AI << Idx << AANT_ArgumentIntegerConstant
5040 << Expr->getSourceRange();
5041 else
5042 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
5043 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
5044 return false;
5045 }
5046
5047 if (!I->isIntN(N: 32)) {
5048 Diag(Loc: Expr->getExprLoc(), DiagID: diag::err_ice_too_large)
5049 << toString(I: *I, Radix: 10, Signed: false) << 32 << /* Unsigned */ 1;
5050 return false;
5051 }
5052
5053 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
5054 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
5055 << &AI << /*non-negative*/ 1;
5056 return false;
5057 }
5058
5059 Val = (uint32_t)I->getZExtValue();
5060 return true;
5061 }
5062
5063 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
5064 /// \#pragma weak during processing of other Decls.
5065 /// I couldn't figure out a clean way to generate these in-line, so
5066 /// we store them here and handle separately -- which is a hack.
5067 /// It would be best to refactor this.
5068 SmallVector<Decl *, 2> WeakTopLevelDecl;
5069
5070 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
5071 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
5072
5073 typedef LazyVector<TypedefNameDecl *, &ExternalSemaSource::ReadExtVectorDecls,
5074 2, 2>
5075 ExtVectorDeclsType;
5076
5077 /// ExtVectorDecls - This is a list all the extended vector types. This allows
5078 /// us to associate a raw vector type with one of the ext_vector type names.
5079 /// This is only necessary for issuing pretty diagnostics.
5080 ExtVectorDeclsType ExtVectorDecls;
5081
5082 /// Check if the argument \p E is a ASCII string literal. If not emit an error
5083 /// and return false, otherwise set \p Str to the value of the string literal
5084 /// and return true.
5085 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
5086 const Expr *E, StringRef &Str,
5087 SourceLocation *ArgLocation = nullptr);
5088
5089 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
5090 /// If not emit an error and return false. If the argument is an identifier it
5091 /// will emit an error with a fixit hint and treat it as if it was a string
5092 /// literal.
5093 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
5094 StringRef &Str,
5095 SourceLocation *ArgLocation = nullptr);
5096
5097 /// Determine if type T is a valid subject for a nonnull and similar
5098 /// attributes. Dependent types are considered valid so they can be checked
5099 /// during instantiation time. By default, we look through references (the
5100 /// behavior used by nonnull), but if the second parameter is true, then we
5101 /// treat a reference type as valid.
5102 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
5103
5104 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
5105 /// declaration.
5106 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5107 Expr *OE);
5108
5109 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
5110 /// declaration.
5111 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
5112 Expr *ParamExpr);
5113
5114 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
5115 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
5116
5117 AvailabilityAttr *
5118 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
5119 const IdentifierInfo *Platform, bool Implicit,
5120 VersionTuple Introduced, VersionTuple Deprecated,
5121 VersionTuple Obsoleted, bool IsUnavailable,
5122 StringRef Message, bool IsStrict, StringRef Replacement,
5123 AvailabilityMergeKind AMK, int Priority,
5124 const IdentifierInfo *IIEnvironment,
5125 const IdentifierInfo *InferredPlatformII = nullptr);
5126
5127 AvailabilityAttr *mergeAndInferAvailabilityAttr(
5128 NamedDecl *D, const AttributeCommonInfo &CI,
5129 const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced,
5130 VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable,
5131 StringRef Message, bool IsStrict, StringRef Replacement,
5132 AvailabilityMergeKind AMK, int Priority,
5133 const IdentifierInfo *IIEnvironment,
5134 const IdentifierInfo *InferredPlatformII);
5135
5136 TypeVisibilityAttr *
5137 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5138 TypeVisibilityAttr::VisibilityType Vis);
5139 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5140 VisibilityAttr::VisibilityType Vis);
5141 void mergeVisibilityType(Decl *D, SourceLocation Loc,
5142 VisibilityAttr::VisibilityType Type);
5143 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
5144 StringRef Name);
5145
5146 /// Used to implement to perform semantic checking on
5147 /// attribute((section("foo"))) specifiers.
5148 ///
5149 /// In this case, "foo" is passed in to be checked. If the section
5150 /// specifier is invalid, return an Error that indicates the problem.
5151 ///
5152 /// This is a simple quality of implementation feature to catch errors
5153 /// and give good diagnostics in cases when the assembler or code generator
5154 /// would otherwise reject the section specifier.
5155 llvm::Error isValidSectionSpecifier(StringRef Str);
5156 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
5157 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
5158 StringRef Name);
5159
5160 // Check for things we'd like to warn about. Multiversioning issues are
5161 // handled later in the process, once we know how many exist.
5162 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
5163
5164 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
5165 StringRef NewUserDiagnostic);
5166 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
5167 const IdentifierInfo *Format, int FormatIdx,
5168 int FirstArg);
5169 FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
5170 const AttributeCommonInfo &CI,
5171 const IdentifierInfo *Format,
5172 int FormatIdx,
5173 StringLiteral *FormatStr);
5174 ModularFormatAttr *mergeModularFormatAttr(Decl *D,
5175 const AttributeCommonInfo &CI,
5176 const IdentifierInfo *ModularImplFn,
5177 StringRef ImplName,
5178 MutableArrayRef<StringRef> Aspects);
5179
5180 PersonalityAttr *mergePersonalityAttr(Decl *D, FunctionDecl *Routine,
5181 const AttributeCommonInfo &CI);
5182
5183 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5184 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5185 bool IsPackExpansion);
5186 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
5187 bool IsPackExpansion);
5188
5189 /// AddAlignValueAttr - Adds an align_value attribute to a particular
5190 /// declaration.
5191 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
5192
5193 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
5194 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
5195 MutableArrayRef<Expr *> Args);
5196 Attr *CreateAnnotationAttr(const ParsedAttr &AL);
5197
5198 bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range,
5199 bool BestCase,
5200 MSInheritanceModel SemanticSpelling);
5201
5202 void CheckAlignasUnderalignment(Decl *D);
5203
5204 /// AddModeAttr - Adds a mode attribute to a particular declaration.
5205 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
5206 const IdentifierInfo *Name, bool InInstantiation = false);
5207 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
5208 const AttributeCommonInfo &CI,
5209 const IdentifierInfo *Ident);
5210 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
5211 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
5212 const AttributeCommonInfo &CI);
5213 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
5214 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
5215 const InternalLinkageAttr &AL);
5216
5217 /// Check validaty of calling convention attribute \p attr. If \p FD
5218 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
5219 /// target. Otherwise, it is specified by \p CFT.
5220 bool CheckCallingConvAttr(
5221 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
5222 CUDAFunctionTarget CFT = CUDAFunctionTarget::InvalidTarget);
5223
5224 /// Checks a regparm attribute, returning true if it is ill-formed and
5225 /// otherwise setting numParams to the appropriate value.
5226 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
5227
5228 /// Create a CUDALaunchBoundsAttr attribute. By default, the function only
5229 /// supports nvptx target architectures and skips MaxBlocks if it is previous
5230 /// to sm_90. Use \p IgnoreArch to skip the architecture check.
5231 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
5232 Expr *MaxThreads,
5233 Expr *MinBlocks, Expr *MaxBlocks,
5234 bool IgnoreArch = false);
5235
5236 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
5237 /// declaration.
5238 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5239 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
5240
5241 /// Add a cluster_dims attribute to a particular declaration.
5242 CUDAClusterDimsAttr *createClusterDimsAttr(const AttributeCommonInfo &CI,
5243 Expr *X, Expr *Y, Expr *Z);
5244 void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
5245 Expr *Y, Expr *Z);
5246 /// Add a no_cluster attribute to a particular declaration.
5247 void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI);
5248
5249 enum class RetainOwnershipKind { NS, CF, OS };
5250
5251 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5252 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5253
5254 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5255
5256 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5257 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5258 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5259 const AttributeCommonInfo &CI,
5260 bool BestCase,
5261 MSInheritanceModel Model);
5262
5263 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5264 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5265 const EnforceTCBLeafAttr &AL);
5266
5267 /// Helper for delayed processing TransparentUnion or
5268 /// BPFPreserveAccessIndexAttr attribute.
5269 void ProcessDeclAttributeDelayed(Decl *D,
5270 const ParsedAttributesView &AttrList);
5271
5272 // Options for ProcessDeclAttributeList().
5273 struct ProcessDeclAttributeOptions {
5274 ProcessDeclAttributeOptions()
5275 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
5276
5277 ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
5278 ProcessDeclAttributeOptions Result = *this;
5279 Result.IncludeCXX11Attributes = Val;
5280 return Result;
5281 }
5282
5283 ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
5284 ProcessDeclAttributeOptions Result = *this;
5285 Result.IgnoreTypeAttributes = Val;
5286 return Result;
5287 }
5288
5289 // Should C++11 attributes be processed?
5290 bool IncludeCXX11Attributes;
5291
5292 // Should any type attributes encountered be ignored?
5293 // If this option is false, a diagnostic will be emitted for any type
5294 // attributes of a kind that does not "slide" from the declaration to
5295 // the decl-specifier-seq.
5296 bool IgnoreTypeAttributes;
5297 };
5298
5299 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5300 /// attribute list to the specified decl, ignoring any type attributes.
5301 void ProcessDeclAttributeList(Scope *S, Decl *D,
5302 const ParsedAttributesView &AttrList,
5303 const ProcessDeclAttributeOptions &Options =
5304 ProcessDeclAttributeOptions());
5305
5306 /// Annotation attributes are the only attributes allowed after an access
5307 /// specifier.
5308 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5309 const ParsedAttributesView &AttrList);
5310
5311 /// checkUnusedDeclAttributes - Given a declarator which is not being
5312 /// used to build a declaration, complain about any decl attributes
5313 /// which might be lying around on it.
5314 void checkUnusedDeclAttributes(Declarator &D);
5315
5316 void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5317
5318 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5319 /// \#pragma weak needs a non-definition decl and source may not have one.
5320 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
5321 SourceLocation Loc);
5322
5323 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5324 /// applied to it, possibly with an alias.
5325 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5326
5327 void ProcessPragmaWeak(Scope *S, Decl *D);
5328 // Decl attributes - this routine is the top level dispatcher.
5329 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5330
5331 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5332
5333 /// Given a set of delayed diagnostics, re-emit them as if they had
5334 /// been delayed in the current context instead of in the given pool.
5335 /// Essentially, this just moves them to the current pool.
5336 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5337
5338 /// Check that the type is a plain record with one field being a pointer
5339 /// type and the other field being an integer. This matches the common
5340 /// implementation of std::span or sized_allocation_t in P0901R11.
5341 bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty);
5342
5343 /// Check if IdxExpr is a valid parameter index for a function or
5344 /// instance method D. May output an error.
5345 ///
5346 /// \returns true if IdxExpr is a valid index.
5347 template <typename AttrInfo>
5348 bool checkFunctionOrMethodParameterIndex(
5349 const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5350 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5351 bool CanIndexVariadicArguments = false) {
5352 assert(isFunctionOrMethodOrBlockForAttrSubject(D));
5353
5354 // In C++ the implicit 'this' function parameter also counts.
5355 // Parameters are counted from one.
5356 bool HP = hasFunctionProto(D);
5357 bool IV = HP && isFunctionOrMethodVariadic(D);
5358 unsigned NumParams =
5359 HP ? getFunctionOrMethodNumParams(D, /*IncludeThis=*/IncludeThis: true) : 0;
5360
5361 std::optional<llvm::APSInt> IdxInt;
5362 if (IdxExpr->isTypeDependent() ||
5363 !(IdxInt = IdxExpr->getIntegerConstantExpr(Ctx: Context))) {
5364 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5365 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5366 << IdxExpr->getSourceRange();
5367 return false;
5368 }
5369
5370 constexpr unsigned Limit = 1 << ParamIdx::IdxBitWidth;
5371 unsigned IdxSource = IdxInt->getLimitedValue(Limit);
5372 if (IdxSource < 1 || IdxSource == Limit ||
5373 ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5374 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5375 << &AI << AttrArgNum << IdxExpr->getSourceRange();
5376 return false;
5377 }
5378 if (hasImplicitObjectParameter(D) && !CanIndexImplicitThis) {
5379 if (IdxSource == 1) {
5380 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5381 << &AI << IdxExpr->getSourceRange();
5382 return false;
5383 }
5384 }
5385
5386 Idx = ParamIdx(IdxSource, D);
5387 return true;
5388 }
5389
5390 ///@}
5391
5392 //
5393 //
5394 // -------------------------------------------------------------------------
5395 //
5396 //
5397
5398 /// \name C++ Declarations
5399 /// Implementations are in SemaDeclCXX.cpp
5400 ///@{
5401
5402public:
5403 void CheckDelegatingCtorCycles();
5404
5405 /// Called before parsing a function declarator belonging to a function
5406 /// declaration.
5407 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
5408 unsigned TemplateParameterDepth);
5409
5410 /// Called after parsing a function declarator belonging to a function
5411 /// declaration.
5412 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
5413
5414 // Act on C++ namespaces
5415 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5416 SourceLocation NamespaceLoc,
5417 SourceLocation IdentLoc, IdentifierInfo *Ident,
5418 SourceLocation LBrace,
5419 const ParsedAttributesView &AttrList,
5420 UsingDirectiveDecl *&UsingDecl, bool IsNested);
5421
5422 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5423 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5424 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5425
5426 NamespaceDecl *getStdNamespace() const;
5427
5428 /// Retrieve the special "std" namespace, which may require us to
5429 /// implicitly define the namespace.
5430 NamespaceDecl *getOrCreateStdNamespace();
5431
5432 CXXRecordDecl *getStdBadAlloc() const;
5433 EnumDecl *getStdAlignValT() const;
5434
5435 TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const;
5436 FunctionDecl *BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl,
5437 QualType AllocType, SourceLocation);
5438
5439 ValueDecl *tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
5440 const IdentifierInfo *MemberOrBase);
5441
5442 enum class ComparisonCategoryUsage {
5443 /// The '<=>' operator was used in an expression and a builtin operator
5444 /// was selected.
5445 OperatorInExpression,
5446 /// A defaulted 'operator<=>' needed the comparison category. This
5447 /// typically only applies to 'std::strong_ordering', due to the implicit
5448 /// fallback return value.
5449 DefaultedOperator,
5450 /// A builtin needed 'std::strong_ordering' (eg. '__builtin_type_order').
5451 Builtin,
5452 };
5453
5454 /// Lookup the specified comparison category types in the standard
5455 /// library, an check the VarDecls possibly returned by the operator<=>
5456 /// builtins for that type.
5457 ///
5458 /// \return The type of the comparison category type corresponding to the
5459 /// specified Kind, or a null type if an error occurs
5460 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5461 SourceLocation Loc,
5462 ComparisonCategoryUsage Usage);
5463
5464 /// Tests whether Ty is an instance of std::initializer_list and, if
5465 /// it is and Element is not NULL, assigns the element type to Element.
5466 bool isStdInitializerList(QualType Ty, QualType *Element);
5467
5468 /// Tests whether Ty is an instance of std::type_identity and, if
5469 /// it is and TypeArgument is not NULL, assigns the element type to Element.
5470 /// If MalformedDecl is not null, and type_identity was ruled out due to being
5471 /// incorrectly structured despite having the correct name, the faulty Decl
5472 /// will be assigned to MalformedDecl.
5473 bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5474 const Decl **MalformedDecl = nullptr);
5475
5476 /// Looks for the std::initializer_list template and instantiates it
5477 /// with Element, or emits an error if it's not found.
5478 ///
5479 /// \returns The instantiated template, or null on error.
5480 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5481
5482 /// Looks for the std::type_identity template and instantiates it
5483 /// with Type, or returns a null type if type_identity has not been declared
5484 ///
5485 /// \returns The instantiated template, or null if std::type_identity is not
5486 /// declared
5487 QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc);
5488
5489 /// Determine whether Ctor is an initializer-list constructor, as
5490 /// defined in [dcl.init.list]p2.
5491 bool isInitListConstructor(const FunctionDecl *Ctor);
5492
5493 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5494 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5495 SourceLocation IdentLoc,
5496 IdentifierInfo *NamespcName,
5497 const ParsedAttributesView &AttrList);
5498
5499 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5500
5501 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5502 SourceLocation AliasLoc, IdentifierInfo *Alias,
5503 CXXScopeSpec &SS, SourceLocation IdentLoc,
5504 IdentifierInfo *Ident);
5505
5506 /// Remove decls we can't actually see from a lookup being used to declare
5507 /// shadow using decls.
5508 ///
5509 /// \param S - The scope of the potential shadow decl
5510 /// \param Previous - The lookup of a potential shadow decl's name.
5511 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5512
5513 /// Hides a using shadow declaration. This is required by the current
5514 /// using-decl implementation when a resolvable using declaration in a
5515 /// class is followed by a declaration which would hide or override
5516 /// one or more of the using decl's targets; for example:
5517 ///
5518 /// struct Base { void foo(int); };
5519 /// struct Derived : Base {
5520 /// using Base::foo;
5521 /// void foo(int);
5522 /// };
5523 ///
5524 /// The governing language is C++03 [namespace.udecl]p12:
5525 ///
5526 /// When a using-declaration brings names from a base class into a
5527 /// derived class scope, member functions in the derived class
5528 /// override and/or hide member functions with the same name and
5529 /// parameter types in a base class (rather than conflicting).
5530 ///
5531 /// There are two ways to implement this:
5532 /// (1) optimistically create shadow decls when they're not hidden
5533 /// by existing declarations, or
5534 /// (2) don't create any shadow decls (or at least don't make them
5535 /// visible) until we've fully parsed/instantiated the class.
5536 /// The problem with (1) is that we might have to retroactively remove
5537 /// a shadow decl, which requires several O(n) operations because the
5538 /// decl structures are (very reasonably) not designed for removal.
5539 /// (2) avoids this but is very fiddly and phase-dependent.
5540 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5541
5542 /// Determines whether to create a using shadow decl for a particular
5543 /// decl, given the set of decls existing prior to this using lookup.
5544 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5545 const LookupResult &PreviousDecls,
5546 UsingShadowDecl *&PrevShadow);
5547
5548 /// Builds a shadow declaration corresponding to a 'using' declaration.
5549 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5550 NamedDecl *Target,
5551 UsingShadowDecl *PrevDecl);
5552
5553 /// Checks that the given using declaration is not an invalid
5554 /// redeclaration. Note that this is checking only for the using decl
5555 /// itself, not for any ill-formedness among the UsingShadowDecls.
5556 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5557 bool HasTypenameKeyword,
5558 const CXXScopeSpec &SS,
5559 SourceLocation NameLoc,
5560 const LookupResult &Previous);
5561
5562 /// Checks that the given nested-name qualifier used in a using decl
5563 /// in the current context is appropriately related to the current
5564 /// scope. If an error is found, diagnoses it and returns true.
5565 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5566 /// the result of that lookup. UD is likewise nullptr, except when we have an
5567 /// already-populated UsingDecl whose shadow decls contain the same
5568 /// information (i.e. we're instantiating a UsingDecl with non-dependent
5569 /// scope).
5570 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5571 const CXXScopeSpec &SS,
5572 const DeclarationNameInfo &NameInfo,
5573 SourceLocation NameLoc,
5574 const LookupResult *R = nullptr,
5575 const UsingDecl *UD = nullptr);
5576
5577 /// Builds a using declaration.
5578 ///
5579 /// \param IsInstantiation - Whether this call arises from an
5580 /// instantiation of an unresolved using declaration. We treat
5581 /// the lookup differently for these declarations.
5582 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5583 SourceLocation UsingLoc,
5584 bool HasTypenameKeyword,
5585 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5586 DeclarationNameInfo NameInfo,
5587 SourceLocation EllipsisLoc,
5588 const ParsedAttributesView &AttrList,
5589 bool IsInstantiation, bool IsUsingIfExists);
5590 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
5591 SourceLocation UsingLoc,
5592 SourceLocation EnumLoc,
5593 SourceLocation NameLoc,
5594 TypeSourceInfo *EnumType, EnumDecl *ED);
5595 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5596 ArrayRef<NamedDecl *> Expansions);
5597
5598 /// Additional checks for a using declaration referring to a constructor name.
5599 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5600
5601 /// Given a derived-class using shadow declaration for a constructor and the
5602 /// correspnding base class constructor, find or create the implicit
5603 /// synthesized derived class constructor to use for this initialization.
5604 CXXConstructorDecl *
5605 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5606 ConstructorUsingShadowDecl *DerivedShadow);
5607
5608 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5609 SourceLocation UsingLoc,
5610 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5611 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5612 const ParsedAttributesView &AttrList);
5613 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
5614 SourceLocation UsingLoc,
5615 SourceLocation EnumLoc, SourceRange TyLoc,
5616 const IdentifierInfo &II, ParsedType Ty,
5617 const CXXScopeSpec &SS);
5618 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5619 MultiTemplateParamsArg TemplateParams,
5620 SourceLocation UsingLoc, UnqualifiedId &Name,
5621 const ParsedAttributesView &AttrList,
5622 TypeResult Type, Decl *DeclFromDeclSpec);
5623
5624 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5625 /// including handling of its default argument expressions.
5626 ///
5627 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5628 ExprResult BuildCXXConstructExpr(
5629 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5630 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5631 bool HadMultipleCandidates, bool IsListInitialization,
5632 bool IsStdInitListInitialization, bool RequiresZeroInit,
5633 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5634
5635 /// Build a CXXConstructExpr whose constructor has already been resolved if
5636 /// it denotes an inherited constructor.
5637 ExprResult BuildCXXConstructExpr(
5638 SourceLocation ConstructLoc, QualType DeclInitType,
5639 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5640 bool HadMultipleCandidates, bool IsListInitialization,
5641 bool IsStdInitListInitialization, bool RequiresZeroInit,
5642 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5643
5644 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5645 // the constructor can be elidable?
5646 ExprResult BuildCXXConstructExpr(
5647 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5648 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5649 bool HadMultipleCandidates, bool IsListInitialization,
5650 bool IsStdInitListInitialization, bool RequiresZeroInit,
5651 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5652
5653 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr,
5654 SourceLocation InitLoc);
5655 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD,
5656 const InitializedEntity &Entity,
5657 Expr *InitExpr,
5658 SourceLocation InitLoc);
5659
5660 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5661 /// constructed variable.
5662 void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit);
5663
5664 /// Helper class that collects exception specifications for
5665 /// implicitly-declared special member functions.
5666 class ImplicitExceptionSpecification {
5667 // Pointer to allow copying
5668 Sema *Self;
5669 // We order exception specifications thus:
5670 // noexcept is the most restrictive, but is only used in C++11.
5671 // throw() comes next.
5672 // Then a throw(collected exceptions)
5673 // Finally no specification, which is expressed as noexcept(false).
5674 // throw(...) is used instead if any called function uses it.
5675 ExceptionSpecificationType ComputedEST;
5676 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5677 SmallVector<QualType, 4> Exceptions;
5678
5679 void ClearExceptions() {
5680 ExceptionsSeen.clear();
5681 Exceptions.clear();
5682 }
5683
5684 public:
5685 explicit ImplicitExceptionSpecification(Sema &Self)
5686 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5687 if (!Self.getLangOpts().CPlusPlus11)
5688 ComputedEST = EST_DynamicNone;
5689 }
5690
5691 /// Get the computed exception specification type.
5692 ExceptionSpecificationType getExceptionSpecType() const {
5693 assert(!isComputedNoexcept(ComputedEST) &&
5694 "noexcept(expr) should not be a possible result");
5695 return ComputedEST;
5696 }
5697
5698 /// The number of exceptions in the exception specification.
5699 unsigned size() const { return Exceptions.size(); }
5700
5701 /// The set of exceptions in the exception specification.
5702 const QualType *data() const { return Exceptions.data(); }
5703
5704 /// Integrate another called method into the collected data.
5705 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5706
5707 /// Integrate an invoked expression into the collected data.
5708 void CalledExpr(Expr *E) { CalledStmt(S: E); }
5709
5710 /// Integrate an invoked statement into the collected data.
5711 void CalledStmt(Stmt *S);
5712
5713 /// Overwrite an EPI's exception specification with this
5714 /// computed exception specification.
5715 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5716 FunctionProtoType::ExceptionSpecInfo ESI;
5717 ESI.Type = getExceptionSpecType();
5718 if (ESI.Type == EST_Dynamic) {
5719 ESI.Exceptions = Exceptions;
5720 } else if (ESI.Type == EST_None) {
5721 /// C++11 [except.spec]p14:
5722 /// The exception-specification is noexcept(false) if the set of
5723 /// potential exceptions of the special member function contains "any"
5724 ESI.Type = EST_NoexceptFalse;
5725 ESI.NoexceptExpr =
5726 Self->ActOnCXXBoolLiteral(OpLoc: SourceLocation(), Kind: tok::kw_false).get();
5727 }
5728 return ESI;
5729 }
5730 };
5731
5732 /// Evaluate the implicit exception specification for a defaulted
5733 /// special member function.
5734 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5735
5736 /// Check the given exception-specification and update the
5737 /// exception specification information with the results.
5738 void checkExceptionSpecification(bool IsTopLevel,
5739 ExceptionSpecificationType EST,
5740 ArrayRef<ParsedType> DynamicExceptions,
5741 ArrayRef<SourceRange> DynamicExceptionRanges,
5742 Expr *NoexceptExpr,
5743 SmallVectorImpl<QualType> &Exceptions,
5744 FunctionProtoType::ExceptionSpecInfo &ESI);
5745
5746 /// Add an exception-specification to the given member or friend function
5747 /// (or function template). The exception-specification was parsed
5748 /// after the function itself was declared.
5749 void actOnDelayedExceptionSpecification(
5750 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5751 ArrayRef<ParsedType> DynamicExceptions,
5752 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5753
5754 class InheritedConstructorInfo;
5755
5756 /// Determine if a special member function should have a deleted
5757 /// definition when it is defaulted.
5758 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
5759 InheritedConstructorInfo *ICI = nullptr,
5760 bool Diagnose = false);
5761
5762 /// Produce notes explaining why a defaulted function was defined as deleted.
5763 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5764
5765 /// Declare the implicit default constructor for the given class.
5766 ///
5767 /// \param ClassDecl The class declaration into which the implicit
5768 /// default constructor will be added.
5769 ///
5770 /// \returns The implicitly-declared default constructor.
5771 CXXConstructorDecl *
5772 DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl);
5773
5774 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5775 /// defining this constructor as the default constructor.
5776 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5777 CXXConstructorDecl *Constructor);
5778
5779 /// Declare the implicit destructor for the given class.
5780 ///
5781 /// \param ClassDecl The class declaration into which the implicit
5782 /// destructor will be added.
5783 ///
5784 /// \returns The implicitly-declared destructor.
5785 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5786
5787 /// DefineImplicitDestructor - Checks for feasibility of
5788 /// defining this destructor as the default destructor.
5789 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5790 CXXDestructorDecl *Destructor);
5791
5792 /// Build an exception spec for destructors that don't have one.
5793 ///
5794 /// C++11 says that user-defined destructors with no exception spec get one
5795 /// that looks as if the destructor was implicitly declared.
5796 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5797
5798 /// Define the specified inheriting constructor.
5799 void DefineInheritingConstructor(SourceLocation UseLoc,
5800 CXXConstructorDecl *Constructor);
5801
5802 /// Declare the implicit copy constructor for the given class.
5803 ///
5804 /// \param ClassDecl The class declaration into which the implicit
5805 /// copy constructor will be added.
5806 ///
5807 /// \returns The implicitly-declared copy constructor.
5808 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5809
5810 /// DefineImplicitCopyConstructor - Checks for feasibility of
5811 /// defining this constructor as the copy constructor.
5812 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5813 CXXConstructorDecl *Constructor);
5814
5815 /// Declare the implicit move constructor for the given class.
5816 ///
5817 /// \param ClassDecl The Class declaration into which the implicit
5818 /// move constructor will be added.
5819 ///
5820 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5821 /// declared.
5822 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5823
5824 /// DefineImplicitMoveConstructor - Checks for feasibility of
5825 /// defining this constructor as the move constructor.
5826 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5827 CXXConstructorDecl *Constructor);
5828
5829 /// Declare the implicit copy assignment operator for the given class.
5830 ///
5831 /// \param ClassDecl The class declaration into which the implicit
5832 /// copy assignment operator will be added.
5833 ///
5834 /// \returns The implicitly-declared copy assignment operator.
5835 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5836
5837 /// Defines an implicitly-declared copy assignment operator.
5838 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5839 CXXMethodDecl *MethodDecl);
5840
5841 /// Declare the implicit move assignment operator for the given class.
5842 ///
5843 /// \param ClassDecl The Class declaration into which the implicit
5844 /// move assignment operator will be added.
5845 ///
5846 /// \returns The implicitly-declared move assignment operator, or NULL if it
5847 /// wasn't declared.
5848 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5849
5850 /// Defines an implicitly-declared move assignment operator.
5851 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5852 CXXMethodDecl *MethodDecl);
5853
5854 /// Check a completed declaration of an implicit special member.
5855 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5856
5857 /// Determine whether the given function is an implicitly-deleted
5858 /// special member function.
5859 bool isImplicitlyDeleted(FunctionDecl *FD);
5860
5861 /// Check whether 'this' shows up in the type of a static member
5862 /// function after the (naturally empty) cv-qualifier-seq would be.
5863 ///
5864 /// \returns true if an error occurred.
5865 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5866
5867 /// Whether this' shows up in the exception specification of a static
5868 /// member function.
5869 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5870
5871 /// Check whether 'this' shows up in the attributes of the given
5872 /// static member function.
5873 ///
5874 /// \returns true if an error occurred.
5875 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5876
5877 bool CheckImmediateEscalatingFunctionDefinition(
5878 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5879
5880 void DiagnoseImmediateEscalatingReason(FunctionDecl *FD);
5881
5882 /// Given a constructor and the set of arguments provided for the
5883 /// constructor, convert the arguments and add any required default arguments
5884 /// to form a proper call to this constructor.
5885 ///
5886 /// \returns true if an error occurred, false otherwise.
5887 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5888 QualType DeclInitType, MultiExprArg ArgsPtr,
5889 SourceLocation Loc,
5890 SmallVectorImpl<Expr *> &ConvertedArgs,
5891 bool AllowExplicit = false,
5892 bool IsListInitialization = false);
5893
5894 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5895 /// initializer for the declaration 'Dcl'.
5896 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5897 /// static data member of class X, names should be looked up in the scope of
5898 /// class X.
5899 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5900
5901 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5902 /// initializer for the declaration 'Dcl'.
5903 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5904
5905 /// Define the "body" of the conversion from a lambda object to a
5906 /// function pointer.
5907 ///
5908 /// This routine doesn't actually define a sensible body; rather, it fills
5909 /// in the initialization expression needed to copy the lambda object into
5910 /// the block, and IR generation actually generates the real body of the
5911 /// block pointer conversion.
5912 void
5913 DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc,
5914 CXXConversionDecl *Conv);
5915
5916 /// Define the "body" of the conversion from a lambda object to a
5917 /// block pointer.
5918 ///
5919 /// This routine doesn't actually define a sensible body; rather, it fills
5920 /// in the initialization expression needed to copy the lambda object into
5921 /// the block, and IR generation actually generates the real body of the
5922 /// block pointer conversion.
5923 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5924 CXXConversionDecl *Conv);
5925
5926 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5927 /// linkage specification, including the language and (if present)
5928 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5929 /// language string literal. LBraceLoc, if valid, provides the location of
5930 /// the '{' brace. Otherwise, this linkage specification does not
5931 /// have any braces.
5932 Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5933 Expr *LangStr, SourceLocation LBraceLoc);
5934
5935 /// ActOnFinishLinkageSpecification - Complete the definition of
5936 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5937 /// valid, it's the position of the closing '}' brace in a linkage
5938 /// specification that uses braces.
5939 Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec,
5940 SourceLocation RBraceLoc);
5941
5942 //===--------------------------------------------------------------------===//
5943 // C++ Classes
5944 //
5945
5946 /// Get the class that is directly named by the current context. This is the
5947 /// class for which an unqualified-id in this scope could name a constructor
5948 /// or destructor.
5949 ///
5950 /// If the scope specifier denotes a class, this will be that class.
5951 /// If the scope specifier is empty, this will be the class whose
5952 /// member-specification we are currently within. Otherwise, there
5953 /// is no such class.
5954 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
5955
5956 /// isCurrentClassName - Determine whether the identifier II is the
5957 /// name of the class type currently being defined. In the case of
5958 /// nested classes, this will only return true if II is the name of
5959 /// the innermost class.
5960 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5961 const CXXScopeSpec *SS = nullptr);
5962
5963 /// Determine whether the identifier II is a typo for the name of
5964 /// the class type currently being defined. If so, update it to the identifier
5965 /// that should have been used.
5966 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5967
5968 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5969 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
5970 SourceLocation ColonLoc,
5971 const ParsedAttributesView &Attrs);
5972
5973 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5974 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5975 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
5976 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
5977 /// present (but parsing it has been deferred).
5978 NamedDecl *
5979 ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
5980 MultiTemplateParamsArg TemplateParameterLists,
5981 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5982 InClassInitStyle InitStyle);
5983
5984 /// Enter a new C++ default initializer scope. After calling this, the
5985 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
5986 /// parsing or instantiating the initializer failed.
5987 void ActOnStartCXXInClassMemberInitializer();
5988
5989 /// This is invoked after parsing an in-class initializer for a
5990 /// non-static C++ class member, and after instantiating an in-class
5991 /// initializer in a class template. Such actions are deferred until the class
5992 /// is complete.
5993 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5994 SourceLocation EqualLoc,
5995 ExprResult Init);
5996
5997 /// Handle a C++ member initializer using parentheses syntax.
5998 MemInitResult
5999 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
6000 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
6001 const DeclSpec &DS, SourceLocation IdLoc,
6002 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
6003 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
6004
6005 /// Handle a C++ member initializer using braced-init-list syntax.
6006 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
6007 CXXScopeSpec &SS,
6008 IdentifierInfo *MemberOrBase,
6009 ParsedType TemplateTypeTy,
6010 const DeclSpec &DS, SourceLocation IdLoc,
6011 Expr *InitList, SourceLocation EllipsisLoc);
6012
6013 /// Handle a C++ member initializer.
6014 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
6015 CXXScopeSpec &SS,
6016 IdentifierInfo *MemberOrBase,
6017 ParsedType TemplateTypeTy,
6018 const DeclSpec &DS, SourceLocation IdLoc,
6019 Expr *Init, SourceLocation EllipsisLoc);
6020
6021 MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init,
6022 SourceLocation IdLoc);
6023
6024 MemInitResult BuildBaseInitializer(QualType BaseType,
6025 TypeSourceInfo *BaseTInfo, Expr *Init,
6026 CXXRecordDecl *ClassDecl,
6027 SourceLocation EllipsisLoc);
6028
6029 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
6030 CXXRecordDecl *ClassDecl);
6031
6032 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
6033 CXXCtorInitializer *Initializer);
6034
6035 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
6036 ArrayRef<CXXCtorInitializer *> Initializers = {});
6037
6038 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
6039 /// mark all the non-trivial destructors of its members and bases as
6040 /// referenced.
6041 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
6042 CXXRecordDecl *Record);
6043
6044 /// Mark destructors of virtual bases of this class referenced. In the Itanium
6045 /// C++ ABI, this is done when emitting a destructor for any non-abstract
6046 /// class. In the Microsoft C++ ABI, this is done any time a class's
6047 /// destructor is referenced.
6048 void MarkVirtualBaseDestructorsReferenced(
6049 SourceLocation Location, CXXRecordDecl *ClassDecl,
6050 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
6051 nullptr);
6052
6053 /// Do semantic checks to allow the complete destructor variant to be emitted
6054 /// when the destructor is defined in another translation unit. In the Itanium
6055 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
6056 /// can be emitted in separate TUs. To emit the complete variant, run a subset
6057 /// of the checks performed when emitting a regular destructor.
6058 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
6059 CXXDestructorDecl *Dtor);
6060
6061 /// The list of classes whose vtables have been used within
6062 /// this translation unit, and the source locations at which the
6063 /// first use occurred.
6064 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
6065
6066 /// The list of vtables that are required but have not yet been
6067 /// materialized.
6068 SmallVector<VTableUse, 16> VTableUses;
6069
6070 /// The set of classes whose vtables have been used within
6071 /// this translation unit, and a bit that will be true if the vtable is
6072 /// required to be emitted (otherwise, it should be emitted only if needed
6073 /// by code generation).
6074 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
6075
6076 /// Load any externally-stored vtable uses.
6077 void LoadExternalVTableUses();
6078
6079 /// Note that the vtable for the given class was used at the
6080 /// given location.
6081 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6082 bool DefinitionRequired = false);
6083
6084 /// Mark the exception specifications of all virtual member functions
6085 /// in the given class as needed.
6086 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
6087 const CXXRecordDecl *RD);
6088
6089 /// MarkVirtualMembersReferenced - Will mark all members of the given
6090 /// CXXRecordDecl referenced.
6091 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
6092 bool ConstexprOnly = false);
6093
6094 /// Define all of the vtables that have been used in this
6095 /// translation unit and reference any virtual members used by those
6096 /// vtables.
6097 ///
6098 /// \returns true if any work was done, false otherwise.
6099 bool DefineUsedVTables();
6100
6101 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6102 /// special functions, such as the default constructor, copy
6103 /// constructor, or destructor, to the given C++ class (C++
6104 /// [special]p1). This routine can only be executed just before the
6105 /// definition of the class is complete.
6106 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
6107
6108 /// ActOnMemInitializers - Handle the member initializers for a constructor.
6109 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
6110 ArrayRef<CXXCtorInitializer *> MemInits,
6111 bool AnyErrors);
6112
6113 /// Check class-level dllimport/dllexport attribute. The caller must
6114 /// ensure that referenceDLLExportedClassMethods is called some point later
6115 /// when all outer classes of Class are complete.
6116 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
6117 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
6118
6119 void referenceDLLExportedClassMethods();
6120
6121 /// Perform propagation of DLL attributes from a derived class to a
6122 /// templated base class for MS compatibility.
6123 void propagateDLLAttrToBaseClassTemplate(
6124 CXXRecordDecl *Class, Attr *ClassAttr,
6125 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6126 SourceLocation BaseLoc);
6127
6128 /// Perform semantic checks on a class definition that has been
6129 /// completing, introducing implicitly-declared members, checking for
6130 /// abstract types, etc.
6131 ///
6132 /// \param S The scope in which the class was parsed. Null if we didn't just
6133 /// parse a class definition.
6134 /// \param Record The completed class.
6135 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
6136
6137 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6138 /// conditions that are needed for the attribute to have an effect.
6139 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6140
6141 /// Check that VTable Pointer authentication is only being set on the first
6142 /// first instantiation of the vtable
6143 void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD);
6144
6145 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6146 Decl *TagDecl, SourceLocation LBrac,
6147 SourceLocation RBrac,
6148 const ParsedAttributesView &AttrList);
6149
6150 /// Perform any semantic analysis which needs to be delayed until all
6151 /// pending class member declarations have been parsed.
6152 void ActOnFinishCXXMemberDecls();
6153 void ActOnFinishCXXNonNestedClass();
6154
6155 /// This is used to implement the constant expression evaluation part of the
6156 /// attribute enable_if extension. There is nothing in standard C++ which
6157 /// would require reentering parameters.
6158 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6159 unsigned ActOnReenterTemplateScope(Decl *Template,
6160 llvm::function_ref<Scope *()> EnterScope);
6161 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6162
6163 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6164 /// parsing a top-level (non-nested) C++ class, and we are now
6165 /// parsing those parts of the given Method declaration that could
6166 /// not be parsed earlier (C++ [class.mem]p2), such as default
6167 /// arguments. This action should enter the scope of the given
6168 /// Method declaration as if we had just parsed the qualified method
6169 /// name. However, it should not bring the parameters into scope;
6170 /// that will be performed by ActOnDelayedCXXMethodParameter.
6171 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6172 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6173 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6174
6175 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6176 /// processing the delayed method declaration for Method. The method
6177 /// declaration is now considered finished. There may be a separate
6178 /// ActOnStartOfFunctionDef action later (not necessarily
6179 /// immediately!) for this method, if it was also defined inside the
6180 /// class body.
6181 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6182 void ActOnFinishDelayedMemberInitializers(Decl *Record);
6183
6184 enum class StringEvaluationContext { StaticAssert = 0, Asm = 1 };
6185
6186 bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
6187 StringEvaluationContext EvalContext,
6188 bool ErrorOnInvalidMessage);
6189 bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
6190 StringEvaluationContext EvalContext,
6191 bool ErrorOnInvalidMessage);
6192
6193 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6194 Expr *AssertExpr, Expr *AssertMessageExpr,
6195 SourceLocation RParenLoc);
6196 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6197 Expr *AssertExpr, Expr *AssertMessageExpr,
6198 SourceLocation RParenLoc, bool Failed);
6199
6200 /// Try to print more useful information about a failed static_assert
6201 /// with expression \E
6202 void DiagnoseStaticAssertDetails(const Expr *E);
6203
6204 /// If E represents a built-in type trait, or a known standard type trait,
6205 /// try to print more information about why the type type-trait failed.
6206 /// This assumes we already evaluated the expression to a false boolean value.
6207 void DiagnoseTypeTraitDetails(const Expr *E);
6208
6209 /// Handle a friend type declaration. This works in tandem with
6210 /// ActOnTag.
6211 ///
6212 /// Notes on friend class templates:
6213 ///
6214 /// We generally treat friend class declarations as if they were
6215 /// declaring a class. So, for example, the elaborated type specifier
6216 /// in a friend declaration is required to obey the restrictions of a
6217 /// class-head (i.e. no typedefs in the scope chain), template
6218 /// parameters are required to match up with simple template-ids, &c.
6219 /// However, unlike when declaring a template specialization, it's
6220 /// okay to refer to a template specialization without an empty
6221 /// template parameter declaration, e.g.
6222 /// friend class A<T>::B<unsigned>;
6223 /// We permit this as a special case; if there are any template
6224 /// parameters present at all, require proper matching, i.e.
6225 /// template <> template \<class T> friend class A<int>::B;
6226 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6227 MultiTemplateParamsArg TemplateParams,
6228 SourceLocation EllipsisLoc);
6229 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6230 MultiTemplateParamsArg TemplateParams);
6231
6232 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6233 /// the well-formedness of the constructor declarator @p D with type @p
6234 /// R. If there are any errors in the declarator, this routine will
6235 /// emit diagnostics and set the invalid bit to true. In any case, the type
6236 /// will be updated to reflect a well-formed type for the constructor and
6237 /// returned.
6238 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6239 StorageClass &SC);
6240
6241 /// CheckConstructor - Checks a fully-formed constructor for
6242 /// well-formedness, issuing any diagnostics required. Returns true if
6243 /// the constructor declarator is invalid.
6244 void CheckConstructor(CXXConstructorDecl *Constructor);
6245
6246 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6247 /// the well-formednes of the destructor declarator @p D with type @p
6248 /// R. If there are any errors in the declarator, this routine will
6249 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6250 /// will be updated to reflect a well-formed type for the destructor and
6251 /// returned.
6252 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6253 StorageClass &SC);
6254
6255 /// CheckDestructor - Checks a fully-formed destructor definition for
6256 /// well-formedness, issuing any diagnostics required. Returns true
6257 /// on error.
6258 bool CheckDestructor(CXXDestructorDecl *Destructor);
6259
6260 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6261 /// well-formednes of the conversion function declarator @p D with
6262 /// type @p R. If there are any errors in the declarator, this routine
6263 /// will emit diagnostics and return true. Otherwise, it will return
6264 /// false. Either way, the type @p R will be updated to reflect a
6265 /// well-formed type for the conversion operator.
6266 void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC);
6267
6268 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6269 /// the declaration of the given C++ conversion function. This routine
6270 /// is responsible for recording the conversion function in the C++
6271 /// class, if possible.
6272 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6273
6274 /// Check the validity of a declarator that we parsed for a deduction-guide.
6275 /// These aren't actually declarators in the grammar, so we need to check that
6276 /// the user didn't specify any pieces that are not part of the
6277 /// deduction-guide grammar. Return true on invalid deduction-guide.
6278 bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6279 StorageClass &SC);
6280
6281 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6282
6283 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6284 CXXSpecialMemberKind CSM,
6285 SourceLocation DefaultLoc);
6286 void CheckDelayedMemberExceptionSpecs();
6287
6288 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6289 DefaultedComparisonKind DCK);
6290 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6291 FunctionDecl *Spaceship);
6292 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6293 DefaultedComparisonKind DCK);
6294
6295 void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name,
6296 QualType R, bool IsLambda,
6297 DeclContext *DC = nullptr);
6298 void CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
6299 DeclarationName Name, QualType R);
6300 void CheckExplicitObjectLambda(Declarator &D);
6301
6302 //===--------------------------------------------------------------------===//
6303 // C++ Derived Classes
6304 //
6305
6306 /// Check the validity of a C++ base class specifier.
6307 ///
6308 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6309 /// and returns NULL otherwise.
6310 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6311 SourceRange SpecifierRange, bool Virtual,
6312 AccessSpecifier Access,
6313 TypeSourceInfo *TInfo,
6314 SourceLocation EllipsisLoc);
6315
6316 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6317 /// one entry in the base class list of a class specifier, for
6318 /// example:
6319 /// class foo : public bar, virtual private baz {
6320 /// 'public bar' and 'virtual private baz' are each base-specifiers.
6321 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6322 const ParsedAttributesView &Attrs, bool Virtual,
6323 AccessSpecifier Access, ParsedType basetype,
6324 SourceLocation BaseLoc,
6325 SourceLocation EllipsisLoc);
6326
6327 /// Performs the actual work of attaching the given base class
6328 /// specifiers to a C++ class.
6329 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6330 MutableArrayRef<CXXBaseSpecifier *> Bases);
6331
6332 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6333 /// class, after checking whether there are any duplicate base
6334 /// classes.
6335 void ActOnBaseSpecifiers(Decl *ClassDecl,
6336 MutableArrayRef<CXXBaseSpecifier *> Bases);
6337
6338 /// Determine whether the type \p Derived is a C++ class that is
6339 /// derived from the type \p Base.
6340 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6341 CXXRecordDecl *Base, CXXBasePaths &Paths);
6342 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6343 CXXRecordDecl *Base);
6344 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6345 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6346 CXXBasePaths &Paths);
6347
6348 // FIXME: I don't like this name.
6349 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6350
6351 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6352 SourceLocation Loc, SourceRange Range,
6353 CXXCastPath *BasePath = nullptr,
6354 bool IgnoreAccess = false);
6355
6356 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6357 /// conversion (where Derived and Base are class types) is
6358 /// well-formed, meaning that the conversion is unambiguous (and
6359 /// that all of the base classes are accessible). Returns true
6360 /// and emits a diagnostic if the code is ill-formed, returns false
6361 /// otherwise. Loc is the location where this routine should point to
6362 /// if there is an error, and Range is the source range to highlight
6363 /// if there is an error.
6364 ///
6365 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6366 /// diagnostic for the respective type of error will be suppressed, but the
6367 /// check for ill-formed code will still be performed.
6368 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6369 unsigned InaccessibleBaseID,
6370 unsigned AmbiguousBaseConvID,
6371 SourceLocation Loc, SourceRange Range,
6372 DeclarationName Name, CXXCastPath *BasePath,
6373 bool IgnoreAccess = false);
6374
6375 /// Builds a string representing ambiguous paths from a
6376 /// specific derived class to different subobjects of the same base
6377 /// class.
6378 ///
6379 /// This function builds a string that can be used in error messages
6380 /// to show the different paths that one can take through the
6381 /// inheritance hierarchy to go from the derived class to different
6382 /// subobjects of a base class. The result looks something like this:
6383 /// @code
6384 /// struct D -> struct B -> struct A
6385 /// struct D -> struct C -> struct A
6386 /// @endcode
6387 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6388
6389 bool CheckOverridingFunctionAttributes(CXXMethodDecl *New,
6390 const CXXMethodDecl *Old);
6391
6392 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6393 /// covariant, according to C++ [class.virtual]p5.
6394 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6395 const CXXMethodDecl *Old);
6396
6397 // Check that the overriding method has no explicit object parameter.
6398 bool CheckExplicitObjectOverride(CXXMethodDecl *New,
6399 const CXXMethodDecl *Old);
6400
6401 /// Mark the given method pure.
6402 ///
6403 /// \param Method the method to be marked pure.
6404 ///
6405 /// \param InitRange the source range that covers the "0" initializer.
6406 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6407
6408 /// CheckOverrideControl - Check C++11 override control semantics.
6409 void CheckOverrideControl(NamedDecl *D);
6410
6411 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6412 /// not used in the declaration of an overriding method.
6413 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
6414
6415 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6416 /// function overrides a virtual member function marked 'final', according to
6417 /// C++11 [class.virtual]p4.
6418 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6419 const CXXMethodDecl *Old);
6420
6421 enum AbstractDiagSelID {
6422 AbstractNone = -1,
6423 AbstractReturnType,
6424 AbstractParamType,
6425 AbstractVariableType,
6426 AbstractFieldType,
6427 AbstractIvarType,
6428 AbstractSynthesizedIvarType,
6429 AbstractArrayType
6430 };
6431
6432 struct TypeDiagnoser;
6433
6434 bool isAbstractType(SourceLocation Loc, QualType T);
6435 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6436 TypeDiagnoser &Diagnoser);
6437 template <typename... Ts>
6438 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6439 const Ts &...Args) {
6440 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6441 return RequireNonAbstractType(Loc, T, Diagnoser);
6442 }
6443
6444 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6445
6446 //===--------------------------------------------------------------------===//
6447 // C++ Overloaded Operators [C++ 13.5]
6448 //
6449
6450 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6451 /// of this overloaded operator is well-formed. If so, returns false;
6452 /// otherwise, emits appropriate diagnostics and returns true.
6453 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6454
6455 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6456 /// of this literal operator function is well-formed. If so, returns
6457 /// false; otherwise, emits appropriate diagnostics and returns true.
6458 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6459
6460 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6461 /// found in an explicit(bool) specifier.
6462 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
6463
6464 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6465 /// Returns true if the explicit specifier is now resolved.
6466 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
6467
6468 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6469 /// C++ if/switch/while/for statement.
6470 /// e.g: "if (int x = f()) {...}"
6471 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
6472
6473 // Emitting members of dllexported classes is delayed until the class
6474 // (including field initializers) is fully parsed.
6475 SmallVector<CXXRecordDecl *, 4> DelayedDllExportClasses;
6476 SmallVector<CXXMethodDecl *, 4> DelayedDllExportMemberFunctions;
6477
6478 /// Merge the exception specifications of two variable declarations.
6479 ///
6480 /// This is called when there's a redeclaration of a VarDecl. The function
6481 /// checks if the redeclaration might have an exception specification and
6482 /// validates compatibility and merges the specs if necessary.
6483 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
6484
6485 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6486 /// function, once we already know that they have the same
6487 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6488 /// error, false otherwise.
6489 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
6490
6491 /// Helpers for dealing with blocks and functions.
6492 void CheckCXXDefaultArguments(FunctionDecl *FD);
6493
6494 /// CheckExtraCXXDefaultArguments - Check for any extra default
6495 /// arguments in the declarator, which is not a function declaration
6496 /// or definition and therefore is not permitted to have default
6497 /// arguments. This routine should be invoked for every declarator
6498 /// that is not a function declaration or definition.
6499 void CheckExtraCXXDefaultArguments(Declarator &D);
6500
6501 /// Perform semantic analysis for the variable declaration that
6502 /// occurs within a C++ catch clause, returning the newly-created
6503 /// variable.
6504 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
6505 SourceLocation StartLoc,
6506 SourceLocation IdLoc,
6507 const IdentifierInfo *Id);
6508
6509 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6510 /// handler.
6511 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
6512
6513 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
6514
6515 /// Handle a friend tag declaration where the scope specifier was
6516 /// templated.
6517 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6518 unsigned TagSpec, SourceLocation TagLoc,
6519 CXXScopeSpec &SS, IdentifierInfo *Name,
6520 SourceLocation NameLoc,
6521 SourceLocation EllipsisLoc,
6522 const ParsedAttributesView &Attr,
6523 MultiTemplateParamsArg TempParamLists,
6524 TemplateIdAnnotation *TemplateId);
6525
6526 bool CheckDependentFriend(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc,
6527 ArrayRef<TemplateParameterList *> TPLs,
6528 bool IsInstantiation);
6529
6530 bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc,
6531 NestedNameSpecifierLoc NNSLoc);
6532
6533 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
6534 SourceLocation DeclStart, Declarator &D,
6535 Expr *BitfieldWidth,
6536 InClassInitStyle InitStyle,
6537 AccessSpecifier AS,
6538 const ParsedAttr &MSPropertyAttr);
6539
6540 /// Diagnose why the specified class does not have a trivial special member of
6541 /// the given kind.
6542 void DiagnoseNontrivial(const CXXRecordDecl *Record,
6543 CXXSpecialMemberKind CSM);
6544
6545 /// Determine whether a defaulted or deleted special member function is
6546 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6547 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6548 bool SpecialMemberIsTrivial(
6549 CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
6550 TrivialABIHandling TAH = TrivialABIHandling::IgnoreTrivialABI,
6551 bool Diagnose = false);
6552
6553 /// Handle a C++11 empty-declaration and attribute-declaration.
6554 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
6555 SourceLocation SemiLoc);
6556
6557 enum class CheckConstexprKind {
6558 /// Diagnose issues that are non-constant or that are extensions.
6559 Diagnose,
6560 /// Identify whether this function satisfies the formal rules for constexpr
6561 /// functions in the current lanugage mode (with no extensions).
6562 CheckValid
6563 };
6564
6565 // Check whether a function declaration satisfies the requirements of a
6566 // constexpr function definition or a constexpr constructor definition. If so,
6567 // return true. If not, produce appropriate diagnostics (unless asked not to
6568 // by Kind) and return false.
6569 //
6570 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6571 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
6572 CheckConstexprKind Kind);
6573
6574 /// Diagnose methods which overload virtual methods in a base class
6575 /// without overriding any.
6576 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
6577
6578 /// Check if a method overloads virtual methods in a base class without
6579 /// overriding any.
6580 void
6581 FindHiddenVirtualMethods(CXXMethodDecl *MD,
6582 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6583 void
6584 NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6585 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6586
6587 /// ActOnParamDefaultArgument - Check whether the default argument
6588 /// provided for a function parameter is well-formed. If so, attach it
6589 /// to the parameter declaration.
6590 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6591 Expr *defarg);
6592
6593 /// ActOnParamUnparsedDefaultArgument - We've seen a default
6594 /// argument for a function parameter, but we can't parse it yet
6595 /// because we're inside a class definition. Note that this default
6596 /// argument will be parsed later.
6597 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
6598 SourceLocation ArgLoc);
6599
6600 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6601 /// the default argument for the parameter param failed.
6602 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
6603 Expr *DefaultArg);
6604 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6605 SourceLocation EqualLoc);
6606 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6607 SourceLocation EqualLoc);
6608
6609 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6610 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6611 StringLiteral *Message = nullptr);
6612 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
6613
6614 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6615 StringLiteral *DeletedMessage = nullptr);
6616 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
6617 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
6618 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
6619
6620 NamedDecl *
6621 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
6622 MultiTemplateParamsArg TemplateParamLists);
6623 void DiagPlaceholderVariableDefinition(SourceLocation Loc);
6624 bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
6625 RecordDecl *ClassDecl,
6626 const IdentifierInfo *Name);
6627
6628 UnsignedOrNone GetDecompositionElementCount(QualType DecompType,
6629 SourceLocation Loc);
6630 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
6631
6632 /// Stack containing information needed when in C++2a an 'auto' is encountered
6633 /// in a function declaration parameter type specifier in order to invent a
6634 /// corresponding template parameter in the enclosing abbreviated function
6635 /// template. This information is also present in LambdaScopeInfo, stored in
6636 /// the FunctionScopes stack.
6637 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
6638
6639 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6640 std::unique_ptr<CXXFieldCollector> FieldCollector;
6641
6642 typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType;
6643 /// Set containing all declared private fields that are not used.
6644 NamedDeclSetType UnusedPrivateFields;
6645
6646 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 8> RecordDeclSetTy;
6647
6648 /// PureVirtualClassDiagSet - a set of class declarations which we have
6649 /// emitted a list of pure virtual functions. Used to prevent emitting the
6650 /// same list more than once.
6651 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6652
6653 typedef LazyVector<CXXConstructorDecl *,
6654 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
6655 DelegatingCtorDeclsType;
6656
6657 /// All the delegating constructors seen so far in the file, used for
6658 /// cycle detection at the end of the TU.
6659 DelegatingCtorDeclsType DelegatingCtorDecls;
6660
6661 /// The C++ "std" namespace, where the standard library resides.
6662 LazyDeclPtr StdNamespace;
6663
6664 /// The C++ "std::initializer_list" template, which is defined in
6665 /// \<initializer_list>.
6666 ClassTemplateDecl *StdInitializerList;
6667
6668 /// The C++ "std::type_identity" template, which is defined in
6669 /// \<type_traits>.
6670 ClassTemplateDecl *StdTypeIdentity;
6671
6672 // Contains the locations of the beginning of unparsed default
6673 // argument locations.
6674 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6675
6676 /// UndefinedInternals - all the used, undefined objects which require a
6677 /// definition in this translation unit.
6678 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6679
6680 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6681 SpecialMemberDecl;
6682
6683 /// The C++ special members which we are currently in the process of
6684 /// declaring. If this process recursively triggers the declaration of the
6685 /// same special member, we should act as if it is not yet declared.
6686 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
6687
6688 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
6689
6690 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6691
6692 typedef ProcessingContextState ParsingClassState;
6693 ParsingClassState PushParsingClass() {
6694 ParsingClassDepth++;
6695 return DelayedDiagnostics.pushUndelayed();
6696 }
6697 void PopParsingClass(ParsingClassState state) {
6698 ParsingClassDepth--;
6699 DelayedDiagnostics.popUndelayed(state);
6700 }
6701
6702 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
6703 CXXScopeSpec &SS,
6704 ParsedType TemplateTypeTy,
6705 IdentifierInfo *MemberOrBase);
6706
6707private:
6708 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6709 QualType ResultTy,
6710 ArrayRef<QualType> Args);
6711 // Helper for ActOnFields to check for all function pointer members.
6712 bool EntirelyFunctionPointers(const RecordDecl *Record);
6713
6714 // A cache representing if we've fully checked the various comparison category
6715 // types stored in ASTContext. The bit-index corresponds to the integer value
6716 // of a ComparisonCategoryType enumerator.
6717 llvm::SmallBitVector FullyCheckedComparisonCategories;
6718
6719 /// Check if there is a field shadowing.
6720 void CheckShadowInheritedFields(const SourceLocation &Loc,
6721 DeclarationName FieldName,
6722 const CXXRecordDecl *RD,
6723 bool DeclIsField = true);
6724
6725 ///@}
6726
6727 //
6728 //
6729 // -------------------------------------------------------------------------
6730 //
6731 //
6732
6733 /// \name C++ Exception Specifications
6734 /// Implementations are in SemaExceptionSpec.cpp
6735 ///@{
6736
6737public:
6738 /// All the overriding functions seen during a class definition
6739 /// that had their exception spec checks delayed, plus the overridden
6740 /// function.
6741 SmallVector<std::pair<const CXXMethodDecl *, const CXXMethodDecl *>, 2>
6742 DelayedOverridingExceptionSpecChecks;
6743
6744 /// All the function redeclarations seen during a class definition that had
6745 /// their exception spec checks delayed, plus the prior declaration they
6746 /// should be checked against. Except during error recovery, the new decl
6747 /// should always be a friend declaration, as that's the only valid way to
6748 /// redeclare a special member before its class is complete.
6749 SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 2>
6750 DelayedEquivalentExceptionSpecChecks;
6751
6752 /// Determine if we're in a case where we need to (incorrectly) eagerly
6753 /// parse an exception specification to work around a libstdc++ bug.
6754 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6755
6756 /// Check the given noexcept-specifier, convert its expression, and compute
6757 /// the appropriate ExceptionSpecificationType.
6758 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6759 ExceptionSpecificationType &EST);
6760
6761 CanThrowResult canThrow(const Stmt *E);
6762 /// Determine whether the callee of a particular function call can throw.
6763 /// E, D and Loc are all optional.
6764 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6765 SourceLocation Loc = SourceLocation());
6766 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
6767 const FunctionProtoType *FPT);
6768 void UpdateExceptionSpec(FunctionDecl *FD,
6769 const FunctionProtoType::ExceptionSpecInfo &ESI);
6770
6771 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6772 /// exception specification. Incomplete types, or pointers to incomplete types
6773 /// other than void are not allowed.
6774 ///
6775 /// \param[in,out] T The exception type. This will be decayed to a pointer
6776 /// type
6777 /// when the input is an array or a function type.
6778 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
6779
6780 /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6781 /// pointer to member to a function with an exception specification. This
6782 /// means that it is invalid to add another level of indirection.
6783 bool CheckDistantExceptionSpec(QualType T);
6784 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
6785
6786 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6787 /// exception specifications. Exception specifications are equivalent if
6788 /// they allow exactly the same set of exception types. It does not matter how
6789 /// that is achieved. See C++ [except.spec]p2.
6790 bool CheckEquivalentExceptionSpec(const FunctionProtoType *Old,
6791 SourceLocation OldLoc,
6792 const FunctionProtoType *New,
6793 SourceLocation NewLoc);
6794 bool CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
6795 const PartialDiagnostic &NoteID,
6796 const FunctionProtoType *Old,
6797 SourceLocation OldLoc,
6798 const FunctionProtoType *New,
6799 SourceLocation NewLoc);
6800 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6801
6802 /// CheckExceptionSpecSubset - Check whether the second function type's
6803 /// exception specification is a subset (or equivalent) of the first function
6804 /// type. This is used by override and pointer assignment checks.
6805 bool CheckExceptionSpecSubset(
6806 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6807 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6808 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6809 SourceLocation SuperLoc, const FunctionProtoType *Subset,
6810 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6811
6812 /// CheckParamExceptionSpec - Check if the parameter and return types of the
6813 /// two functions have equivalent exception specs. This is part of the
6814 /// assignment and override compatibility check. We do not check the
6815 /// parameters of parameter function pointers recursively, as no sane
6816 /// programmer would even be able to write such a function type.
6817 bool CheckParamExceptionSpec(
6818 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6819 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6820 SourceLocation TargetLoc, const FunctionProtoType *Source,
6821 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6822
6823 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6824
6825 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6826 /// spec is a subset of base spec.
6827 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6828 const CXXMethodDecl *Old);
6829
6830 ///@}
6831
6832 //
6833 //
6834 // -------------------------------------------------------------------------
6835 //
6836 //
6837
6838 /// \name Expressions
6839 /// Implementations are in SemaExpr.cpp
6840 ///@{
6841
6842public:
6843 /// Describes how the expressions currently being parsed are
6844 /// evaluated at run-time, if at all.
6845 enum class ExpressionEvaluationContext {
6846 /// The current expression and its subexpressions occur within an
6847 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6848 /// \c sizeof, where the type of the expression may be significant but
6849 /// no code will be generated to evaluate the value of the expression at
6850 /// run time.
6851 Unevaluated,
6852
6853 /// The current expression occurs within a braced-init-list within
6854 /// an unevaluated operand. This is mostly like a regular unevaluated
6855 /// context, except that we still instantiate constexpr functions that are
6856 /// referenced here so that we can perform narrowing checks correctly.
6857 UnevaluatedList,
6858
6859 /// The current expression occurs within a discarded statement.
6860 /// This behaves largely similarly to an unevaluated operand in preventing
6861 /// definitions from being required, but not in other ways.
6862 DiscardedStatement,
6863
6864 /// The current expression occurs within an unevaluated
6865 /// operand that unconditionally permits abstract references to
6866 /// fields, such as a SIZE operator in MS-style inline assembly.
6867 UnevaluatedAbstract,
6868
6869 /// The current context is "potentially evaluated" in C++11 terms,
6870 /// but the expression is evaluated at compile-time (like the values of
6871 /// cases in a switch statement).
6872 ConstantEvaluated,
6873
6874 /// In addition of being constant evaluated, the current expression
6875 /// occurs in an immediate function context - either a consteval function
6876 /// or a consteval if statement.
6877 ImmediateFunctionContext,
6878
6879 /// The current expression is potentially evaluated at run time,
6880 /// which means that code may be generated to evaluate the value of the
6881 /// expression at run time.
6882 PotentiallyEvaluated,
6883
6884 /// The current expression is potentially evaluated, but any
6885 /// declarations referenced inside that expression are only used if
6886 /// in fact the current expression is used.
6887 ///
6888 /// This value is used when parsing default function arguments, for which
6889 /// we would like to provide diagnostics (e.g., passing non-POD arguments
6890 /// through varargs) but do not want to mark declarations as "referenced"
6891 /// until the default argument is used.
6892 PotentiallyEvaluatedIfUsed
6893 };
6894
6895 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6896 /// to a variable (constant) that may or may not be odr-used in this Expr, and
6897 /// we won't know until all lvalue-to-rvalue and discarded value conversions
6898 /// have been applied to all subexpressions of the enclosing full expression.
6899 /// This is cleared at the end of each full expression.
6900 using MaybeODRUseExprSet = llvm::SmallSetVector<Expr *, 4>;
6901 MaybeODRUseExprSet MaybeODRUseExprs;
6902
6903 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6904
6905 /// Data structure used to record current or nested
6906 /// expression evaluation contexts.
6907 struct ExpressionEvaluationContextRecord {
6908 /// The expression evaluation context.
6909 ExpressionEvaluationContext Context;
6910
6911 /// Whether the enclosing context needed a cleanup.
6912 CleanupInfo ParentCleanup;
6913
6914 /// The number of active cleanup objects when we entered
6915 /// this expression evaluation context.
6916 unsigned NumCleanupObjects;
6917
6918 MaybeODRUseExprSet SavedMaybeODRUseExprs;
6919
6920 /// The lambdas that are present within this context, if it
6921 /// is indeed an unevaluated context.
6922 SmallVector<LambdaExpr *, 2> Lambdas;
6923
6924 /// The declaration that provides context for lambda expressions
6925 /// and block literals if the normal declaration context does not
6926 /// suffice, e.g., in a default function argument.
6927 Decl *ManglingContextDecl;
6928
6929 /// Declaration for initializer if one is currently being
6930 /// parsed. Used when an expression has a possibly unreachable
6931 /// diagnostic to reference the declaration as a whole.
6932 VarDecl *DeclForInitializer = nullptr;
6933
6934 /// If we are processing a decltype type, a set of call expressions
6935 /// for which we have deferred checking the completeness of the return type.
6936 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
6937
6938 /// If we are processing a decltype type, a set of temporary binding
6939 /// expressions for which we have deferred checking the destructor.
6940 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
6941
6942 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
6943
6944 /// Expressions appearing as the LHS of a volatile assignment in this
6945 /// context. We produce a warning for these when popping the context if
6946 /// they are not discarded-value expressions nor unevaluated operands.
6947 SmallVector<Expr *, 2> VolatileAssignmentLHSs;
6948
6949 /// Set of candidates for starting an immediate invocation.
6950 llvm::SmallVector<ImmediateInvocationCandidate, 4>
6951 ImmediateInvocationCandidates;
6952
6953 /// Set of DeclRefExprs referencing a consteval function when used in a
6954 /// context not already known to be immediately invoked.
6955 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
6956
6957 /// P2718R0 - Lifetime extension in range-based for loops.
6958 /// MaterializeTemporaryExprs in for-range-init expressions which need to
6959 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
6960 /// InLifetimeExtendingContext is true.
6961 SmallVector<MaterializeTemporaryExpr *, 8> ForRangeLifetimeExtendTemps;
6962
6963 /// Small set of gathered accesses to potentially misaligned members
6964 /// due to the packed attribute.
6965 SmallVector<MisalignedMember, 4> MisalignedMembers;
6966
6967 /// \brief Describes whether we are in an expression constext which we have
6968 /// to handle differently.
6969 enum ExpressionKind {
6970 EK_Decltype,
6971 EK_TemplateArgument,
6972 EK_AttrArgument,
6973 EK_VariableInit,
6974 EK_Other
6975 } ExprContext;
6976
6977 // A context can be nested in both a discarded statement context and
6978 // an immediate function context, so they need to be tracked independently.
6979 bool InDiscardedStatement;
6980 bool InImmediateFunctionContext;
6981 bool InImmediateEscalatingFunctionContext;
6982
6983 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
6984
6985 // We are in a constant context, but we also allow
6986 // non constant expressions, for example for array bounds (which may be
6987 // VLAs).
6988 bool InConditionallyConstantEvaluateContext = false;
6989
6990 /// Whether we are currently in a context in which all temporaries must be
6991 /// lifetime-extended, even if they're not bound to a reference (for
6992 /// example, in a for-range initializer).
6993 bool InLifetimeExtendingContext = false;
6994
6995 /// Whether evaluating an expression for a switch case label.
6996 bool IsCaseExpr = false;
6997
6998 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
6999 bool RebuildDefaultArgOrDefaultInit = false;
7000
7001 // When evaluating immediate functions in the initializer of a default
7002 // argument or default member initializer, this is the declaration whose
7003 // default initializer is being evaluated and the location of the call
7004 // or constructor definition.
7005 struct InitializationContext {
7006 InitializationContext(SourceLocation Loc, ValueDecl *Decl,
7007 DeclContext *Context)
7008 : Loc(Loc), Decl(Decl), Context(Context) {
7009 assert(Decl && Context && "invalid initialization context");
7010 }
7011
7012 SourceLocation Loc;
7013 ValueDecl *Decl = nullptr;
7014 DeclContext *Context = nullptr;
7015 };
7016 std::optional<InitializationContext> DelayedDefaultInitializationContext;
7017
7018 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
7019 unsigned NumCleanupObjects,
7020 CleanupInfo ParentCleanup,
7021 Decl *ManglingContextDecl,
7022 ExpressionKind ExprContext)
7023 : Context(Context), ParentCleanup(ParentCleanup),
7024 NumCleanupObjects(NumCleanupObjects),
7025 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
7026 InDiscardedStatement(false), InImmediateFunctionContext(false),
7027 InImmediateEscalatingFunctionContext(false) {}
7028
7029 bool isUnevaluated() const {
7030 return Context == ExpressionEvaluationContext::Unevaluated ||
7031 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
7032 Context == ExpressionEvaluationContext::UnevaluatedList;
7033 }
7034
7035 bool isPotentiallyEvaluated() const {
7036 return Context == ExpressionEvaluationContext::PotentiallyEvaluated ||
7037 Context ==
7038 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed ||
7039 Context == ExpressionEvaluationContext::ConstantEvaluated;
7040 }
7041
7042 bool isConstantEvaluated() const {
7043 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
7044 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
7045 }
7046
7047 bool isImmediateFunctionContext() const {
7048 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
7049 (Context == ExpressionEvaluationContext::DiscardedStatement &&
7050 InImmediateFunctionContext) ||
7051 // C++23 [expr.const]p14:
7052 // An expression or conversion is in an immediate function
7053 // context if it is potentially evaluated and either:
7054 // * its innermost enclosing non-block scope is a function
7055 // parameter scope of an immediate function, or
7056 // * its enclosing statement is enclosed by the compound-
7057 // statement of a consteval if statement.
7058 (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
7059 InImmediateFunctionContext);
7060 }
7061
7062 bool isDiscardedStatementContext() const {
7063 return Context == ExpressionEvaluationContext::DiscardedStatement ||
7064 ((Context ==
7065 ExpressionEvaluationContext::ImmediateFunctionContext ||
7066 isPotentiallyEvaluated()) &&
7067 InDiscardedStatement);
7068 }
7069 };
7070
7071 const ExpressionEvaluationContextRecord &currentEvaluationContext() const {
7072 assert(!ExprEvalContexts.empty() &&
7073 "Must be in an expression evaluation context");
7074 return ExprEvalContexts.back();
7075 }
7076
7077 ExpressionEvaluationContextRecord &currentEvaluationContext() {
7078 assert(!ExprEvalContexts.empty() &&
7079 "Must be in an expression evaluation context");
7080 return ExprEvalContexts.back();
7081 }
7082
7083 ExpressionEvaluationContextRecord &parentEvaluationContext() {
7084 assert(ExprEvalContexts.size() >= 2 &&
7085 "Must be in an expression evaluation context");
7086 return ExprEvalContexts[ExprEvalContexts.size() - 2];
7087 }
7088
7089 const ExpressionEvaluationContextRecord &parentEvaluationContext() const {
7090 return const_cast<Sema *>(this)->parentEvaluationContext();
7091 }
7092
7093 bool isAttrContext() const {
7094 return ExprEvalContexts.back().ExprContext ==
7095 ExpressionEvaluationContextRecord::ExpressionKind::EK_AttrArgument;
7096 }
7097
7098 /// Increment when we find a reference; decrement when we find an ignored
7099 /// assignment. Ultimately the value is 0 if every reference is an ignored
7100 /// assignment.
7101 ///
7102 /// Uses canonical VarDecl as key so in-class decls and out-of-class defs of
7103 /// static data members get tracked as a single entry.
7104 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
7105
7106 /// Used to control the generation of ExprWithCleanups.
7107 CleanupInfo Cleanup;
7108
7109 /// ExprCleanupObjects - This is the stack of objects requiring
7110 /// cleanup that are created by the current full expression.
7111 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
7112
7113 /// Determine whether the use of this declaration is valid, without
7114 /// emitting diagnostics.
7115 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
7116 // A version of DiagnoseUseOfDecl that should be used if overload resolution
7117 // has been used to find this declaration, which means we don't have to bother
7118 // checking the trailing requires clause.
7119 bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) {
7120 return DiagnoseUseOfDecl(
7121 D, Locs: Loc, /*UnknownObjCClass=*/UnknownObjCClass: nullptr, /*ObjCPropertyAccess=*/ObjCPropertyAccess: false,
7122 /*AvoidPartialAvailabilityChecks=*/AvoidPartialAvailabilityChecks: false, /*ClassReceiver=*/ClassReceiver: nullptr,
7123 /*SkipTrailingRequiresClause=*/SkipTrailingRequiresClause: true);
7124 }
7125
7126 /// Determine whether the use of this declaration is valid, and
7127 /// emit any corresponding diagnostics.
7128 ///
7129 /// This routine diagnoses various problems with referencing
7130 /// declarations that can occur when using a declaration. For example,
7131 /// it might warn if a deprecated or unavailable declaration is being
7132 /// used, or produce an error (and return true) if a C++0x deleted
7133 /// function is being used.
7134 ///
7135 /// \returns true if there was an error (this declaration cannot be
7136 /// referenced), false otherwise.
7137 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
7138 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
7139 bool ObjCPropertyAccess = false,
7140 bool AvoidPartialAvailabilityChecks = false,
7141 ObjCInterfaceDecl *ClassReceiver = nullptr,
7142 bool SkipTrailingRequiresClause = false);
7143
7144 /// Emit a note explaining that this function is deleted.
7145 void NoteDeletedFunction(FunctionDecl *FD);
7146
7147 /// DiagnoseSentinelCalls - This routine checks whether a call or
7148 /// message-send is to a declaration with the sentinel attribute, and
7149 /// if so, it checks that the requirements of the sentinel are
7150 /// satisfied.
7151 void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
7152 ArrayRef<Expr *> Args);
7153
7154 void PushExpressionEvaluationContext(
7155 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
7156 ExpressionEvaluationContextRecord::ExpressionKind Type =
7157 ExpressionEvaluationContextRecord::EK_Other);
7158
7159 void PushExpressionEvaluationContextForFunction(
7160 ExpressionEvaluationContext NewContext, FunctionDecl *FD);
7161
7162 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
7163 void PushExpressionEvaluationContext(
7164 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
7165 ExpressionEvaluationContextRecord::ExpressionKind Type =
7166 ExpressionEvaluationContextRecord::EK_Other);
7167 void PopExpressionEvaluationContext();
7168
7169 void DiscardCleanupsInEvaluationContext();
7170
7171 ExprResult TransformToPotentiallyEvaluated(Expr *E);
7172 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
7173 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
7174
7175 /// Check whether E, which is either a discarded-value expression or an
7176 /// unevaluated operand, is a simple-assignment to a volatlie-qualified
7177 /// lvalue, and if so, remove it from the list of volatile-qualified
7178 /// assignments that we are going to warn are deprecated.
7179 void CheckUnusedVolatileAssignment(Expr *E);
7180
7181 ExprResult ActOnConstantExpression(ExprResult Res);
7182
7183 // Functions for marking a declaration referenced. These functions also
7184 // contain the relevant logic for marking if a reference to a function or
7185 // variable is an odr-use (in the C++11 sense). There are separate variants
7186 // for expressions referring to a decl; these exist because odr-use marking
7187 // needs to be delayed for some constant variables when we build one of the
7188 // named expressions.
7189 //
7190 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
7191 // should usually be true. This only needs to be set to false if the lack of
7192 // odr-use cannot be determined from the current context (for instance,
7193 // because the name denotes a virtual function and was written without an
7194 // explicit nested-name-specifier).
7195 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
7196
7197 /// Mark a function referenced, and check whether it is odr-used
7198 /// (C++ [basic.def.odr]p2, C99 6.9p3)
7199 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
7200 bool MightBeOdrUse = true);
7201
7202 /// Mark a variable referenced, and check whether it is odr-used
7203 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
7204 /// used directly for normal expressions referring to VarDecl.
7205 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
7206
7207 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7208 ///
7209 /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7210 /// be handled with care if the DeclRefExpr is not newly-created.
7211 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7212
7213 /// Perform reference-marking and odr-use handling for a MemberExpr.
7214 void MarkMemberReferenced(MemberExpr *E);
7215
7216 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7217 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
7218 void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc,
7219 unsigned CapturingScopeIndex);
7220
7221 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
7222 void CleanupVarDeclMarking();
7223
7224 /// Try to capture the given variable.
7225 ///
7226 /// \param Var The variable to capture.
7227 ///
7228 /// \param Loc The location at which the capture occurs.
7229 ///
7230 /// \param Kind The kind of capture, which may be implicit (for either a
7231 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7232 ///
7233 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7234 /// an explicit lambda capture.
7235 ///
7236 /// \param BuildAndDiagnose Whether we are actually supposed to add the
7237 /// captures or diagnose errors. If false, this routine merely check whether
7238 /// the capture can occur without performing the capture itself or complaining
7239 /// if the variable cannot be captured.
7240 ///
7241 /// \param CaptureType Will be set to the type of the field used to capture
7242 /// this variable in the innermost block or lambda. Only valid when the
7243 /// variable can be captured.
7244 ///
7245 /// \param DeclRefType Will be set to the type of a reference to the capture
7246 /// from within the current scope. Only valid when the variable can be
7247 /// captured.
7248 ///
7249 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7250 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7251 /// This is useful when enclosing lambdas must speculatively capture
7252 /// variables that may or may not be used in certain specializations of
7253 /// a nested generic lambda.
7254 ///
7255 /// \returns true if an error occurred (i.e., the variable cannot be
7256 /// captured) and false if the capture succeeded.
7257 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7258 TryCaptureKind Kind, SourceLocation EllipsisLoc,
7259 bool BuildAndDiagnose, QualType &CaptureType,
7260 QualType &DeclRefType,
7261 const unsigned *const FunctionScopeIndexToStopAt);
7262
7263 /// Try to capture the given variable.
7264 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7265 TryCaptureKind Kind = TryCaptureKind::Implicit,
7266 SourceLocation EllipsisLoc = SourceLocation());
7267
7268 /// Checks if the variable must be captured.
7269 bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc);
7270
7271 /// Given a variable, determine the type that a reference to that
7272 /// variable will have in the given scope.
7273 QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc);
7274
7275 /// Mark all of the declarations referenced within a particular AST node as
7276 /// referenced. Used when template instantiation instantiates a non-dependent
7277 /// type -- entities referenced by the type are now referenced.
7278 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
7279
7280 /// Mark any declarations that appear within this expression or any
7281 /// potentially-evaluated subexpressions as "referenced".
7282 ///
7283 /// \param SkipLocalVariables If true, don't mark local variables as
7284 /// 'referenced'.
7285 /// \param StopAt Subexpressions that we shouldn't recurse into.
7286 void MarkDeclarationsReferencedInExpr(Expr *E,
7287 bool SkipLocalVariables = false,
7288 ArrayRef<const Expr *> StopAt = {});
7289
7290 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7291 /// conversion.
7292 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7293
7294 /// Conditionally issue a diagnostic based on the statements's reachability
7295 /// analysis.
7296 ///
7297 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7298 /// the function body is parsed, and then do a basic reachability analysis to
7299 /// determine if the statement is reachable. If it is unreachable, the
7300 /// diagnostic will not be emitted.
7301 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7302 const PartialDiagnostic &PD);
7303
7304 /// Conditionally issue a diagnostic based on the current
7305 /// evaluation context.
7306 ///
7307 /// \param Statement If Statement is non-null, delay reporting the
7308 /// diagnostic until the function body is parsed, and then do a basic
7309 /// reachability analysis to determine if the statement is reachable.
7310 /// If it is unreachable, the diagnostic will not be emitted.
7311 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7312 const PartialDiagnostic &PD);
7313 /// Similar, but diagnostic is only produced if all the specified statements
7314 /// are reachable.
7315 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7316 const PartialDiagnostic &PD);
7317
7318 // Primary Expressions.
7319 SourceRange getExprRange(Expr *E) const;
7320
7321 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7322 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7323 bool HasTrailingLParen, bool IsAddressOfOperand,
7324 CorrectionCandidateCallback *CCC = nullptr,
7325 bool IsInlineAsmIdentifier = false);
7326
7327 /// Decomposes the given name into a DeclarationNameInfo, its location, and
7328 /// possibly a list of template arguments.
7329 ///
7330 /// If this produces template arguments, it is permitted to call
7331 /// DecomposeTemplateName.
7332 ///
7333 /// This actually loses a lot of source location information for
7334 /// non-standard name kinds; we should consider preserving that in
7335 /// some way.
7336 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7337 TemplateArgumentListInfo &Buffer,
7338 DeclarationNameInfo &NameInfo,
7339 const TemplateArgumentListInfo *&TemplateArgs);
7340
7341 /// Diagnose a lookup that found results in an enclosing class during error
7342 /// recovery. This usually indicates that the results were found in a
7343 /// dependent base class that could not be searched as part of a template
7344 /// definition. Always issues a diagnostic (though this may be only a warning
7345 /// in MS compatibility mode).
7346 ///
7347 /// Return \c true if the error is unrecoverable, or \c false if the caller
7348 /// should attempt to recover using these lookup results.
7349 bool DiagnoseDependentMemberLookup(const LookupResult &R);
7350
7351 /// Diagnose an empty lookup.
7352 ///
7353 /// \return false if new lookup candidates were found
7354 bool
7355 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7356 CorrectionCandidateCallback &CCC,
7357 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7358 ArrayRef<Expr *> Args = {},
7359 DeclContext *LookupCtx = nullptr);
7360
7361 /// If \p D cannot be odr-used in the current expression evaluation context,
7362 /// return a reason explaining why. Otherwise, return NOUR_None.
7363 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
7364
7365 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7366 SourceLocation Loc,
7367 const CXXScopeSpec *SS = nullptr);
7368 DeclRefExpr *
7369 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7370 const DeclarationNameInfo &NameInfo,
7371 const CXXScopeSpec *SS = nullptr,
7372 NamedDecl *FoundD = nullptr,
7373 SourceLocation TemplateKWLoc = SourceLocation(),
7374 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7375
7376 /// BuildDeclRefExpr - Build an expression that references a
7377 /// declaration that does not require a closure capture.
7378 DeclRefExpr *
7379 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7380 const DeclarationNameInfo &NameInfo,
7381 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7382 SourceLocation TemplateKWLoc = SourceLocation(),
7383 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7384
7385 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7386 bool HasTrailingLParen);
7387
7388 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7389 /// declaration name, generally during template instantiation.
7390 /// There's a large number of things which don't need to be done along
7391 /// this path.
7392 ExprResult BuildQualifiedDeclarationNameExpr(
7393 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7394 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7395
7396 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7397 bool NeedsADL,
7398 bool AcceptInvalidDecl = false);
7399
7400 /// Complete semantic analysis for a reference to the given declaration.
7401 ExprResult BuildDeclarationNameExpr(
7402 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7403 NamedDecl *FoundD = nullptr,
7404 const TemplateArgumentListInfo *TemplateArgs = nullptr,
7405 bool AcceptInvalidDecl = false);
7406
7407 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7408 // where Tokens representing function local predefined macros (such as
7409 // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7410 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7411
7412 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7413 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7414 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7415
7416 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7417
7418 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7419 ExprResult ActOnCharacterConstant(const Token &Tok,
7420 Scope *UDLScope = nullptr);
7421 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7422 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7423 MultiExprArg Val);
7424 ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7425 unsigned NumUserSpecifiedExprs,
7426 SourceLocation InitLoc,
7427 SourceLocation LParenLoc,
7428 SourceLocation RParenLoc);
7429
7430 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7431 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle
7432 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7433 /// from multiple tokens. However, the common case is that StringToks points
7434 /// to one string.
7435 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7436 Scope *UDLScope = nullptr);
7437
7438 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7439
7440 /// ControllingExprOrType is either an opaque pointer coming out of a
7441 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7442 /// into two so we don't take a void *, but that's awkward because one of
7443 /// the operands is either a ParsedType or an Expr *, which doesn't lend
7444 /// itself to generic code very well.
7445 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7446 SourceLocation DefaultLoc,
7447 SourceLocation RParenLoc,
7448 bool PredicateIsExpr,
7449 void *ControllingExprOrType,
7450 ArrayRef<ParsedType> ArgTypes,
7451 ArrayRef<Expr *> ArgExprs);
7452 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7453 /// it'd be better to split this interface into two so we don't take a
7454 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7455 /// isn't a trivial change.
7456 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7457 SourceLocation DefaultLoc,
7458 SourceLocation RParenLoc,
7459 bool PredicateIsExpr,
7460 void *ControllingExprOrType,
7461 ArrayRef<TypeSourceInfo *> Types,
7462 ArrayRef<Expr *> Exprs);
7463
7464 // Binary/Unary Operators. 'Tok' is the token for the operator.
7465 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7466 Expr *InputExpr, bool IsAfterAmp = false);
7467 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7468 Expr *Input, bool IsAfterAmp = false);
7469
7470 /// Unary Operators. 'Tok' is the token for the operator.
7471 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7472 Expr *Input, bool IsAfterAmp = false);
7473
7474 /// Determine whether the given expression is a qualified member
7475 /// access expression, of a form that could be turned into a pointer to member
7476 /// with the address-of operator.
7477 bool isQualifiedMemberAccess(Expr *E);
7478 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7479 const Expr *Op,
7480 const CXXMethodDecl *MD);
7481
7482 /// CheckAddressOfOperand - The operand of & must be either a function
7483 /// designator or an lvalue designating an object. If it is an lvalue, the
7484 /// object cannot be declared with storage class register or be a bit field.
7485 /// Note: The usual conversions are *not* applied to the operand of the &
7486 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7487 /// In C++, the operand might be an overloaded function name, in which case
7488 /// we allow the '&' but retain the overloaded-function type.
7489 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7490
7491 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7492 /// _Alignas(type-name) .
7493 /// [dcl.align] An alignment-specifier of the form
7494 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7495 ///
7496 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7497 /// _Alignas(_Alignof(type-name)).
7498 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7499 SourceLocation OpLoc, SourceRange R);
7500 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7501 SourceLocation OpLoc, SourceRange R);
7502
7503 /// Build a sizeof or alignof expression given a type operand.
7504 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7505 SourceLocation OpLoc,
7506 UnaryExprOrTypeTrait ExprKind,
7507 SourceRange R);
7508
7509 /// Build a sizeof or alignof expression given an expression
7510 /// operand.
7511 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7512 UnaryExprOrTypeTrait ExprKind);
7513
7514 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7515 /// expr and the same for @c alignof and @c __alignof
7516 /// Note that the ArgRange is invalid if isType is false.
7517 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7518 UnaryExprOrTypeTrait ExprKind,
7519 bool IsType, void *TyOrEx,
7520 SourceRange ArgRange);
7521
7522 /// Check for operands with placeholder types and complain if found.
7523 /// Returns ExprError() if there was an error and no recovery was possible.
7524 ExprResult CheckPlaceholderExpr(Expr *E);
7525 bool CheckVecStepExpr(Expr *E);
7526
7527 /// Check the constraints on expression operands to unary type expression
7528 /// and type traits.
7529 ///
7530 /// Completes any types necessary and validates the constraints on the operand
7531 /// expression. The logic mostly mirrors the type-based overload, but may
7532 /// modify the expression as it completes the type for that expression through
7533 /// template instantiation, etc.
7534 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
7535
7536 /// Check the constraints on operands to unary expression and type
7537 /// traits.
7538 ///
7539 /// This will complete any types necessary, and validate the various
7540 /// constraints on those operands.
7541 ///
7542 /// The UsualUnaryConversions() function is *not* called by this routine.
7543 /// C99 6.3.2.1p[2-4] all state:
7544 /// Except when it is the operand of the sizeof operator ...
7545 ///
7546 /// C++ [expr.sizeof]p4
7547 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7548 /// standard conversions are not applied to the operand of sizeof.
7549 ///
7550 /// This policy is followed for all of the unary trait expressions.
7551 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7552 SourceRange ExprRange,
7553 UnaryExprOrTypeTrait ExprKind,
7554 StringRef KWName);
7555
7556 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7557 tok::TokenKind Kind, Expr *Input);
7558
7559 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7560 MultiExprArg ArgExprs,
7561 SourceLocation RLoc);
7562 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7563 Expr *Idx, SourceLocation RLoc);
7564
7565 ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx,
7566 SourceLocation RBLoc);
7567
7568 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7569 Expr *ColumnIdx,
7570 SourceLocation RBLoc);
7571
7572 /// ConvertArgumentsForCall - Converts the arguments specified in
7573 /// Args/NumArgs to the parameter types of the function FDecl with
7574 /// function prototype Proto. Call is the call expression itself, and
7575 /// Fn is the function expression. For a C++ member function, this
7576 /// routine does not attempt to convert the object argument. Returns
7577 /// true if the call is ill-formed.
7578 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7579 const FunctionProtoType *Proto,
7580 ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7581 bool ExecConfig = false);
7582
7583 /// CheckStaticArrayArgument - If the given argument corresponds to a static
7584 /// array parameter, check that it is non-null, and that if it is formed by
7585 /// array-to-pointer decay, the underlying array is sufficiently large.
7586 ///
7587 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7588 /// the array type derivation, then for each call to the function, the value
7589 /// of the corresponding actual argument shall provide access to the first
7590 /// element of an array with at least as many elements as specified by the
7591 /// size expression.
7592 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7593 const Expr *ArgExpr);
7594
7595 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7596 /// This provides the location of the left/right parens and a list of comma
7597 /// locations.
7598 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7599 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7600 Expr *ExecConfig = nullptr);
7601
7602 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7603 /// This provides the location of the left/right parens and a list of comma
7604 /// locations.
7605 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7606 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7607 Expr *ExecConfig = nullptr,
7608 bool IsExecConfig = false,
7609 bool AllowRecovery = false);
7610
7611 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7612 // with the specified CallArgs
7613 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7614 MultiExprArg CallArgs);
7615
7616 using ADLCallKind = CallExpr::ADLCallKind;
7617
7618 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7619 /// i.e. an expression not of \p OverloadTy. The expression should
7620 /// unary-convert to an expression of function-pointer or
7621 /// block-pointer type.
7622 ///
7623 /// \param NDecl the declaration being called, if available
7624 ExprResult
7625 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7626 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7627 Expr *Config = nullptr, bool IsExecConfig = false,
7628 ADLCallKind UsesADL = ADLCallKind::NotADL);
7629
7630 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D,
7631 ParsedType &Ty, SourceLocation RParenLoc,
7632 Expr *CastExpr);
7633
7634 /// Prepares for a scalar cast, performing all the necessary stages
7635 /// except the final cast and returning the kind required.
7636 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
7637
7638 /// Build an altivec or OpenCL literal.
7639 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
7640 SourceLocation RParenLoc, Expr *E,
7641 TypeSourceInfo *TInfo);
7642
7643 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7644 /// the ParenListExpr into a sequence of comma binary operators.
7645 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
7646
7647 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7648 SourceLocation RParenLoc, Expr *InitExpr);
7649
7650 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
7651 TypeSourceInfo *TInfo,
7652 SourceLocation RParenLoc,
7653 Expr *LiteralExpr);
7654
7655 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7656 SourceLocation RBraceLoc);
7657
7658 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7659 SourceLocation RBraceLoc, bool IsExplicit);
7660
7661 /// Binary Operators. 'Tok' is the token for the operator.
7662 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind,
7663 Expr *LHSExpr, Expr *RHSExpr);
7664 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7665 Expr *LHSExpr, Expr *RHSExpr,
7666 bool ForFoldExpression = false);
7667
7668 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7669 /// operator @p Opc at location @c TokLoc. This routine only supports
7670 /// built-in operations; ActOnBinOp handles overloaded operators.
7671 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
7672 Expr *LHSExpr, Expr *RHSExpr,
7673 bool ForFoldExpression = false);
7674 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7675 UnresolvedSetImpl &Functions);
7676
7677 /// Look for instances where it is likely the comma operator is confused with
7678 /// another operator. There is an explicit list of acceptable expressions for
7679 /// the left hand side of the comma operator, otherwise emit a warning.
7680 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7681
7682 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7683 /// in the case of a the GNU conditional expr extension.
7684 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
7685 SourceLocation ColonLoc, Expr *CondExpr,
7686 Expr *LHSExpr, Expr *RHSExpr);
7687
7688 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7689 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
7690 LabelDecl *TheDecl);
7691
7692 void ActOnStartStmtExpr();
7693 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7694 SourceLocation RPLoc);
7695 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
7696 SourceLocation RPLoc, unsigned TemplateDepth);
7697 // Handle the final expression in a statement expression.
7698 ExprResult ActOnStmtExprResult(ExprResult E);
7699 void ActOnStmtExprError();
7700
7701 /// __builtin_offsetof(type, a.b[123][456].c)
7702 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
7703 TypeSourceInfo *TInfo,
7704 const Designation &Desig,
7705 SourceLocation RParenLoc);
7706 ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
7707 SourceLocation TypeLoc,
7708 ParsedType ParsedArgTy,
7709 const Designation &Desig,
7710 SourceLocation RParenLoc);
7711
7712 // __builtin_choose_expr(constExpr, expr1, expr2)
7713 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7714 Expr *LHSExpr, Expr *RHSExpr,
7715 SourceLocation RPLoc);
7716
7717 // __builtin_va_arg(expr, type)
7718 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
7719 SourceLocation RPLoc);
7720 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
7721 TypeSourceInfo *TInfo, SourceLocation RPLoc);
7722
7723 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7724 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7725 ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind,
7726 SourceLocation BuiltinLoc,
7727 SourceLocation RPLoc);
7728
7729 // #embed
7730 ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
7731 StringLiteral *BinaryData, StringRef FileName);
7732
7733 // Build a potentially resolved SourceLocExpr.
7734 ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
7735 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7736 DeclContext *ParentContext);
7737
7738 // __null
7739 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
7740
7741 bool CheckCaseExpression(Expr *E);
7742
7743 //===------------------------- "Block" Extension ------------------------===//
7744
7745 /// ActOnBlockStart - This callback is invoked when a block literal is
7746 /// started.
7747 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7748
7749 /// ActOnBlockArguments - This callback allows processing of block arguments.
7750 /// If there are no arguments, this is still invoked.
7751 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7752 Scope *CurScope);
7753
7754 /// ActOnBlockError - If there is an error parsing a block, this callback
7755 /// is invoked to pop the information about the block from the action impl.
7756 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7757
7758 /// ActOnBlockStmtExpr - This is called when the body of a block statement
7759 /// literal was successfully completed. ^(int x){...}
7760 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
7761 Scope *CurScope);
7762
7763 //===---------------------------- Clang Extensions ----------------------===//
7764
7765 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7766 /// provided arguments.
7767 ///
7768 /// __builtin_convertvector( value, dst type )
7769 ///
7770 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7771 SourceLocation BuiltinLoc,
7772 SourceLocation RParenLoc);
7773
7774 //===---------------------------- OpenCL Features -----------------------===//
7775
7776 /// Parse a __builtin_astype expression.
7777 ///
7778 /// __builtin_astype( value, dst type )
7779 ///
7780 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7781 SourceLocation BuiltinLoc,
7782 SourceLocation RParenLoc);
7783
7784 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7785 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
7786 SourceLocation BuiltinLoc,
7787 SourceLocation RParenLoc);
7788
7789 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7790 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
7791 ArrayRef<Expr *> SubExprs,
7792 QualType T = QualType());
7793
7794 /// Cast a base object to a member's actual type.
7795 ///
7796 /// There are two relevant checks:
7797 ///
7798 /// C++ [class.access.base]p7:
7799 ///
7800 /// If a class member access operator [...] is used to access a non-static
7801 /// data member or non-static member function, the reference is ill-formed
7802 /// if the left operand [...] cannot be implicitly converted to a pointer to
7803 /// the naming class of the right operand.
7804 ///
7805 /// C++ [expr.ref]p7:
7806 ///
7807 /// If E2 is a non-static data member or a non-static member function, the
7808 /// program is ill-formed if the class of which E2 is directly a member is
7809 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7810 ///
7811 /// Note that the latter check does not consider access; the access of the
7812 /// "real" base class is checked as appropriate when checking the access of
7813 /// the member name.
7814 ExprResult PerformObjectMemberConversion(Expr *From,
7815 NestedNameSpecifier Qualifier,
7816 NamedDecl *FoundDecl,
7817 NamedDecl *Member);
7818
7819 /// CheckCallReturnType - Checks that a call expression's return type is
7820 /// complete. Returns true on failure. The location passed in is the location
7821 /// that best represents the call.
7822 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7823 CallExpr *CE, FunctionDecl *FD);
7824
7825 /// Emit a warning for all pending noderef expressions that we recorded.
7826 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
7827
7828private:
7829 /// Shared logic for building default member initializer which used in a
7830 /// constructor or an aggregate initialization.
7831 ///
7832 ///
7833 /// The caller enters that evaluation context and decides whether the result
7834 /// is finished as a full-expression. \p NestedDefaultChecking and
7835 /// \p NeedRebuild have to be sampled before entering it.
7836 ExprResult BuildCXXDefaultInitInternal(SourceLocation Loc, FieldDecl *Field,
7837 const InitializedEntity &Entity,
7838 bool NestedDefaultChecking,
7839 bool NeedRebuild);
7840
7841public:
7842 ExprResult BuildCXXCtorDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
7843 ExprResult
7844 BuildCXXAggregateDefaultInitExpr(SourceLocation Loc, FieldDecl *Field,
7845 const InitializedEntity &MemberEntity);
7846
7847 /// Instantiate or parse a C++ default argument expression as necessary.
7848 /// Return true on error.
7849 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7850 ParmVarDecl *Param, Expr *Init = nullptr,
7851 bool SkipImmediateInvocations = true);
7852
7853 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7854 /// the default expr if needed.
7855 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7856 ParmVarDecl *Param, Expr *Init = nullptr);
7857
7858 /// Wrap the expression in a ConstantExpr if it is a potential immediate
7859 /// invocation.
7860 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
7861
7862 void MarkExpressionAsImmediateEscalating(Expr *E);
7863
7864 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7865 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7866
7867 /// Abstract base class used for diagnosing integer constant
7868 /// expression violations.
7869 class VerifyICEDiagnoser {
7870 public:
7871 bool Suppress;
7872
7873 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) {}
7874
7875 virtual SemaDiagnosticBuilder
7876 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7877 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7878 SourceLocation Loc) = 0;
7879 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
7880 virtual ~VerifyICEDiagnoser() {}
7881 };
7882
7883 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7884 /// and reports the appropriate diagnostics. Returns false on success.
7885 /// Can optionally return the value of the expression.
7886 ExprResult
7887 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7888 VerifyICEDiagnoser &Diagnoser,
7889 AllowFoldKind CanFold = AllowFoldKind::No);
7890 ExprResult
7891 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7892 unsigned DiagID,
7893 AllowFoldKind CanFold = AllowFoldKind::No);
7894 ExprResult
7895 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7896 AllowFoldKind CanFold = AllowFoldKind::No);
7897 ExprResult
7898 VerifyIntegerConstantExpression(Expr *E,
7899 AllowFoldKind CanFold = AllowFoldKind::No) {
7900 return VerifyIntegerConstantExpression(E, Result: nullptr, CanFold);
7901 }
7902
7903 /// DiagnoseAssignmentAsCondition - Given that an expression is
7904 /// being used as a boolean condition, warn if it's an assignment.
7905 void DiagnoseAssignmentAsCondition(Expr *E);
7906
7907 /// Redundant parentheses over an equality comparison can indicate
7908 /// that the user intended an assignment used as condition.
7909 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7910
7911 class FullExprArg {
7912 public:
7913 FullExprArg() : E(nullptr) {}
7914 FullExprArg(Sema &actions) : E(nullptr) {}
7915
7916 ExprResult release() { return E; }
7917
7918 Expr *get() const { return E; }
7919
7920 Expr *operator->() { return E; }
7921
7922 private:
7923 // FIXME: No need to make the entire Sema class a friend when it's just
7924 // Sema::MakeFullExpr that needs access to the constructor below.
7925 friend class Sema;
7926
7927 explicit FullExprArg(Expr *expr) : E(expr) {}
7928
7929 Expr *E;
7930 };
7931
7932 FullExprArg MakeFullExpr(Expr *Arg) {
7933 return MakeFullExpr(Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation());
7934 }
7935 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
7936 return FullExprArg(
7937 ActOnFinishFullExpr(Expr: Arg, CC, /*DiscardedValue*/ DiscardedValue: false).get());
7938 }
7939 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
7940 ExprResult FE =
7941 ActOnFinishFullExpr(Expr: Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation(),
7942 /*DiscardedValue*/ DiscardedValue: true);
7943 return FullExprArg(FE.get());
7944 }
7945
7946 class ConditionResult {
7947 Decl *ConditionVar;
7948 ExprResult Condition;
7949 bool Invalid;
7950 std::optional<bool> KnownValue;
7951
7952 friend class Sema;
7953 ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
7954 bool IsConstexpr)
7955 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
7956 if (IsConstexpr && Condition.get()) {
7957 if (std::optional<llvm::APSInt> Val =
7958 Condition.get()->getIntegerConstantExpr(Ctx: S.Context)) {
7959 KnownValue = !!(*Val);
7960 }
7961 }
7962 }
7963 explicit ConditionResult(bool Invalid)
7964 : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
7965 KnownValue(std::nullopt) {}
7966
7967 public:
7968 ConditionResult() : ConditionResult(false) {}
7969 bool isInvalid() const { return Invalid; }
7970 std::pair<VarDecl *, Expr *> get() const {
7971 return std::make_pair(x: cast_or_null<VarDecl>(Val: ConditionVar),
7972 y: Condition.get());
7973 }
7974 std::optional<bool> getKnownValue() const { return KnownValue; }
7975 };
7976 static ConditionResult ConditionError() { return ConditionResult(true); }
7977
7978 /// CheckBooleanCondition - Diagnose problems involving the use of
7979 /// the given expression as a boolean condition (e.g. in an if
7980 /// statement). Also performs the standard function and array
7981 /// decays, possibly changing the input variable.
7982 ///
7983 /// \param Loc - A location associated with the condition, e.g. the
7984 /// 'if' keyword.
7985 /// \return true iff there were any errors
7986 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
7987 bool IsConstexpr = false);
7988
7989 enum class ConditionKind {
7990 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
7991 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
7992 Switch ///< An integral condition for a 'switch' statement.
7993 };
7994
7995 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
7996 ConditionKind CK, bool MissingOK = false);
7997
7998 QualType CheckConditionalOperands( // C99 6.5.15
7999 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
8000 ExprObjectKind &OK, SourceLocation QuestionLoc);
8001
8002 /// Emit a specialized diagnostic when one expression is a null pointer
8003 /// constant and the other is not a pointer. Returns true if a diagnostic is
8004 /// emitted.
8005 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8006 SourceLocation QuestionLoc);
8007
8008 /// type checking for vector binary operators.
8009 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8010 SourceLocation Loc, bool IsCompAssign,
8011 bool AllowBothBool, bool AllowBoolConversion,
8012 bool AllowBoolOperation);
8013
8014 /// Return a signed ext_vector_type that is of identical size and number of
8015 /// elements. For floating point vectors, return an integer type of identical
8016 /// size and number of elements. In the non ext_vector_type case, search from
8017 /// the largest type to the smallest type to avoid cases where long long ==
8018 /// long, where long gets picked over long long.
8019 QualType GetSignedVectorType(QualType V);
8020 QualType GetSignedSizelessVectorType(QualType V);
8021
8022 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8023 /// operates on extended vector types. Instead of producing an IntTy result,
8024 /// like a scalar comparison, a vector comparison produces a vector of integer
8025 /// types.
8026 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8027 SourceLocation Loc,
8028 BinaryOperatorKind Opc);
8029 QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8030 SourceLocation Loc,
8031 BinaryOperatorKind Opc);
8032 QualType CheckMatrixCompareOperands(ExprResult &LHS, ExprResult &RHS,
8033 SourceLocation Loc,
8034 BinaryOperatorKind Opc);
8035 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8036 SourceLocation Loc,
8037 BinaryOperatorKind Opc);
8038 QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8039 SourceLocation Loc,
8040 BinaryOperatorKind Opc);
8041 // type checking for sizeless vector binary operators.
8042 QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
8043 SourceLocation Loc, bool IsCompAssign,
8044 ArithConvKind OperationKind);
8045
8046 /// Type checking for matrix binary operators.
8047 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
8048 SourceLocation Loc,
8049 bool IsCompAssign);
8050 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
8051 SourceLocation Loc, bool IsCompAssign);
8052
8053 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
8054 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
8055 /// VLST) allowed?
8056 ///
8057 /// This will also return false if the two given types do not make sense from
8058 /// the perspective of SVE bitcasts.
8059 bool isValidSveBitcast(QualType srcType, QualType destType);
8060
8061 /// Are the two types matrix types and do they have the same dimensions i.e.
8062 /// do they have the same number of rows and the same number of columns?
8063 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
8064
8065 bool areVectorTypesSameSize(QualType srcType, QualType destType);
8066
8067 /// Are the two types lax-compatible vector types? That is, given
8068 /// that one of them is a vector, do they have equal storage sizes,
8069 /// where the storage size is the number of elements times the element
8070 /// size?
8071 ///
8072 /// This will also return false if either of the types is neither a
8073 /// vector nor a real type.
8074 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
8075
8076 /// Is this a legal conversion between two types, one of which is
8077 /// known to be a vector type?
8078 bool isLaxVectorConversion(QualType srcType, QualType destType);
8079
8080 // This returns true if at least one of the types is an altivec vector.
8081 bool anyAltivecTypes(QualType srcType, QualType destType);
8082
8083 // type checking C++ declaration initializers (C++ [dcl.init]).
8084
8085 /// Check a cast of an unknown-any type. We intentionally only
8086 /// trigger this for C-style casts.
8087 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8088 Expr *CastExpr, CastKind &CastKind,
8089 ExprValueKind &VK, CXXCastPath &Path);
8090
8091 /// Force an expression with unknown-type to an expression of the
8092 /// given type.
8093 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8094
8095 /// Type-check an expression that's being passed to an
8096 /// __unknown_anytype parameter.
8097 ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result,
8098 QualType &paramType);
8099
8100 // CheckMatrixCast - Check type constraints for matrix casts.
8101 // We allow casting between matrixes of the same dimensions i.e. when they
8102 // have the same number of rows and column. Returns true if the cast is
8103 // invalid.
8104 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8105 CastKind &Kind);
8106
8107 // CheckVectorCast - check type constraints for vectors.
8108 // Since vectors are an extension, there are no C standard reference for this.
8109 // We allow casting between vectors and integer datatypes of the same size.
8110 // returns true if the cast is invalid
8111 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8112 CastKind &Kind);
8113
8114 /// Prepare `SplattedExpr` for a vector splat operation, adding
8115 /// implicit casts if necessary.
8116 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8117
8118 /// Prepare `SplattedExpr` for a matrix splat operation, adding
8119 /// implicit casts if necessary.
8120 ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr);
8121
8122 // CheckExtVectorCast - check type constraints for extended vectors.
8123 // Since vectors are an extension, there are no C standard reference for this.
8124 // We allow casting between vectors and integer datatypes of the same size,
8125 // or vectors and the element type of that vector.
8126 // returns the cast expr
8127 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8128 CastKind &Kind);
8129
8130 QualType PreferredConditionType(ConditionKind K) const {
8131 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
8132 }
8133
8134 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
8135 // functions and arrays to their respective pointers (C99 6.3.2.1), and
8136 // promotes floating-piont types according to the language semantics.
8137 ExprResult UsualUnaryConversions(Expr *E);
8138
8139 // UsualUnaryFPConversions - promotes floating-point types according to the
8140 // current language semantics.
8141 ExprResult UsualUnaryFPConversions(Expr *E);
8142
8143 /// CallExprUnaryConversions - a special case of an unary conversion
8144 /// performed on a function designator of a call expression.
8145 ExprResult CallExprUnaryConversions(Expr *E);
8146
8147 // DefaultFunctionArrayConversion - converts functions and arrays
8148 // to their respective pointers (C99 6.3.2.1).
8149 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8150
8151 // DefaultFunctionArrayLvalueConversion - converts functions and
8152 // arrays to their respective pointers and performs the
8153 // lvalue-to-rvalue conversion.
8154 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8155 bool Diagnose = true);
8156
8157 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8158 // the operand. This function is a no-op if the operand has a function type
8159 // or an array type.
8160 ExprResult DefaultLvalueConversion(Expr *E);
8161
8162 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8163 // do not have a prototype. Integer promotions are performed on each
8164 // argument, and arguments that have type float are promoted to double.
8165 ExprResult DefaultArgumentPromotion(Expr *E);
8166
8167 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8168 const FunctionProtoType *Proto,
8169 Expr *Fn);
8170
8171 /// Determine the degree of POD-ness for an expression.
8172 /// Incomplete types are considered POD, since this check can be performed
8173 /// when we're in an unevaluated context.
8174 VarArgKind isValidVarArgType(const QualType &Ty);
8175
8176 /// Check to see if the given expression is a valid argument to a variadic
8177 /// function, issuing a diagnostic if not.
8178 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8179
8180 /// GatherArgumentsForCall - Collector argument expressions for various
8181 /// form of call prototypes.
8182 bool GatherArgumentsForCall(
8183 SourceLocation CallLoc, FunctionDecl *FDecl,
8184 const FunctionProtoType *Proto, unsigned FirstParam,
8185 ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs,
8186 VariadicCallType CallType = VariadicCallType::DoesNotApply,
8187 bool AllowExplicit = false, bool IsListInitialization = false);
8188
8189 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8190 // will create a runtime trap if the resulting type is not a POD type.
8191 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8192 FunctionDecl *FDecl);
8193
8194 // Check that the usual arithmetic conversions can be performed on this pair
8195 // of expressions that might be of enumeration type.
8196 void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc,
8197 ArithConvKind ACK);
8198
8199 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8200 // operands and then handles various conversions that are common to binary
8201 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8202 // routine returns the first non-arithmetic type found. The client is
8203 // responsible for emitting appropriate error diagnostics.
8204 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8205 SourceLocation Loc, ArithConvKind ACK);
8206
8207 bool IsAssignConvertCompatible(AssignConvertType ConvTy) {
8208 switch (ConvTy) {
8209 default:
8210 return false;
8211 case AssignConvertType::Compatible:
8212 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
8213 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
8214 return true;
8215 }
8216 llvm_unreachable("impossible");
8217 }
8218
8219 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8220 /// assignment conversion type specified by ConvTy. This returns true if the
8221 /// conversion was invalid or false if the conversion was accepted.
8222 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc,
8223 QualType DstType, QualType SrcType,
8224 Expr *SrcExpr, AssignmentAction Action,
8225 bool *Complained = nullptr);
8226
8227 /// CheckAssignmentConstraints - Perform type checking for assignment,
8228 /// argument passing, variable initialization, and function return values.
8229 /// C99 6.5.16.
8230 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8231 QualType LHSType,
8232 QualType RHSType);
8233
8234 /// Check assignment constraints and optionally prepare for a conversion of
8235 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8236 /// is true.
8237 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8238 ExprResult &RHS, CastKind &Kind,
8239 bool ConvertRHS = true);
8240
8241 /// Check assignment constraints for an assignment of RHS to LHSType.
8242 ///
8243 /// \param LHSType The destination type for the assignment.
8244 /// \param RHS The source expression for the assignment.
8245 /// \param Diagnose If \c true, diagnostics may be produced when checking
8246 /// for assignability. If a diagnostic is produced, \p RHS will be
8247 /// set to ExprError(). Note that this function may still return
8248 /// without producing a diagnostic, even for an invalid assignment.
8249 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8250 /// in an audited Core Foundation API and does not need to be checked
8251 /// for ARC retain issues.
8252 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8253 /// conversions necessary to perform the assignment. If \c false,
8254 /// \p Diagnose must also be \c false.
8255 AssignConvertType CheckSingleAssignmentConstraints(
8256 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8257 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8258
8259 // If the lhs type is a transparent union, check whether we
8260 // can initialize the transparent union with the given expression.
8261 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8262 ExprResult &RHS);
8263
8264 /// the following "Check" methods will return a valid/converted QualType
8265 /// or a null QualType (indicating an error diagnostic was issued).
8266
8267 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8268 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8269 ExprResult &RHS);
8270
8271 /// Diagnose cases where a scalar was implicitly converted to a vector and
8272 /// diagnose the underlying types. Otherwise, diagnose the error
8273 /// as invalid vector logical operands for non-C++ cases.
8274 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8275 ExprResult &RHS);
8276
8277 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8278 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8279 BinaryOperatorKind Opc);
8280 QualType CheckRemainderOperands( // C99 6.5.5
8281 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8282 bool IsCompAssign = false);
8283 QualType CheckAdditionOperands( // C99 6.5.6
8284 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8285 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8286 QualType CheckSubtractionOperands( // C99 6.5.6
8287 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8288 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8289 QualType CheckShiftOperands( // C99 6.5.7
8290 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8291 BinaryOperatorKind Opc, bool IsCompAssign = false);
8292 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
8293 QualType CheckCompareOperands( // C99 6.5.8/9
8294 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8295 BinaryOperatorKind Opc);
8296 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8297 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8298 BinaryOperatorKind Opc);
8299 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8300 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8301 BinaryOperatorKind Opc);
8302 // CheckAssignmentOperands is used for both simple and compound assignment.
8303 // For simple assignment, pass both expressions and a null converted type.
8304 // For compound assignment, pass both expressions and the converted type.
8305 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8306 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8307 BinaryOperatorKind Opc);
8308
8309 /// To be used for checking whether the arguments being passed to
8310 /// function exceeds the number of parameters expected for it.
8311 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8312 bool PartialOverloading = false) {
8313 // We check whether we're just after a comma in code-completion.
8314 if (NumArgs > 0 && PartialOverloading)
8315 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8316 return NumArgs > NumParams;
8317 }
8318
8319 /// Whether the AST is currently being rebuilt to correct immediate
8320 /// invocations. Immediate invocation candidates and references to consteval
8321 /// functions aren't tracked when this is set.
8322 bool RebuildingImmediateInvocation = false;
8323
8324 bool isAlwaysConstantEvaluatedContext() const {
8325 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8326 return (Ctx.isConstantEvaluated() || isConstantEvaluatedOverride) &&
8327 !Ctx.InConditionallyConstantEvaluateContext;
8328 }
8329
8330 /// Determines whether we are currently in a context that
8331 /// is not evaluated as per C++ [expr] p5.
8332 bool isUnevaluatedContext() const {
8333 return currentEvaluationContext().isUnevaluated();
8334 }
8335
8336 bool isImmediateFunctionContext() const {
8337 return currentEvaluationContext().isImmediateFunctionContext();
8338 }
8339
8340 bool isInLifetimeExtendingContext() const {
8341 return currentEvaluationContext().InLifetimeExtendingContext;
8342 }
8343
8344 bool needsRebuildOfDefaultArgOrInit() const {
8345 return currentEvaluationContext().RebuildDefaultArgOrDefaultInit;
8346 }
8347
8348 bool isCheckingDefaultArgumentOrInitializer() const {
8349 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8350 return (Ctx.Context ==
8351 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) ||
8352 Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer;
8353 }
8354
8355 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8356 InnermostDeclarationWithDelayedImmediateInvocations() const {
8357 assert(!ExprEvalContexts.empty() &&
8358 "Must be in an expression evaluation context");
8359 for (const auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8360 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8361 Ctx.DelayedDefaultInitializationContext)
8362 return Ctx.DelayedDefaultInitializationContext;
8363 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8364 Ctx.isUnevaluated())
8365 break;
8366 }
8367 return std::nullopt;
8368 }
8369
8370 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8371 OutermostDeclarationWithDelayedImmediateInvocations() const {
8372 assert(!ExprEvalContexts.empty() &&
8373 "Must be in an expression evaluation context");
8374 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8375 for (auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8376 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8377 !Ctx.DelayedDefaultInitializationContext && Res)
8378 break;
8379 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8380 Ctx.isUnevaluated())
8381 break;
8382 Res = Ctx.DelayedDefaultInitializationContext;
8383 }
8384 return Res;
8385 }
8386
8387 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8388 /// SelfAssigned when inside a CXXMethodDecl.
8389 const FieldDecl *
8390 getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
8391
8392 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
8393
8394 template <typename... Ts>
8395 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
8396 const Ts &...Args) {
8397 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8398 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8399 }
8400
8401 template <typename... Ts>
8402 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8403 const Ts &...Args) {
8404 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8405 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
8406 }
8407
8408 /// Abstract class used to diagnose incomplete types.
8409 struct TypeDiagnoser {
8410 TypeDiagnoser() {}
8411
8412 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
8413 virtual ~TypeDiagnoser() {}
8414 };
8415
8416 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8417 protected:
8418 unsigned DiagID;
8419 std::tuple<const Ts &...> Args;
8420
8421 template <std::size_t... Is>
8422 void emit(const SemaDiagnosticBuilder &DB,
8423 std::index_sequence<Is...>) const {
8424 // Apply all tuple elements to the builder in order.
8425 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8426 (void)Dummy;
8427 }
8428
8429 public:
8430 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8431 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8432 assert(DiagID != 0 && "no diagnostic for type diagnoser");
8433 }
8434
8435 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8436 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8437 emit(DB, std::index_sequence_for<Ts...>());
8438 DB << T;
8439 }
8440 };
8441
8442 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8443 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8444 /// For example, a diagnostic with no other parameters would generally have
8445 /// the form "...%select{incomplete|sizeless}0 type %1...".
8446 template <typename... Ts>
8447 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
8448 public:
8449 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8450 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8451
8452 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8453 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8454 this->emit(DB, std::index_sequence_for<Ts...>());
8455 DB << T->isSizelessType() << T;
8456 }
8457 };
8458
8459 /// Check an argument list for placeholders that we won't try to
8460 /// handle later.
8461 bool CheckArgsForPlaceholders(MultiExprArg args);
8462
8463 /// The C++ "std::source_location::__impl" struct, defined in
8464 /// \<source_location>.
8465 RecordDecl *StdSourceLocationImplDecl;
8466
8467 /// A stack of expression evaluation contexts.
8468 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
8469
8470 // Set of failed immediate invocations to avoid double diagnosing.
8471 llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
8472
8473 /// List of SourceLocations where 'self' is implicitly retained inside a
8474 /// block.
8475 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
8476 ImplicitlyRetainedSelfLocs;
8477
8478 /// Do an explicit extend of the given block pointer if we're in ARC.
8479 void maybeExtendBlockObject(ExprResult &E);
8480
8481 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8482 SourceLocation LocationOfExcessPrecisionNotSatisfied;
8483 void DiagnosePrecisionLossInComplexDivision();
8484
8485private:
8486 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8487
8488 /// Methods for marking which expressions involve dereferencing a pointer
8489 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8490 /// they are parsed, meaning that a noderef pointer may not be accessed. For
8491 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8492 /// `*p`, but need to check that `address of` is called on it. This requires
8493 /// keeping a container of all pending expressions and checking if the address
8494 /// of them are eventually taken.
8495 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8496 void CheckAddressOfNoDeref(const Expr *E);
8497
8498 ///@}
8499
8500 //
8501 //
8502 // -------------------------------------------------------------------------
8503 //
8504 //
8505
8506 /// \name C++ Expressions
8507 /// Implementations are in SemaExprCXX.cpp
8508 ///@{
8509
8510public:
8511 /// The C++ "std::bad_alloc" class, which is defined by the C++
8512 /// standard library.
8513 LazyDeclPtr StdBadAlloc;
8514
8515 /// The C++ "std::align_val_t" enum class, which is defined by the C++
8516 /// standard library.
8517 LazyDeclPtr StdAlignValT;
8518
8519 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
8520 RecordDecl *CXXTypeInfoDecl;
8521
8522 /// A flag to remember whether the implicit forms of operator new and delete
8523 /// have been declared.
8524 bool GlobalNewDeleteDeclared;
8525
8526 /// Delete-expressions to be analyzed at the end of translation unit
8527 ///
8528 /// This list contains class members, and locations of delete-expressions
8529 /// that could not be proven as to whether they mismatch with new-expression
8530 /// used in initializer of the field.
8531 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8532
8533 /// Handle the result of the special case name lookup for inheriting
8534 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8535 /// constructor names in member using declarations, even if 'X' is not the
8536 /// name of the corresponding type.
8537 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
8538 SourceLocation NameLoc,
8539 const IdentifierInfo &Name);
8540
8541 ParsedType getConstructorName(const IdentifierInfo &II,
8542 SourceLocation NameLoc, Scope *S,
8543 CXXScopeSpec &SS, bool EnteringContext);
8544 ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc,
8545 Scope *S, CXXScopeSpec &SS,
8546 ParsedType ObjectType, bool EnteringContext);
8547
8548 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
8549 ParsedType ObjectType);
8550
8551 /// Build a C++ typeid expression with a type operand.
8552 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8553 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8554
8555 /// Build a C++ typeid expression with an expression operand.
8556 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8557 Expr *Operand, SourceLocation RParenLoc);
8558
8559 /// ActOnCXXTypeid - Parse typeid( something ).
8560 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
8561 bool isType, void *TyOrExpr,
8562 SourceLocation RParenLoc);
8563
8564 /// Build a Microsoft __uuidof expression with a type operand.
8565 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8566 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8567
8568 /// Build a Microsoft __uuidof expression with an expression operand.
8569 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8570 Expr *Operand, SourceLocation RParenLoc);
8571
8572 /// ActOnCXXUuidof - Parse __uuidof( something ).
8573 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
8574 bool isType, void *TyOrExpr,
8575 SourceLocation RParenLoc);
8576
8577 //// ActOnCXXThis - Parse 'this' pointer.
8578 ExprResult ActOnCXXThis(SourceLocation Loc);
8579
8580 /// Check whether the type of 'this' is valid in the current context.
8581 bool CheckCXXThisType(SourceLocation Loc, QualType Type);
8582
8583 /// Build a CXXThisExpr and mark it referenced in the current context.
8584 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8585 void MarkThisReferenced(CXXThisExpr *This);
8586
8587 /// Try to retrieve the type of the 'this' pointer.
8588 ///
8589 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8590 QualType getCurrentThisType();
8591
8592 /// When non-NULL, the C++ 'this' expression is allowed despite the
8593 /// current context not being a non-static member function. In such cases,
8594 /// this provides the type used for 'this'.
8595 QualType CXXThisTypeOverride;
8596
8597 /// RAII object used to temporarily allow the C++ 'this' expression
8598 /// to be used, with the given qualifiers on the current class type.
8599 class CXXThisScopeRAII {
8600 Sema &S;
8601 QualType OldCXXThisTypeOverride;
8602 bool Enabled;
8603
8604 public:
8605 /// Introduce a new scope where 'this' may be allowed (when enabled),
8606 /// using the given declaration (which is either a class template or a
8607 /// class) along with the given qualifiers.
8608 /// along with the qualifiers placed on '*this'.
8609 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8610 bool Enabled = true);
8611
8612 ~CXXThisScopeRAII();
8613 CXXThisScopeRAII(const CXXThisScopeRAII &) = delete;
8614 CXXThisScopeRAII &operator=(const CXXThisScopeRAII &) = delete;
8615 };
8616
8617 /// Make sure the value of 'this' is actually available in the current
8618 /// context, if it is a potentially evaluated context.
8619 ///
8620 /// \param Loc The location at which the capture of 'this' occurs.
8621 ///
8622 /// \param Explicit Whether 'this' is explicitly captured in a lambda
8623 /// capture list.
8624 ///
8625 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8626 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8627 /// This is useful when enclosing lambdas must speculatively capture
8628 /// 'this' that may or may not be used in certain specializations of
8629 /// a nested generic lambda (depending on whether the name resolves to
8630 /// a non-static member function or a static function).
8631 /// \return returns 'true' if failed, 'false' if success.
8632 bool CheckCXXThisCapture(
8633 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8634 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8635 bool ByCopy = false);
8636
8637 /// Determine whether the given type is the type of *this that is used
8638 /// outside of the body of a member function for a type that is currently
8639 /// being defined.
8640 bool isThisOutsideMemberFunctionBody(QualType BaseType);
8641
8642 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8643 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
8644
8645 /// Build a boolean-typed literal expression.
8646 ExprResult BuildBoolLiteral(SourceLocation Loc, bool Value);
8647
8648 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8649 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
8650
8651 //// ActOnCXXThrow - Parse throw expressions.
8652 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
8653 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
8654 bool IsThrownVarInScope);
8655
8656 /// CheckCXXThrowOperand - Validate the operand of a throw.
8657 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8658
8659 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8660 /// Can be interpreted either as function-style casting ("int(x)")
8661 /// or class type construction ("ClassType(x,y,z)")
8662 /// or creation of a value-initialized type ("int()").
8663 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
8664 SourceLocation LParenOrBraceLoc,
8665 MultiExprArg Exprs,
8666 SourceLocation RParenOrBraceLoc,
8667 bool ListInitialization);
8668
8669 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
8670 SourceLocation LParenLoc,
8671 MultiExprArg Exprs,
8672 SourceLocation RParenLoc,
8673 bool ListInitialization);
8674
8675 /// Parsed a C++ 'new' expression (C++ 5.3.4).
8676 ///
8677 /// E.g.:
8678 /// @code new (memory) int[size][4] @endcode
8679 /// or
8680 /// @code ::new Foo(23, "hello") @endcode
8681 ///
8682 /// \param StartLoc The first location of the expression.
8683 /// \param UseGlobal True if 'new' was prefixed with '::'.
8684 /// \param PlacementLParen Opening paren of the placement arguments.
8685 /// \param PlacementArgs Placement new arguments.
8686 /// \param PlacementRParen Closing paren of the placement arguments.
8687 /// \param TypeIdParens If the type is in parens, the source range.
8688 /// \param D The type to be allocated, as well as array dimensions.
8689 /// \param Initializer The initializing expression or initializer-list, or
8690 /// null if there is none.
8691 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8692 SourceLocation PlacementLParen,
8693 MultiExprArg PlacementArgs,
8694 SourceLocation PlacementRParen,
8695 SourceRange TypeIdParens, Declarator &D,
8696 Expr *Initializer);
8697 ExprResult
8698 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8699 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8700 SourceRange TypeIdParens, QualType AllocType,
8701 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8702 SourceRange DirectInitRange, Expr *Initializer);
8703
8704 /// Determine whether \p FD is an aligned allocation or deallocation
8705 /// function that is unavailable.
8706 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
8707
8708 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8709 /// function that is unavailable.
8710 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
8711 SourceLocation Loc);
8712
8713 /// Checks that a type is suitable as the allocated type
8714 /// in a new-expression.
8715 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8716 SourceRange R);
8717
8718 /// Finds the overloads of operator new and delete that are appropriate
8719 /// for the allocation.
8720 std::optional<ResolvedAllocation> FindAllocationFunctions(
8721 SourceLocation StartLoc, SourceRange Range,
8722 AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope,
8723 QualType AllocType, bool IsArray, const ImplicitAllocationParameters &IAP,
8724 MultiExprArg PlaceArgs, bool Diagnose = true);
8725
8726 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8727 /// delete. These are:
8728 /// @code
8729 /// // C++03:
8730 /// void* operator new(std::size_t) throw(std::bad_alloc);
8731 /// void* operator new[](std::size_t) throw(std::bad_alloc);
8732 /// void operator delete(void *) throw();
8733 /// void operator delete[](void *) throw();
8734 /// // C++11:
8735 /// void* operator new(std::size_t);
8736 /// void* operator new[](std::size_t);
8737 /// void operator delete(void *) noexcept;
8738 /// void operator delete[](void *) noexcept;
8739 /// // C++1y:
8740 /// void* operator new(std::size_t);
8741 /// void* operator new[](std::size_t);
8742 /// void operator delete(void *) noexcept;
8743 /// void operator delete[](void *) noexcept;
8744 /// void operator delete(void *, std::size_t) noexcept;
8745 /// void operator delete[](void *, std::size_t) noexcept;
8746 /// @endcode
8747 /// Note that the placement and nothrow forms of new are *not* implicitly
8748 /// declared. Their use requires including \<new\>.
8749 void DeclareGlobalNewDelete();
8750 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
8751 ArrayRef<QualType> Params);
8752
8753 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
8754 DeclarationName Name, FunctionDecl *&Operator,
8755 ImplicitDeallocationParameters,
8756 bool Diagnose = true);
8757 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
8758 ImplicitDeallocationParameters,
8759 DeclarationName Name,
8760 bool Diagnose = true);
8761 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
8762 CXXRecordDecl *RD,
8763 bool Diagnose,
8764 bool LookForGlobal,
8765 DeclarationName Name);
8766
8767 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8768 /// @code ::delete ptr; @endcode
8769 /// or
8770 /// @code delete [] ptr; @endcode
8771 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8772 bool ArrayForm, Expr *Operand);
8773 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
8774 bool IsDelete, bool CallCanBeVirtual,
8775 bool WarnOnNonAbstractTypes,
8776 SourceLocation DtorLoc);
8777
8778 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
8779 Expr *Operand, SourceLocation RParen);
8780 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8781 SourceLocation RParen);
8782
8783 ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base,
8784 SourceLocation OpLoc,
8785 tok::TokenKind OpKind,
8786 ParsedType &ObjectType,
8787 bool &MayBePseudoDestructor);
8788
8789 ExprResult BuildPseudoDestructorExpr(
8790 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8791 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8792 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8793
8794 ExprResult ActOnPseudoDestructorExpr(
8795 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8796 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8797 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8798
8799 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
8800 SourceLocation OpLoc,
8801 tok::TokenKind OpKind,
8802 SourceLocation TildeLoc,
8803 const DeclSpec &DS);
8804
8805 /// MaybeCreateExprWithCleanups - If the current full-expression
8806 /// requires any cleanups, surround it with a ExprWithCleanups node.
8807 /// Otherwise, just returns the passed-in expression.
8808 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
8809 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
8810 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
8811
8812 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8813 return ActOnFinishFullExpr(
8814 Expr, CC: Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8815 }
8816 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
8817 bool DiscardedValue, bool IsConstexpr = false,
8818 bool IsTemplateArgument = false);
8819 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
8820
8821 /// Process the expression contained within a decltype. For such expressions,
8822 /// certain semantic checks on temporaries are delayed until this point, and
8823 /// are omitted for the 'topmost' call in the decltype expression. If the
8824 /// topmost call bound a temporary, strip that temporary off the expression.
8825 ExprResult ActOnDecltypeExpression(Expr *E);
8826
8827 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8828 bool IsUDSuffix);
8829
8830 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
8831
8832 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8833 SourceLocation StmtLoc,
8834 ConditionKind CK);
8835
8836 /// Check the use of the given variable as a C++ condition in an if,
8837 /// while, do-while, or switch statement.
8838 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
8839 SourceLocation StmtLoc, ConditionKind CK);
8840
8841 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8842 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8843
8844 /// Helper function to determine whether this is the (deprecated) C++
8845 /// conversion from a string literal to a pointer to non-const char or
8846 /// non-const wchar_t (for narrow and wide string literals,
8847 /// respectively).
8848 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8849
8850 /// PerformImplicitConversion - Perform an implicit conversion of the
8851 /// expression From to the type ToType using the pre-computed implicit
8852 /// conversion sequence ICS. Returns the converted
8853 /// expression. Action is the kind of conversion we're performing,
8854 /// used in the error message.
8855 ExprResult PerformImplicitConversion(
8856 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8857 AssignmentAction Action,
8858 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
8859
8860 /// PerformImplicitConversion - Perform an implicit conversion of the
8861 /// expression From to the type ToType by following the standard
8862 /// conversion sequence SCS. Returns the converted
8863 /// expression. Flavor is the context in which we're performing this
8864 /// conversion, for use in error messages.
8865 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8866 const StandardConversionSequence &SCS,
8867 AssignmentAction Action,
8868 CheckedConversionKind CCK);
8869
8870 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8871
8872 /// Parsed one of the type trait support pseudo-functions.
8873 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8874 ArrayRef<ParsedType> Args,
8875 SourceLocation RParenLoc);
8876 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8877 ArrayRef<TypeSourceInfo *> Args,
8878 SourceLocation RParenLoc);
8879
8880 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8881 /// pseudo-functions.
8882 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8883 ParsedType LhsTy, Expr *DimExpr,
8884 SourceLocation RParen);
8885
8886 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8887 TypeSourceInfo *TSInfo, Expr *DimExpr,
8888 SourceLocation RParen);
8889
8890 /// ActOnExpressionTrait - Parsed one of the unary type trait support
8891 /// pseudo-functions.
8892 ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8893 Expr *Queried, SourceLocation RParen);
8894
8895 ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8896 Expr *Queried, SourceLocation RParen);
8897
8898 QualType CheckPointerToMemberOperands( // C++ 5.5
8899 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc,
8900 bool isIndirect);
8901 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
8902 ExprResult &RHS,
8903 SourceLocation QuestionLoc);
8904
8905 //// Determines if a type is trivially relocatable
8906 /// according to the C++26 rules.
8907 // FIXME: This is in Sema because it requires
8908 // overload resolution, can we move to ASTContext?
8909 bool IsCXXTriviallyRelocatableType(QualType T);
8910 bool IsCXXTriviallyRelocatableType(const CXXRecordDecl &RD);
8911
8912 /// Check the operands of ?: under C++ semantics.
8913 ///
8914 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8915 /// extension. In this case, LHS == Cond. (But they're not aliases.)
8916 ///
8917 /// This function also implements GCC's vector extension and the
8918 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8919 /// permit the use of a?b:c where the type of a is that of a integer vector
8920 /// with the same number of elements and size as the vectors of b and c. If
8921 /// one of either b or c is a scalar it is implicitly converted to match the
8922 /// type of the vector. Otherwise the expression is ill-formed. If both b and
8923 /// c are scalars, then b and c are checked and converted to the type of a if
8924 /// possible.
8925 ///
8926 /// The expressions are evaluated differently for GCC's and OpenCL's
8927 /// extensions. For the GCC extension, the ?: operator is evaluated as
8928 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8929 /// For the OpenCL extensions, the ?: operator is evaluated as
8930 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
8931 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
8932 QualType CXXCheckConditionalOperands( // C++ 5.16
8933 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8934 ExprObjectKind &OK, SourceLocation questionLoc);
8935
8936 /// Find a merged pointer type and convert the two expressions to it.
8937 ///
8938 /// This finds the composite pointer type for \p E1 and \p E2 according to
8939 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8940 /// it. It does not emit diagnostics (FIXME: that's not true if \p
8941 /// ConvertArgs is \c true).
8942 ///
8943 /// \param Loc The location of the operator requiring these two expressions to
8944 /// be converted to the composite pointer type.
8945 ///
8946 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
8947 /// type.
8948 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8949 bool ConvertArgs = true);
8950 QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1,
8951 ExprResult &E2, bool ConvertArgs = true) {
8952 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8953 QualType Composite =
8954 FindCompositePointerType(Loc, E1&: E1Tmp, E2&: E2Tmp, ConvertArgs);
8955 E1 = E1Tmp;
8956 E2 = E2Tmp;
8957 return Composite;
8958 }
8959
8960 /// MaybeBindToTemporary - If the passed in expression has a record type with
8961 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
8962 /// it simply returns the passed in expression.
8963 ExprResult MaybeBindToTemporary(Expr *E);
8964
8965 /// IgnoredValueConversions - Given that an expression's result is
8966 /// syntactically ignored, perform any conversions that are
8967 /// required.
8968 ExprResult IgnoredValueConversions(Expr *E);
8969
8970 ExprResult CheckUnevaluatedOperand(Expr *E);
8971
8972 IfExistsResult
8973 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
8974 const DeclarationNameInfo &TargetNameInfo);
8975
8976 IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S,
8977 SourceLocation KeywordLoc,
8978 bool IsIfExists, CXXScopeSpec &SS,
8979 UnqualifiedId &Name);
8980
8981 RequiresExprBodyDecl *
8982 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8983 ArrayRef<ParmVarDecl *> LocalParameters,
8984 Scope *BodyScope);
8985 void ActOnFinishRequiresExpr();
8986 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8987 concepts::Requirement *ActOnTypeRequirement(SourceLocation TypenameKWLoc,
8988 CXXScopeSpec &SS,
8989 SourceLocation NameLoc,
8990 const IdentifierInfo *TypeName,
8991 TemplateIdAnnotation *TemplateId);
8992 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8993 SourceLocation NoexceptLoc);
8994 concepts::Requirement *ActOnCompoundRequirement(
8995 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8996 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8997 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8998 concepts::ExprRequirement *BuildExprRequirement(
8999 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
9000 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
9001 concepts::ExprRequirement *BuildExprRequirement(
9002 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
9003 bool IsSatisfied, SourceLocation NoexceptLoc,
9004 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
9005 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
9006 concepts::TypeRequirement *BuildTypeRequirement(
9007 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
9008 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
9009 concepts::NestedRequirement *
9010 BuildNestedRequirement(StringRef InvalidConstraintEntity,
9011 const ASTConstraintSatisfaction &Satisfaction);
9012 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
9013 RequiresExprBodyDecl *Body,
9014 SourceLocation LParenLoc,
9015 ArrayRef<ParmVarDecl *> LocalParameters,
9016 SourceLocation RParenLoc,
9017 ArrayRef<concepts::Requirement *> Requirements,
9018 SourceLocation ClosingBraceLoc);
9019
9020private:
9021 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
9022 bool IsDelete);
9023
9024 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
9025 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
9026 bool DeleteWasArrayForm);
9027
9028 std::optional<AllocationArgumentSet>
9029 resolveAllocationArguments(LookupResult &R,
9030 const ImplicitAllocationParameters &,
9031 ArrayRef<Expr *> PlacementArguments);
9032
9033 // Attempts to construct the type identity argument for the call to a
9034 // type aware operator new. Returns null on failure.
9035 Expr *tryGetTypeIdentityArgument(QualType Type, SourceLocation);
9036
9037 Expr *AllocationSizeExpr = nullptr;
9038 Expr *AllocationAlignmentExpr = nullptr;
9039 llvm::DenseMap<QualType, Expr *> AllocationTypeIdentityArguments;
9040
9041 ///@}
9042
9043 //
9044 //
9045 // -------------------------------------------------------------------------
9046 //
9047 //
9048
9049 /// \name Member Access Expressions
9050 /// Implementations are in SemaExprMember.cpp
9051 ///@{
9052
9053public:
9054 /// Check whether an expression might be an implicit class member access.
9055 bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R,
9056 bool IsAddressOfOperand);
9057
9058 /// Builds an expression which might be an implicit member expression.
9059 ExprResult BuildPossibleImplicitMemberExpr(
9060 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
9061 const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
9062
9063 /// Builds an implicit member access expression. The current context
9064 /// is known to be an instance method, and the given unqualified lookup
9065 /// set is known to contain only instance members, at least one of which
9066 /// is from an appropriate type.
9067 ExprResult
9068 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9069 LookupResult &R,
9070 const TemplateArgumentListInfo *TemplateArgs,
9071 bool IsDefiniteInstance, const Scope *S);
9072
9073 ExprResult ActOnDependentMemberExpr(
9074 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
9075 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9076 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9077 const TemplateArgumentListInfo *TemplateArgs);
9078
9079 /// The main callback when the parser finds something like
9080 /// expression . [nested-name-specifier] identifier
9081 /// expression -> [nested-name-specifier] identifier
9082 /// where 'identifier' encompasses a fairly broad spectrum of
9083 /// possibilities, including destructor and operator references.
9084 ///
9085 /// \param OpKind either tok::arrow or tok::period
9086 /// \param ObjCImpDecl the current Objective-C \@implementation
9087 /// decl; this is an ugly hack around the fact that Objective-C
9088 /// \@implementations aren't properly put in the context chain
9089 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
9090 tok::TokenKind OpKind, CXXScopeSpec &SS,
9091 SourceLocation TemplateKWLoc,
9092 UnqualifiedId &Member, Decl *ObjCImpDecl);
9093
9094 MemberExpr *
9095 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
9096 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
9097 ValueDecl *Member, DeclAccessPair FoundDecl,
9098 bool HadMultipleCandidates,
9099 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
9100 ExprValueKind VK, ExprObjectKind OK,
9101 const TemplateArgumentListInfo *TemplateArgs = nullptr);
9102
9103 // Check whether the declarations we found through a nested-name
9104 // specifier in a member expression are actually members of the base
9105 // type. The restriction here is:
9106 //
9107 // C++ [expr.ref]p2:
9108 // ... In these cases, the id-expression shall name a
9109 // member of the class or of one of its base classes.
9110 //
9111 // So it's perfectly legitimate for the nested-name specifier to name
9112 // an unrelated class, and for us to find an overload set including
9113 // decls from classes which are not superclasses, as long as the decl
9114 // we actually pick through overload resolution is from a superclass.
9115 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
9116 const CXXScopeSpec &SS,
9117 const LookupResult &R);
9118
9119 // This struct is for use by ActOnMemberAccess to allow
9120 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
9121 // changing the access operator from a '.' to a '->' (to see if that is the
9122 // change needed to fix an error about an unknown member, e.g. when the class
9123 // defines a custom operator->).
9124 struct ActOnMemberAccessExtraArgs {
9125 Scope *S;
9126 UnqualifiedId &Id;
9127 Decl *ObjCImpDecl;
9128 };
9129
9130 ExprResult BuildMemberReferenceExpr(
9131 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
9132 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9133 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9134 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
9135 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9136
9137 ExprResult
9138 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
9139 bool IsArrow, const CXXScopeSpec &SS,
9140 SourceLocation TemplateKWLoc,
9141 NamedDecl *FirstQualifierInScope, LookupResult &R,
9142 const TemplateArgumentListInfo *TemplateArgs,
9143 const Scope *S, bool SuppressQualifierCheck = false,
9144 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9145
9146 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
9147 SourceLocation OpLoc,
9148 const CXXScopeSpec &SS, FieldDecl *Field,
9149 DeclAccessPair FoundDecl,
9150 const DeclarationNameInfo &MemberNameInfo);
9151
9152 /// Perform conversions on the LHS of a member access expression.
9153 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
9154
9155 ExprResult BuildAnonymousStructUnionMemberReference(
9156 const CXXScopeSpec &SS, SourceLocation nameLoc,
9157 IndirectFieldDecl *indirectField,
9158 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none),
9159 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
9160
9161private:
9162 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
9163
9164 ///@}
9165
9166 //
9167 //
9168 // -------------------------------------------------------------------------
9169 //
9170 //
9171
9172 /// \name Initializers
9173 /// Implementations are in SemaInit.cpp
9174 ///@{
9175
9176public:
9177 /// Stack of types that correspond to the parameter entities that are
9178 /// currently being copy-initialized. Can be empty.
9179 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
9180
9181 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
9182 AggregateDeductionCandidates;
9183
9184 bool IsStringInit(Expr *Init, const ArrayType *AT);
9185
9186 /// Determine whether we can perform aggregate initialization for the purposes
9187 /// of overload resolution.
9188 bool CanPerformAggregateInitializationForOverloadResolution(
9189 const InitializedEntity &Entity, InitListExpr *From);
9190
9191 ExprResult ActOnDesignatedInitializer(Designation &Desig,
9192 SourceLocation EqualOrColonLoc,
9193 bool GNUSyntax, ExprResult Init);
9194
9195 /// Check that the lifetime of the initializer (and its subobjects) is
9196 /// sufficient for initializing the entity, and perform lifetime extension
9197 /// (when permitted) if not.
9198 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
9199
9200 MaterializeTemporaryExpr *
9201 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
9202 bool BoundToLvalueReference);
9203
9204 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9205 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9206 /// we don't have xvalues there.
9207 ExprResult TemporaryMaterializationConversion(Expr *E);
9208
9209 ExprResult PerformQualificationConversion(
9210 Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
9211 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
9212
9213 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
9214 ExprResult Init);
9215 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
9216 SourceLocation EqualLoc, ExprResult Init,
9217 bool TopLevelOfInitList = false,
9218 bool AllowExplicit = false);
9219
9220 QualType DeduceTemplateSpecializationFromInitializer(
9221 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9222 const InitializationKind &Kind, MultiExprArg Init);
9223
9224 ///@}
9225
9226 //
9227 //
9228 // -------------------------------------------------------------------------
9229 //
9230 //
9231
9232 /// \name C++ Lambda Expressions
9233 /// Implementations are in SemaLambda.cpp
9234 ///@{
9235
9236public:
9237 /// Create a new lambda closure type.
9238 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
9239 TypeSourceInfo *Info,
9240 unsigned LambdaDependencyKind,
9241 LambdaCaptureDefault CaptureDefault);
9242
9243 /// Number lambda for linkage purposes if necessary.
9244 void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method,
9245 std::optional<CXXRecordDecl::LambdaNumbering>
9246 NumberingOverride = std::nullopt);
9247
9248 /// Endow the lambda scope info with the relevant properties.
9249 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9250 SourceRange IntroducerRange,
9251 LambdaCaptureDefault CaptureDefault,
9252 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9253 bool Mutable);
9254
9255 CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange,
9256 CXXRecordDecl *Class);
9257
9258 void AddTemplateParametersToLambdaCallOperator(
9259 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9260 TemplateParameterList *TemplateParams);
9261
9262 void
9263 CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc,
9264 SourceLocation CallOperatorLoc,
9265 const AssociatedConstraint &TrailingRequiresClause,
9266 TypeSourceInfo *MethodTyInfo,
9267 ConstexprSpecKind ConstexprKind, StorageClass SC,
9268 ArrayRef<ParmVarDecl *> Params,
9269 bool HasExplicitResultType);
9270
9271 /// Returns true if the explicit object parameter was invalid.
9272 bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method,
9273 SourceLocation CallLoc);
9274
9275 /// Perform initialization analysis of the init-capture and perform
9276 /// any implicit conversions such as an lvalue-to-rvalue conversion if
9277 /// not being used to initialize a reference.
9278 ParsedType actOnLambdaInitCaptureInitialization(
9279 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9280 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9281 return ParsedType::make(P: buildLambdaInitCaptureInitialization(
9282 Loc, ByRef, EllipsisLoc, NumExpansions: std::nullopt, Id,
9283 DirectInit: InitKind != LambdaCaptureInitKind::CopyInit, Init));
9284 }
9285 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
9286 SourceLocation EllipsisLoc,
9287 UnsignedOrNone NumExpansions,
9288 IdentifierInfo *Id,
9289 bool DirectInit, Expr *&Init);
9290
9291 /// Create a dummy variable within the declcontext of the lambda's
9292 /// call operator, for name lookup purposes for a lambda init capture.
9293 ///
9294 /// CodeGen handles emission of lambda captures, ignoring these dummy
9295 /// variables appropriately.
9296 VarDecl *createLambdaInitCaptureVarDecl(
9297 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9298 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9299
9300 /// Add an init-capture to a lambda scope.
9301 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9302
9303 /// Note that we have finished the explicit captures for the
9304 /// given lambda.
9305 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
9306
9307 /// Deduce a block or lambda's return type based on the return
9308 /// statements present in the body.
9309 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
9310
9311 /// Once the Lambdas capture are known, we can start to create the closure,
9312 /// call operator method, and keep track of the captures.
9313 /// We do the capture lookup here, but they are not actually captured until
9314 /// after we know what the qualifiers of the call operator are.
9315 void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
9316 Scope *CurContext);
9317
9318 /// This is called after parsing the explicit template parameter list
9319 /// on a lambda (if it exists) in C++2a.
9320 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
9321 SourceLocation LAngleLoc,
9322 ArrayRef<NamedDecl *> TParams,
9323 SourceLocation RAngleLoc,
9324 ExprResult RequiresClause);
9325
9326 void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
9327 SourceLocation MutableLoc);
9328
9329 void ActOnLambdaClosureParameters(
9330 Scope *LambdaScope,
9331 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo);
9332
9333 /// ActOnStartOfLambdaDefinition - This is called just before we start
9334 /// parsing the body of a lambda; it analyzes the explicit captures and
9335 /// arguments, and sets up various data-structures for the body of the
9336 /// lambda.
9337 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
9338 Declarator &ParamInfo, const DeclSpec &DS);
9339
9340 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9341 /// is invoked to pop the information about the lambda.
9342 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9343 bool IsInstantiation = false);
9344
9345 /// ActOnLambdaExpr - This is called when the body of a lambda expression
9346 /// was successfully completed.
9347 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body);
9348
9349 /// Does copying/destroying the captured variable have side effects?
9350 bool CaptureHasSideEffects(const sema::Capture &From);
9351
9352 /// Diagnose if an explicit lambda capture is unused. Returns true if a
9353 /// diagnostic is emitted.
9354 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9355 SourceRange FixItRange,
9356 const sema::Capture &From);
9357
9358 /// Build a FieldDecl suitable to hold the given capture.
9359 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture,
9360 bool IsOpenMP = false);
9361
9362 /// Initialize the given capture with a suitable expression.
9363 ExprResult BuildCaptureInit(const sema::Capture &Capture,
9364 SourceLocation ImplicitCaptureLoc,
9365 bool IsOpenMPMapping = false);
9366
9367 /// Complete a lambda-expression having processed and attached the
9368 /// lambda body.
9369 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc);
9370
9371 /// Get the return type to use for a lambda's conversion function(s) to
9372 /// function pointer type, given the type of the call operator.
9373 QualType
9374 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
9375 CallingConv CC);
9376
9377 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
9378 SourceLocation ConvLocation,
9379 CXXConversionDecl *Conv, Expr *Src);
9380
9381 class LambdaScopeForCallOperatorInstantiationRAII
9382 : private FunctionScopeRAII {
9383 public:
9384 LambdaScopeForCallOperatorInstantiationRAII(
9385 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9386 LocalInstantiationScope &Scope,
9387 bool ShouldAddDeclsFromParentScope = true);
9388 };
9389
9390 /// Compute the mangling number context for a lambda expression or
9391 /// block literal. Also return the extra mangling decl if any.
9392 ///
9393 /// \param DC - The DeclContext containing the lambda expression or
9394 /// block literal.
9395 std::tuple<MangleNumberingContext *, Decl *>
9396 getCurrentMangleNumberContext(const DeclContext *DC);
9397
9398 ///@}
9399
9400 //
9401 //
9402 // -------------------------------------------------------------------------
9403 //
9404 //
9405
9406 /// \name Name Lookup
9407 ///
9408 /// These routines provide name lookup that is used during semantic
9409 /// analysis to resolve the various kinds of names (identifiers,
9410 /// overloaded operator names, constructor names, etc.) into zero or
9411 /// more declarations within a particular scope. The major entry
9412 /// points are LookupName, which performs unqualified name lookup,
9413 /// and LookupQualifiedName, which performs qualified name lookup.
9414 ///
9415 /// All name lookup is performed based on some specific criteria,
9416 /// which specify what names will be visible to name lookup and how
9417 /// far name lookup should work. These criteria are important both
9418 /// for capturing language semantics (certain lookups will ignore
9419 /// certain names, for example) and for performance, since name
9420 /// lookup is often a bottleneck in the compilation of C++. Name
9421 /// lookup criteria is specified via the LookupCriteria enumeration.
9422 ///
9423 /// The results of name lookup can vary based on the kind of name
9424 /// lookup performed, the current language, and the translation
9425 /// unit. In C, for example, name lookup will either return nothing
9426 /// (no entity found) or a single declaration. In C++, name lookup
9427 /// can additionally refer to a set of overloaded functions or
9428 /// result in an ambiguity. All of the possible results of name
9429 /// lookup are captured by the LookupResult class, which provides
9430 /// the ability to distinguish among them.
9431 ///
9432 /// Implementations are in SemaLookup.cpp
9433 ///@{
9434
9435public:
9436 /// Tracks whether we are in a context where typo correction is
9437 /// disabled.
9438 bool DisableTypoCorrection;
9439
9440 /// The number of typos corrected by CorrectTypo.
9441 unsigned TyposCorrected;
9442
9443 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9444 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9445
9446 /// A cache containing identifiers for which typo correction failed and
9447 /// their locations, so that repeated attempts to correct an identifier in a
9448 /// given location are ignored if typo correction already failed for it.
9449 IdentifierSourceLocations TypoCorrectionFailures;
9450
9451 /// SpecialMemberOverloadResult - The overloading result for a special member
9452 /// function.
9453 ///
9454 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9455 /// integer are used to determine whether overload resolution succeeded.
9456 class SpecialMemberOverloadResult {
9457 public:
9458 enum Kind { NoMemberOrDeleted, Ambiguous, Success };
9459
9460 private:
9461 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9462
9463 public:
9464 SpecialMemberOverloadResult() {}
9465 SpecialMemberOverloadResult(CXXMethodDecl *MD)
9466 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9467
9468 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
9469 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9470
9471 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
9472 void setKind(Kind K) { Pair.setInt(K); }
9473 };
9474
9475 using SpecialMemberCacheKey = std::pair<const CXXRecordDecl *, unsigned>;
9476
9477 /// A cache of special member function overload resolution results
9478 /// for C++ records.
9479 llvm::DenseMap<SpecialMemberCacheKey, SpecialMemberOverloadResult>
9480 SpecialMemberCache;
9481
9482 enum class AcceptableKind { Visible, Reachable };
9483
9484 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9485 // TODO: make this is a typesafe union.
9486 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
9487 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
9488
9489 /// Describes the kind of name lookup to perform.
9490 enum LookupNameKind {
9491 /// Ordinary name lookup, which finds ordinary names (functions,
9492 /// variables, typedefs, etc.) in C and most kinds of names
9493 /// (functions, variables, members, types, etc.) in C++.
9494 LookupOrdinaryName = 0,
9495 /// Tag name lookup, which finds the names of enums, classes,
9496 /// structs, and unions.
9497 LookupTagName,
9498 /// Label name lookup.
9499 LookupLabel,
9500 /// Member name lookup, which finds the names of
9501 /// class/struct/union members.
9502 LookupMemberName,
9503 /// Look up of an operator name (e.g., operator+) for use with
9504 /// operator overloading. This lookup is similar to ordinary name
9505 /// lookup, but will ignore any declarations that are class members.
9506 LookupOperatorName,
9507 /// Look up a name following ~ in a destructor name. This is an ordinary
9508 /// lookup, but prefers tags to typedefs.
9509 LookupDestructorName,
9510 /// Look up of a name that precedes the '::' scope resolution
9511 /// operator in C++. This lookup completely ignores operator, object,
9512 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9513 LookupNestedNameSpecifierName,
9514 /// Look up a namespace name within a C++ using directive or
9515 /// namespace alias definition, ignoring non-namespace names (C++
9516 /// [basic.lookup.udir]p1).
9517 LookupNamespaceName,
9518 /// Look up all declarations in a scope with the given name,
9519 /// including resolved using declarations. This is appropriate
9520 /// for checking redeclarations for a using declaration.
9521 LookupUsingDeclName,
9522 /// Look up an ordinary name that is going to be redeclared as a
9523 /// name with linkage. This lookup ignores any declarations that
9524 /// are outside of the current scope unless they have linkage. See
9525 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9526 LookupRedeclarationWithLinkage,
9527 /// Look up a friend of a local class. This lookup does not look
9528 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9529 LookupLocalFriendName,
9530 /// Look up the name of an Objective-C protocol.
9531 LookupObjCProtocolName,
9532 /// Look up implicit 'self' parameter of an objective-c method.
9533 LookupObjCImplicitSelfParam,
9534 /// Look up the name of an OpenMP user-defined reduction operation.
9535 LookupOMPReductionName,
9536 /// Look up the name of an OpenMP user-defined mapper.
9537 LookupOMPMapperName,
9538 /// Look up any declaration with any name.
9539 LookupAnyName
9540 };
9541
9542 /// The possible outcomes of name lookup for a literal operator.
9543 enum LiteralOperatorLookupResult {
9544 /// The lookup resulted in an error.
9545 LOLR_Error,
9546 /// The lookup found no match but no diagnostic was issued.
9547 LOLR_ErrorNoDiagnostic,
9548 /// The lookup found a single 'cooked' literal operator, which
9549 /// expects a normal literal to be built and passed to it.
9550 LOLR_Cooked,
9551 /// The lookup found a single 'raw' literal operator, which expects
9552 /// a string literal containing the spelling of the literal token.
9553 LOLR_Raw,
9554 /// The lookup found an overload set of literal operator templates,
9555 /// which expect the characters of the spelling of the literal token to be
9556 /// passed as a non-type template argument pack.
9557 LOLR_Template,
9558 /// The lookup found an overload set of literal operator templates,
9559 /// which expect the character type and characters of the spelling of the
9560 /// string literal token to be passed as template arguments.
9561 LOLR_StringTemplatePack,
9562 };
9563
9564 SpecialMemberOverloadResult
9565 LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg,
9566 bool VolatileArg, bool RValueThis, bool ConstThis,
9567 bool VolatileThis);
9568
9569 RedeclarationKind forRedeclarationInCurContext() const;
9570
9571 /// Look up a name, looking for a single declaration. Return
9572 /// null if the results were absent, ambiguous, or overloaded.
9573 ///
9574 /// It is preferable to use the elaborated form and explicitly handle
9575 /// ambiguity and overloaded.
9576 NamedDecl *LookupSingleName(
9577 Scope *S, DeclarationName Name, SourceLocation Loc,
9578 LookupNameKind NameKind,
9579 RedeclarationKind Redecl = RedeclarationKind::NotForRedeclaration);
9580
9581 /// Lookup a builtin function, when name lookup would otherwise
9582 /// fail.
9583 bool LookupBuiltin(LookupResult &R);
9584 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9585
9586 /// Perform unqualified name lookup starting from a given
9587 /// scope.
9588 ///
9589 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9590 /// used to find names within the current scope. For example, 'x' in
9591 /// @code
9592 /// int x;
9593 /// int f() {
9594 /// return x; // unqualified name look finds 'x' in the global scope
9595 /// }
9596 /// @endcode
9597 ///
9598 /// Different lookup criteria can find different names. For example, a
9599 /// particular scope can have both a struct and a function of the same
9600 /// name, and each can be found by certain lookup criteria. For more
9601 /// information about lookup criteria, see the documentation for the
9602 /// class LookupCriteria.
9603 ///
9604 /// @param S The scope from which unqualified name lookup will
9605 /// begin. If the lookup criteria permits, name lookup may also search
9606 /// in the parent scopes.
9607 ///
9608 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9609 /// look up and the lookup kind), and is updated with the results of lookup
9610 /// including zero or more declarations and possibly additional information
9611 /// used to diagnose ambiguities.
9612 ///
9613 /// @returns \c true if lookup succeeded and false otherwise.
9614 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9615 bool ForceNoCPlusPlus = false);
9616
9617 /// Perform qualified name lookup into a given context.
9618 ///
9619 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9620 /// names when the context of those names is explicit specified, e.g.,
9621 /// "std::vector" or "x->member", or as part of unqualified name lookup.
9622 ///
9623 /// Different lookup criteria can find different names. For example, a
9624 /// particular scope can have both a struct and a function of the same
9625 /// name, and each can be found by certain lookup criteria. For more
9626 /// information about lookup criteria, see the documentation for the
9627 /// class LookupCriteria.
9628 ///
9629 /// \param R captures both the lookup criteria and any lookup results found.
9630 ///
9631 /// \param LookupCtx The context in which qualified name lookup will
9632 /// search. If the lookup criteria permits, name lookup may also search
9633 /// in the parent contexts or (for C++ classes) base classes.
9634 ///
9635 /// \param InUnqualifiedLookup true if this is qualified name lookup that
9636 /// occurs as part of unqualified name lookup.
9637 ///
9638 /// \returns true if lookup succeeded, false if it failed.
9639 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9640 bool InUnqualifiedLookup = false);
9641
9642 /// Performs qualified name lookup or special type of lookup for
9643 /// "__super::" scope specifier.
9644 ///
9645 /// This routine is a convenience overload meant to be called from contexts
9646 /// that need to perform a qualified name lookup with an optional C++ scope
9647 /// specifier that might require special kind of lookup.
9648 ///
9649 /// \param R captures both the lookup criteria and any lookup results found.
9650 ///
9651 /// \param LookupCtx The context in which qualified name lookup will
9652 /// search.
9653 ///
9654 /// \param SS An optional C++ scope-specifier.
9655 ///
9656 /// \returns true if lookup succeeded, false if it failed.
9657 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9658 CXXScopeSpec &SS);
9659
9660 /// Performs name lookup for a name that was parsed in the
9661 /// source code, and may contain a C++ scope specifier.
9662 ///
9663 /// This routine is a convenience routine meant to be called from
9664 /// contexts that receive a name and an optional C++ scope specifier
9665 /// (e.g., "N::M::x"). It will then perform either qualified or
9666 /// unqualified name lookup (with LookupQualifiedName or LookupName,
9667 /// respectively) on the given name and return those results. It will
9668 /// perform a special type of lookup for "__super::" scope specifier.
9669 ///
9670 /// @param S The scope from which unqualified name lookup will
9671 /// begin.
9672 ///
9673 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
9674 ///
9675 /// @param EnteringContext Indicates whether we are going to enter the
9676 /// context of the scope-specifier SS (if present).
9677 ///
9678 /// @returns True if any decls were found (but possibly ambiguous)
9679 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
9680 QualType ObjectType, bool AllowBuiltinCreation = false,
9681 bool EnteringContext = false);
9682
9683 /// Perform qualified name lookup into all base classes of the given
9684 /// class.
9685 ///
9686 /// \param R captures both the lookup criteria and any lookup results found.
9687 ///
9688 /// \param Class The context in which qualified name lookup will
9689 /// search. Name lookup will search in all base classes merging the results.
9690 ///
9691 /// @returns True if any decls were found (but possibly ambiguous)
9692 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
9693
9694 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
9695 UnresolvedSetImpl &Functions);
9696
9697 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9698 /// If GnuLabelLoc is a valid source location, then this is a definition
9699 /// of an __label__ label name, otherwise it is a normal label definition
9700 /// or use. If IsLabelStmt is true, then this is the label of a
9701 /// labeled-statement.
9702 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
9703 SourceLocation GnuLabelLoc = SourceLocation(),
9704 bool IsLabelStmt = false);
9705
9706 /// Perform a name lookup for a label with the specified name; this does not
9707 /// create a new label if the lookup fails.
9708 LabelDecl *LookupExistingLabel(IdentifierInfo *II, SourceLocation IdentLoc);
9709
9710 /// Look up the constructors for the given class.
9711 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
9712
9713 /// Look up the default constructor for the given class.
9714 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
9715
9716 /// Look up the copying constructor for the given class.
9717 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
9718 unsigned Quals);
9719
9720 /// Look up the copying assignment operator for the given class.
9721 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
9722 bool RValueThis, unsigned ThisQuals);
9723
9724 /// Look up the moving constructor for the given class.
9725 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
9726 unsigned Quals);
9727
9728 /// Look up the moving assignment operator for the given class.
9729 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
9730 bool RValueThis, unsigned ThisQuals);
9731
9732 /// Look for the destructor of the given class.
9733 ///
9734 /// During semantic analysis, this routine should be used in lieu of
9735 /// CXXRecordDecl::getDestructor().
9736 ///
9737 /// \returns The destructor for this class.
9738 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
9739
9740 /// Force the declaration of any implicitly-declared members of this
9741 /// class.
9742 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
9743
9744 /// Make a merged definition of an existing hidden definition \p ND
9745 /// visible at the specified location.
9746 void makeMergedDefinitionVisible(NamedDecl *ND);
9747
9748 /// Check ODR hashes for C/ObjC when merging types from modules.
9749 /// Differently from C++, actually parse the body and reject in case
9750 /// of a mismatch.
9751 template <typename T,
9752 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
9753 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
9754 if (Duplicate->getODRHash() != Previous->getODRHash())
9755 return false;
9756
9757 // Make the previous decl visible.
9758 makeMergedDefinitionVisible(ND: Previous);
9759 return true;
9760 }
9761
9762 /// Get the set of additional modules that should be checked during
9763 /// name lookup. A module and its imports become visible when instanting a
9764 /// template defined within it.
9765 llvm::DenseSet<Module *> &getLookupModules();
9766
9767 bool hasVisibleMergedDefinition(const NamedDecl *Def);
9768 bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
9769
9770 /// Determine if the template parameter \p D has a visible default argument.
9771 bool
9772 hasVisibleDefaultArgument(const NamedDecl *D,
9773 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9774 /// Determine if the template parameter \p D has a reachable default argument.
9775 bool hasReachableDefaultArgument(
9776 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9777 /// Determine if the template parameter \p D has a reachable default argument.
9778 bool hasAcceptableDefaultArgument(const NamedDecl *D,
9779 llvm::SmallVectorImpl<Module *> *Modules,
9780 Sema::AcceptableKind Kind);
9781
9782 /// Determine if there is a visible declaration of \p D that is an explicit
9783 /// specialization declaration for a specialization of a template. (For a
9784 /// member specialization, use hasVisibleMemberSpecialization.)
9785 bool hasVisibleExplicitSpecialization(
9786 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9787 /// Determine if there is a reachable declaration of \p D that is an explicit
9788 /// specialization declaration for a specialization of a template. (For a
9789 /// member specialization, use hasReachableMemberSpecialization.)
9790 bool hasReachableExplicitSpecialization(
9791 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9792
9793 /// Determine if there is a visible declaration of \p D that is a member
9794 /// specialization declaration (as opposed to an instantiated declaration).
9795 bool hasVisibleMemberSpecialization(
9796 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9797 /// Determine if there is a reachable declaration of \p D that is a member
9798 /// specialization declaration (as opposed to an instantiated declaration).
9799 bool hasReachableMemberSpecialization(
9800 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9801
9802 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9803
9804 /// Determine whether any declaration of an entity is visible.
9805 bool
9806 hasVisibleDeclaration(const NamedDecl *D,
9807 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9808 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9809 }
9810
9811 bool hasVisibleDeclarationSlow(const NamedDecl *D,
9812 llvm::SmallVectorImpl<Module *> *Modules);
9813 /// Determine whether any declaration of an entity is reachable.
9814 bool
9815 hasReachableDeclaration(const NamedDecl *D,
9816 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9817 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9818 }
9819 bool hasReachableDeclarationSlow(
9820 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9821
9822 void diagnoseTypo(const TypoCorrection &Correction,
9823 const PartialDiagnostic &TypoDiag,
9824 bool ErrorRecovery = true);
9825
9826 /// Diagnose a successfully-corrected typo. Separated from the correction
9827 /// itself to allow external validation of the result, etc.
9828 ///
9829 /// \param Correction The result of performing typo correction.
9830 /// \param TypoDiag The diagnostic to produce. This will have the corrected
9831 /// string added to it (and usually also a fixit).
9832 /// \param PrevNote A note to use when indicating the location of the entity
9833 /// to which we are correcting. Will have the correction string added
9834 /// to it.
9835 /// \param ErrorRecovery If \c true (the default), the caller is going to
9836 /// recover from the typo as if the corrected string had been typed.
9837 /// In this case, \c PDiag must be an error, and we will attach a fixit
9838 /// to it.
9839 void diagnoseTypo(const TypoCorrection &Correction,
9840 const PartialDiagnostic &TypoDiag,
9841 const PartialDiagnostic &PrevNote,
9842 bool ErrorRecovery = true);
9843
9844 /// Find the associated classes and namespaces for
9845 /// argument-dependent lookup for a call with the given set of
9846 /// arguments.
9847 ///
9848 /// This routine computes the sets of associated classes and associated
9849 /// namespaces searched by argument-dependent lookup
9850 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9851 void FindAssociatedClassesAndNamespaces(
9852 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9853 AssociatedNamespaceSet &AssociatedNamespaces,
9854 AssociatedClassSet &AssociatedClasses);
9855
9856 /// Produce a diagnostic describing the ambiguity that resulted
9857 /// from name lookup.
9858 ///
9859 /// \param Result The result of the ambiguous lookup to be diagnosed.
9860 void DiagnoseAmbiguousLookup(LookupResult &Result);
9861
9862 /// LookupLiteralOperator - Determine which literal operator should be used
9863 /// for a user-defined literal, per C++11 [lex.ext].
9864 ///
9865 /// Normal overload resolution is not used to select which literal operator to
9866 /// call for a user-defined literal. Look up the provided literal operator
9867 /// name, and filter the results to the appropriate set for the given argument
9868 /// types.
9869 LiteralOperatorLookupResult
9870 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
9871 bool AllowRaw, bool AllowTemplate,
9872 bool AllowStringTemplate, bool DiagnoseMissing,
9873 StringLiteral *StringLit = nullptr);
9874
9875 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
9876 ArrayRef<Expr *> Args, ADLResult &Functions);
9877
9878 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9879 VisibleDeclConsumer &Consumer,
9880 bool IncludeGlobalScope = true,
9881 bool LoadExternal = true);
9882 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9883 VisibleDeclConsumer &Consumer,
9884 bool IncludeGlobalScope = true,
9885 bool IncludeDependentBases = false,
9886 bool LoadExternal = true);
9887
9888 /// Try to "correct" a typo in the source code by finding
9889 /// visible declarations whose names are similar to the name that was
9890 /// present in the source code.
9891 ///
9892 /// \param TypoName the \c DeclarationNameInfo structure that contains
9893 /// the name that was present in the source code along with its location.
9894 ///
9895 /// \param LookupKind the name-lookup criteria used to search for the name.
9896 ///
9897 /// \param S the scope in which name lookup occurs.
9898 ///
9899 /// \param SS the nested-name-specifier that precedes the name we're
9900 /// looking for, if present.
9901 ///
9902 /// \param CCC A CorrectionCandidateCallback object that provides further
9903 /// validation of typo correction candidates. It also provides flags for
9904 /// determining the set of keywords permitted.
9905 ///
9906 /// \param MemberContext if non-NULL, the context in which to look for
9907 /// a member access expression.
9908 ///
9909 /// \param EnteringContext whether we're entering the context described by
9910 /// the nested-name-specifier SS.
9911 ///
9912 /// \param OPT when non-NULL, the search for visible declarations will
9913 /// also walk the protocols in the qualified interfaces of \p OPT.
9914 ///
9915 /// \returns a \c TypoCorrection containing the corrected name if the typo
9916 /// along with information such as the \c NamedDecl where the corrected name
9917 /// was declared, and any additional \c NestedNameSpecifier needed to access
9918 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9919 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
9920 Sema::LookupNameKind LookupKind, Scope *S,
9921 CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9922 CorrectTypoKind Mode,
9923 DeclContext *MemberContext = nullptr,
9924 bool EnteringContext = false,
9925 const ObjCObjectPointerType *OPT = nullptr,
9926 bool RecordFailure = true);
9927
9928 /// Kinds of missing import. Note, the values of these enumerators correspond
9929 /// to %select values in diagnostics.
9930 enum class MissingImportKind {
9931 Declaration,
9932 Definition,
9933 DefaultArgument,
9934 ExplicitSpecialization,
9935 PartialSpecialization
9936 };
9937
9938 /// Diagnose that the specified declaration needs to be visible but
9939 /// isn't, and suggest a module import that would resolve the problem.
9940 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9941 MissingImportKind MIK, bool Recover = true);
9942 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9943 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
9944 MissingImportKind MIK, bool Recover);
9945
9946 /// Called on #pragma clang __debug dump II
9947 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9948
9949 /// Called on #pragma clang __debug dump E
9950 void ActOnPragmaDump(Expr *E);
9951
9952private:
9953 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
9954 //
9955 // The boolean value will be true to indicate that the namespace was loaded
9956 // from an AST/PCH file, or false otherwise.
9957 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
9958
9959 /// Whether we have already loaded known namespaces from an extenal
9960 /// source.
9961 bool LoadedExternalKnownNamespaces;
9962
9963 bool CppLookupName(LookupResult &R, Scope *S);
9964
9965 /// Determine if we could use all the declarations in the module.
9966 bool isUsableModule(const Module *M);
9967
9968 /// Helper for CorrectTypo used to create and populate a new
9969 /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
9970 /// skipped entirely.
9971 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
9972 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
9973 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9974 DeclContext *MemberContext, bool EnteringContext,
9975 const ObjCObjectPointerType *OPT, bool ErrorRecovery);
9976
9977 /// Cache for module units which is usable for current module.
9978 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
9979
9980 /// Record the typo correction failure and return an empty correction.
9981 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
9982 bool RecordFailure = true) {
9983 if (RecordFailure)
9984 TypoCorrectionFailures[Typo].insert(V: TypoLoc);
9985 return TypoCorrection();
9986 }
9987
9988 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
9989
9990 /// Determine whether two declarations should be linked together, given that
9991 /// the old declaration might not be visible and the new declaration might
9992 /// not have external linkage.
9993 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
9994 const NamedDecl *New) {
9995 if (isVisible(D: Old))
9996 return true;
9997 // See comment in below overload for why it's safe to compute the linkage
9998 // of the new declaration here.
9999 if (New->isExternallyDeclarable()) {
10000 assert(Old->isExternallyDeclarable() &&
10001 "should not have found a non-externally-declarable previous decl");
10002 return true;
10003 }
10004 return false;
10005 }
10006 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
10007
10008 ///@}
10009
10010 //
10011 //
10012 // -------------------------------------------------------------------------
10013 //
10014 //
10015
10016 /// \name Modules
10017 /// Implementations are in SemaModule.cpp
10018 ///@{
10019
10020public:
10021 /// Get the module unit whose scope we are currently within.
10022 Module *getCurrentModule() const {
10023 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
10024 }
10025
10026 /// Is the module scope we are an implementation unit?
10027 bool currentModuleIsImplementation() const {
10028 if (ModuleScopes.empty())
10029 return false;
10030 const Module *M = ModuleScopes.back().Module;
10031 return M->isModuleImplementation() || M->isModulePartitionImplementation();
10032 }
10033
10034 // When loading a non-modular PCH files, this is used to restore module
10035 // visibility.
10036 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
10037 VisibleModules.setVisible(M: Mod, Loc: ImportLoc);
10038 }
10039
10040 enum class ModuleDeclKind {
10041 Interface, ///< 'export module X;'
10042 Implementation, ///< 'module X;'
10043 PartitionInterface, ///< 'export module X:Y;'
10044 PartitionImplementation, ///< 'module X:Y;'
10045 };
10046
10047 /// An enumeration to represent the transition of states in parsing module
10048 /// fragments and imports. If we are not parsing a C++20 TU, or we find
10049 /// an error in state transition, the state is set to NotACXX20Module.
10050 enum class ModuleImportState {
10051 FirstDecl, ///< Parsing the first decl in a TU.
10052 GlobalFragment, ///< after 'module;' but before 'module X;'
10053 ImportAllowed, ///< after 'module X;' but before any non-import decl.
10054 ImportFinished, ///< after any non-import decl.
10055 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
10056 ///< non-import decl.
10057 PrivateFragmentImportFinished, ///< after 'module :private;' but a
10058 ///< non-import decl has already been seen.
10059 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
10060 };
10061
10062 /// The parser has processed a module-declaration that begins the definition
10063 /// of a module interface or implementation.
10064 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
10065 SourceLocation ModuleLoc, ModuleDeclKind MDK,
10066 ModuleIdPath Path, ModuleIdPath Partition,
10067 ModuleImportState &ImportState,
10068 bool SeenNoTrivialPPDirective);
10069
10070 /// The parser has processed a global-module-fragment declaration that begins
10071 /// the definition of the global module fragment of the current module unit.
10072 /// \param ModuleLoc The location of the 'module' keyword.
10073 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
10074
10075 /// The parser has processed a private-module-fragment declaration that begins
10076 /// the definition of the private module fragment of the current module unit.
10077 /// \param ModuleLoc The location of the 'module' keyword.
10078 /// \param PrivateLoc The location of the 'private' keyword.
10079 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
10080 SourceLocation PrivateLoc);
10081
10082 /// The parser has processed a module import declaration.
10083 ///
10084 /// \param StartLoc The location of the first token in the declaration. This
10085 /// could be the location of an '@', 'export', or 'import'.
10086 /// \param ExportLoc The location of the 'export' keyword, if any.
10087 /// \param ImportLoc The location of the 'import' keyword.
10088 /// \param Path The module toplevel name as an access path.
10089 /// \param IsPartition If the name is for a partition.
10090 DeclResult ActOnModuleImport(SourceLocation StartLoc,
10091 SourceLocation ExportLoc,
10092 SourceLocation ImportLoc, ModuleIdPath Path,
10093 bool IsPartition = false);
10094 DeclResult ActOnModuleImport(SourceLocation StartLoc,
10095 SourceLocation ExportLoc,
10096 SourceLocation ImportLoc, Module *M,
10097 ModuleIdPath Path = {});
10098
10099 /// The parser has processed a module import translated from a
10100 /// #include or similar preprocessing directive.
10101 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10102 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10103
10104 /// The parsed has entered a submodule.
10105 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
10106 /// The parser has left a submodule.
10107 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
10108
10109 /// Create an implicit import of the given module at the given
10110 /// source location, for error recovery, if possible.
10111 ///
10112 /// This routine is typically used when an entity found by name lookup
10113 /// is actually hidden within a module that we know about but the user
10114 /// has forgotten to import.
10115 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
10116 Module *Mod);
10117
10118 /// We have parsed the start of an export declaration, including the '{'
10119 /// (if present).
10120 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
10121 SourceLocation LBraceLoc);
10122
10123 /// Complete the definition of an export declaration.
10124 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
10125 SourceLocation RBraceLoc);
10126
10127private:
10128 /// The parser has begun a translation unit to be compiled as a C++20
10129 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
10130 void HandleStartOfHeaderUnit();
10131
10132 struct ModuleScope {
10133 SourceLocation BeginLoc;
10134 clang::Module *Module = nullptr;
10135 VisibleModuleSet OuterVisibleModules;
10136 };
10137 /// The modules we're currently parsing.
10138 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
10139
10140 /// For an interface unit, this is the implicitly imported interface unit.
10141 clang::Module *ThePrimaryInterface = nullptr;
10142
10143 /// The explicit global module fragment of the current translation unit.
10144 /// The explicit Global Module Fragment, as specified in C++
10145 /// [module.global.frag].
10146 clang::Module *TheGlobalModuleFragment = nullptr;
10147
10148 /// The implicit global module fragments of the current translation unit.
10149 ///
10150 /// The contents in the implicit global module fragment can't be discarded.
10151 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
10152
10153 /// Namespace definitions that we will export when they finish.
10154 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
10155
10156 /// In a C++ standard module, inline declarations require a definition to be
10157 /// present at the end of a definition domain. This set holds the decls to
10158 /// be checked at the end of the TU.
10159 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
10160
10161 /// Helper function to judge if we are in module purview.
10162 /// Return false if we are not in a module.
10163 bool isCurrentModulePurview() const;
10164
10165 /// Enter the scope of the explicit global module fragment.
10166 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
10167 /// Leave the scope of the explicit global module fragment.
10168 void PopGlobalModuleFragment();
10169
10170 /// Enter the scope of an implicit global module fragment.
10171 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
10172 /// Leave the scope of an implicit global module fragment.
10173 void PopImplicitGlobalModuleFragment();
10174
10175 VisibleModuleSet VisibleModules;
10176
10177 /// Whether we had imported any named modules.
10178 bool HadImportedNamedModules = false;
10179 /// The set of instantiations we need to check if they references TU-local
10180 /// entity from TUs. This only makes sense if we imported any named modules.
10181 llvm::SmallVector<std::pair<FunctionDecl *, SourceLocation>>
10182 PendingCheckReferenceForTULocal;
10183 /// Implement [basic.link]p18, which requires that we can't use TU-local
10184 /// entities from other TUs (ignoring header units).
10185 void checkReferenceToTULocalFromOtherTU(FunctionDecl *FD,
10186 SourceLocation PointOfInstantiation);
10187 /// Implement [basic.link]p17, which diagnose for non TU local exposure in
10188 /// module interface or module partition.
10189 void checkExposure(const TranslationUnitDecl *TU);
10190
10191 ///@}
10192
10193 //
10194 //
10195 // -------------------------------------------------------------------------
10196 //
10197 //
10198
10199 /// \name C++ Overloading
10200 /// Implementations are in SemaOverload.cpp
10201 ///@{
10202
10203public:
10204 /// Whether deferrable diagnostics should be deferred.
10205 bool DeferDiags = false;
10206
10207 /// RAII class to control scope of DeferDiags.
10208 class DeferDiagsRAII {
10209 Sema &S;
10210 bool SavedDeferDiags = false;
10211
10212 public:
10213 DeferDiagsRAII(Sema &S, bool DeferDiags)
10214 : S(S), SavedDeferDiags(S.DeferDiags) {
10215 S.DeferDiags = SavedDeferDiags || DeferDiags;
10216 }
10217 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
10218 DeferDiagsRAII(const DeferDiagsRAII &) = delete;
10219 DeferDiagsRAII &operator=(const DeferDiagsRAII &) = delete;
10220 };
10221
10222 /// Flag indicating if Sema is building a recovery call expression.
10223 ///
10224 /// This flag is used to avoid building recovery call expressions
10225 /// if Sema is already doing so, which would cause infinite recursions.
10226 bool IsBuildingRecoveryCallExpr;
10227
10228 /// Determine whether the given New declaration is an overload of the
10229 /// declarations in Old. This routine returns OverloadKind::Match or
10230 /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
10231 /// New has the same signature as some function in Old (C++ 1.3.10) or if the
10232 /// Old declarations aren't functions (or function templates) at all. When it
10233 /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
10234 /// will point to the decl that New cannot be overloaded with. This decl may
10235 /// be a UsingShadowDecl on top of the underlying declaration.
10236 ///
10237 /// Example: Given the following input:
10238 ///
10239 /// void f(int, float); // #1
10240 /// void f(int, int); // #2
10241 /// int f(int, int); // #3
10242 ///
10243 /// When we process #1, there is no previous declaration of "f", so IsOverload
10244 /// will not be used.
10245 ///
10246 /// When we process #2, Old contains only the FunctionDecl for #1. By
10247 /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10248 /// they have different signatures), so this routine returns
10249 /// OverloadKind::Overload; MatchedDecl is unchanged.
10250 ///
10251 /// When we process #3, Old is an overload set containing #1 and #2. We
10252 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10253 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10254 /// types of functions are not part of the signature), IsOverload returns
10255 /// OverloadKind::Match and MatchedDecl will be set to point to the
10256 /// FunctionDecl for #2.
10257 ///
10258 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10259 /// class by a using declaration. The rules for whether to hide shadow
10260 /// declarations ignore some properties which otherwise figure into a function
10261 /// template's signature.
10262 OverloadKind CheckOverload(Scope *S, FunctionDecl *New,
10263 const LookupResult &OldDecls, NamedDecl *&OldDecl,
10264 bool UseMemberUsingDeclRules);
10265 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
10266 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10267
10268 // Checks whether MD constitutes an override the base class method BaseMD.
10269 // When checking for overrides, the object object members are ignored.
10270 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10271 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10272
10273 enum class AllowedExplicit {
10274 /// Allow no explicit functions to be used.
10275 None,
10276 /// Allow explicit conversion functions but not explicit constructors.
10277 Conversions,
10278 /// Allow both explicit conversion functions and explicit constructors.
10279 All
10280 };
10281
10282 ImplicitConversionSequence TryImplicitConversion(
10283 Expr *From, QualType ToType, bool SuppressUserConversions,
10284 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10285 bool AllowObjCWritebackConversion);
10286
10287 /// PerformImplicitConversion - Perform an implicit conversion of the
10288 /// expression From to the type ToType. Returns the
10289 /// converted expression. Flavor is the kind of conversion we're
10290 /// performing, used in the error message. If @p AllowExplicit,
10291 /// explicit user-defined conversions are permitted.
10292 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10293 AssignmentAction Action,
10294 bool AllowExplicit = false);
10295
10296 /// IsIntegralPromotion - Determines whether the conversion from the
10297 /// expression From (whose potentially-adjusted type is FromType) to
10298 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10299 /// sets PromotedType to the promoted type.
10300 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10301
10302 /// IsFloatingPointPromotion - Determines whether the conversion from
10303 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10304 /// returns true and sets PromotedType to the promoted type.
10305 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10306
10307 /// Determine if a conversion is a complex promotion.
10308 ///
10309 /// A complex promotion is defined as a complex -> complex conversion
10310 /// where the conversion between the underlying real types is a
10311 /// floating-point or integral promotion.
10312 bool IsComplexPromotion(QualType FromType, QualType ToType);
10313
10314 /// IsOverflowBehaviorTypePromotion - Determines whether the conversion from
10315 /// FromType to ToType involves an OverflowBehaviorType FromType being
10316 /// promoted to an OverflowBehaviorType ToType which has a larger bitwidth.
10317 /// If so, returns true and sets FromType to ToType.
10318 bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType);
10319
10320 /// IsOverflowBehaviorTypeConversion - Determines whether the conversion from
10321 /// FromType to ToType necessarily involves both an OverflowBehaviorType and
10322 /// a non-OverflowBehaviorType. If so, returns true and sets FromType to
10323 /// ToType.
10324 bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType);
10325
10326 /// IsPointerConversion - Determines whether the conversion of the
10327 /// expression From, which has the (possibly adjusted) type FromType,
10328 /// can be converted to the type ToType via a pointer conversion (C++
10329 /// 4.10). If so, returns true and places the converted type (that
10330 /// might differ from ToType in its cv-qualifiers at some level) into
10331 /// ConvertedType.
10332 ///
10333 /// This routine also supports conversions to and from block pointers
10334 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10335 /// pointers to interfaces. FIXME: Once we've determined the
10336 /// appropriate overloading rules for Objective-C, we may want to
10337 /// split the Objective-C checks into a different routine; however,
10338 /// GCC seems to consider all of these conversions to be pointer
10339 /// conversions, so for now they live here. IncompatibleObjC will be
10340 /// set if the conversion is an allowed Objective-C conversion that
10341 /// should result in a warning.
10342 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10343 bool InOverloadResolution, QualType &ConvertedType,
10344 bool &IncompatibleObjC);
10345
10346 /// isObjCPointerConversion - Determines whether this is an
10347 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10348 /// with the same arguments and return values.
10349 bool isObjCPointerConversion(QualType FromType, QualType ToType,
10350 QualType &ConvertedType, bool &IncompatibleObjC);
10351 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10352 QualType &ConvertedType);
10353
10354 /// FunctionParamTypesAreEqual - This routine checks two function proto types
10355 /// for equality of their parameter types. Caller has already checked that
10356 /// they have same number of parameters. If the parameters are different,
10357 /// ArgPos will have the parameter index of the first different parameter.
10358 /// If `Reversed` is true, the parameters of `NewType` will be compared in
10359 /// reverse order. That's useful if one of the functions is being used as a
10360 /// C++20 synthesized operator overload with a reversed parameter order.
10361 bool FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
10362 ArrayRef<QualType> New,
10363 unsigned *ArgPos = nullptr,
10364 bool Reversed = false);
10365
10366 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
10367 const FunctionProtoType *NewType,
10368 unsigned *ArgPos = nullptr,
10369 bool Reversed = false);
10370
10371 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10372 const FunctionDecl *NewFunction,
10373 unsigned *ArgPos = nullptr,
10374 bool Reversed = false);
10375
10376 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10377 /// function types. Catches different number of parameter, mismatch in
10378 /// parameter types, and different return types.
10379 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType,
10380 QualType ToType);
10381
10382 /// CheckPointerConversion - Check the pointer conversion from the
10383 /// expression From to the type ToType. This routine checks for
10384 /// ambiguous or inaccessible derived-to-base pointer
10385 /// conversions for which IsPointerConversion has already returned
10386 /// true. It returns true and produces a diagnostic if there was an
10387 /// error, or returns false otherwise.
10388 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10389 CXXCastPath &BasePath, bool IgnoreBaseAccess,
10390 bool Diagnose = true);
10391
10392 /// IsMemberPointerConversion - Determines whether the conversion of the
10393 /// expression From, which has the (possibly adjusted) type FromType, can be
10394 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10395 /// If so, returns true and places the converted type (that might differ from
10396 /// ToType in its cv-qualifiers at some level) into ConvertedType.
10397 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10398 bool InOverloadResolution,
10399 QualType &ConvertedType);
10400
10401 enum class MemberPointerConversionResult {
10402 Success,
10403 DifferentPointee,
10404 NotDerived,
10405 Ambiguous,
10406 Virtual,
10407 Inaccessible
10408 };
10409 enum class MemberPointerConversionDirection : bool { Downcast, Upcast };
10410 /// CheckMemberPointerConversion - Check the member pointer conversion from
10411 /// the expression From to the type ToType. This routine checks for ambiguous
10412 /// or virtual or inaccessible base-to-derived member pointer conversions for
10413 /// which IsMemberPointerConversion has already returned true. It produces a
10414 // diagnostic if there was an error.
10415 MemberPointerConversionResult CheckMemberPointerConversion(
10416 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10417 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10418 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10419
10420 /// IsQualificationConversion - Determines whether the conversion from
10421 /// an rvalue of type FromType to ToType is a qualification conversion
10422 /// (C++ 4.4).
10423 ///
10424 /// \param ObjCLifetimeConversion Output parameter that will be set to
10425 /// indicate when the qualification conversion involves a change in the
10426 /// Objective-C object lifetime.
10427 bool IsQualificationConversion(QualType FromType, QualType ToType,
10428 bool CStyle, bool &ObjCLifetimeConversion);
10429
10430 /// Determine whether the conversion from FromType to ToType is a valid
10431 /// conversion of ExtInfo/ExtProtoInfo on the nested function type.
10432 /// More precisely, this method checks whether FromType can be transformed
10433 /// into an exact match for ToType, by transforming its extended function
10434 /// type information in legal manner (e.g. by strictly stripping "noreturn"
10435 /// or "noexcept", or by stripping "noescape" for arguments).
10436 bool IsFunctionConversion(QualType FromType, QualType ToType) const;
10437
10438 /// Same as `IsFunctionConversion`, but if this would return true, it sets
10439 /// `ResultTy` to `ToType`.
10440 bool TryFunctionConversion(QualType FromType, QualType ToType,
10441 QualType &ResultTy) const;
10442
10443 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
10444 void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
10445 DeclarationName Name,
10446 OverloadCandidateSet &CandidateSet,
10447 FunctionDecl *Fn, MultiExprArg Args,
10448 bool IsMember = false);
10449
10450 ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
10451 FunctionDecl *Fun);
10452 ExprResult PerformImplicitObjectArgumentInitialization(
10453 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
10454 CXXMethodDecl *Method);
10455
10456 /// PerformContextuallyConvertToBool - Perform a contextual conversion
10457 /// of the expression From to bool (C++0x [conv]p3).
10458 ExprResult PerformContextuallyConvertToBool(Expr *From);
10459
10460 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10461 /// conversion of the expression From to an Objective-C pointer type.
10462 /// Returns a valid but null ExprResult if no conversion sequence exists.
10463 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
10464
10465 ExprResult BuildConvertedConstantExpression(Expr *From, QualType T,
10466 CCEKind CCE,
10467 NamedDecl *Dest = nullptr);
10468
10469 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10470 llvm::APSInt &Value, CCEKind CCE);
10471 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10472 APValue &Value, CCEKind CCE,
10473 NamedDecl *Dest = nullptr);
10474
10475 /// EvaluateConvertedConstantExpression - Evaluate an Expression
10476 /// That is a converted constant expression
10477 /// (which was built with BuildConvertedConstantExpression)
10478 ExprResult
10479 EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
10480 CCEKind CCE, bool RequireInt,
10481 const APValue &PreNarrowingValue);
10482
10483 /// Abstract base class used to perform a contextual implicit
10484 /// conversion from an expression to any type passing a filter.
10485 class ContextualImplicitConverter {
10486 public:
10487 bool Suppress;
10488 bool SuppressConversion;
10489
10490 ContextualImplicitConverter(bool Suppress = false,
10491 bool SuppressConversion = false)
10492 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
10493
10494 /// Determine whether the specified type is a valid destination type
10495 /// for this conversion.
10496 virtual bool match(QualType T) = 0;
10497
10498 /// Emits a diagnostic complaining that the expression does not have
10499 /// integral or enumeration type.
10500 virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10501 QualType T) = 0;
10502
10503 /// Emits a diagnostic when the expression has incomplete class type.
10504 virtual SemaDiagnosticBuilder
10505 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
10506
10507 /// Emits a diagnostic when the only matching conversion function
10508 /// is explicit.
10509 virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S,
10510 SourceLocation Loc,
10511 QualType T,
10512 QualType ConvTy) = 0;
10513
10514 /// Emits a note for the explicit conversion function.
10515 virtual SemaDiagnosticBuilder
10516 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10517
10518 /// Emits a diagnostic when there are multiple possible conversion
10519 /// functions.
10520 virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10521 QualType T) = 0;
10522
10523 /// Emits a note for one of the candidate conversions.
10524 virtual SemaDiagnosticBuilder
10525 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10526
10527 /// Emits a diagnostic when we picked a conversion function
10528 /// (for cases when we are not allowed to pick a conversion function).
10529 virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S,
10530 SourceLocation Loc,
10531 QualType T,
10532 QualType ConvTy) = 0;
10533
10534 virtual ~ContextualImplicitConverter() {}
10535 };
10536
10537 class ICEConvertDiagnoser : public ContextualImplicitConverter {
10538 bool AllowScopedEnumerations;
10539
10540 public:
10541 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10542 bool SuppressConversion)
10543 : ContextualImplicitConverter(Suppress, SuppressConversion),
10544 AllowScopedEnumerations(AllowScopedEnumerations) {}
10545
10546 /// Match an integral or (possibly scoped) enumeration type.
10547 bool match(QualType T) override;
10548
10549 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10550 QualType T) override {
10551 return diagnoseNotInt(S, Loc, T);
10552 }
10553
10554 /// Emits a diagnostic complaining that the expression does not have
10555 /// integral or enumeration type.
10556 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10557 QualType T) = 0;
10558 };
10559
10560 /// Perform a contextual implicit conversion.
10561 ExprResult
10562 PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE,
10563 ContextualImplicitConverter &Converter);
10564
10565 /// ReferenceCompareResult - Expresses the result of comparing two
10566 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10567 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10568 enum ReferenceCompareResult {
10569 /// Ref_Incompatible - The two types are incompatible, so direct
10570 /// reference binding is not possible.
10571 Ref_Incompatible = 0,
10572 /// Ref_Related - The two types are reference-related, which means
10573 /// that their unqualified forms (T1 and T2) are either the same
10574 /// or T1 is a base class of T2.
10575 Ref_Related,
10576 /// Ref_Compatible - The two types are reference-compatible.
10577 Ref_Compatible
10578 };
10579
10580 // Fake up a scoped enumeration that still contextually converts to bool.
10581 struct ReferenceConversionsScope {
10582 /// The conversions that would be performed on an lvalue of type T2 when
10583 /// binding a reference of type T1 to it, as determined when evaluating
10584 /// whether T1 is reference-compatible with T2.
10585 enum ReferenceConversions {
10586 Qualification = 0x1,
10587 NestedQualification = 0x2,
10588 Function = 0x4,
10589 DerivedToBase = 0x8,
10590 ObjC = 0x10,
10591 ObjCLifetime = 0x20,
10592
10593 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
10594 };
10595 };
10596 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
10597
10598 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10599 /// determine whether they are reference-compatible,
10600 /// reference-related, or incompatible, for use in C++ initialization by
10601 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10602 /// type, and the first type (T1) is the pointee type of the reference
10603 /// type being initialized.
10604 ReferenceCompareResult
10605 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
10606 ReferenceConversions *Conv = nullptr);
10607
10608 /// AddOverloadCandidate - Adds the given function to the set of
10609 /// candidate functions, using the given function call arguments. If
10610 /// @p SuppressUserConversions, then don't allow user-defined
10611 /// conversions via constructors or conversion operators.
10612 ///
10613 /// \param PartialOverloading true if we are performing "partial" overloading
10614 /// based on an incomplete set of function arguments. This feature is used by
10615 /// code completion.
10616 void AddOverloadCandidate(
10617 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
10618 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10619 bool PartialOverloading = false, bool AllowExplicit = true,
10620 bool AllowExplicitConversion = false,
10621 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10622 ConversionSequenceList EarlyConversions = {},
10623 OverloadCandidateParamOrder PO = {},
10624 bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10625
10626 /// Add all of the function declarations in the given function set to
10627 /// the overload candidate set.
10628 void AddFunctionCandidates(
10629 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10630 OverloadCandidateSet &CandidateSet,
10631 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10632 bool SuppressUserConversions = false, bool PartialOverloading = false,
10633 bool FirstArgumentIsBase = false);
10634
10635 /// AddMethodCandidate - Adds a named decl (which is some kind of
10636 /// method) as a method candidate to the given overload set.
10637 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10638 Expr::Classification ObjectClassification,
10639 ArrayRef<Expr *> Args,
10640 OverloadCandidateSet &CandidateSet,
10641 bool SuppressUserConversion = false,
10642 OverloadCandidateParamOrder PO = {});
10643
10644 /// AddMethodCandidate - Adds the given C++ member function to the set
10645 /// of candidate functions, using the given function call arguments
10646 /// and the object argument (@c Object). For example, in a call
10647 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10648 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10649 /// allow user-defined conversions via constructors or conversion
10650 /// operators.
10651 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10652 CXXRecordDecl *ActingContext, QualType ObjectType,
10653 Expr::Classification ObjectClassification,
10654 ArrayRef<Expr *> Args,
10655 OverloadCandidateSet &CandidateSet,
10656 bool SuppressUserConversions = false,
10657 bool PartialOverloading = false,
10658 ConversionSequenceList EarlyConversions = {},
10659 OverloadCandidateParamOrder PO = {},
10660 bool StrictPackMatch = false);
10661
10662 /// Add a C++ member function template as a candidate to the candidate
10663 /// set, using template argument deduction to produce an appropriate member
10664 /// function template specialization.
10665 void AddMethodTemplateCandidate(
10666 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10667 CXXRecordDecl *ActingContext,
10668 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10669 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10670 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10671 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10672
10673 /// Add a C++ function template specialization as a candidate
10674 /// in the candidate set, using template argument deduction to produce
10675 /// an appropriate function template specialization.
10676 void AddTemplateOverloadCandidate(
10677 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10678 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10679 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10680 bool PartialOverloading = false, bool AllowExplicit = true,
10681 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10682 OverloadCandidateParamOrder PO = {},
10683 bool AggregateCandidateDeduction = false);
10684
10685 struct CheckNonDependentConversionsFlag {
10686 /// Do not consider any user-defined conversions when constructing the
10687 /// initializing sequence.
10688 bool SuppressUserConversions;
10689
10690 /// Before constructing the initializing sequence, we check whether the
10691 /// parameter type and argument type contain any user defined conversions.
10692 /// If so, do not initialize them. This effectively bypasses some undesired
10693 /// instantiation before checking constaints, which might otherwise result
10694 /// in non-SFINAE errors e.g. recursive constraints.
10695 bool OnlyInitializeNonUserDefinedConversions;
10696
10697 CheckNonDependentConversionsFlag(
10698 bool SuppressUserConversions,
10699 bool OnlyInitializeNonUserDefinedConversions)
10700 : SuppressUserConversions(SuppressUserConversions),
10701 OnlyInitializeNonUserDefinedConversions(
10702 OnlyInitializeNonUserDefinedConversions) {}
10703 };
10704
10705 /// Check that implicit conversion sequences can be formed for each argument
10706 /// whose corresponding parameter has a non-dependent type, per DR1391's
10707 /// [temp.deduct.call]p10.
10708 bool CheckNonDependentConversions(
10709 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
10710 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10711 ConversionSequenceList &Conversions,
10712 CheckNonDependentConversionsFlag UserConversionFlag,
10713 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10714 Expr::Classification ObjectClassification = {},
10715 OverloadCandidateParamOrder PO = {});
10716
10717 /// AddConversionCandidate - Add a C++ conversion function as a
10718 /// candidate in the candidate set (C++ [over.match.conv],
10719 /// C++ [over.match.copy]). From is the expression we're converting from,
10720 /// and ToType is the type that we're eventually trying to convert to
10721 /// (which may or may not be the same type as the type that the
10722 /// conversion function produces).
10723 void AddConversionCandidate(
10724 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10725 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10726 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10727 bool AllowExplicit, bool AllowResultConversion = true,
10728 bool StrictPackMatch = false);
10729
10730 /// Adds a conversion function template specialization
10731 /// candidate to the overload set, using template argument deduction
10732 /// to deduce the template arguments of the conversion function
10733 /// template from the type that we are converting to (C++
10734 /// [temp.deduct.conv]).
10735 void AddTemplateConversionCandidate(
10736 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10737 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10738 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10739 bool AllowExplicit, bool AllowResultConversion = true);
10740
10741 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10742 /// converts the given @c Object to a function pointer via the
10743 /// conversion function @c Conversion, and then attempts to call it
10744 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10745 /// the type of function that we'll eventually be calling.
10746 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10747 DeclAccessPair FoundDecl,
10748 CXXRecordDecl *ActingContext,
10749 const FunctionProtoType *Proto, Expr *Object,
10750 ArrayRef<Expr *> Args,
10751 OverloadCandidateSet &CandidateSet);
10752
10753 /// Add all of the non-member operator function declarations in the given
10754 /// function set to the overload candidate set.
10755 void AddNonMemberOperatorCandidates(
10756 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10757 OverloadCandidateSet &CandidateSet,
10758 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10759
10760 /// Add overload candidates for overloaded operators that are
10761 /// member functions.
10762 ///
10763 /// Add the overloaded operator candidates that are member functions
10764 /// for the operator Op that was used in an operator expression such
10765 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10766 /// CandidateSet will store the added overload candidates. (C++
10767 /// [over.match.oper]).
10768 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
10769 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10770 OverloadCandidateSet &CandidateSet,
10771 OverloadCandidateParamOrder PO = {});
10772
10773 /// AddBuiltinCandidate - Add a candidate for a built-in
10774 /// operator. ResultTy and ParamTys are the result and parameter types
10775 /// of the built-in candidate, respectively. Args and NumArgs are the
10776 /// arguments being passed to the candidate. IsAssignmentOperator
10777 /// should be true when this built-in candidate is an assignment
10778 /// operator. NumContextualBoolArguments is the number of arguments
10779 /// (at the beginning of the argument list) that will be contextually
10780 /// converted to bool.
10781 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10782 OverloadCandidateSet &CandidateSet,
10783 bool IsAssignmentOperator = false,
10784 unsigned NumContextualBoolArguments = 0);
10785
10786 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10787 /// operator overloads to the candidate set (C++ [over.built]), based
10788 /// on the operator @p Op and the arguments given. For example, if the
10789 /// operator is a binary '+', this routine might add "int
10790 /// operator+(int, int)" to cover integer addition.
10791 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10792 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10793 OverloadCandidateSet &CandidateSet);
10794
10795 /// Add function candidates found via argument-dependent lookup
10796 /// to the set of overloading candidates.
10797 ///
10798 /// This routine performs argument-dependent name lookup based on the
10799 /// given function name (which may also be an operator name) and adds
10800 /// all of the overload candidates found by ADL to the overload
10801 /// candidate set (C++ [basic.lookup.argdep]).
10802 void AddArgumentDependentLookupCandidates(
10803 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10804 TemplateArgumentListInfo *ExplicitTemplateArgs,
10805 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10806
10807 /// Check the enable_if expressions on the given function. Returns the first
10808 /// failing attribute, or NULL if they were all successful.
10809 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10810 ArrayRef<Expr *> Args,
10811 bool MissingImplicitThis = false);
10812
10813 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10814 /// non-ArgDependent DiagnoseIfAttrs.
10815 ///
10816 /// Argument-dependent diagnose_if attributes should be checked each time a
10817 /// function is used as a direct callee of a function call.
10818 ///
10819 /// Returns true if any errors were emitted.
10820 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10821 const Expr *ThisArg,
10822 ArrayRef<const Expr *> Args,
10823 SourceLocation Loc);
10824
10825 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10826 /// ArgDependent DiagnoseIfAttrs.
10827 ///
10828 /// Argument-independent diagnose_if attributes should be checked on every use
10829 /// of a function.
10830 ///
10831 /// Returns true if any errors were emitted.
10832 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10833 SourceLocation Loc);
10834
10835 /// Determine if \p A and \p B are equivalent internal linkage declarations
10836 /// from different modules, and thus an ambiguity error can be downgraded to
10837 /// an extension warning.
10838 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10839 const NamedDecl *B);
10840 void diagnoseEquivalentInternalLinkageDeclarations(
10841 SourceLocation Loc, const NamedDecl *D,
10842 ArrayRef<const NamedDecl *> Equiv);
10843
10844 // Emit as a 'note' the specific overload candidate
10845 void NoteOverloadCandidate(
10846 const NamedDecl *Found, const FunctionDecl *Fn,
10847 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
10848 QualType DestType = QualType(), bool TakingAddress = false);
10849
10850 // Emit as a series of 'note's all template and non-templates identified by
10851 // the expression Expr
10852 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10853 bool TakingAddress = false);
10854
10855 /// Returns whether the given function's address can be taken or not,
10856 /// optionally emitting a diagnostic if the address can't be taken.
10857 ///
10858 /// Returns false if taking the address of the function is illegal.
10859 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10860 bool Complain = false,
10861 SourceLocation Loc = SourceLocation());
10862
10863 // [PossiblyAFunctionType] --> [Return]
10864 // NonFunctionType --> NonFunctionType
10865 // R (A) --> R(A)
10866 // R (*)(A) --> R (A)
10867 // R (&)(A) --> R (A)
10868 // R (S::*)(A) --> R (A)
10869 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10870
10871 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10872 /// an overloaded function (C++ [over.over]), where @p From is an
10873 /// expression with overloaded function type and @p ToType is the type
10874 /// we're trying to resolve to. For example:
10875 ///
10876 /// @code
10877 /// int f(double);
10878 /// int f(int);
10879 ///
10880 /// int (*pfd)(double) = f; // selects f(double)
10881 /// @endcode
10882 ///
10883 /// This routine returns the resulting FunctionDecl if it could be
10884 /// resolved, and NULL otherwise. When @p Complain is true, this
10885 /// routine will emit diagnostics if there is an error.
10886 FunctionDecl *
10887 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10888 bool Complain, DeclAccessPair &Found,
10889 bool *pHadMultipleCandidates = nullptr);
10890
10891 /// Given an expression that refers to an overloaded function, try to
10892 /// resolve that function to a single function that can have its address
10893 /// taken. This will modify `Pair` iff it returns non-null.
10894 ///
10895 /// This routine can only succeed if from all of the candidates in the
10896 /// overload set for SrcExpr that can have their addresses taken, there is one
10897 /// candidate that is more constrained than the rest.
10898 FunctionDecl *
10899 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10900
10901 /// Given an overloaded function, tries to turn it into a non-overloaded
10902 /// function reference using resolveAddressOfSingleOverloadCandidate. This
10903 /// will perform access checks, diagnose the use of the resultant decl, and,
10904 /// if requested, potentially perform a function-to-pointer decay.
10905 ///
10906 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10907 /// Otherwise, returns true. This may emit diagnostics and return true.
10908 bool resolveAndFixAddressOfSingleOverloadCandidate(
10909 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10910
10911 /// Given an expression that refers to an overloaded function, try to
10912 /// resolve that overloaded function expression down to a single function.
10913 ///
10914 /// This routine can only resolve template-ids that refer to a single function
10915 /// template, where that template-id refers to a single template whose
10916 /// template arguments are either provided by the template-id or have
10917 /// defaults, as described in C++0x [temp.arg.explicit]p3.
10918 ///
10919 /// If no template-ids are found, no diagnostics are emitted and NULL is
10920 /// returned.
10921 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(
10922 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10923 TemplateSpecCandidateSet *FailedTSC = nullptr,
10924 bool ForTypeDeduction = false);
10925
10926 // Resolve and fix an overloaded expression that can be resolved
10927 // because it identifies a single function template specialization.
10928 //
10929 // Last three arguments should only be supplied if Complain = true
10930 //
10931 // Return true if it was logically possible to so resolve the
10932 // expression, regardless of whether or not it succeeded. Always
10933 // returns true if 'complain' is set.
10934 bool ResolveAndFixSingleFunctionTemplateSpecialization(
10935 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10936 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10937 QualType DestTypeForComplaining = QualType(),
10938 unsigned DiagIDForComplaining = 0);
10939
10940 /// Add the overload candidates named by callee and/or found by argument
10941 /// dependent lookup to the given overload set.
10942 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10943 ArrayRef<Expr *> Args,
10944 OverloadCandidateSet &CandidateSet,
10945 bool PartialOverloading = false);
10946
10947 /// Add the call candidates from the given set of lookup results to the given
10948 /// overload set. Non-function lookup results are ignored.
10949 void AddOverloadedCallCandidates(
10950 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
10951 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
10952
10953 // An enum used to represent the different possible results of building a
10954 // range-based for loop.
10955 enum ForRangeStatus {
10956 FRS_Success,
10957 FRS_NoViableFunction,
10958 FRS_DiagnosticIssued
10959 };
10960
10961 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
10962 /// given LookupResult is non-empty, it is assumed to describe a member which
10963 /// will be invoked. Otherwise, the function will be found via argument
10964 /// dependent lookup.
10965 /// CallExpr is set to a valid expression and FRS_Success returned on success,
10966 /// otherwise CallExpr is set to ExprError() and some non-success value
10967 /// is returned.
10968 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
10969 SourceLocation RangeLoc,
10970 const DeclarationNameInfo &NameInfo,
10971 LookupResult &MemberLookup,
10972 OverloadCandidateSet *CandidateSet,
10973 Expr *Range, ExprResult *CallExpr);
10974
10975 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10976 /// (which eventually refers to the declaration Func) and the call
10977 /// arguments Args/NumArgs, attempt to resolve the function call down
10978 /// to a specific function. If overload resolution succeeds, returns
10979 /// the call expression produced by overload resolution.
10980 /// Otherwise, emits diagnostics and returns ExprError.
10981 ExprResult BuildOverloadedCallExpr(
10982 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
10983 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
10984 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
10985
10986 /// Constructs and populates an OverloadedCandidateSet from
10987 /// the given function.
10988 /// \returns true when an the ExprResult output parameter has been set.
10989 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
10990 MultiExprArg Args, SourceLocation RParenLoc,
10991 OverloadCandidateSet *CandidateSet,
10992 ExprResult *Result);
10993
10994 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
10995 NestedNameSpecifierLoc NNSLoc,
10996 DeclarationNameInfo DNI,
10997 const UnresolvedSetImpl &Fns,
10998 bool PerformADL = true);
10999
11000 /// Perform lookup for an overloaded unary operator.
11001 void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet,
11002 OverloadedOperatorKind Op,
11003 const UnresolvedSetImpl &Fns,
11004 ArrayRef<Expr *> Args, bool RequiresADL = true);
11005
11006 /// Create a unary operation that may resolve to an overloaded
11007 /// operator.
11008 ///
11009 /// \param OpLoc The location of the operator itself (e.g., '*').
11010 ///
11011 /// \param Opc The UnaryOperatorKind that describes this operator.
11012 ///
11013 /// \param Fns The set of non-member functions that will be
11014 /// considered by overload resolution. The caller needs to build this
11015 /// set based on the context using, e.g.,
11016 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11017 /// set should not contain any member functions; those will be added
11018 /// by CreateOverloadedUnaryOp().
11019 ///
11020 /// \param Input The input argument.
11021 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
11022 UnaryOperatorKind Opc,
11023 const UnresolvedSetImpl &Fns, Expr *input,
11024 bool RequiresADL = true);
11025
11026 /// Perform lookup for an overloaded binary operator.
11027 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
11028 OverloadedOperatorKind Op,
11029 const UnresolvedSetImpl &Fns,
11030 ArrayRef<Expr *> Args, bool RequiresADL = true);
11031
11032 /// Create a binary operation that may resolve to an overloaded
11033 /// operator.
11034 ///
11035 /// \param OpLoc The location of the operator itself (e.g., '+').
11036 ///
11037 /// \param Opc The BinaryOperatorKind that describes this operator.
11038 ///
11039 /// \param Fns The set of non-member functions that will be
11040 /// considered by overload resolution. The caller needs to build this
11041 /// set based on the context using, e.g.,
11042 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11043 /// set should not contain any member functions; those will be added
11044 /// by CreateOverloadedBinOp().
11045 ///
11046 /// \param LHS Left-hand argument.
11047 /// \param RHS Right-hand argument.
11048 /// \param PerformADL Whether to consider operator candidates found by ADL.
11049 /// \param AllowRewrittenCandidates Whether to consider candidates found by
11050 /// C++20 operator rewrites.
11051 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
11052 /// the function in question. Such a function is never a candidate in
11053 /// our overload resolution. This also enables synthesizing a three-way
11054 /// comparison from < and == as described in C++20 [class.spaceship]p1.
11055 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
11056 const UnresolvedSetImpl &Fns, Expr *LHS,
11057 Expr *RHS, bool RequiresADL = true,
11058 bool AllowRewrittenCandidates = true,
11059 FunctionDecl *DefaultedFn = nullptr);
11060 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
11061 const UnresolvedSetImpl &Fns,
11062 Expr *LHS, Expr *RHS,
11063 FunctionDecl *DefaultedFn);
11064
11065 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11066 SourceLocation RLoc, Expr *Base,
11067 MultiExprArg Args);
11068
11069 /// BuildCallToMemberFunction - Build a call to a member
11070 /// function. MemExpr is the expression that refers to the member
11071 /// function (and includes the object parameter), Args/NumArgs are the
11072 /// arguments to the function call (not including the object
11073 /// parameter). The caller needs to validate that the member
11074 /// expression refers to a non-static member function or an overloaded
11075 /// member function.
11076 ExprResult BuildCallToMemberFunction(
11077 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
11078 SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
11079 bool IsExecConfig = false, bool AllowRecovery = false);
11080
11081 /// BuildCallToObjectOfClassType - Build a call to an object of class
11082 /// type (C++ [over.call.object]), which can end up invoking an
11083 /// overloaded function call operator (@c operator()) or performing a
11084 /// user-defined conversion on the object argument.
11085 ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object,
11086 SourceLocation LParenLoc,
11087 MultiExprArg Args,
11088 SourceLocation RParenLoc);
11089
11090 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11091 /// (if one exists), where @c Base is an expression of class type and
11092 /// @c Member is the name of the member we're trying to find.
11093 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
11094 SourceLocation OpLoc,
11095 bool *NoArrowOperatorFound = nullptr);
11096
11097 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
11098 CXXConversionDecl *Method,
11099 bool HadMultipleCandidates);
11100
11101 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
11102 /// to a literal operator described by the provided lookup results.
11103 ExprResult BuildLiteralOperatorCall(
11104 LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args,
11105 SourceLocation LitEndLoc,
11106 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
11107
11108 /// FixOverloadedFunctionReference - E is an expression that refers to
11109 /// a C++ overloaded function (possibly with some parentheses and
11110 /// perhaps a '&' around it). We have resolved the overloaded function
11111 /// to the function declaration Fn, so patch up the expression E to
11112 /// refer (possibly indirectly) to Fn. Returns the new expr.
11113 ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl,
11114 FunctionDecl *Fn);
11115 ExprResult FixOverloadedFunctionReference(ExprResult,
11116 DeclAccessPair FoundDecl,
11117 FunctionDecl *Fn);
11118
11119 /// - Returns a selector which best matches given argument list or
11120 /// nullptr if none could be found
11121 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
11122 bool IsInstance,
11123 SmallVectorImpl<ObjCMethodDecl *> &Methods);
11124
11125 ///@}
11126
11127 //
11128 //
11129 // -------------------------------------------------------------------------
11130 //
11131 //
11132
11133 /// \name Statements
11134 /// Implementations are in SemaStmt.cpp
11135 ///@{
11136
11137public:
11138 /// Stack of active SEH __finally scopes. Can be empty.
11139 SmallVector<Scope *, 2> CurrentSEHFinally;
11140
11141 /// Stack of '_Defer' statements that are currently being parsed, as well
11142 /// as the locations of their '_Defer' keywords. Can be empty.
11143 SmallVector<std::pair<Scope *, SourceLocation>, 2> CurrentDefer;
11144
11145 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
11146 StmtResult ActOnExprStmtError();
11147
11148 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
11149 bool HasLeadingEmptyMacro = false);
11150
11151 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc,
11152 SourceLocation EndLoc);
11153 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
11154
11155 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
11156 /// whose result is unused, warn.
11157 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
11158
11159 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
11160 void ActOnAfterCompoundStatementLeadingPragmas();
11161 void ActOnFinishOfCompoundStmt();
11162 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
11163 ArrayRef<Stmt *> Elts, bool isStmtExpr);
11164
11165 sema::CompoundScopeInfo &getCurCompoundScope() const;
11166
11167 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
11168 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
11169 SourceLocation DotDotDotLoc, ExprResult RHS,
11170 SourceLocation ColonLoc);
11171
11172 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
11173 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
11174
11175 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
11176 SourceLocation ColonLoc, Stmt *SubStmt,
11177 Scope *CurScope);
11178 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
11179 SourceLocation ColonLoc, Stmt *SubStmt);
11180
11181 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
11182 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
11183 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
11184 Stmt *SubStmt);
11185
11186 /// Check whether the given statement can have musttail applied to it,
11187 /// issuing a diagnostic and returning false if not. In the success case,
11188 /// the statement is rewritten to remove implicit nodes from the return
11189 /// value.
11190 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11191
11192 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11193 SourceLocation LParenLoc, Stmt *InitStmt,
11194 ConditionResult Cond, SourceLocation RParenLoc,
11195 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11196 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11197 SourceLocation LParenLoc, Stmt *InitStmt,
11198 ConditionResult Cond, SourceLocation RParenLoc,
11199 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11200
11201 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11202
11203 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
11204 SourceLocation LParenLoc, Stmt *InitStmt,
11205 ConditionResult Cond,
11206 SourceLocation RParenLoc);
11207 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
11208 Stmt *Body);
11209
11210 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11211 /// integer not in the range of enum values.
11212 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11213 Expr *SrcExpr);
11214
11215 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
11216 ConditionResult Cond, SourceLocation RParenLoc,
11217 Stmt *Body);
11218 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
11219 SourceLocation WhileLoc, SourceLocation CondLParen,
11220 Expr *Cond, SourceLocation CondRParen);
11221
11222 StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
11223 Stmt *First, ConditionResult Second,
11224 FullExprArg Third, SourceLocation RParenLoc,
11225 Stmt *Body);
11226
11227 /// In an Objective C collection iteration statement:
11228 /// for (x in y)
11229 /// x can be an arbitrary l-value expression. Bind it up as a
11230 /// full-expression.
11231 StmtResult ActOnForEachLValueExpr(Expr *E);
11232
11233 enum BuildForRangeKind {
11234 /// Initial building of a for-range statement.
11235 BFRK_Build,
11236 /// Instantiation or recovery rebuild of a for-range statement. Don't
11237 /// attempt any typo-correction.
11238 BFRK_Rebuild,
11239 /// Determining whether a for-range statement could be built. Avoid any
11240 /// unnecessary or irreversible actions.
11241 BFRK_Check
11242 };
11243
11244 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
11245 ///
11246 /// C++11 [stmt.ranged]:
11247 /// A range-based for statement is equivalent to
11248 ///
11249 /// {
11250 /// auto && __range = range-init;
11251 /// for ( auto __begin = begin-expr,
11252 /// __end = end-expr;
11253 /// __begin != __end;
11254 /// ++__begin ) {
11255 /// for-range-declaration = *__begin;
11256 /// statement
11257 /// }
11258 /// }
11259 ///
11260 /// The body of the loop is not available yet, since it cannot be analysed
11261 /// until we have determined the type of the for-range-declaration.
11262 StmtResult ActOnCXXForRangeStmt(
11263 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11264 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11265 SourceLocation RParenLoc, BuildForRangeKind Kind,
11266 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11267
11268 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11269 StmtResult BuildCXXForRangeStmt(
11270 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11271 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11272 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11273 BuildForRangeKind Kind,
11274 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11275
11276 /// Set the type of a for-range declaration whose for-range or expansion
11277 /// initialiser is dependent.
11278 void ActOnDependentForRangeInitializer(VarDecl *LoopVar,
11279 BuildForRangeKind BFRK);
11280
11281 /// Holds the 'begin' and 'end' variables of a range-based for loop or
11282 /// expansion statement; begin-expr and end-expr are also provided; the
11283 /// latter are used in some diagnostics.
11284 struct ForRangeBeginEndInfo {
11285 VarDecl *BeginVar = nullptr;
11286 VarDecl *EndVar = nullptr;
11287 Expr *BeginExpr = nullptr;
11288 Expr *EndExpr = nullptr;
11289 bool isValid() const { return BeginVar != nullptr && EndVar != nullptr; }
11290 };
11291
11292 /// Determine begin-expr and end-expr and build variable declarations for
11293 /// them as per [stmt.ranged].
11294 ForRangeBeginEndInfo BuildCXXForRangeBeginEndVars(
11295 Scope *S, VarDecl *RangeVar, SourceLocation ColonLoc,
11296 SourceLocation CoawaitLoc,
11297 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps,
11298 BuildForRangeKind Kind, bool IsConstexpr,
11299 StmtResult *RebuildResult = nullptr,
11300 llvm::function_ref<StmtResult()> RebuildWithDereference = {},
11301 IdentifierInfo *BeginName = nullptr, IdentifierInfo *EndName = nullptr);
11302
11303 /// Helper used by the expansion statements and for-range code to build
11304 /// a variable declaration for e.g. 'begin' and 'end'.
11305 VarDecl *BuildForRangeVarDecl(SourceLocation Loc, QualType Type,
11306 IdentifierInfo *Name, bool IsConstexpr);
11307
11308 /// Build the range variable of a range-based for loop or iterating
11309 /// expansion statement and return its DeclStmt.
11310 StmtResult BuildCXXForRangeRangeVar(Scope *S, Expr *Range, QualType Type,
11311 bool IsConstexpr = false);
11312
11313 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11314 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11315 /// body cannot be performed until after the type of the range variable is
11316 /// determined.
11317 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11318
11319 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11320 LabelDecl *TheDecl);
11321 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11322 SourceLocation StarLoc, Expr *DestExp);
11323 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
11324 LabelDecl *Label, SourceLocation LabelLoc);
11325 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
11326 LabelDecl *Label, SourceLocation LabelLoc);
11327
11328 void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope);
11329 void ActOnDeferStmtError(Scope *CurScope);
11330 StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope);
11331
11332 struct NamedReturnInfo {
11333 const VarDecl *Candidate;
11334
11335 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
11336 Status S;
11337
11338 bool isMoveEligible() const { return S != None; };
11339 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
11340 };
11341 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
11342
11343 /// Determine whether the given expression might be move-eligible or
11344 /// copy-elidable in either a (co_)return statement or throw expression,
11345 /// without considering function return type, if applicable.
11346 ///
11347 /// \param E The expression being returned from the function or block,
11348 /// being thrown, or being co_returned from a coroutine. This expression
11349 /// might be modified by the implementation.
11350 ///
11351 /// \param Mode Overrides detection of current language mode
11352 /// and uses the rules for C++23.
11353 ///
11354 /// \returns An aggregate which contains the Candidate and isMoveEligible
11355 /// and isCopyElidable methods. If Candidate is non-null, it means
11356 /// isMoveEligible() would be true under the most permissive language
11357 /// standard.
11358 NamedReturnInfo getNamedReturnInfo(
11359 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
11360
11361 /// Determine whether the given NRVO candidate variable is move-eligible or
11362 /// copy-elidable, without considering function return type.
11363 ///
11364 /// \param VD The NRVO candidate variable.
11365 ///
11366 /// \returns An aggregate which contains the Candidate and isMoveEligible
11367 /// and isCopyElidable methods. If Candidate is non-null, it means
11368 /// isMoveEligible() would be true under the most permissive language
11369 /// standard.
11370 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11371
11372 /// Updates given NamedReturnInfo's move-eligible and
11373 /// copy-elidable statuses, considering the function
11374 /// return type criteria as applicable to return statements.
11375 ///
11376 /// \param Info The NamedReturnInfo object to update.
11377 ///
11378 /// \param ReturnType This is the return type of the function.
11379 /// \returns The copy elision candidate, in case the initial return expression
11380 /// was copy elidable, or nullptr otherwise.
11381 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11382 QualType ReturnType);
11383
11384 /// Perform the initialization of a potentially-movable value, which
11385 /// is the result of return value.
11386 ///
11387 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11388 /// treat returned lvalues as rvalues in certain cases (to prefer move
11389 /// construction), then falls back to treating them as lvalues if that failed.
11390 ExprResult
11391 PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
11392 const NamedReturnInfo &NRInfo, Expr *Value,
11393 bool SupressSimplerImplicitMoves = false);
11394
11395 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
11396
11397 /// Deduce the return type for a function from a returned expression, per
11398 /// C++1y [dcl.spec.auto]p6.
11399 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
11400 SourceLocation ReturnLoc, Expr *RetExpr,
11401 const AutoType *AT);
11402
11403 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11404 Scope *CurScope);
11405 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11406 bool AllowRecovery = false);
11407
11408 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11409 /// for capturing scopes.
11410 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11411 NamedReturnInfo &NRInfo,
11412 bool SupressSimplerImplicitMoves);
11413
11414 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11415 /// and creates a proper catch handler from them.
11416 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
11417 Stmt *HandlerBlock);
11418
11419 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11420 /// handlers and creates a try statement from them.
11421 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
11422 ArrayRef<Stmt *> Handlers);
11423
11424 void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11425
11426 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11427 SourceLocation TryLoc, Stmt *TryBlock,
11428 Stmt *Handler);
11429 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
11430 Stmt *Block);
11431 void ActOnStartSEHFinallyBlock();
11432 void ActOnAbortSEHFinallyBlock();
11433 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
11434 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
11435
11436 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
11437 bool IsIfExists,
11438 NestedNameSpecifierLoc QualifierLoc,
11439 DeclarationNameInfo NameInfo,
11440 Stmt *Nested);
11441 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
11442 bool IsIfExists, CXXScopeSpec &SS,
11443 UnqualifiedId &Name, Stmt *Nested);
11444
11445 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11446 CapturedRegionKind Kind, unsigned NumParams);
11447 typedef std::pair<StringRef, QualType> CapturedParamNameType;
11448 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11449 CapturedRegionKind Kind,
11450 ArrayRef<CapturedParamNameType> Params,
11451 unsigned OpenMPCaptureLevel = 0);
11452 StmtResult ActOnCapturedRegionEnd(Stmt *S);
11453 void ActOnCapturedRegionError();
11454 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
11455 SourceLocation Loc,
11456 unsigned NumParams);
11457
11458 void ApplyForRangeOrExpansionStatementLifetimeExtension(
11459 VarDecl *RangeVar, ArrayRef<MaterializeTemporaryExpr *> Temporaries);
11460
11461private:
11462 /// Check whether the given statement can have musttail applied to it,
11463 /// issuing a diagnostic and returning false if not.
11464 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11465
11466 ///@}
11467
11468 //
11469 //
11470 // -------------------------------------------------------------------------
11471 //
11472 //
11473
11474 /// \name `inline asm` Statement
11475 /// Implementations are in SemaStmtAsm.cpp
11476 ///@{
11477
11478public:
11479 ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel);
11480 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11481 bool IsVolatile, unsigned NumOutputs,
11482 unsigned NumInputs, IdentifierInfo **Names,
11483 MultiExprArg Constraints, MultiExprArg Exprs,
11484 Expr *AsmString, MultiExprArg Clobbers,
11485 unsigned NumLabels, SourceLocation RParenLoc);
11486
11487 void FillInlineAsmIdentifierInfo(Expr *Res,
11488 llvm::InlineAsmIdentifierInfo &Info);
11489 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
11490 SourceLocation TemplateKWLoc,
11491 UnqualifiedId &Id,
11492 bool IsUnevaluatedContext);
11493 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11494 SourceLocation AsmLoc);
11495 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
11496 SourceLocation AsmLoc);
11497 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
11498 ArrayRef<Token> AsmToks, StringRef AsmString,
11499 unsigned NumOutputs, unsigned NumInputs,
11500 ArrayRef<StringRef> Constraints,
11501 ArrayRef<StringRef> Clobbers,
11502 ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11503 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11504 SourceLocation Location, bool AlwaysCreate);
11505
11506 ///@}
11507
11508 //
11509 //
11510 // -------------------------------------------------------------------------
11511 //
11512 //
11513
11514 /// \name Statement Attribute Handling
11515 /// Implementations are in SemaStmtAttr.cpp
11516 ///@{
11517
11518public:
11519 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11520 const AttributeCommonInfo &A);
11521 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11522 const AttributeCommonInfo &A);
11523
11524 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11525 bool CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs);
11526
11527 /// Process the attributes before creating an attributed statement. Returns
11528 /// the semantic attributes that have been processed.
11529 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11530 SmallVectorImpl<const Attr *> &OutAttrs);
11531
11532 ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A,
11533 SourceRange Range);
11534 ExprResult BuildCXXAssumeExpr(Expr *Assumption,
11535 const IdentifierInfo *AttrName,
11536 SourceRange Range);
11537
11538 ///@}
11539
11540 //
11541 //
11542 // -------------------------------------------------------------------------
11543 //
11544 //
11545
11546 /// \name C++ Templates
11547 /// Implementations are in SemaTemplate.cpp
11548 ///@{
11549
11550public:
11551 // Saves the current floating-point pragma stack and clear it in this Sema.
11552 class FpPragmaStackSaveRAII {
11553 public:
11554 FpPragmaStackSaveRAII(Sema &S)
11555 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11556 S.FpPragmaStack.Stack.clear();
11557 }
11558 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11559 FpPragmaStackSaveRAII(const FpPragmaStackSaveRAII &) = delete;
11560 FpPragmaStackSaveRAII &operator=(const FpPragmaStackSaveRAII &) = delete;
11561
11562 private:
11563 Sema &S;
11564 PragmaStack<FPOptionsOverride> SavedStack;
11565 };
11566
11567 void resetFPOptions(FPOptions FPO) {
11568 CurFPFeatures = FPO;
11569 FpPragmaStack.CurrentValue = FPO.getChangesFrom(Base: FPOptions(LangOpts));
11570 }
11571
11572 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
11573 return llvm::ArrayRef(InventedParameterInfos.begin() +
11574 InventedParameterInfosStart,
11575 InventedParameterInfos.end());
11576 }
11577
11578 ArrayRef<sema::FunctionScopeInfo *> getFunctionScopes() const {
11579 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
11580 FunctionScopes.end());
11581 }
11582
11583 typedef llvm::MapVector<const FunctionDecl *,
11584 std::unique_ptr<LateParsedTemplate>>
11585 LateParsedTemplateMapT;
11586 LateParsedTemplateMapT LateParsedTemplateMap;
11587
11588 /// Determine the number of levels of enclosing template parameters. This is
11589 /// only usable while parsing. Note that this does not include dependent
11590 /// contexts in which no template parameters have yet been declared, such as
11591 /// in a terse function template or generic lambda before the first 'auto' is
11592 /// encountered.
11593 unsigned getTemplateDepth(Scope *S) const;
11594
11595 void FilterAcceptableTemplateNames(LookupResult &R,
11596 bool AllowFunctionTemplates = true,
11597 bool AllowDependent = true);
11598 bool hasAnyAcceptableTemplateNames(LookupResult &R,
11599 bool AllowFunctionTemplates = true,
11600 bool AllowDependent = true,
11601 bool AllowNonTemplateFunctions = false);
11602 /// Try to interpret the lookup result D as a template-name.
11603 ///
11604 /// \param D A declaration found by name lookup.
11605 /// \param AllowFunctionTemplates Whether function templates should be
11606 /// considered valid results.
11607 /// \param AllowDependent Whether unresolved using declarations (that might
11608 /// name templates) should be considered valid results.
11609 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
11610 bool AllowFunctionTemplates = true,
11611 bool AllowDependent = true);
11612
11613 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
11614 /// Whether and why a template name is required in this lookup.
11615 class RequiredTemplateKind {
11616 public:
11617 /// Template name is required if TemplateKWLoc is valid.
11618 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
11619 : TemplateKW(TemplateKWLoc) {}
11620 /// Template name is unconditionally required.
11621 RequiredTemplateKind(TemplateNameIsRequiredTag) {}
11622
11623 SourceLocation getTemplateKeywordLoc() const {
11624 return TemplateKW.value_or(u: SourceLocation());
11625 }
11626 bool hasTemplateKeyword() const {
11627 return getTemplateKeywordLoc().isValid();
11628 }
11629 bool isRequired() const { return TemplateKW != SourceLocation(); }
11630 explicit operator bool() const { return isRequired(); }
11631
11632 private:
11633 std::optional<SourceLocation> TemplateKW;
11634 };
11635
11636 enum class AssumedTemplateKind {
11637 /// This is not assumed to be a template name.
11638 None,
11639 /// This is assumed to be a template name because lookup found nothing.
11640 FoundNothing,
11641 /// This is assumed to be a template name because lookup found one or more
11642 /// functions (but no function templates).
11643 FoundFunctions,
11644 };
11645
11646 bool
11647 LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
11648 QualType ObjectType, bool EnteringContext,
11649 RequiredTemplateKind RequiredTemplate = SourceLocation(),
11650 AssumedTemplateKind *ATK = nullptr,
11651 bool AllowTypoCorrection = true);
11652
11653 TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS,
11654 bool hasTemplateKeyword,
11655 const UnqualifiedId &Name,
11656 ParsedType ObjectType, bool EnteringContext,
11657 TemplateTy &Template,
11658 bool &MemberOfUnknownSpecialization,
11659 bool AllowTypoCorrection = true);
11660
11661 /// Try to resolve an undeclared template name as a type template.
11662 ///
11663 /// Sets II to the identifier corresponding to the template name, and updates
11664 /// Name to a corresponding (typo-corrected) type template name and TNK to
11665 /// the corresponding kind, if possible.
11666 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
11667 TemplateNameKind &TNK,
11668 SourceLocation NameLoc,
11669 IdentifierInfo *&II);
11670
11671 /// Determine whether a particular identifier might be the name in a C++1z
11672 /// deduction-guide declaration.
11673 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11674 SourceLocation NameLoc, CXXScopeSpec &SS,
11675 ParsedTemplateTy *Template = nullptr);
11676
11677 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
11678 SourceLocation IILoc, Scope *S,
11679 const CXXScopeSpec *SS,
11680 TemplateTy &SuggestedTemplate,
11681 TemplateNameKind &SuggestedKind);
11682
11683 /// Determine whether we would be unable to instantiate this template (because
11684 /// it either has no definition, or is in the process of being instantiated).
11685 bool DiagnoseUninstantiableTemplate(
11686 SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11687 bool InstantiatedFromMember, const NamedDecl *Pattern,
11688 const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11689 bool Complain = true, bool *Unreachable = nullptr);
11690
11691 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11692 /// that the template parameter 'PrevDecl' is being shadowed by a new
11693 /// declaration at location Loc. Returns true to indicate that this is
11694 /// an error, and false otherwise.
11695 ///
11696 /// \param Loc The location of the declaration that shadows a template
11697 /// parameter.
11698 ///
11699 /// \param PrevDecl The template parameter that the declaration shadows.
11700 ///
11701 /// \param SupportedForCompatibility Whether to issue the diagnostic as
11702 /// a warning for compatibility with older versions of clang.
11703 /// Ignored when MSVC compatibility is enabled.
11704 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
11705 bool SupportedForCompatibility = false);
11706
11707 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11708 /// the parameter D to reference the templated declaration and return a
11709 /// pointer to the template declaration. Otherwise, do nothing to D and return
11710 /// null.
11711 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
11712
11713 /// ActOnTypeParameter - Called when a C++ template type parameter
11714 /// (e.g., "typename T") has been parsed. Typename specifies whether
11715 /// the keyword "typename" was used to declare the type parameter
11716 /// (otherwise, "class" was used), and KeyLoc is the location of the
11717 /// "class" or "typename" keyword. ParamName is the name of the
11718 /// parameter (NULL indicates an unnamed template parameter) and
11719 /// ParamNameLoc is the location of the parameter name (if any).
11720 /// If the type parameter has a default argument, it will be added
11721 /// later via ActOnTypeParameterDefault.
11722 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
11723 SourceLocation EllipsisLoc,
11724 SourceLocation KeyLoc,
11725 IdentifierInfo *ParamName,
11726 SourceLocation ParamNameLoc, unsigned Depth,
11727 unsigned Position, SourceLocation EqualLoc,
11728 ParsedType DefaultArg, bool HasTypeConstraint);
11729
11730 bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint);
11731
11732 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11733 TemplateIdAnnotation *TypeConstraint,
11734 TemplateTypeParmDecl *ConstrainedParameter,
11735 SourceLocation EllipsisLoc);
11736 bool BuildTypeConstraint(const CXXScopeSpec &SS,
11737 TemplateIdAnnotation *TypeConstraint,
11738 TemplateTypeParmDecl *ConstrainedParameter,
11739 SourceLocation EllipsisLoc,
11740 bool AllowUnexpandedPack);
11741
11742 /// Attach a type-constraint to a template parameter.
11743 /// \returns true if an error occurred. This can happen if the
11744 /// immediately-declared constraint could not be formed (e.g. incorrect number
11745 /// of arguments for the named concept).
11746 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
11747 DeclarationNameInfo NameInfo,
11748 TemplateName NamedConcept, NamedDecl *FoundDecl,
11749 const TemplateArgumentListInfo *TemplateArgs,
11750 TemplateTypeParmDecl *ConstrainedParameter,
11751 SourceLocation EllipsisLoc);
11752
11753 bool AttachTypeConstraint(AutoTypeLoc TL,
11754 NonTypeTemplateParmDecl *NewConstrainedParm,
11755 NonTypeTemplateParmDecl *OrigConstrainedParm,
11756 SourceLocation EllipsisLoc);
11757
11758 /// Require the given type to be a structural type, and diagnose if it is not.
11759 ///
11760 /// \return \c true if an error was produced.
11761 bool RequireStructuralType(QualType T, SourceLocation Loc);
11762
11763 /// Check that the type of a non-type template parameter is
11764 /// well-formed.
11765 ///
11766 /// \returns the (possibly-promoted) parameter type if valid;
11767 /// otherwise, produces a diagnostic and returns a NULL type.
11768 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
11769 SourceLocation Loc);
11770 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
11771
11772 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
11773 unsigned Depth, unsigned Position,
11774 SourceLocation EqualLoc,
11775 Expr *DefaultArg);
11776
11777 /// ActOnTemplateTemplateParameter - Called when a C++ template template
11778 /// parameter (e.g. T in template <template \<typename> class T> class array)
11779 /// has been parsed. S is the current scope.
11780 NamedDecl *ActOnTemplateTemplateParameter(
11781 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind,
11782 bool TypenameKeyword, TemplateParameterList *Params,
11783 SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11784 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11785 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11786
11787 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11788 /// constrained by RequiresClause, that contains the template parameters in
11789 /// Params.
11790 TemplateParameterList *ActOnTemplateParameterList(
11791 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11792 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11793 SourceLocation RAngleLoc, Expr *RequiresClause);
11794
11795 /// The context in which we are checking a template parameter list.
11796 enum TemplateParamListContext {
11797 // For this context, Class, Variable, TypeAlias, and non-pack Template
11798 // Template Parameters are treated uniformly.
11799 TPC_Other,
11800
11801 TPC_FunctionTemplate,
11802 TPC_ClassTemplateMember,
11803 TPC_FriendClassTemplate,
11804 TPC_FriendFunctionTemplate,
11805 TPC_FriendFunctionTemplateDefinition,
11806 TPC_TemplateTemplateParameterPack,
11807 };
11808
11809 /// Checks the validity of a template parameter list, possibly
11810 /// considering the template parameter list from a previous
11811 /// declaration.
11812 ///
11813 /// If an "old" template parameter list is provided, it must be
11814 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11815 /// template parameter list.
11816 ///
11817 /// \param NewParams Template parameter list for a new template
11818 /// declaration. This template parameter list will be updated with any
11819 /// default arguments that are carried through from the previous
11820 /// template parameter list.
11821 ///
11822 /// \param OldParams If provided, template parameter list from a
11823 /// previous declaration of the same template. Default template
11824 /// arguments will be merged from the old template parameter list to
11825 /// the new template parameter list.
11826 ///
11827 /// \param TPC Describes the context in which we are checking the given
11828 /// template parameter list.
11829 ///
11830 /// \param SkipBody If we might have already made a prior merged definition
11831 /// of this template visible, the corresponding body-skipping information.
11832 /// Default argument redefinition is not an error when skipping such a body,
11833 /// because (under the ODR) we can assume the default arguments are the same
11834 /// as the prior merged definition.
11835 ///
11836 /// \returns true if an error occurred, false otherwise.
11837 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
11838 TemplateParameterList *OldParams,
11839 TemplateParamListContext TPC,
11840 SkipBodyInfo *SkipBody = nullptr);
11841
11842 /// Match the given template parameter lists to the given scope
11843 /// specifier, returning the template parameter list that applies to the
11844 /// name.
11845 ///
11846 /// \param DeclStartLoc the start of the declaration that has a scope
11847 /// specifier or a template parameter list.
11848 ///
11849 /// \param DeclLoc The location of the declaration itself.
11850 ///
11851 /// \param SS the scope specifier that will be matched to the given template
11852 /// parameter lists. This scope specifier precedes a qualified name that is
11853 /// being declared.
11854 ///
11855 /// \param TemplateId The template-id following the scope specifier, if there
11856 /// is one. Used to check for a missing 'template<>'.
11857 ///
11858 /// \param ParamLists the template parameter lists, from the outermost to the
11859 /// innermost template parameter lists.
11860 ///
11861 /// \param IsFriend Whether to apply the slightly different rules for
11862 /// matching template parameters to scope specifiers in friend
11863 /// declarations.
11864 ///
11865 /// \param IsMemberSpecialization will be set true if the scope specifier
11866 /// denotes a fully-specialized type, and therefore this is a declaration of
11867 /// a member specialization.
11868 ///
11869 /// \returns the template parameter list, if any, that corresponds to the
11870 /// name that is preceded by the scope specifier @p SS. This template
11871 /// parameter list may have template parameters (if we're declaring a
11872 /// template) or may have no template parameters (if we're declaring a
11873 /// template specialization), or may be NULL (if what we're declaring isn't
11874 /// itself a template).
11875 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
11876 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11877 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11878 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11879 bool &IsMemberSpecialization, bool &Invalid,
11880 bool SuppressDiagnostic = false);
11881
11882 /// Returns the template parameter list with all default template argument
11883 /// information.
11884 TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD);
11885
11886 DeclResult CheckClassTemplate(
11887 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11888 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11889 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11890 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11891 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11892 TemplateParameterList **OuterTemplateParamLists,
11893 bool IsMemberSpecialization, SkipBodyInfo *SkipBody = nullptr);
11894
11895 /// Translates template arguments as provided by the parser
11896 /// into template arguments used by semantic analysis.
11897 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
11898 TemplateArgumentListInfo &Out);
11899
11900 /// Convert a parsed type into a parsed template argument. This is mostly
11901 /// trivial, except that we may have parsed a C++17 deduced class template
11902 /// specialization type, in which case we should form a template template
11903 /// argument instead of a type template argument.
11904 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
11905
11906 void NoteAllFoundTemplates(TemplateName Name);
11907
11908 QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
11909 TemplateName Template,
11910 SourceLocation TemplateLoc,
11911 TemplateArgumentListInfo &TemplateArgs,
11912 Scope *Scope, bool ForNestedNameSpecifier);
11913
11914 TypeResult
11915 ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
11916 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
11917 SourceLocation TemplateKWLoc, TemplateTy Template,
11918 const IdentifierInfo *TemplateII,
11919 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11920 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11921 bool IsCtorOrDtorName = false, bool IsClassName = false,
11922 ImplicitTypenameContext AllowImplicitTypename =
11923 ImplicitTypenameContext::No);
11924
11925 /// Parsed an elaborated-type-specifier that refers to a template-id,
11926 /// such as \c class T::template apply<U>.
11927 TypeResult ActOnTagTemplateIdType(
11928 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11929 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11930 SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11931 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11932
11933 DeclResult ActOnVarTemplateSpecialization(
11934 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
11935 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11936 StorageClass SC, bool IsPartialSpecialization);
11937
11938 /// Get the specialization of the given variable template corresponding to
11939 /// the specified argument list, or a null-but-valid result if the arguments
11940 /// are dependent.
11941 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
11942 SourceLocation TemplateLoc,
11943 SourceLocation TemplateNameLoc,
11944 const TemplateArgumentListInfo &TemplateArgs,
11945 bool SetWrittenArgs);
11946
11947 /// Form a reference to the specialization of the given variable template
11948 /// corresponding to the specified argument list, or a null-but-valid result
11949 /// if the arguments are dependent.
11950 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
11951 const DeclarationNameInfo &NameInfo,
11952 VarTemplateDecl *Template, NamedDecl *FoundD,
11953 SourceLocation TemplateLoc,
11954 const TemplateArgumentListInfo *TemplateArgs);
11955
11956 ExprResult CheckVarOrConceptTemplateTemplateId(
11957 const DeclarationNameInfo &NameInfo, TemplateName Template,
11958 const TemplateArgumentListInfo *TemplateArgs);
11959
11960 ExprResult
11961 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11962 const DeclarationNameInfo &ConceptNameInfo,
11963 NamedDecl *FoundDecl, TemplateDecl *NamedConcept,
11964 const TemplateArgumentListInfo *TemplateArgs,
11965 bool DoCheckConstraintSatisfaction = true);
11966
11967 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
11968 void diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
11969 bool TemplateKeyword, TemplateDecl *TD,
11970 SourceLocation Loc);
11971
11972 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
11973 SourceLocation TemplateKWLoc, LookupResult &R,
11974 bool RequiresADL,
11975 const TemplateArgumentListInfo *TemplateArgs);
11976
11977 // We actually only call this from template instantiation.
11978 ExprResult
11979 BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11980 const DeclarationNameInfo &NameInfo,
11981 const TemplateArgumentListInfo *TemplateArgs,
11982 bool IsAddressOfOperand);
11983
11984 UnsignedOrNone getPackIndex(TemplateArgument Pack) const {
11985 return Pack.pack_size() - 1 - *ArgPackSubstIndex;
11986 }
11987
11988 TemplateArgument
11989 getPackSubstitutedTemplateArgument(TemplateArgument Arg) const {
11990 Arg = Arg.pack_elements()[*ArgPackSubstIndex];
11991 if (Arg.isPackExpansion())
11992 Arg = Arg.getPackExpansionPattern();
11993 return Arg;
11994 }
11995
11996 ExprResult
11997 BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
11998 QualType ParamType, SourceLocation loc,
11999 TemplateArgument Replacement,
12000 UnsignedOrNone PackIndex, bool Final);
12001
12002 /// Form a template name from a name that is syntactically required to name a
12003 /// template, either due to use of the 'template' keyword or because a name in
12004 /// this syntactic context is assumed to name a template (C++
12005 /// [temp.names]p2-4).
12006 ///
12007 /// This action forms a template name given the name of the template and its
12008 /// optional scope specifier. This is used when the 'template' keyword is used
12009 /// or when the parsing context unambiguously treats a following '<' as
12010 /// introducing a template argument list. Note that this may produce a
12011 /// non-dependent template name if we can perform the lookup now and identify
12012 /// the named template.
12013 ///
12014 /// For example, given "x.MetaFun::template apply", the scope specifier
12015 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
12016 /// of the "template" keyword, and "apply" is the \p Name.
12017 TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS,
12018 SourceLocation TemplateKWLoc,
12019 const UnqualifiedId &Name,
12020 ParsedType ObjectType,
12021 bool EnteringContext, TemplateTy &Template,
12022 bool AllowInjectedClassName = false);
12023
12024 DeclResult ActOnClassTemplateSpecialization(
12025 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
12026 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
12027 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
12028 MultiTemplateParamsArg TemplateParameterLists,
12029 SkipBodyInfo *SkipBody = nullptr);
12030
12031 /// Check the non-type template arguments of a class template
12032 /// partial specialization according to C++ [temp.class.spec]p9.
12033 ///
12034 /// \param TemplateNameLoc the location of the template name.
12035 /// \param PrimaryTemplate the template parameters of the primary class
12036 /// template.
12037 /// \param NumExplicit the number of explicitly-specified template arguments.
12038 /// \param TemplateArgs the template arguments of the class template
12039 /// partial specialization.
12040 ///
12041 /// \returns \c true if there was an error, \c false otherwise.
12042 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
12043 TemplateDecl *PrimaryTemplate,
12044 unsigned NumExplicitArgs,
12045 ArrayRef<TemplateArgument> Args);
12046 void CheckTemplatePartialSpecialization(
12047 ClassTemplatePartialSpecializationDecl *Partial);
12048 void CheckTemplatePartialSpecialization(
12049 VarTemplatePartialSpecializationDecl *Partial);
12050
12051 Decl *ActOnTemplateDeclarator(Scope *S,
12052 MultiTemplateParamsArg TemplateParameterLists,
12053 Declarator &D);
12054
12055 /// Diagnose cases where we have an explicit template specialization
12056 /// before/after an explicit template instantiation, producing diagnostics
12057 /// for those cases where they are required and determining whether the
12058 /// new specialization/instantiation will have any effect.
12059 ///
12060 /// \param NewLoc the location of the new explicit specialization or
12061 /// instantiation.
12062 ///
12063 /// \param NewTSK the kind of the new explicit specialization or
12064 /// instantiation.
12065 ///
12066 /// \param PrevDecl the previous declaration of the entity.
12067 ///
12068 /// \param PrevTSK the kind of the old explicit specialization or
12069 /// instantiatin.
12070 ///
12071 /// \param PrevPointOfInstantiation if valid, indicates where the previous
12072 /// declaration was instantiated (either implicitly or explicitly).
12073 ///
12074 /// \param HasNoEffect will be set to true to indicate that the new
12075 /// specialization or instantiation has no effect and should be ignored.
12076 ///
12077 /// \returns true if there was an error that should prevent the introduction
12078 /// of the new declaration into the AST, false otherwise.
12079 bool CheckSpecializationInstantiationRedecl(
12080 SourceLocation NewLoc,
12081 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
12082 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
12083 SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
12084
12085 /// Perform semantic analysis for the given dependent function
12086 /// template specialization.
12087 ///
12088 /// The only possible way to get a dependent function template specialization
12089 /// is with a friend declaration, like so:
12090 ///
12091 /// \code
12092 /// template \<class T> void foo(T);
12093 /// template \<class T> class A {
12094 /// friend void foo<>(T);
12095 /// };
12096 /// \endcode
12097 ///
12098 /// There really isn't any useful analysis we can do here, so we
12099 /// just store the information.
12100 bool CheckDependentFunctionTemplateSpecialization(
12101 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
12102 LookupResult &Previous);
12103
12104 /// Perform semantic analysis for the given function template
12105 /// specialization.
12106 ///
12107 /// This routine performs all of the semantic analysis required for an
12108 /// explicit function template specialization. On successful completion,
12109 /// the function declaration \p FD will become a function template
12110 /// specialization.
12111 ///
12112 /// \param FD the function declaration, which will be updated to become a
12113 /// function template specialization.
12114 ///
12115 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
12116 /// if any. Note that this may be valid info even when 0 arguments are
12117 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
12118 /// as it anyway contains info on the angle brackets locations.
12119 ///
12120 /// \param Previous the set of declarations that may be specialized by
12121 /// this function specialization.
12122 ///
12123 /// \param QualifiedFriend whether this is a lookup for a qualified friend
12124 /// declaration with no explicit template argument list that might be
12125 /// befriending a function template specialization.
12126 bool CheckFunctionTemplateSpecialization(
12127 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
12128 LookupResult &Previous, bool QualifiedFriend = false);
12129
12130 /// Perform semantic analysis for the given non-template member
12131 /// specialization.
12132 ///
12133 /// This routine performs all of the semantic analysis required for an
12134 /// explicit member function specialization. On successful completion,
12135 /// the function declaration \p FD will become a member function
12136 /// specialization.
12137 ///
12138 /// \param Member the member declaration, which will be updated to become a
12139 /// specialization.
12140 ///
12141 /// \param Previous the set of declarations, one of which may be specialized
12142 /// by this function specialization; the set will be modified to contain the
12143 /// redeclared member.
12144 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12145 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12146
12147 // Explicit instantiation of a class template specialization
12148 DeclResult ActOnExplicitInstantiation(
12149 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
12150 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
12151 TemplateTy Template, SourceLocation TemplateNameLoc,
12152 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
12153 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
12154
12155 // Explicit instantiation of a member class of a class template.
12156 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12157 SourceLocation TemplateLoc,
12158 unsigned TagSpec, SourceLocation KWLoc,
12159 CXXScopeSpec &SS, IdentifierInfo *Name,
12160 SourceLocation NameLoc,
12161 const ParsedAttributesView &Attr);
12162
12163 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12164 SourceLocation TemplateLoc,
12165 Declarator &D);
12166
12167 /// If the given template parameter has a default template
12168 /// argument, substitute into that default template argument and
12169 /// return the corresponding template argument.
12170 TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(
12171 TemplateDecl *Template, SourceLocation TemplateKWLoc,
12172 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
12173 ArrayRef<TemplateArgument> SugaredConverted,
12174 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
12175
12176 /// Returns the top most location responsible for the definition of \p N.
12177 /// If \p N is a a template specialization, this is the location
12178 /// of the top of the instantiation stack.
12179 /// Otherwise, the location of \p N is returned.
12180 SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const;
12181
12182 /// Specifies the context in which a particular template
12183 /// argument is being checked.
12184 enum CheckTemplateArgumentKind {
12185 /// The template argument was specified in the code or was
12186 /// instantiated with some deduced template arguments.
12187 CTAK_Specified,
12188
12189 /// The template argument was deduced via template argument
12190 /// deduction.
12191 CTAK_Deduced,
12192
12193 /// The template argument was deduced from an array bound
12194 /// via template argument deduction.
12195 CTAK_DeducedFromArrayBound
12196 };
12197
12198 struct CheckTemplateArgumentInfo {
12199 explicit CheckTemplateArgumentInfo(bool PartialOrdering = false,
12200 bool MatchingTTP = false)
12201 : PartialOrdering(PartialOrdering), MatchingTTP(MatchingTTP) {}
12202 CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &) = delete;
12203 CheckTemplateArgumentInfo &
12204 operator=(const CheckTemplateArgumentInfo &) = delete;
12205
12206 /// The checked, converted argument will be added to the
12207 /// end of these vectors.
12208 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
12209
12210 /// The check is being performed in the context of partial ordering.
12211 bool PartialOrdering;
12212
12213 /// If true, assume these template arguments are
12214 /// the injected template arguments for a template template parameter.
12215 /// This will relax the requirement that all its possible uses are valid:
12216 /// TTP checking is loose, and assumes that invalid uses will be diagnosed
12217 /// during instantiation.
12218 bool MatchingTTP;
12219
12220 /// Is set to true when, in the context of TTP matching, a pack parameter
12221 /// matches non-pack arguments.
12222 bool StrictPackMatch = false;
12223 };
12224
12225 /// Check that the given template argument corresponds to the given
12226 /// template parameter.
12227 ///
12228 /// \param Param The template parameter against which the argument will be
12229 /// checked.
12230 ///
12231 /// \param Arg The template argument, which may be updated due to conversions.
12232 ///
12233 /// \param Template The template in which the template argument resides.
12234 ///
12235 /// \param TemplateLoc The location of the template name for the template
12236 /// whose argument list we're matching.
12237 ///
12238 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
12239 /// the template argument list.
12240 ///
12241 /// \param ArgumentPackIndex The index into the argument pack where this
12242 /// argument will be placed. Only valid if the parameter is a parameter pack.
12243 ///
12244 /// \param CTAK Describes how we arrived at this particular template argument:
12245 /// explicitly written, deduced, etc.
12246 ///
12247 /// \returns true on error, false otherwise.
12248 bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
12249 NamedDecl *Template, SourceLocation TemplateLoc,
12250 SourceLocation RAngleLoc,
12251 unsigned ArgumentPackIndex,
12252 CheckTemplateArgumentInfo &CTAI,
12253 CheckTemplateArgumentKind CTAK);
12254
12255 /// Check that the given template arguments can be provided to
12256 /// the given template, converting the arguments along the way.
12257 ///
12258 /// \param Template The template to which the template arguments are being
12259 /// provided.
12260 ///
12261 /// \param TemplateLoc The location of the template name in the source.
12262 ///
12263 /// \param TemplateArgs The list of template arguments. If the template is
12264 /// a template template parameter, this function may extend the set of
12265 /// template arguments to also include substituted, defaulted template
12266 /// arguments.
12267 ///
12268 /// \param PartialTemplateArgs True if the list of template arguments is
12269 /// intentionally partial, e.g., because we're checking just the initial
12270 /// set of template arguments.
12271 ///
12272 /// \param Converted Will receive the converted, canonicalized template
12273 /// arguments.
12274 ///
12275 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
12276 /// contain the converted forms of the template arguments as written.
12277 /// Otherwise, \p TemplateArgs will not be modified.
12278 ///
12279 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
12280 /// receive true if the cause for the error is the associated constraints of
12281 /// the template not being satisfied by the template arguments.
12282 ///
12283 /// \param DefaultArgs any default arguments from template specialization
12284 /// deduction.
12285 ///
12286 /// \returns true if an error occurred, false otherwise.
12287 bool CheckTemplateArgumentList(TemplateDecl *Template,
12288 SourceLocation TemplateLoc,
12289 TemplateArgumentListInfo &TemplateArgs,
12290 const DefaultArguments &DefaultArgs,
12291 bool PartialTemplateArgs,
12292 CheckTemplateArgumentInfo &CTAI,
12293 bool UpdateArgsWithConversions = true,
12294 bool *ConstraintsNotSatisfied = nullptr);
12295
12296 bool CheckTemplateArgumentList(
12297 TemplateDecl *Template, TemplateParameterList *Params,
12298 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
12299 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
12300 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions = true,
12301 bool *ConstraintsNotSatisfied = nullptr);
12302
12303 bool CheckTemplateTypeArgument(
12304 TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
12305 SmallVectorImpl<TemplateArgument> &SugaredConverted,
12306 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
12307
12308 /// Check a template argument against its corresponding
12309 /// template type parameter.
12310 ///
12311 /// This routine implements the semantics of C++ [temp.arg.type]. It
12312 /// returns true if an error occurred, and false otherwise.
12313 bool CheckTemplateArgument(TypeSourceInfo *Arg);
12314
12315 /// Check a template argument against its corresponding
12316 /// non-type template parameter.
12317 ///
12318 /// This routine implements the semantics of C++ [temp.arg.nontype].
12319 /// If an error occurred, it returns ExprError(); otherwise, it
12320 /// returns the converted template argument. \p ParamType is the
12321 /// type of the non-type template parameter after it has been instantiated.
12322 ExprResult CheckTemplateArgument(NamedDecl *Param,
12323 QualType InstantiatedParamType, Expr *Arg,
12324 TemplateArgument &SugaredConverted,
12325 TemplateArgument &CanonicalConverted,
12326 bool StrictCheck,
12327 CheckTemplateArgumentKind CTAK);
12328
12329 /// Check a template argument against its corresponding
12330 /// template template parameter.
12331 ///
12332 /// This routine implements the semantics of C++ [temp.arg.template].
12333 /// It returns true if an error occurred, and false otherwise.
12334 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
12335 TemplateParameterList *Params,
12336 TemplateArgumentLoc &Arg,
12337 bool PartialOrdering,
12338 bool *StrictPackMatch);
12339
12340 bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template,
12341 TemplateTemplateParmDecl *Param,
12342 const TemplateArgumentLoc &Arg);
12343
12344 void NoteTemplateLocation(const NamedDecl &Decl,
12345 std::optional<SourceRange> ParamRange = {});
12346 void NoteTemplateParameterLocation(const NamedDecl &Decl);
12347
12348 /// Given a non-type template argument that refers to a
12349 /// declaration and the type of its corresponding non-type template
12350 /// parameter, produce an expression that properly refers to that
12351 /// declaration.
12352 /// FIXME: This is used in some contexts where the resulting expression
12353 /// doesn't need to live too long. It would be useful if this function
12354 /// could return a temporary expression.
12355 ExprResult BuildExpressionFromDeclTemplateArgument(
12356 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc);
12357 ExprResult
12358 BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
12359 SourceLocation Loc);
12360
12361 /// Enumeration describing how template parameter lists are compared
12362 /// for equality.
12363 enum TemplateParameterListEqualKind {
12364 /// We are matching the template parameter lists of two templates
12365 /// that might be redeclarations.
12366 ///
12367 /// \code
12368 /// template<typename T> struct X;
12369 /// template<typename T> struct X;
12370 /// \endcode
12371 TPL_TemplateMatch,
12372
12373 /// We are matching the template parameter lists of two template
12374 /// template parameters as part of matching the template parameter lists
12375 /// of two templates that might be redeclarations.
12376 ///
12377 /// \code
12378 /// template<template<int I> class TT> struct X;
12379 /// template<template<int Value> class Other> struct X;
12380 /// \endcode
12381 TPL_TemplateTemplateParmMatch,
12382
12383 /// We are determining whether the template-parameters are equivalent
12384 /// according to C++ [temp.over.link]/6. This comparison does not consider
12385 /// constraints.
12386 ///
12387 /// \code
12388 /// template<C1 T> void f(T);
12389 /// template<C2 T> void f(T);
12390 /// \endcode
12391 TPL_TemplateParamsEquivalent,
12392 };
12393
12394 // A struct to represent the 'new' declaration, which is either itself just
12395 // the named decl, or the important information we need about it in order to
12396 // do constraint comparisons.
12397 class TemplateCompareNewDeclInfo {
12398 const NamedDecl *ND = nullptr;
12399 const DeclContext *DC = nullptr;
12400 const DeclContext *LexicalDC = nullptr;
12401 SourceLocation Loc;
12402
12403 public:
12404 TemplateCompareNewDeclInfo(const NamedDecl *ND) : ND(ND) {}
12405 TemplateCompareNewDeclInfo(const DeclContext *DeclCtx,
12406 const DeclContext *LexicalDeclCtx,
12407 SourceLocation Loc)
12408
12409 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12410 assert(DC && LexicalDC &&
12411 "Constructor only for cases where we have the information to put "
12412 "in here");
12413 }
12414
12415 // If this was constructed with no information, we cannot do substitution
12416 // for constraint comparison, so make sure we can check that.
12417 bool isInvalid() const { return !ND && !DC; }
12418
12419 const NamedDecl *getDecl() const { return ND; }
12420
12421 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12422
12423 const DeclContext *getLexicalDeclContext() const {
12424 return ND ? ND->getLexicalDeclContext() : LexicalDC;
12425 }
12426
12427 const DeclContext *getDeclContext() const {
12428 return ND ? ND->getDeclContext() : DC;
12429 }
12430
12431 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12432 };
12433
12434 /// Determine whether the given template parameter lists are
12435 /// equivalent.
12436 ///
12437 /// \param New The new template parameter list, typically written in the
12438 /// source code as part of a new template declaration.
12439 ///
12440 /// \param Old The old template parameter list, typically found via
12441 /// name lookup of the template declared with this template parameter
12442 /// list.
12443 ///
12444 /// \param Complain If true, this routine will produce a diagnostic if
12445 /// the template parameter lists are not equivalent.
12446 ///
12447 /// \param Kind describes how we are to match the template parameter lists.
12448 ///
12449 /// \param TemplateArgLoc If this source location is valid, then we
12450 /// are actually checking the template parameter list of a template
12451 /// argument (New) against the template parameter list of its
12452 /// corresponding template template parameter (Old). We produce
12453 /// slightly different diagnostics in this scenario.
12454 ///
12455 /// \returns True if the template parameter lists are equal, false
12456 /// otherwise.
12457 bool TemplateParameterListsAreEqual(
12458 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12459 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12460 TemplateParameterListEqualKind Kind,
12461 SourceLocation TemplateArgLoc = SourceLocation());
12462
12463 bool TemplateParameterListsAreEqual(
12464 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12465 TemplateParameterListEqualKind Kind,
12466 SourceLocation TemplateArgLoc = SourceLocation()) {
12467 return TemplateParameterListsAreEqual(NewInstFrom: nullptr, New, OldInstFrom: nullptr, Old, Complain,
12468 Kind, TemplateArgLoc);
12469 }
12470
12471 /// Check whether a template can be declared within this scope.
12472 ///
12473 /// If the template declaration is valid in this scope, returns
12474 /// false. Otherwise, issues a diagnostic and returns true.
12475 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12476
12477 /// Called when the parser has parsed a C++ typename
12478 /// specifier, e.g., "typename T::type".
12479 ///
12480 /// \param S The scope in which this typename type occurs.
12481 /// \param TypenameLoc the location of the 'typename' keyword
12482 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12483 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12484 /// \param IdLoc the location of the identifier.
12485 /// \param IsImplicitTypename context where T::type refers to a type.
12486 TypeResult ActOnTypenameType(
12487 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12488 const IdentifierInfo &II, SourceLocation IdLoc,
12489 ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No);
12490
12491 /// Called when the parser has parsed a C++ typename
12492 /// specifier that ends in a template-id, e.g.,
12493 /// "typename MetaFun::template apply<T1, T2>".
12494 ///
12495 /// \param S The scope in which this typename type occurs.
12496 /// \param TypenameLoc the location of the 'typename' keyword
12497 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12498 /// \param TemplateLoc the location of the 'template' keyword, if any.
12499 /// \param TemplateName The template name.
12500 /// \param TemplateII The identifier used to name the template.
12501 /// \param TemplateIILoc The location of the template name.
12502 /// \param LAngleLoc The location of the opening angle bracket ('<').
12503 /// \param TemplateArgs The template arguments.
12504 /// \param RAngleLoc The location of the closing angle bracket ('>').
12505 TypeResult
12506 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12507 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12508 TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12509 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12510 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12511
12512 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12513 SourceLocation KeywordLoc,
12514 NestedNameSpecifierLoc QualifierLoc,
12515 const IdentifierInfo &II, SourceLocation IILoc,
12516 TypeSourceInfo **TSI, bool DeducedTSTContext);
12517
12518 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12519 SourceLocation KeywordLoc,
12520 NestedNameSpecifierLoc QualifierLoc,
12521 const IdentifierInfo &II, SourceLocation IILoc,
12522 bool DeducedTSTContext = true);
12523
12524 /// Rebuilds a type within the context of the current instantiation.
12525 ///
12526 /// The type \p T is part of the type of an out-of-line member definition of
12527 /// a class template (or class template partial specialization) that was
12528 /// parsed and constructed before we entered the scope of the class template
12529 /// (or partial specialization thereof). This routine will rebuild that type
12530 /// now that we have entered the declarator's scope, which may produce
12531 /// different canonical types, e.g.,
12532 ///
12533 /// \code
12534 /// template<typename T>
12535 /// struct X {
12536 /// typedef T* pointer;
12537 /// pointer data();
12538 /// };
12539 ///
12540 /// template<typename T>
12541 /// typename X<T>::pointer X<T>::data() { ... }
12542 /// \endcode
12543 ///
12544 /// Here, the type "typename X<T>::pointer" will be created as a
12545 /// DependentNameType, since we do not know that we can look into X<T> when we
12546 /// parsed the type. This function will rebuild the type, performing the
12547 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12548 /// canonical type is the same as the canonical type of T*, allowing the
12549 /// return types of the out-of-line definition and the declaration to match.
12550 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
12551 SourceLocation Loc,
12552 DeclarationName Name);
12553 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
12554
12555 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
12556
12557 /// Rebuild the template parameters now that we know we're in a current
12558 /// instantiation.
12559 bool
12560 RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params);
12561
12562 /// Produces a formatted string that describes the binding of
12563 /// template parameters to template arguments.
12564 std::string
12565 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12566 const TemplateArgumentList &Args);
12567
12568 std::string
12569 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12570 const TemplateArgument *Args,
12571 unsigned NumArgs);
12572
12573 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
12574 SourceLocation Less,
12575 SourceLocation Greater);
12576
12577 /// ActOnDependentIdExpression - Handle a dependent id-expression that
12578 /// was just parsed. This is only possible with an explicit scope
12579 /// specifier naming a dependent type.
12580 ExprResult ActOnDependentIdExpression(
12581 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12582 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12583 const TemplateArgumentListInfo *TemplateArgs);
12584
12585 ExprResult
12586 BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
12587 SourceLocation TemplateKWLoc,
12588 const DeclarationNameInfo &NameInfo,
12589 const TemplateArgumentListInfo *TemplateArgs);
12590
12591 // Calculates whether the expression Constraint depends on an enclosing
12592 // template, for the purposes of [temp.friend] p9.
12593 // TemplateDepth is the 'depth' of the friend function, which is used to
12594 // compare whether a declaration reference is referring to a containing
12595 // template, or just the current friend function. A 'lower' TemplateDepth in
12596 // the AST refers to a 'containing' template. As the constraint is
12597 // uninstantiated, this is relative to the 'top' of the TU.
12598 bool
12599 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
12600 unsigned TemplateDepth,
12601 const Expr *Constraint);
12602
12603 /// Find the failed Boolean condition within a given Boolean
12604 /// constant expression, and describe it with a string.
12605 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12606
12607 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
12608
12609 ConceptDecl *ActOnStartConceptDefinition(
12610 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12611 const IdentifierInfo *Name, SourceLocation NameLoc);
12612
12613 ConceptDecl *ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
12614 Expr *ConstraintExpr,
12615 const ParsedAttributesView &Attrs);
12616
12617 void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
12618 bool &AddToScope);
12619 bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc);
12620
12621 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12622 const CXXScopeSpec &SS,
12623 const IdentifierInfo *Name,
12624 SourceLocation TagLoc, SourceLocation NameLoc);
12625
12626 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
12627 CachedTokens &Toks);
12628 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
12629 bool IsInsideALocalClassWithinATemplateFunction();
12630
12631 /// We've found a use of a templated declaration that would trigger an
12632 /// implicit instantiation. Check that any relevant explicit specializations
12633 /// and partial specializations are visible/reachable, and diagnose if not.
12634 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
12635 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
12636
12637 ///@}
12638
12639 //
12640 //
12641 // -------------------------------------------------------------------------
12642 //
12643 //
12644
12645 /// \name C++ Template Argument Deduction
12646 /// Implementations are in SemaTemplateDeduction.cpp
12647 ///@{
12648
12649public:
12650 class SFINAETrap;
12651
12652 struct SFINAEContextBase {
12653 SFINAEContextBase(Sema &S, SFINAETrap *Cur)
12654 : S(S), Prev(std::exchange(obj&: S.CurrentSFINAEContext, new_val&: Cur)) {}
12655
12656 protected:
12657 Sema &S;
12658 ~SFINAEContextBase() { S.CurrentSFINAEContext = Prev; }
12659 SFINAEContextBase(const SFINAEContextBase &) = delete;
12660 SFINAEContextBase &operator=(const SFINAEContextBase &) = delete;
12661
12662 private:
12663 SFINAETrap *Prev;
12664 };
12665
12666 struct NonSFINAEContext : SFINAEContextBase {
12667 NonSFINAEContext(Sema &S) : SFINAEContextBase(S, nullptr) {}
12668 };
12669
12670 /// RAII class used to determine whether SFINAE has
12671 /// trapped any errors that occur during template argument
12672 /// deduction.
12673 class SFINAETrap : SFINAEContextBase {
12674 bool HasErrorOcurred = false;
12675 bool WithAccessChecking = false;
12676 bool PrevLastDiagnosticIgnored =
12677 S.getDiagnostics().isLastDiagnosticIgnored();
12678 sema::TemplateDeductionInfo *DeductionInfo = nullptr;
12679
12680 SFINAETrap(Sema &S, sema::TemplateDeductionInfo *Info,
12681 bool WithAccessChecking)
12682 : SFINAEContextBase(S, this), WithAccessChecking(WithAccessChecking),
12683 DeductionInfo(Info) {}
12684
12685 public:
12686 /// \param WithAccessChecking If true, discard all diagnostics (from the
12687 /// immediate context) instead of adding them to the currently active
12688 /// \ref TemplateDeductionInfo.
12689 explicit SFINAETrap(Sema &S, bool WithAccessChecking = false)
12690 : SFINAETrap(S, /*Info=*/nullptr, WithAccessChecking) {}
12691
12692 SFINAETrap(Sema &S, sema::TemplateDeductionInfo &Info)
12693 : SFINAETrap(S, &Info, /*WithAccessChecking=*/false) {}
12694
12695 ~SFINAETrap() {
12696 S.getDiagnostics().setLastDiagnosticIgnored(PrevLastDiagnosticIgnored);
12697 }
12698
12699 SFINAETrap(const SFINAETrap &) = delete;
12700 SFINAETrap &operator=(const SFINAETrap &) = delete;
12701
12702 sema::TemplateDeductionInfo *getDeductionInfo() const {
12703 return DeductionInfo;
12704 }
12705
12706 /// Determine whether any SFINAE errors have been trapped.
12707 bool hasErrorOccurred() const { return HasErrorOcurred; }
12708 void setErrorOccurred() { HasErrorOcurred = true; }
12709
12710 bool withAccessChecking() const { return WithAccessChecking; }
12711 };
12712
12713 /// RAII class used to indicate that we are performing provisional
12714 /// semantic analysis to determine the validity of a construct, so
12715 /// typo-correction and diagnostics in the immediate context (not within
12716 /// implicitly-instantiated templates) should be suppressed.
12717 class TentativeAnalysisScope {
12718 Sema &SemaRef;
12719 // FIXME: Using a SFINAETrap for this is a hack.
12720 SFINAETrap Trap;
12721 bool PrevDisableTypoCorrection;
12722
12723 public:
12724 explicit TentativeAnalysisScope(Sema &SemaRef)
12725 : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12726 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12727 SemaRef.DisableTypoCorrection = true;
12728 }
12729 ~TentativeAnalysisScope() {
12730 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12731 }
12732
12733 TentativeAnalysisScope(const TentativeAnalysisScope &) = delete;
12734 TentativeAnalysisScope &operator=(const TentativeAnalysisScope &) = delete;
12735 };
12736
12737 /// For each declaration that involved template argument deduction, the
12738 /// set of diagnostics that were suppressed during that template argument
12739 /// deduction.
12740 ///
12741 /// FIXME: Serialize this structure to the AST file.
12742 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12743 SuppressedDiagnosticsMap;
12744 SuppressedDiagnosticsMap SuppressedDiagnostics;
12745
12746 /// Compare types for equality with respect to possibly compatible
12747 /// function types (noreturn adjustment, implicit calling conventions). If any
12748 /// of parameter and argument is not a function, just perform type comparison.
12749 ///
12750 /// \param P the template parameter type.
12751 ///
12752 /// \param A the argument type.
12753 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
12754
12755 /// Allocate a TemplateArgumentLoc where all locations have
12756 /// been initialized to the given location.
12757 ///
12758 /// \param Arg The template argument we are producing template argument
12759 /// location information for.
12760 ///
12761 /// \param NTTPType For a declaration template argument, the type of
12762 /// the non-type template parameter that corresponds to this template
12763 /// argument. Can be null if no type sugar is available to add to the
12764 /// type from the template argument.
12765 ///
12766 /// \param Loc The source location to use for the resulting template
12767 /// argument.
12768 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
12769 QualType NTTPType,
12770 SourceLocation Loc);
12771
12772 /// Get a template argument mapping the given template parameter to itself,
12773 /// e.g. for X in \c template<int X>, this would return an expression template
12774 /// argument referencing X.
12775 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
12776 SourceLocation Location);
12777
12778 /// Adjust the type \p ArgFunctionType to match the calling convention,
12779 /// noreturn, and optionally the exception specification of \p FunctionType.
12780 /// Deduction often wants to ignore these properties when matching function
12781 /// types.
12782 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
12783 bool AdjustExceptionSpec = false);
12784
12785 TemplateDeductionResult
12786 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
12787 ArrayRef<TemplateArgument> TemplateArgs,
12788 sema::TemplateDeductionInfo &Info);
12789
12790 TemplateDeductionResult
12791 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
12792 ArrayRef<TemplateArgument> TemplateArgs,
12793 sema::TemplateDeductionInfo &Info);
12794
12795 /// Deduce the template arguments of the given template from \p FromType.
12796 /// Used to implement the IsDeducible constraint for alias CTAD per C++
12797 /// [over.match.class.deduct]p4.
12798 ///
12799 /// It only supports class or type alias templates.
12800 TemplateDeductionResult
12801 DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType,
12802 sema::TemplateDeductionInfo &Info);
12803
12804 TemplateDeductionResult DeduceTemplateArguments(
12805 TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps,
12806 ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info,
12807 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12808 bool NumberOfArgumentsMustMatch);
12809
12810 /// Substitute the explicitly-provided template arguments into the
12811 /// given function template according to C++ [temp.arg.explicit].
12812 ///
12813 /// \param FunctionTemplate the function template into which the explicit
12814 /// template arguments will be substituted.
12815 ///
12816 /// \param ExplicitTemplateArgs the explicitly-specified template
12817 /// arguments.
12818 ///
12819 /// \param Deduced the deduced template arguments, which will be populated
12820 /// with the converted and checked explicit template arguments.
12821 ///
12822 /// \param ParamTypes will be populated with the instantiated function
12823 /// parameters.
12824 ///
12825 /// \param FunctionType if non-NULL, the result type of the function template
12826 /// will also be instantiated and the pointed-to value will be updated with
12827 /// the instantiated function type.
12828 ///
12829 /// \param Info if substitution fails for any reason, this object will be
12830 /// populated with more information about the failure.
12831 ///
12832 /// \returns TemplateDeductionResult::Success if substitution was successful,
12833 /// or some failure condition.
12834 TemplateDeductionResult SubstituteExplicitTemplateArguments(
12835 FunctionTemplateDecl *FunctionTemplate,
12836 TemplateArgumentListInfo &ExplicitTemplateArgs,
12837 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12838 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
12839 sema::TemplateDeductionInfo &Info);
12840
12841 /// brief A function argument from which we performed template argument
12842 // deduction for a call.
12843 struct OriginalCallArg {
12844 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
12845 unsigned ArgIdx, QualType OriginalArgType)
12846 : OriginalParamType(OriginalParamType),
12847 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
12848 OriginalArgType(OriginalArgType) {}
12849
12850 QualType OriginalParamType;
12851 bool DecomposedParam;
12852 unsigned ArgIdx;
12853 QualType OriginalArgType;
12854 };
12855
12856 /// Finish template argument deduction for a function template,
12857 /// checking the deduced template arguments for completeness and forming
12858 /// the function template specialization.
12859 ///
12860 /// \param OriginalCallArgs If non-NULL, the original call arguments against
12861 /// which the deduced argument types should be compared.
12862 /// \param CheckNonDependent Callback before substituting into the declaration
12863 /// with the deduced template arguments.
12864 /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12865 /// some breakages introduced by CWG2369, where non-user-defined conversions
12866 /// are checked first before the constraints.
12867 TemplateDeductionResult FinishTemplateArgumentDeduction(
12868 FunctionTemplateDecl *FunctionTemplate,
12869 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12870 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12871 sema::TemplateDeductionInfo &Info,
12872 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12873 bool PartialOverloading, bool PartialOrdering,
12874 bool ForOverloadSetAddressResolution,
12875 llvm::function_ref<bool(bool)> CheckNonDependent =
12876 [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12877 return false;
12878 });
12879
12880 /// Perform [temp.friend] p5 template argument deduction for a dependent
12881 /// friend declaration and a candidate class template specialization.
12882 bool DeduceTemplateArguments(FriendTemplateDecl *FTD,
12883 ClassTemplateDecl *PatternCTD,
12884 ClassTemplateDecl *CandidateCTD,
12885 ArrayRef<TemplateParameterList *> TPLs,
12886 ArrayRef<TemplateArgument> PatternArgs,
12887 ArrayRef<TemplateArgument> CandidateArgs,
12888 SourceLocation Loc,
12889 TemplateSpecCandidateSet *FailedTSC,
12890 MultiLevelTemplateArgumentList &DeducedArgs);
12891
12892 /// Perform template argument deduction from a function call
12893 /// (C++ [temp.deduct.call]).
12894 ///
12895 /// \param FunctionTemplate the function template for which we are performing
12896 /// template argument deduction.
12897 ///
12898 /// \param ExplicitTemplateArgs the explicit template arguments provided
12899 /// for this call.
12900 ///
12901 /// \param Args the function call arguments
12902 ///
12903 /// \param Specialization if template argument deduction was successful,
12904 /// this will be set to the function template specialization produced by
12905 /// template argument deduction.
12906 ///
12907 /// \param Info the argument will be updated to provide additional information
12908 /// about template argument deduction.
12909 ///
12910 /// \param CheckNonDependent A callback to invoke to check conversions for
12911 /// non-dependent parameters, between deduction and substitution, per DR1391.
12912 /// If this returns true, substitution will be skipped and we return
12913 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12914 /// passed the parameter types (after substituting explicit template
12915 /// arguments).
12916 ///
12917 /// \returns the result of template argument deduction.
12918 TemplateDeductionResult DeduceTemplateArguments(
12919 FunctionTemplateDecl *FunctionTemplate,
12920 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12921 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12922 bool PartialOverloading, bool AggregateDeductionCandidate,
12923 bool PartialOrdering, QualType ObjectType,
12924 Expr::Classification ObjectClassification,
12925 bool ForOverloadSetAddressResolution,
12926 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12927
12928 /// Deduce template arguments when taking the address of a function
12929 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12930 /// a template.
12931 ///
12932 /// \param FunctionTemplate the function template for which we are performing
12933 /// template argument deduction.
12934 ///
12935 /// \param ExplicitTemplateArgs the explicitly-specified template
12936 /// arguments.
12937 ///
12938 /// \param ArgFunctionType the function type that will be used as the
12939 /// "argument" type (A) when performing template argument deduction from the
12940 /// function template's function type. This type may be NULL, if there is no
12941 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
12942 ///
12943 /// \param Specialization if template argument deduction was successful,
12944 /// this will be set to the function template specialization produced by
12945 /// template argument deduction.
12946 ///
12947 /// \param Info the argument will be updated to provide additional information
12948 /// about template argument deduction.
12949 ///
12950 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12951 /// the address of a function template per [temp.deduct.funcaddr] and
12952 /// [over.over]. If \c false, we are looking up a function template
12953 /// specialization based on its signature, per [temp.deduct.decl].
12954 ///
12955 /// \returns the result of template argument deduction.
12956 TemplateDeductionResult DeduceTemplateArguments(
12957 FunctionTemplateDecl *FunctionTemplate,
12958 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
12959 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12960 bool IsAddressOfFunction = false);
12961
12962 /// Deduce template arguments for a templated conversion
12963 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
12964 /// conversion function template specialization.
12965 TemplateDeductionResult DeduceTemplateArguments(
12966 FunctionTemplateDecl *FunctionTemplate, QualType ObjectType,
12967 Expr::Classification ObjectClassification, QualType ToType,
12968 CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info);
12969
12970 /// Deduce template arguments for a function template when there is
12971 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
12972 ///
12973 /// \param FunctionTemplate the function template for which we are performing
12974 /// template argument deduction.
12975 ///
12976 /// \param ExplicitTemplateArgs the explicitly-specified template
12977 /// arguments.
12978 ///
12979 /// \param Specialization if template argument deduction was successful,
12980 /// this will be set to the function template specialization produced by
12981 /// template argument deduction.
12982 ///
12983 /// \param Info the argument will be updated to provide additional information
12984 /// about template argument deduction.
12985 ///
12986 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12987 /// the address of a function template in a context where we do not have a
12988 /// target type, per [over.over]. If \c false, we are looking up a function
12989 /// template specialization based on its signature, which only happens when
12990 /// deducing a function parameter type from an argument that is a template-id
12991 /// naming a function template specialization.
12992 ///
12993 /// \returns the result of template argument deduction.
12994 TemplateDeductionResult
12995 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
12996 TemplateArgumentListInfo *ExplicitTemplateArgs,
12997 FunctionDecl *&Specialization,
12998 sema::TemplateDeductionInfo &Info,
12999 bool IsAddressOfFunction = false);
13000
13001 /// Substitute Replacement for \p auto in \p TypeWithAuto
13002 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
13003 /// Substitute Replacement for auto in TypeWithAuto
13004 TypeSourceInfo *SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
13005 QualType Replacement);
13006
13007 // Substitute auto in TypeWithAuto for a Dependent auto type
13008 QualType SubstAutoTypeDependent(QualType TypeWithAuto);
13009
13010 // Substitute auto in TypeWithAuto for a Dependent auto type
13011 TypeSourceInfo *
13012 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
13013
13014 /// Completely replace the \c auto in \p TypeWithAuto by
13015 /// \p Replacement. This does not retain any \c auto type sugar.
13016 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
13017 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
13018 QualType Replacement);
13019
13020 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
13021 ///
13022 /// Note that this is done even if the initializer is dependent. (This is
13023 /// necessary to support partial ordering of templates using 'auto'.)
13024 /// A dependent type will be produced when deducing from a dependent type.
13025 ///
13026 /// \param Type the type pattern using the auto type-specifier.
13027 /// \param Init the initializer for the variable whose type is to be deduced.
13028 /// \param Result if type deduction was successful, this will be set to the
13029 /// deduced type.
13030 /// \param Info the argument will be updated to provide additional information
13031 /// about template argument deduction.
13032 /// \param DependentDeduction Set if we should permit deduction in
13033 /// dependent cases. This is necessary for template partial ordering
13034 /// with 'auto' template parameters. The template parameter depth to be
13035 /// used should be specified in the 'Info' parameter.
13036 /// \param IgnoreConstraints Set if we should not fail if the deduced type
13037 /// does not satisfy the type-constraint in the auto
13038 /// type.
13039 TemplateDeductionResult
13040 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result,
13041 sema::TemplateDeductionInfo &Info,
13042 bool DependentDeduction = false,
13043 bool IgnoreConstraints = false,
13044 TemplateSpecCandidateSet *FailedTSC = nullptr);
13045 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
13046 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
13047 bool Diagnose = true);
13048
13049 bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD,
13050 SourceLocation Loc);
13051
13052 /// Returns the more specialized class template partial specialization
13053 /// according to the rules of partial ordering of class template partial
13054 /// specializations (C++ [temp.class.order]).
13055 ///
13056 /// \param PS1 the first class template partial specialization
13057 ///
13058 /// \param PS2 the second class template partial specialization
13059 ///
13060 /// \returns the more specialized class template partial specialization. If
13061 /// neither partial specialization is more specialized, returns NULL.
13062 ClassTemplatePartialSpecializationDecl *
13063 getMoreSpecializedPartialSpecialization(
13064 ClassTemplatePartialSpecializationDecl *PS1,
13065 ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
13066
13067 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
13068 sema::TemplateDeductionInfo &Info);
13069
13070 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
13071 VarTemplatePartialSpecializationDecl *PS1,
13072 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
13073
13074 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
13075 sema::TemplateDeductionInfo &Info);
13076
13077 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
13078 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
13079 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
13080 bool PartialOrdering, bool *StrictPackMatch);
13081
13082 /// Determine the declared type of the constant template parameter that \p Arg
13083 /// names, if any.
13084 static QualType
13085 getTypeOfConstantTemplateParameter(const TemplateArgument &Arg);
13086
13087 /// Mark which template parameters are used in a given expression.
13088 ///
13089 /// \param E the expression from which template parameters will be deduced.
13090 ///
13091 /// \param Used a bit vector whose elements will be set to \c true
13092 /// to indicate when the corresponding template parameter will be
13093 /// deduced.
13094 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
13095 unsigned Depth, llvm::SmallBitVector &Used);
13096
13097 /// Mark which template parameters are named in a given expression.
13098 ///
13099 /// Unlike MarkUsedTemplateParameters, this excludes parameter that
13100 /// are used but not directly named by an expression - i.e. it excludes
13101 /// any template parameter that denotes the type of a referenced NTTP.
13102 ///
13103 /// \param Used a bit vector whose elements will be set to \c true
13104 /// to indicate when the corresponding template parameter will be
13105 /// deduced.
13106 void MarkUsedTemplateParametersForSubsumptionParameterMapping(
13107 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used);
13108
13109 /// Mark which template parameters can be deduced from a given
13110 /// template argument list.
13111 ///
13112 /// \param TemplateArgs the template argument list from which template
13113 /// parameters will be deduced.
13114 ///
13115 /// \param Used a bit vector whose elements will be set to \c true
13116 /// to indicate when the corresponding template parameter will be
13117 /// deduced.
13118 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
13119 bool OnlyDeduced, unsigned Depth,
13120 llvm::SmallBitVector &Used);
13121
13122 void MarkUsedTemplateParameters(ArrayRef<TemplateArgument> TemplateArgs,
13123 bool OnlyDeduced, unsigned Depth,
13124 llvm::SmallBitVector &Used);
13125
13126 void MarkUsedTemplateParameters(ArrayRef<TemplateArgumentLoc> TemplateArgs,
13127 unsigned Depth, llvm::SmallBitVector &Used);
13128
13129 void
13130 MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate,
13131 llvm::SmallBitVector &Deduced) {
13132 return MarkDeducedTemplateParameters(Ctx&: Context, FunctionTemplate, Deduced);
13133 }
13134
13135 /// Marks all of the template parameters that will be deduced by a
13136 /// call to the given function template.
13137 static void
13138 MarkDeducedTemplateParameters(ASTContext &Ctx,
13139 const FunctionTemplateDecl *FunctionTemplate,
13140 llvm::SmallBitVector &Deduced);
13141
13142 /// Returns the more specialized function template according
13143 /// to the rules of function template partial ordering (C++
13144 /// [temp.func.order]).
13145 ///
13146 /// \param FT1 the first function template
13147 ///
13148 /// \param FT2 the second function template
13149 ///
13150 /// \param TPOC the context in which we are performing partial ordering of
13151 /// function templates.
13152 ///
13153 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
13154 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
13155 /// when calling a member function.
13156 ///
13157 /// \param RawObj1Ty The type of the object parameter of FT1 if a member
13158 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
13159 /// template from a member function
13160 ///
13161 /// \param RawObj2Ty The type of the object parameter of FT2 if a member
13162 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
13163 /// template from a member function
13164 ///
13165 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
13166 /// candidate with a reversed parameter order. In this case, the corresponding
13167 /// P/A pairs between FT1 and FT2 are reversed.
13168 ///
13169 /// \returns the more specialized function template. If neither
13170 /// template is more specialized, returns NULL.
13171 FunctionTemplateDecl *getMoreSpecializedTemplate(
13172 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
13173 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
13174 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
13175 bool PartialOverloading = false);
13176
13177 /// Retrieve the most specialized of the given function template
13178 /// specializations.
13179 ///
13180 /// \param SpecBegin the start iterator of the function template
13181 /// specializations that we will be comparing.
13182 ///
13183 /// \param SpecEnd the end iterator of the function template
13184 /// specializations, paired with \p SpecBegin.
13185 ///
13186 /// \param Loc the location where the ambiguity or no-specializations
13187 /// diagnostic should occur.
13188 ///
13189 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
13190 /// no matching candidates.
13191 ///
13192 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
13193 /// occurs.
13194 ///
13195 /// \param CandidateDiag partial diagnostic used for each function template
13196 /// specialization that is a candidate in the ambiguous ordering. One
13197 /// parameter in this diagnostic should be unbound, which will correspond to
13198 /// the string describing the template arguments for the function template
13199 /// specialization.
13200 ///
13201 /// \returns the most specialized function template specialization, if
13202 /// found. Otherwise, returns SpecEnd.
13203 UnresolvedSetIterator
13204 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
13205 TemplateSpecCandidateSet &FailedCandidates,
13206 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
13207 const PartialDiagnostic &AmbigDiag,
13208 const PartialDiagnostic &CandidateDiag,
13209 bool Complain = true, QualType TargetType = QualType());
13210
13211 /// Returns the more constrained function according to the rules of
13212 /// partial ordering by constraints (C++ [temp.constr.order]).
13213 ///
13214 /// \param FD1 the first function
13215 ///
13216 /// \param FD2 the second function
13217 ///
13218 /// \returns the more constrained function. If neither function is
13219 /// more constrained, returns NULL.
13220 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
13221 FunctionDecl *FD2);
13222
13223 ///@}
13224
13225 //
13226 //
13227 // -------------------------------------------------------------------------
13228 //
13229 //
13230
13231 /// \name C++ Template Deduction Guide
13232 /// Implementations are in SemaTemplateDeductionGuide.cpp
13233 ///@{
13234
13235 /// Declare implicit deduction guides for a class template if we've
13236 /// not already done so.
13237 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
13238 SourceLocation Loc);
13239
13240 CXXDeductionGuideDecl *DeclareAggregateDeductionGuideFromInitList(
13241 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
13242 SourceLocation Loc);
13243
13244 ///@}
13245
13246 //
13247 //
13248 // -------------------------------------------------------------------------
13249 //
13250 //
13251
13252 /// \name C++ Template Instantiation
13253 /// Implementations are in SemaTemplateInstantiate.cpp
13254 ///@{
13255
13256public:
13257 /// A helper class for building up ExtParameterInfos.
13258 class ExtParameterInfoBuilder {
13259 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
13260 bool HasInteresting = false;
13261
13262 public:
13263 /// Set the ExtParameterInfo for the parameter at the given index,
13264 ///
13265 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
13266 assert(Infos.size() <= index);
13267 Infos.resize(N: index);
13268 Infos.push_back(Elt: info);
13269
13270 if (!HasInteresting)
13271 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
13272 }
13273
13274 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
13275 /// ExtParameterInfo array we've built up.
13276 const FunctionProtoType::ExtParameterInfo *
13277 getPointerOrNull(unsigned numParams) {
13278 if (!HasInteresting)
13279 return nullptr;
13280 Infos.resize(N: numParams);
13281 return Infos.data();
13282 }
13283 };
13284
13285 /// The current instantiation scope used to store local
13286 /// variables.
13287 LocalInstantiationScope *CurrentInstantiationScope;
13288
13289 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
13290 UnparsedDefaultArgInstantiationsMap;
13291
13292 /// A mapping from parameters with unparsed default arguments to the
13293 /// set of instantiations of each parameter.
13294 ///
13295 /// This mapping is a temporary data structure used when parsing
13296 /// nested class templates or nested classes of class templates,
13297 /// where we might end up instantiating an inner class before the
13298 /// default arguments of its methods have been parsed.
13299 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
13300
13301 using InstantiatingSpecializationsKey = llvm::PointerIntPair<Decl *, 2>;
13302
13303 struct RecursiveInstGuard {
13304 enum class Kind {
13305 Template,
13306 DefaultArgument,
13307 ExceptionSpec,
13308 };
13309
13310 RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
13311 : S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
13312 auto [_, Created] = S.InstantiatingSpecializations.insert(V: Key);
13313 if (!Created)
13314 Key = {};
13315 }
13316
13317 ~RecursiveInstGuard() {
13318 if (Key.getOpaqueValue()) {
13319 [[maybe_unused]] bool Erased =
13320 S.InstantiatingSpecializations.erase(V: Key);
13321 assert(Erased);
13322 }
13323 }
13324
13325 RecursiveInstGuard(const RecursiveInstGuard &) = delete;
13326 RecursiveInstGuard &operator=(const RecursiveInstGuard &) = delete;
13327
13328 operator bool() const { return Key.getOpaqueValue() == nullptr; }
13329
13330 private:
13331 Sema &S;
13332 Sema::InstantiatingSpecializationsKey Key;
13333 };
13334
13335 /// A context in which code is being synthesized (where a source location
13336 /// alone is not sufficient to identify the context). This covers template
13337 /// instantiation and various forms of implicitly-generated functions.
13338 struct CodeSynthesisContext {
13339 /// The kind of template instantiation we are performing
13340 enum SynthesisKind {
13341 /// We are instantiating a template declaration. The entity is
13342 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
13343 TemplateInstantiation,
13344
13345 /// We are instantiating a default argument for a template
13346 /// parameter. The Entity is the template parameter whose argument is
13347 /// being instantiated, the Template is the template, and the
13348 /// TemplateArgs/NumTemplateArguments provide the template arguments as
13349 /// specified.
13350 DefaultTemplateArgumentInstantiation,
13351
13352 /// We are instantiating a default argument for a function.
13353 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
13354 /// provides the template arguments as specified.
13355 DefaultFunctionArgumentInstantiation,
13356
13357 /// We are substituting explicit template arguments provided for
13358 /// a function template. The entity is a FunctionTemplateDecl.
13359 ExplicitTemplateArgumentSubstitution,
13360
13361 /// We are substituting template argument determined as part of
13362 /// template argument deduction for either a class template
13363 /// partial specialization or a function template. The
13364 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
13365 /// a TemplateDecl.
13366 DeducedTemplateArgumentSubstitution,
13367
13368 /// We are substituting into a lambda expression.
13369 LambdaExpressionSubstitution,
13370
13371 /// We are substituting prior template arguments into a new
13372 /// template parameter. The template parameter itself is either a
13373 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
13374 PriorTemplateArgumentSubstitution,
13375
13376 /// We are checking the validity of a default template argument that
13377 /// has been used when naming a template-id.
13378 DefaultTemplateArgumentChecking,
13379
13380 /// We are computing the exception specification for a defaulted special
13381 /// member function.
13382 ExceptionSpecEvaluation,
13383
13384 /// We are instantiating the exception specification for a function
13385 /// template which was deferred until it was needed.
13386 ExceptionSpecInstantiation,
13387
13388 /// We are instantiating a requirement of a requires expression.
13389 RequirementInstantiation,
13390
13391 /// We are checking the satisfaction of a nested requirement of a requires
13392 /// expression.
13393 NestedRequirementConstraintsCheck,
13394
13395 /// We are declaring an implicit special member function.
13396 DeclaringSpecialMember,
13397
13398 /// We are declaring an implicit 'operator==' for a defaulted
13399 /// 'operator<=>'.
13400 DeclaringImplicitEqualityComparison,
13401
13402 /// We are defining a synthesized function (such as a defaulted special
13403 /// member).
13404 DefiningSynthesizedFunction,
13405
13406 // We are checking the constraints associated with a constrained entity or
13407 // the constraint expression of a concept. This includes the checks that
13408 // atomic constraints have the type 'bool' and that they can be constant
13409 // evaluated.
13410 ConstraintsCheck,
13411
13412 // We are substituting template arguments into a constraint expression.
13413 ConstraintSubstitution,
13414
13415 // Instantiating a Requires Expression parameter clause.
13416 RequirementParameterInstantiation,
13417
13418 // We are substituting into the parameter mapping of an atomic constraint
13419 // during normalization.
13420 ParameterMappingSubstitution,
13421
13422 /// We are rewriting a comparison operator in terms of an operator<=>.
13423 RewritingOperatorAsSpaceship,
13424
13425 /// We are initializing a structured binding.
13426 InitializingStructuredBinding,
13427
13428 /// We are marking a class as __dllexport.
13429 MarkingClassDllexported,
13430
13431 /// We are building an implied call from __builtin_dump_struct. The
13432 /// arguments are in CallArgs.
13433 BuildingBuiltinDumpStructCall,
13434
13435 /// Added for Template instantiation observation.
13436 /// Memoization means we are _not_ instantiating a template because
13437 /// it is already instantiated (but we entered a context where we
13438 /// would have had to if it was not already instantiated).
13439 Memoization,
13440
13441 /// We are building deduction guides for a class.
13442 BuildingDeductionGuides,
13443
13444 /// We are instantiating a type alias template declaration.
13445 TypeAliasTemplateInstantiation,
13446
13447 /// We are performing partial ordering for template template parameters.
13448 PartialOrderingTTP,
13449
13450 /// We are performing name lookup for a function template or variable
13451 /// template named 'sycl_kernel_launch'.
13452 SYCLKernelLaunchLookup,
13453
13454 /// We are performing overload resolution for a call to a function
13455 /// template or variable template named 'sycl_kernel_launch'.
13456 SYCLKernelLaunchOverloadResolution,
13457
13458 /// We are instantiating an expansion statement.
13459 ExpansionStmtInstantiation,
13460 } Kind;
13461
13462 /// Whether we're substituting into constraints.
13463 bool InConstraintSubstitution;
13464
13465 /// Whether we're substituting into the parameter mapping of a constraint.
13466 bool InParameterMappingSubstitution;
13467
13468 /// The point of instantiation or synthesis within the source code.
13469 SourceLocation PointOfInstantiation;
13470
13471 /// The entity that is being synthesized.
13472 Decl *Entity;
13473
13474 /// The template (or partial specialization) in which we are
13475 /// performing the instantiation, for substitutions of prior template
13476 /// arguments.
13477 NamedDecl *Template;
13478
13479 union {
13480 /// The list of template arguments we are substituting, if they
13481 /// are not part of the entity.
13482 const TemplateArgument *TemplateArgs;
13483
13484 /// The list of argument expressions in a synthesized call.
13485 const Expr *const *CallArgs;
13486 };
13487
13488 // FIXME: Wrap this union around more members, or perhaps store the
13489 // kind-specific members in the RAII object owning the context.
13490 union {
13491 /// The number of template arguments in TemplateArgs.
13492 unsigned NumTemplateArgs;
13493
13494 /// The number of expressions in CallArgs.
13495 unsigned NumCallArgs;
13496
13497 /// The special member being declared or defined.
13498 CXXSpecialMemberKind SpecialMember;
13499 };
13500
13501 ArrayRef<TemplateArgument> template_arguments() const {
13502 assert(Kind != DeclaringSpecialMember);
13503 return {TemplateArgs, NumTemplateArgs};
13504 }
13505
13506 /// The source range that covers the construct that cause
13507 /// the instantiation, e.g., the template-id that causes a class
13508 /// template instantiation.
13509 SourceRange InstantiationRange;
13510
13511 CodeSynthesisContext()
13512 : Kind(TemplateInstantiation), InConstraintSubstitution(false),
13513 InParameterMappingSubstitution(false), Entity(nullptr),
13514 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0) {}
13515
13516 /// Determines whether this template is an actual instantiation
13517 /// that should be counted toward the maximum instantiation depth.
13518 bool isInstantiationRecord() const;
13519 };
13520
13521 /// A stack object to be created when performing template
13522 /// instantiation.
13523 ///
13524 /// Construction of an object of type \c InstantiatingTemplate
13525 /// pushes the current instantiation onto the stack of active
13526 /// instantiations. If the size of this stack exceeds the maximum
13527 /// number of recursive template instantiations, construction
13528 /// produces an error and evaluates true.
13529 ///
13530 /// Destruction of this object will pop the named instantiation off
13531 /// the stack.
13532 struct InstantiatingTemplate {
13533 /// Note that we are instantiating a class template,
13534 /// function template, variable template, alias template,
13535 /// or a member thereof.
13536 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13537 Decl *Entity,
13538 SourceRange InstantiationRange = SourceRange());
13539
13540 struct ExceptionSpecification {};
13541 /// Note that we are instantiating an exception specification
13542 /// of a function template.
13543 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13544 FunctionDecl *Entity, ExceptionSpecification,
13545 SourceRange InstantiationRange = SourceRange());
13546
13547 /// Note that we are instantiating a type alias template declaration.
13548 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13549 TypeAliasTemplateDecl *Entity,
13550 ArrayRef<TemplateArgument> TemplateArgs,
13551 SourceRange InstantiationRange = SourceRange());
13552
13553 /// Note that we are instantiating a default argument in a
13554 /// template-id.
13555 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13556 TemplateParameter Param, TemplateDecl *Template,
13557 ArrayRef<TemplateArgument> TemplateArgs,
13558 SourceRange InstantiationRange = SourceRange());
13559
13560 /// Note that we are substituting either explicitly-specified or
13561 /// deduced template arguments during function template argument deduction.
13562 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13563 FunctionTemplateDecl *FunctionTemplate,
13564 ArrayRef<TemplateArgument> TemplateArgs,
13565 CodeSynthesisContext::SynthesisKind Kind,
13566 SourceRange InstantiationRange = SourceRange());
13567
13568 /// Note that we are instantiating as part of template
13569 /// argument deduction for a class template declaration.
13570 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13571 TemplateDecl *Template,
13572 ArrayRef<TemplateArgument> TemplateArgs,
13573 SourceRange InstantiationRange = SourceRange());
13574
13575 /// Note that we are instantiating as part of template
13576 /// argument deduction for a class template partial
13577 /// specialization.
13578 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13579 ClassTemplatePartialSpecializationDecl *PartialSpec,
13580 ArrayRef<TemplateArgument> TemplateArgs,
13581 SourceRange InstantiationRange = SourceRange());
13582
13583 /// Note that we are instantiating as part of template
13584 /// argument deduction for a variable template partial
13585 /// specialization.
13586 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13587 VarTemplatePartialSpecializationDecl *PartialSpec,
13588 ArrayRef<TemplateArgument> TemplateArgs,
13589 SourceRange InstantiationRange = SourceRange());
13590
13591 /// Note that we are instantiating a default argument for a function
13592 /// parameter.
13593 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13594 ParmVarDecl *Param,
13595 ArrayRef<TemplateArgument> TemplateArgs,
13596 SourceRange InstantiationRange = SourceRange());
13597
13598 /// Note that we are substituting prior template arguments into a
13599 /// non-type parameter.
13600 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13601 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
13602 ArrayRef<TemplateArgument> TemplateArgs,
13603 SourceRange InstantiationRange);
13604
13605 /// Note that we are substituting prior template arguments into a
13606 /// template template parameter.
13607 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13608 NamedDecl *Template, TemplateTemplateParmDecl *Param,
13609 ArrayRef<TemplateArgument> TemplateArgs,
13610 SourceRange InstantiationRange);
13611
13612 /// Note that we are checking the default template argument
13613 /// against the template parameter for a given template-id.
13614 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13615 TemplateDecl *Template, NamedDecl *Param,
13616 ArrayRef<TemplateArgument> TemplateArgs,
13617 SourceRange InstantiationRange);
13618
13619 struct ConstraintsCheck {};
13620 /// \brief Note that we are checking the constraints associated with some
13621 /// constrained entity (a concept declaration or a template with associated
13622 /// constraints).
13623 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13624 ConstraintsCheck, NamedDecl *Template,
13625 ArrayRef<TemplateArgument> TemplateArgs,
13626 SourceRange InstantiationRange);
13627
13628 struct ConstraintSubstitution {};
13629 /// \brief Note that we are checking a constraint expression associated
13630 /// with a template declaration or as part of the satisfaction check of a
13631 /// concept.
13632 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13633 ConstraintSubstitution, NamedDecl *Template,
13634 SourceRange InstantiationRange);
13635
13636 struct ParameterMappingSubstitution {};
13637 /// \brief Note that we are subtituting into the parameter mapping of an
13638 /// atomic constraint during constraint normalization.
13639 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13640 ParameterMappingSubstitution, NamedDecl *Template,
13641 SourceRange InstantiationRange);
13642
13643 /// \brief Note that we are substituting template arguments into a part of
13644 /// a requirement of a requires expression.
13645 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13646 concepts::Requirement *Req,
13647 SourceRange InstantiationRange = SourceRange());
13648
13649 /// \brief Note that we are substituting the body of an expansion statement.
13650 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13651 CXXExpansionStmtPattern *ExpansionStmt,
13652 ArrayRef<TemplateArgument> TArgs,
13653 SourceRange InstantiationRange);
13654
13655 /// \brief Note that we are checking the satisfaction of the constraint
13656 /// expression inside of a nested requirement.
13657 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13658 concepts::NestedRequirement *Req, ConstraintsCheck,
13659 SourceRange InstantiationRange = SourceRange());
13660
13661 /// \brief Note that we are checking a requires clause.
13662 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13663 const RequiresExpr *E,
13664 SourceRange InstantiationRange);
13665
13666 struct BuildingDeductionGuidesTag {};
13667 /// \brief Note that we are building deduction guides.
13668 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13669 TemplateDecl *Entity, BuildingDeductionGuidesTag,
13670 SourceRange InstantiationRange = SourceRange());
13671
13672 struct PartialOrderingTTP {};
13673 /// \brief Note that we are partial ordering template template parameters.
13674 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13675 PartialOrderingTTP, TemplateDecl *PArg,
13676 SourceRange InstantiationRange = SourceRange());
13677
13678 /// Note that we have finished instantiating this template.
13679 void Clear();
13680
13681 ~InstantiatingTemplate() { Clear(); }
13682
13683 /// Determines whether we have exceeded the maximum
13684 /// recursive template instantiations.
13685 bool isInvalid() const { return Invalid; }
13686
13687 private:
13688 Sema &SemaRef;
13689 bool Invalid;
13690
13691 InstantiatingTemplate(Sema &SemaRef,
13692 CodeSynthesisContext::SynthesisKind Kind,
13693 SourceLocation PointOfInstantiation,
13694 SourceRange InstantiationRange, Decl *Entity,
13695 NamedDecl *Template = nullptr,
13696 ArrayRef<TemplateArgument> TemplateArgs = {});
13697
13698 InstantiatingTemplate(const InstantiatingTemplate &) = delete;
13699
13700 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13701 };
13702
13703 bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13704 const MultiLevelTemplateArgumentList &TemplateArgs,
13705 TemplateArgumentLoc &Output,
13706 SourceLocation Loc = {},
13707 const DeclarationName &Entity = {});
13708 bool
13709 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13710 const MultiLevelTemplateArgumentList &TemplateArgs,
13711 TemplateArgumentListInfo &Outputs);
13712
13713 /// Substitute concept template arguments in the constraint expression
13714 /// of a concept-id. This is used to implement [temp.constr.normal].
13715 ExprResult
13716 SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE,
13717 const Expr *ConstraintExpr,
13718 const MultiLevelTemplateArgumentList &MLTAL);
13719
13720 bool SubstTemplateArgumentsInParameterMapping(
13721 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
13722 const MultiLevelTemplateArgumentList &TemplateArgs,
13723 TemplateArgumentListInfo &Out);
13724
13725 /// Retrieve the template argument list(s) that should be used to
13726 /// instantiate the definition of the given declaration.
13727 ///
13728 /// \param ND the declaration for which we are computing template
13729 /// instantiation arguments.
13730 ///
13731 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13732 /// the decl context where it will be created. In this case, the `Innermost`
13733 /// should likely be provided. If ND is non-null, this is ignored.
13734 ///
13735 /// \param Innermost if non-NULL, specifies a template argument list for the
13736 /// template declaration passed as ND.
13737 ///
13738 /// \param RelativeToPrimary true if we should get the template
13739 /// arguments relative to the primary template, even when we're
13740 /// dealing with a specialization. This is only relevant for function
13741 /// template specializations.
13742 ///
13743 /// \param Pattern If non-NULL, indicates the pattern from which we will be
13744 /// instantiating the definition of the given declaration, \p ND. This is
13745 /// used to determine the proper set of template instantiation arguments for
13746 /// friend function template specializations.
13747 ///
13748 /// \param ForConstraintInstantiation when collecting arguments,
13749 /// ForConstraintInstantiation indicates we should continue looking when
13750 /// encountering a lambda generic call operator, and continue looking for
13751 /// arguments on an enclosing class template.
13752 ///
13753 /// \param SkipForSpecialization when specified, any template specializations
13754 /// in a traversal would be ignored.
13755 ///
13756 /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13757 /// when encountering a specialized member function template, rather than
13758 /// returning immediately.
13759 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13760 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13761 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13762 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13763 bool ForConstraintInstantiation = false,
13764 bool SkipForSpecialization = false,
13765 bool ForDefaultArgumentSubstitution = false);
13766
13767 /// RAII object to handle the state changes required to synthesize
13768 /// a function body.
13769 class SynthesizedFunctionScope {
13770 Sema &S;
13771 Sema::ContextRAII SavedContext;
13772 bool PushedCodeSynthesisContext = false;
13773
13774 public:
13775 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
13776 : S(S), SavedContext(S, DC) {
13777 auto *FD = dyn_cast<FunctionDecl>(Val: DC);
13778 S.PushFunctionScope();
13779 S.PushExpressionEvaluationContextForFunction(
13780 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, FD);
13781 if (FD)
13782 FD->setWillHaveBody(true);
13783 else
13784 assert(isa<ObjCMethodDecl>(DC));
13785 }
13786
13787 void addContextNote(SourceLocation UseLoc) {
13788 assert(!PushedCodeSynthesisContext);
13789
13790 Sema::CodeSynthesisContext Ctx;
13791 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
13792 Ctx.PointOfInstantiation = UseLoc;
13793 Ctx.Entity = cast<Decl>(Val: S.CurContext);
13794 S.pushCodeSynthesisContext(Ctx);
13795
13796 PushedCodeSynthesisContext = true;
13797 }
13798
13799 ~SynthesizedFunctionScope() {
13800 if (PushedCodeSynthesisContext)
13801 S.popCodeSynthesisContext();
13802 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
13803 FD->setWillHaveBody(false);
13804 S.CheckImmediateEscalatingFunctionDefinition(FD, FSI: S.getCurFunction());
13805 }
13806 S.PopExpressionEvaluationContext();
13807 S.PopFunctionScopeInfo();
13808 }
13809
13810 SynthesizedFunctionScope(const SynthesizedFunctionScope &) = delete;
13811 SynthesizedFunctionScope &
13812 operator=(const SynthesizedFunctionScope &) = delete;
13813 };
13814
13815 /// RAII object to ensure that a code synthesis context is popped on scope
13816 /// exit.
13817 class ScopedCodeSynthesisContext {
13818 Sema &S;
13819
13820 public:
13821 ScopedCodeSynthesisContext(Sema &S, const CodeSynthesisContext &Ctx)
13822 : S(S) {
13823 S.pushCodeSynthesisContext(Ctx);
13824 }
13825
13826 ~ScopedCodeSynthesisContext() { S.popCodeSynthesisContext(); }
13827 ScopedCodeSynthesisContext(const ScopedCodeSynthesisContext &) = delete;
13828 ScopedCodeSynthesisContext &
13829 operator=(const ScopedCodeSynthesisContext &) = delete;
13830 };
13831
13832 /// List of active code synthesis contexts.
13833 ///
13834 /// This vector is treated as a stack. As synthesis of one entity requires
13835 /// synthesis of another, additional contexts are pushed onto the stack.
13836 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
13837
13838 /// Specializations whose definitions are currently being instantiated.
13839 llvm::DenseSet<InstantiatingSpecializationsKey> InstantiatingSpecializations;
13840
13841 /// Non-dependent types used in templates that have already been instantiated
13842 /// by some template instantiation.
13843 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13844
13845 /// Extra modules inspected when performing a lookup during a template
13846 /// instantiation. Computed lazily.
13847 SmallVector<Module *, 16> CodeSynthesisContextLookupModules;
13848
13849 /// Cache of additional modules that should be used for name lookup
13850 /// within the current template instantiation. Computed lazily; use
13851 /// getLookupModules() to get a complete set.
13852 llvm::DenseSet<Module *> LookupModulesCache;
13853
13854 /// Map from the most recent declaration of a namespace to the most
13855 /// recent visible declaration of that namespace.
13856 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13857
13858 SFINAETrap *CurrentSFINAEContext = nullptr;
13859
13860 /// The number of \p CodeSynthesisContexts that are not template
13861 /// instantiations and, therefore, should not be counted as part of the
13862 /// instantiation depth.
13863 ///
13864 /// When the instantiation depth reaches the user-configurable limit
13865 /// \p LangOptions::InstantiationDepth we will abort instantiation.
13866 // FIXME: Should we have a similar limit for other forms of synthesis?
13867 unsigned NonInstantiationEntries;
13868
13869 /// The depth of the context stack at the point when the most recent
13870 /// error or warning was produced.
13871 ///
13872 /// This value is used to suppress printing of redundant context stacks
13873 /// when there are multiple errors or warnings in the same instantiation.
13874 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13875 unsigned LastEmittedCodeSynthesisContextDepth = 0;
13876
13877 /// The current index into pack expansion arguments that will be
13878 /// used for substitution of parameter packs.
13879 ///
13880 /// The pack expansion index will be none to indicate that parameter packs
13881 /// should be instantiated as themselves. Otherwise, the index specifies
13882 /// which argument within the parameter pack will be used for substitution.
13883 UnsignedOrNone ArgPackSubstIndex;
13884
13885 /// RAII object used to change the argument pack substitution index
13886 /// within a \c Sema object.
13887 ///
13888 /// See \c ArgPackSubstIndex for more information.
13889 class ArgPackSubstIndexRAII {
13890 Sema &Self;
13891 UnsignedOrNone OldSubstIndex;
13892
13893 public:
13894 ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
13895 : Self(Self),
13896 OldSubstIndex(std::exchange(obj&: Self.ArgPackSubstIndex, new_val&: NewSubstIndex)) {}
13897
13898 ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13899 ArgPackSubstIndexRAII(const ArgPackSubstIndexRAII &) = delete;
13900 ArgPackSubstIndexRAII &operator=(const ArgPackSubstIndexRAII &) = delete;
13901 };
13902
13903 bool pushCodeSynthesisContext(CodeSynthesisContext Ctx);
13904 void popCodeSynthesisContext();
13905
13906 void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc) {
13907 if (!CodeSynthesisContexts.empty() &&
13908 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
13909 PrintInstantiationStack(DiagFunc);
13910 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
13911 }
13912 if (PragmaAttributeCurrentTargetDecl)
13913 PrintPragmaAttributeInstantiationPoint(DiagFunc);
13914 }
13915 void PrintContextStack() { PrintContextStack(DiagFunc: getDefaultDiagFunc()); }
13916 /// Prints the current instantiation stack through a series of
13917 /// notes.
13918 void PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc);
13919 void PrintInstantiationStack() {
13920 PrintInstantiationStack(DiagFunc: getDefaultDiagFunc());
13921 }
13922
13923 /// Returns a pointer to the current SFINAE context, if any.
13924 [[nodiscard]] SFINAETrap *getSFINAEContext() const {
13925 return CurrentSFINAEContext;
13926 }
13927 [[nodiscard]] bool isSFINAEContext() const {
13928 return CurrentSFINAEContext != nullptr;
13929 }
13930
13931 /// Perform substitution on the type T with a given set of template
13932 /// arguments.
13933 ///
13934 /// This routine substitutes the given template arguments into the
13935 /// type T and produces the instantiated type.
13936 ///
13937 /// \param T the type into which the template arguments will be
13938 /// substituted. If this type is not dependent, it will be returned
13939 /// immediately.
13940 ///
13941 /// \param Args the template arguments that will be
13942 /// substituted for the top-level template parameters within T.
13943 ///
13944 /// \param Loc the location in the source code where this substitution
13945 /// is being performed. It will typically be the location of the
13946 /// declarator (if we're instantiating the type of some declaration)
13947 /// or the location of the type in the source code (if, e.g., we're
13948 /// instantiating the type of a cast expression).
13949 ///
13950 /// \param Entity the name of the entity associated with a declaration
13951 /// being instantiated (if any). May be empty to indicate that there
13952 /// is no such entity (if, e.g., this is a type that occurs as part of
13953 /// a cast expression) or that the entity has no name (e.g., an
13954 /// unnamed function parameter).
13955 ///
13956 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
13957 /// acceptable as the top level type of the result.
13958 ///
13959 /// \param IsIncompleteSubstitution If provided, the pointee will be set
13960 /// whenever substitution would perform a replacement with a null or
13961 /// non-existent template argument.
13962 ///
13963 /// \returns If the instantiation succeeds, the instantiated
13964 /// type. Otherwise, produces diagnostics and returns a NULL type.
13965 TypeSourceInfo *SubstType(TypeSourceInfo *T,
13966 const MultiLevelTemplateArgumentList &TemplateArgs,
13967 SourceLocation Loc, DeclarationName Entity,
13968 bool AllowDeducedTST = false);
13969
13970 QualType SubstType(QualType T,
13971 const MultiLevelTemplateArgumentList &TemplateArgs,
13972 SourceLocation Loc, DeclarationName Entity,
13973 bool *IsIncompleteSubstitution = nullptr);
13974
13975 TypeSourceInfo *SubstType(TypeLoc TL,
13976 const MultiLevelTemplateArgumentList &TemplateArgs,
13977 SourceLocation Loc, DeclarationName Entity);
13978
13979 TypeSourceInfo *
13980 SubstFriendType(TypeSourceInfo *TSI,
13981 const MultiLevelTemplateArgumentList &TemplateArgs,
13982 SourceLocation Loc, DeclarationName Entity);
13983
13984 /// A form of SubstType intended specifically for instantiating the
13985 /// type of a FunctionDecl. Its purpose is solely to force the
13986 /// instantiation of default-argument expressions and to avoid
13987 /// instantiating an exception-specification.
13988 TypeSourceInfo *SubstFunctionDeclType(
13989 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
13990 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
13991 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
13992 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
13993 const MultiLevelTemplateArgumentList &Args);
13994 bool SubstExceptionSpec(SourceLocation Loc,
13995 FunctionProtoType::ExceptionSpecInfo &ESI,
13996 SmallVectorImpl<QualType> &ExceptionStorage,
13997 const MultiLevelTemplateArgumentList &Args);
13998 ParmVarDecl *
13999 SubstParmVarDecl(ParmVarDecl *D,
14000 const MultiLevelTemplateArgumentList &TemplateArgs,
14001 int indexAdjustment, UnsignedOrNone NumExpansions,
14002 bool ExpectParameterPack, bool EvaluateConstraints = true);
14003
14004 /// Substitute the given template arguments into the given set of
14005 /// parameters, producing the set of parameter types that would be generated
14006 /// from such a substitution.
14007 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
14008 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
14009 const MultiLevelTemplateArgumentList &TemplateArgs,
14010 SmallVectorImpl<QualType> &ParamTypes,
14011 SmallVectorImpl<ParmVarDecl *> *OutParams,
14012 ExtParameterInfoBuilder &ParamInfos);
14013
14014 /// Substitute the given template arguments into the default argument.
14015 bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param,
14016 const MultiLevelTemplateArgumentList &TemplateArgs,
14017 bool ForCallExpr = false);
14018 ExprResult SubstExpr(Expr *E,
14019 const MultiLevelTemplateArgumentList &TemplateArgs);
14020 /// Substitute an expression as if it is a address-of-operand, which makes it
14021 /// act like a CXXIdExpression rather than an attempt to call.
14022 ExprResult SubstCXXIdExpr(Expr *E,
14023 const MultiLevelTemplateArgumentList &TemplateArgs);
14024
14025 // Must be used instead of SubstExpr at 'constraint checking' time.
14026 ExprResult
14027 SubstConstraintExpr(Expr *E,
14028 const MultiLevelTemplateArgumentList &TemplateArgs);
14029 // Unlike the above, this does not evaluate constraints.
14030 ExprResult SubstConstraintExprWithoutSatisfaction(
14031 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
14032
14033 /// Substitute the given template arguments into a list of
14034 /// expressions, expanding pack expansions if required.
14035 ///
14036 /// \param Exprs The list of expressions to substitute into.
14037 ///
14038 /// \param IsCall Whether this is some form of call, in which case
14039 /// default arguments will be dropped.
14040 ///
14041 /// \param TemplateArgs The set of template arguments to substitute.
14042 ///
14043 /// \param Outputs Will receive all of the substituted arguments.
14044 ///
14045 /// \returns true if an error occurred, false otherwise.
14046 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
14047 const MultiLevelTemplateArgumentList &TemplateArgs,
14048 SmallVectorImpl<Expr *> &Outputs);
14049
14050 StmtResult SubstStmt(Stmt *S,
14051 const MultiLevelTemplateArgumentList &TemplateArgs);
14052
14053 ExprResult
14054 SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs,
14055 bool CXXDirectInit);
14056
14057 /// Perform substitution on the base class specifiers of the
14058 /// given class template specialization.
14059 ///
14060 /// Produces a diagnostic and returns true on error, returns false and
14061 /// attaches the instantiated base classes to the class template
14062 /// specialization if successful.
14063 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
14064 const MultiLevelTemplateArgumentList &TemplateArgs);
14065
14066 /// Instantiate the definition of a class from a given pattern.
14067 ///
14068 /// \param PointOfInstantiation The point of instantiation within the
14069 /// source code.
14070 ///
14071 /// \param Instantiation is the declaration whose definition is being
14072 /// instantiated. This will be either a class template specialization
14073 /// or a member class of a class template specialization.
14074 ///
14075 /// \param Pattern is the pattern from which the instantiation
14076 /// occurs. This will be either the declaration of a class template or
14077 /// the declaration of a member class of a class template.
14078 ///
14079 /// \param TemplateArgs The template arguments to be substituted into
14080 /// the pattern.
14081 ///
14082 /// \param TSK the kind of implicit or explicit instantiation to perform.
14083 ///
14084 /// \param Complain whether to complain if the class cannot be instantiated
14085 /// due to the lack of a definition.
14086 ///
14087 /// \returns true if an error occurred, false otherwise.
14088 bool InstantiateClass(SourceLocation PointOfInstantiation,
14089 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
14090 const MultiLevelTemplateArgumentList &TemplateArgs,
14091 TemplateSpecializationKind TSK, bool Complain = true);
14092
14093private:
14094 bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
14095 CXXRecordDecl *Instantiation,
14096 CXXRecordDecl *Pattern,
14097 const MultiLevelTemplateArgumentList &TemplateArgs,
14098 TemplateSpecializationKind TSK, bool Complain);
14099
14100public:
14101 /// Instantiate the definition of an enum from a given pattern.
14102 ///
14103 /// \param PointOfInstantiation The point of instantiation within the
14104 /// source code.
14105 /// \param Instantiation is the declaration whose definition is being
14106 /// instantiated. This will be a member enumeration of a class
14107 /// temploid specialization, or a local enumeration within a
14108 /// function temploid specialization.
14109 /// \param Pattern The templated declaration from which the instantiation
14110 /// occurs.
14111 /// \param TemplateArgs The template arguments to be substituted into
14112 /// the pattern.
14113 /// \param TSK The kind of implicit or explicit instantiation to perform.
14114 ///
14115 /// \return \c true if an error occurred, \c false otherwise.
14116 bool InstantiateEnum(SourceLocation PointOfInstantiation,
14117 EnumDecl *Instantiation, EnumDecl *Pattern,
14118 const MultiLevelTemplateArgumentList &TemplateArgs,
14119 TemplateSpecializationKind TSK);
14120
14121 /// Instantiate the definition of a field from the given pattern.
14122 ///
14123 /// \param PointOfInstantiation The point of instantiation within the
14124 /// source code.
14125 /// \param Instantiation is the declaration whose definition is being
14126 /// instantiated. This will be a class of a class temploid
14127 /// specialization, or a local enumeration within a function temploid
14128 /// specialization.
14129 /// \param Pattern The templated declaration from which the instantiation
14130 /// occurs.
14131 /// \param TemplateArgs The template arguments to be substituted into
14132 /// the pattern.
14133 ///
14134 /// \return \c true if an error occurred, \c false otherwise.
14135 bool InstantiateInClassInitializer(
14136 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
14137 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
14138
14139 bool usesPartialOrExplicitSpecialization(
14140 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
14141
14142 bool InstantiateClassTemplateSpecialization(
14143 SourceLocation PointOfInstantiation,
14144 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14145 TemplateSpecializationKind TSK, bool Complain,
14146 bool PrimaryStrictPackMatch);
14147
14148 /// Instantiates the definitions of all of the member
14149 /// of the given class, which is an instantiation of a class template
14150 /// or a member class of a template.
14151 void
14152 InstantiateClassMembers(SourceLocation PointOfInstantiation,
14153 CXXRecordDecl *Instantiation,
14154 const MultiLevelTemplateArgumentList &TemplateArgs,
14155 TemplateSpecializationKind TSK);
14156
14157 /// Instantiate the definitions of all of the members of the
14158 /// given class template specialization, which was named as part of an
14159 /// explicit instantiation.
14160 void InstantiateClassTemplateSpecializationMembers(
14161 SourceLocation PointOfInstantiation,
14162 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14163 TemplateSpecializationKind TSK);
14164
14165 NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(
14166 NestedNameSpecifierLoc NNS,
14167 const MultiLevelTemplateArgumentList &TemplateArgs);
14168
14169 /// Do template substitution on declaration name info.
14170 DeclarationNameInfo
14171 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
14172 const MultiLevelTemplateArgumentList &TemplateArgs);
14173 TemplateName
14174 SubstTemplateName(SourceLocation TemplateKWLoc,
14175 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
14176 SourceLocation NameLoc,
14177 const MultiLevelTemplateArgumentList &TemplateArgs);
14178
14179 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
14180 const MultiLevelTemplateArgumentList &TemplateArgs,
14181 bool EvaluateConstraint);
14182
14183 /// Determine whether we are currently performing template instantiation.
14184 bool inTemplateInstantiation() const {
14185 return CodeSynthesisContexts.size() > NonInstantiationEntries;
14186 }
14187
14188 /// Determine whether we are currently performing constraint substitution.
14189 bool inConstraintSubstitution() const {
14190 return !CodeSynthesisContexts.empty() &&
14191 CodeSynthesisContexts.back().InConstraintSubstitution;
14192 }
14193
14194 bool inParameterMappingSubstitution() const {
14195 return !CodeSynthesisContexts.empty() &&
14196 CodeSynthesisContexts.back().InParameterMappingSubstitution &&
14197 !inConstraintSubstitution();
14198 }
14199
14200 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
14201
14202 /// \brief create a Requirement::SubstitutionDiagnostic with only a
14203 /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
14204 concepts::Requirement::SubstitutionDiagnostic *
14205 createSubstDiagAt(SourceLocation Location, EntityPrinter Printer);
14206
14207 ///@}
14208
14209 //
14210 //
14211 // -------------------------------------------------------------------------
14212 //
14213 //
14214
14215 /// \name C++ Template Declaration Instantiation
14216 /// Implementations are in SemaTemplateInstantiateDecl.cpp
14217 ///@{
14218
14219public:
14220 /// An entity for which implicit template instantiation is required.
14221 ///
14222 /// The source location associated with the declaration is the first place in
14223 /// the source code where the declaration was "used". It is not necessarily
14224 /// the point of instantiation (which will be either before or after the
14225 /// namespace-scope declaration that triggered this implicit instantiation),
14226 /// However, it is the location that diagnostics should generally refer to,
14227 /// because users will need to know what code triggered the instantiation.
14228 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
14229
14230 /// The queue of implicit template instantiations that are required
14231 /// but have not yet been performed.
14232 std::deque<PendingImplicitInstantiation> PendingInstantiations;
14233
14234 /// Queue of implicit template instantiations that cannot be performed
14235 /// eagerly.
14236 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
14237
14238 SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses;
14239 SmallVector<std::deque<PendingImplicitInstantiation>, 8>
14240 SavedPendingInstantiations;
14241
14242 /// The queue of implicit template instantiations that are required
14243 /// and must be performed within the current local scope.
14244 ///
14245 /// This queue is only used for member functions of local classes in
14246 /// templates, which must be instantiated in the same scope as their
14247 /// enclosing function, so that they can reference function-local
14248 /// types, static variables, enumerators, etc.
14249 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
14250
14251 class LocalEagerInstantiationScope {
14252 public:
14253 LocalEagerInstantiationScope(Sema &S, bool AtEndOfTU)
14254 : S(S), AtEndOfTU(AtEndOfTU) {
14255 SavedPendingLocalImplicitInstantiations.swap(
14256 x&: S.PendingLocalImplicitInstantiations);
14257 }
14258
14259 void perform() {
14260 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: true,
14261 /*AtEndOfTU=*/AtEndOfTU);
14262 }
14263
14264 ~LocalEagerInstantiationScope() {
14265 assert(S.PendingLocalImplicitInstantiations.empty() &&
14266 "there shouldn't be any pending local implicit instantiations");
14267 SavedPendingLocalImplicitInstantiations.swap(
14268 x&: S.PendingLocalImplicitInstantiations);
14269 }
14270
14271 LocalEagerInstantiationScope(const LocalEagerInstantiationScope &) = delete;
14272 LocalEagerInstantiationScope &
14273 operator=(const LocalEagerInstantiationScope &) = delete;
14274
14275 private:
14276 Sema &S;
14277 bool AtEndOfTU;
14278 std::deque<PendingImplicitInstantiation>
14279 SavedPendingLocalImplicitInstantiations;
14280 };
14281
14282 /// Records and restores the CurFPFeatures state on entry/exit of compound
14283 /// statements.
14284 class FPFeaturesStateRAII {
14285 public:
14286 FPFeaturesStateRAII(Sema &S);
14287 ~FPFeaturesStateRAII();
14288 FPFeaturesStateRAII(const FPFeaturesStateRAII &) = delete;
14289 FPFeaturesStateRAII &operator=(const FPFeaturesStateRAII &) = delete;
14290 FPOptionsOverride getOverrides() { return OldOverrides; }
14291
14292 private:
14293 Sema &S;
14294 FPOptions OldFPFeaturesState;
14295 FPOptionsOverride OldOverrides;
14296 LangOptions::FPEvalMethodKind OldEvalMethod;
14297 SourceLocation OldFPPragmaLocation;
14298 };
14299
14300 class GlobalEagerInstantiationScope {
14301 public:
14302 GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
14303 : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
14304 if (!Enabled)
14305 return;
14306
14307 S.SavedPendingInstantiations.emplace_back();
14308 S.SavedPendingInstantiations.back().swap(x&: S.PendingInstantiations);
14309
14310 S.SavedVTableUses.emplace_back();
14311 S.SavedVTableUses.back().swap(RHS&: S.VTableUses);
14312 }
14313
14314 void perform() {
14315 if (Enabled) {
14316 S.DefineUsedVTables();
14317 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: false,
14318 /*AtEndOfTU=*/AtEndOfTU);
14319 }
14320 }
14321
14322 ~GlobalEagerInstantiationScope() {
14323 if (!Enabled)
14324 return;
14325
14326 // Restore the set of pending vtables.
14327 assert(S.VTableUses.empty() &&
14328 "VTableUses should be empty before it is discarded.");
14329 S.VTableUses.swap(RHS&: S.SavedVTableUses.back());
14330 S.SavedVTableUses.pop_back();
14331
14332 // Restore the set of pending implicit instantiations.
14333 if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
14334 AtEndOfTU) {
14335 assert(S.PendingInstantiations.empty() &&
14336 "PendingInstantiations should be empty before it is discarded.");
14337 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14338 S.SavedPendingInstantiations.pop_back();
14339 } else {
14340 // Template instantiations in the PCH may be delayed until the TU.
14341 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14342 S.PendingInstantiations.insert(
14343 position: S.PendingInstantiations.end(),
14344 first: S.SavedPendingInstantiations.back().begin(),
14345 last: S.SavedPendingInstantiations.back().end());
14346 S.SavedPendingInstantiations.pop_back();
14347 }
14348 }
14349
14350 GlobalEagerInstantiationScope(const GlobalEagerInstantiationScope &) =
14351 delete;
14352 GlobalEagerInstantiationScope &
14353 operator=(const GlobalEagerInstantiationScope &) = delete;
14354
14355 private:
14356 Sema &S;
14357 bool Enabled;
14358 bool AtEndOfTU;
14359 };
14360
14361 ExplicitSpecifier instantiateExplicitSpecifier(
14362 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
14363
14364 struct LateInstantiatedAttribute {
14365 const Attr *TmplAttr;
14366 LocalInstantiationScope *Scope;
14367 Decl *NewDecl;
14368
14369 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
14370 Decl *D)
14371 : TmplAttr(A), Scope(S), NewDecl(D) {}
14372 };
14373 typedef SmallVector<LateInstantiatedAttribute, 1> LateInstantiatedAttrVec;
14374
14375 /// Recheck instantiated thread-safety attributes that could not be validated
14376 /// on the dependent pattern declaration.
14377 bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A);
14378
14379 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14380 const Decl *Pattern, Decl *Inst,
14381 LateInstantiatedAttrVec *LateAttrs = nullptr,
14382 LocalInstantiationScope *OuterMostScope = nullptr);
14383
14384 /// Update instantiation attributes after template was late parsed.
14385 ///
14386 /// Some attributes are evaluated based on the body of template. If it is
14387 /// late parsed, such attributes cannot be evaluated when declaration is
14388 /// instantiated. This function is used to update instantiation attributes
14389 /// when template definition is ready.
14390 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
14391
14392 void
14393 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
14394 const Decl *Pattern, Decl *Inst,
14395 LateInstantiatedAttrVec *LateAttrs = nullptr,
14396 LocalInstantiationScope *OuterMostScope = nullptr);
14397
14398 bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor,
14399 bool IsCopy = false);
14400
14401 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
14402 ParmVarDecl *Param);
14403 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
14404 FunctionDecl *Function);
14405
14406 /// Instantiate (or find existing instantiation of) a function template with a
14407 /// given set of template arguments.
14408 ///
14409 /// Usually this should not be used, and template argument deduction should be
14410 /// used in its place.
14411 FunctionDecl *InstantiateFunctionDeclaration(
14412 FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
14413 SourceLocation Loc,
14414 CodeSynthesisContext::SynthesisKind CSC =
14415 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution);
14416
14417 /// Instantiate the definition of the given function from its
14418 /// template.
14419 ///
14420 /// \param PointOfInstantiation the point at which the instantiation was
14421 /// required. Note that this is not precisely a "point of instantiation"
14422 /// for the function, but it's close.
14423 ///
14424 /// \param Function the already-instantiated declaration of a
14425 /// function template specialization or member function of a class template
14426 /// specialization.
14427 ///
14428 /// \param Recursive if true, recursively instantiates any functions that
14429 /// are required by this instantiation.
14430 ///
14431 /// \param DefinitionRequired if true, then we are performing an explicit
14432 /// instantiation where the body of the function is required. Complain if
14433 /// there is no such body.
14434 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
14435 FunctionDecl *Function,
14436 bool Recursive = false,
14437 bool DefinitionRequired = false,
14438 bool AtEndOfTU = false);
14439 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
14440 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
14441 const TemplateArgumentList *PartialSpecArgs,
14442 SmallVectorImpl<TemplateArgument> &Converted,
14443 SourceLocation PointOfInstantiation,
14444 LateInstantiatedAttrVec *LateAttrs = nullptr,
14445 LocalInstantiationScope *StartingScope = nullptr);
14446
14447 /// Instantiates a variable template specialization by completing it
14448 /// with appropriate type information and initializer.
14449 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
14450 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14451 const MultiLevelTemplateArgumentList &TemplateArgs);
14452
14453 /// BuildVariableInstantiation - Used after a new variable has been created.
14454 /// Sets basic variable data and decides whether to postpone the
14455 /// variable instantiation.
14456 void
14457 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
14458 const MultiLevelTemplateArgumentList &TemplateArgs,
14459 LateInstantiatedAttrVec *LateAttrs,
14460 DeclContext *Owner,
14461 LocalInstantiationScope *StartingScope,
14462 bool InstantiatingVarTemplate = false,
14463 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14464
14465 /// Instantiate the initializer of a variable.
14466 void InstantiateVariableInitializer(
14467 VarDecl *Var, VarDecl *OldVar,
14468 const MultiLevelTemplateArgumentList &TemplateArgs);
14469
14470 /// Instantiate the definition of the given variable from its
14471 /// template.
14472 ///
14473 /// \param PointOfInstantiation the point at which the instantiation was
14474 /// required. Note that this is not precisely a "point of instantiation"
14475 /// for the variable, but it's close.
14476 ///
14477 /// \param Var the already-instantiated declaration of a templated variable.
14478 ///
14479 /// \param Recursive if true, recursively instantiates any functions that
14480 /// are required by this instantiation.
14481 ///
14482 /// \param DefinitionRequired if true, then we are performing an explicit
14483 /// instantiation where a definition of the variable is required. Complain
14484 /// if there is no such definition.
14485 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14486 VarDecl *Var, bool Recursive = false,
14487 bool DefinitionRequired = false,
14488 bool AtEndOfTU = false);
14489
14490 void InstantiateMemInitializers(
14491 CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl,
14492 const MultiLevelTemplateArgumentList &TemplateArgs);
14493
14494 /// Find the instantiation of the given declaration within the
14495 /// current instantiation.
14496 ///
14497 /// This routine is intended to be used when \p D is a declaration
14498 /// referenced from within a template, that needs to mapped into the
14499 /// corresponding declaration within an instantiation. For example,
14500 /// given:
14501 ///
14502 /// \code
14503 /// template<typename T>
14504 /// struct X {
14505 /// enum Kind {
14506 /// KnownValue = sizeof(T)
14507 /// };
14508 ///
14509 /// bool getKind() const { return KnownValue; }
14510 /// };
14511 ///
14512 /// template struct X<int>;
14513 /// \endcode
14514 ///
14515 /// In the instantiation of X<int>::getKind(), we need to map the \p
14516 /// EnumConstantDecl for \p KnownValue (which refers to
14517 /// X<T>::<Kind>::KnownValue) to its instantiation
14518 /// (X<int>::<Kind>::KnownValue).
14519 /// \p FindInstantiatedDecl performs this mapping from within the
14520 /// instantiation of X<int>.
14521 NamedDecl *
14522 FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
14523 const MultiLevelTemplateArgumentList &TemplateArgs,
14524 bool FindingInstantiatedContext = false);
14525
14526 /// Finds the instantiation of the given declaration context
14527 /// within the current instantiation.
14528 ///
14529 /// \returns NULL if there was an error
14530 DeclContext *
14531 FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
14532 const MultiLevelTemplateArgumentList &TemplateArgs);
14533
14534 Decl *SubstDecl(Decl *D, DeclContext *Owner,
14535 const MultiLevelTemplateArgumentList &TemplateArgs);
14536
14537 /// Substitute the name and return type of a defaulted 'operator<=>' to form
14538 /// an implicit 'operator=='.
14539 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
14540 FunctionDecl *Spaceship);
14541
14542 /// Performs template instantiation for all implicit template
14543 /// instantiations we have seen until this point.
14544 void PerformPendingInstantiations(bool LocalOnly = false,
14545 bool AtEndOfTU = true);
14546
14547 TemplateParameterList *
14548 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
14549 const MultiLevelTemplateArgumentList &TemplateArgs,
14550 bool EvaluateConstraints = true);
14551
14552 void PerformDependentDiagnostics(
14553 const DeclContext *Pattern,
14554 const MultiLevelTemplateArgumentList &TemplateArgs);
14555
14556private:
14557 /// Introduce the instantiated local variables into the local
14558 /// instantiation scope.
14559 void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14560 const FunctionDecl *PatternDecl,
14561 LocalInstantiationScope &Scope);
14562 /// Introduce the instantiated function parameters into the local
14563 /// instantiation scope, and set the parameter names to those used
14564 /// in the template.
14565 bool addInstantiatedParametersToScope(
14566 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14567 LocalInstantiationScope &Scope,
14568 const MultiLevelTemplateArgumentList &TemplateArgs);
14569
14570 /// Introduce the instantiated captures of the lambda into the local
14571 /// instantiation scope.
14572 bool addInstantiatedCapturesToScope(
14573 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14574 LocalInstantiationScope &Scope,
14575 const MultiLevelTemplateArgumentList &TemplateArgs);
14576
14577 int ParsingClassDepth = 0;
14578
14579 class SavePendingParsedClassStateRAII {
14580 public:
14581 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14582
14583 ~SavePendingParsedClassStateRAII() {
14584 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14585 "there shouldn't be any pending delayed exception spec checks");
14586 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14587 "there shouldn't be any pending delayed exception spec checks");
14588 swapSavedState();
14589 }
14590
14591 SavePendingParsedClassStateRAII(const SavePendingParsedClassStateRAII &) =
14592 delete;
14593 SavePendingParsedClassStateRAII &
14594 operator=(const SavePendingParsedClassStateRAII &) = delete;
14595
14596 private:
14597 Sema &S;
14598 decltype(DelayedOverridingExceptionSpecChecks)
14599 SavedOverridingExceptionSpecChecks;
14600 decltype(DelayedEquivalentExceptionSpecChecks)
14601 SavedEquivalentExceptionSpecChecks;
14602
14603 void swapSavedState() {
14604 SavedOverridingExceptionSpecChecks.swap(
14605 RHS&: S.DelayedOverridingExceptionSpecChecks);
14606 SavedEquivalentExceptionSpecChecks.swap(
14607 RHS&: S.DelayedEquivalentExceptionSpecChecks);
14608 }
14609 };
14610
14611 ///@}
14612
14613 //
14614 //
14615 // -------------------------------------------------------------------------
14616 //
14617 //
14618
14619 /// \name C++ Variadic Templates
14620 /// Implementations are in SemaTemplateVariadic.cpp
14621 ///@{
14622
14623public:
14624 /// Determine whether an unexpanded parameter pack might be permitted in this
14625 /// location. Useful for error recovery.
14626 bool isUnexpandedParameterPackPermitted();
14627
14628 /// The context in which an unexpanded parameter pack is
14629 /// being diagnosed.
14630 ///
14631 /// Note that the values of this enumeration line up with the first
14632 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14633 enum UnexpandedParameterPackContext {
14634 /// An arbitrary expression.
14635 UPPC_Expression = 0,
14636
14637 /// The base type of a class type.
14638 UPPC_BaseType,
14639
14640 /// The type of an arbitrary declaration.
14641 UPPC_DeclarationType,
14642
14643 /// The type of a data member.
14644 UPPC_DataMemberType,
14645
14646 /// The size of a bit-field.
14647 UPPC_BitFieldWidth,
14648
14649 /// The expression in a static assertion.
14650 UPPC_StaticAssertExpression,
14651
14652 /// The fixed underlying type of an enumeration.
14653 UPPC_FixedUnderlyingType,
14654
14655 /// The enumerator value.
14656 UPPC_EnumeratorValue,
14657
14658 /// A using declaration.
14659 UPPC_UsingDeclaration,
14660
14661 /// A friend declaration.
14662 UPPC_FriendDeclaration,
14663
14664 /// A declaration qualifier.
14665 UPPC_DeclarationQualifier,
14666
14667 /// An initializer.
14668 UPPC_Initializer,
14669
14670 /// A default argument.
14671 UPPC_DefaultArgument,
14672
14673 /// The type of a non-type template parameter.
14674 UPPC_NonTypeTemplateParameterType,
14675
14676 /// The type of an exception.
14677 UPPC_ExceptionType,
14678
14679 /// Explicit specialization.
14680 UPPC_ExplicitSpecialization,
14681
14682 /// Partial specialization.
14683 UPPC_PartialSpecialization,
14684
14685 /// Microsoft __if_exists.
14686 UPPC_IfExists,
14687
14688 /// Microsoft __if_not_exists.
14689 UPPC_IfNotExists,
14690
14691 /// Lambda expression.
14692 UPPC_Lambda,
14693
14694 /// Block expression.
14695 UPPC_Block,
14696
14697 /// A type constraint.
14698 UPPC_TypeConstraint,
14699
14700 // A requirement in a requires-expression.
14701 UPPC_Requirement,
14702
14703 // A requires-clause.
14704 UPPC_RequiresClause,
14705 };
14706
14707 /// Diagnose unexpanded parameter packs.
14708 ///
14709 /// \param Loc The location at which we should emit the diagnostic.
14710 ///
14711 /// \param UPPC The context in which we are diagnosing unexpanded
14712 /// parameter packs.
14713 ///
14714 /// \param Unexpanded the set of unexpanded parameter packs.
14715 ///
14716 /// \returns true if an error occurred, false otherwise.
14717 bool DiagnoseUnexpandedParameterPacks(
14718 SourceLocation Loc, UnexpandedParameterPackContext UPPC,
14719 ArrayRef<UnexpandedParameterPack> Unexpanded);
14720
14721 /// If the given type contains an unexpanded parameter pack,
14722 /// diagnose the error.
14723 ///
14724 /// \param Loc The source location where a diagnostc should be emitted.
14725 ///
14726 /// \param T The type that is being checked for unexpanded parameter
14727 /// packs.
14728 ///
14729 /// \returns true if an error occurred, false otherwise.
14730 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
14731 UnexpandedParameterPackContext UPPC);
14732
14733 /// If the given expression contains an unexpanded parameter
14734 /// pack, diagnose the error.
14735 ///
14736 /// \param E The expression that is being checked for unexpanded
14737 /// parameter packs.
14738 ///
14739 /// \returns true if an error occurred, false otherwise.
14740 bool DiagnoseUnexpandedParameterPack(
14741 Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression);
14742
14743 /// If the given requirees-expression contains an unexpanded reference to one
14744 /// of its own parameter packs, diagnose the error.
14745 ///
14746 /// \param RE The requiress-expression that is being checked for unexpanded
14747 /// parameter packs.
14748 ///
14749 /// \returns true if an error occurred, false otherwise.
14750 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
14751
14752 /// If the given nested-name-specifier contains an unexpanded
14753 /// parameter pack, diagnose the error.
14754 ///
14755 /// \param SS The nested-name-specifier that is being checked for
14756 /// unexpanded parameter packs.
14757 ///
14758 /// \returns true if an error occurred, false otherwise.
14759 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
14760 UnexpandedParameterPackContext UPPC);
14761
14762 /// If the given name contains an unexpanded parameter pack,
14763 /// diagnose the error.
14764 ///
14765 /// \param NameInfo The name (with source location information) that
14766 /// is being checked for unexpanded parameter packs.
14767 ///
14768 /// \returns true if an error occurred, false otherwise.
14769 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
14770 UnexpandedParameterPackContext UPPC);
14771
14772 /// If the given template name contains an unexpanded parameter pack,
14773 /// diagnose the error.
14774 ///
14775 /// \param Loc The location of the template name.
14776 ///
14777 /// \param Template The template name that is being checked for unexpanded
14778 /// parameter packs.
14779 ///
14780 /// \returns true if an error occurred, false otherwise.
14781 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
14782 TemplateName Template,
14783 UnexpandedParameterPackContext UPPC);
14784
14785 /// If the given template argument contains an unexpanded parameter
14786 /// pack, diagnose the error.
14787 ///
14788 /// \param Arg The template argument that is being checked for unexpanded
14789 /// parameter packs.
14790 ///
14791 /// \returns true if an error occurred, false otherwise.
14792 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
14793 UnexpandedParameterPackContext UPPC);
14794
14795 /// Collect the set of unexpanded parameter packs within the given
14796 /// template argument.
14797 ///
14798 /// \param Arg The template argument that will be traversed to find
14799 /// unexpanded parameter packs.
14800 void collectUnexpandedParameterPacks(
14801 TemplateArgument Arg,
14802 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14803
14804 /// Collect the set of unexpanded parameter packs within the given
14805 /// template argument.
14806 ///
14807 /// \param Arg The template argument that will be traversed to find
14808 /// unexpanded parameter packs.
14809 void collectUnexpandedParameterPacks(
14810 TemplateArgumentLoc Arg,
14811 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14812
14813 /// Collect the set of unexpanded parameter packs within the given
14814 /// type.
14815 ///
14816 /// \param T The type that will be traversed to find
14817 /// unexpanded parameter packs.
14818 void collectUnexpandedParameterPacks(
14819 QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14820
14821 /// Collect the set of unexpanded parameter packs within the given
14822 /// template name.
14823 ///
14824 /// \param Template The template name that will be traversed to find
14825 /// unexpanded parameter packs.
14826 void collectUnexpandedParameterPacks(
14827 TemplateName Template,
14828 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14829
14830 /// Collect the set of unexpanded parameter packs within the given
14831 /// type.
14832 ///
14833 /// \param TL The type that will be traversed to find
14834 /// unexpanded parameter packs.
14835 void collectUnexpandedParameterPacks(
14836 TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14837
14838 /// Collect the set of unexpanded parameter packs within the given
14839 /// nested-name-specifier.
14840 ///
14841 /// \param NNS The nested-name-specifier that will be traversed to find
14842 /// unexpanded parameter packs.
14843 void collectUnexpandedParameterPacks(
14844 NestedNameSpecifierLoc NNS,
14845 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14846
14847 /// Collect the set of unexpanded parameter packs within the given
14848 /// name.
14849 ///
14850 /// \param NameInfo The name that will be traversed to find
14851 /// unexpanded parameter packs.
14852 void collectUnexpandedParameterPacks(
14853 const DeclarationNameInfo &NameInfo,
14854 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14855
14856 /// Collect the set of unexpanded parameter packs within the given
14857 /// expression.
14858 static void collectUnexpandedParameterPacks(
14859 Expr *E, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14860
14861 /// Invoked when parsing a template argument.
14862 ///
14863 /// \param Arg the template argument, which may already be invalid.
14864 ///
14865 /// If it is followed by ellipsis, this function is called before
14866 /// `ActOnPackExpansion`.
14867 ParsedTemplateArgument
14868 ActOnTemplateTemplateArgument(const ParsedTemplateArgument &Arg);
14869
14870 /// Invoked when parsing a template argument followed by an
14871 /// ellipsis, which creates a pack expansion.
14872 ///
14873 /// \param Arg The template argument preceding the ellipsis, which
14874 /// may already be invalid.
14875 ///
14876 /// \param EllipsisLoc The location of the ellipsis.
14877 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
14878 SourceLocation EllipsisLoc);
14879
14880 /// Invoked when parsing a type followed by an ellipsis, which
14881 /// creates a pack expansion.
14882 ///
14883 /// \param Type The type preceding the ellipsis, which will become
14884 /// the pattern of the pack expansion.
14885 ///
14886 /// \param EllipsisLoc The location of the ellipsis.
14887 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
14888
14889 /// Construct a pack expansion type from the pattern of the pack
14890 /// expansion.
14891 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
14892 SourceLocation EllipsisLoc,
14893 UnsignedOrNone NumExpansions);
14894
14895 /// Construct a pack expansion type from the pattern of the pack
14896 /// expansion.
14897 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14898 SourceLocation EllipsisLoc,
14899 UnsignedOrNone NumExpansions);
14900
14901 /// Invoked when parsing an expression followed by an ellipsis, which
14902 /// creates a pack expansion.
14903 ///
14904 /// \param Pattern The expression preceding the ellipsis, which will become
14905 /// the pattern of the pack expansion.
14906 ///
14907 /// \param EllipsisLoc The location of the ellipsis.
14908 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14909
14910 /// Invoked when parsing an expression followed by an ellipsis, which
14911 /// creates a pack expansion.
14912 ///
14913 /// \param Pattern The expression preceding the ellipsis, which will become
14914 /// the pattern of the pack expansion.
14915 ///
14916 /// \param EllipsisLoc The location of the ellipsis.
14917 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14918 UnsignedOrNone NumExpansions);
14919
14920 /// Determine whether we could expand a pack expansion with the
14921 /// given set of parameter packs into separate arguments by repeatedly
14922 /// transforming the pattern.
14923 ///
14924 /// \param EllipsisLoc The location of the ellipsis that identifies the
14925 /// pack expansion.
14926 ///
14927 /// \param PatternRange The source range that covers the entire pattern of
14928 /// the pack expansion.
14929 ///
14930 /// \param Unexpanded The set of unexpanded parameter packs within the
14931 /// pattern.
14932 ///
14933 /// \param ShouldExpand Will be set to \c true if the transformer should
14934 /// expand the corresponding pack expansions into separate arguments. When
14935 /// set, \c NumExpansions must also be set.
14936 ///
14937 /// \param RetainExpansion Whether the caller should add an unexpanded
14938 /// pack expansion after all of the expanded arguments. This is used
14939 /// when extending explicitly-specified template argument packs per
14940 /// C++0x [temp.arg.explicit]p9.
14941 ///
14942 /// \param NumExpansions The number of separate arguments that will be in
14943 /// the expanded form of the corresponding pack expansion. This is both an
14944 /// input and an output parameter, which can be set by the caller if the
14945 /// number of expansions is known a priori (e.g., due to a prior substitution)
14946 /// and will be set by the callee when the number of expansions is known.
14947 /// The callee must set this value when \c ShouldExpand is \c true; it may
14948 /// set this value in other cases.
14949 ///
14950 /// \returns true if an error occurred (e.g., because the parameter packs
14951 /// are to be instantiated with arguments of different lengths), false
14952 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
14953 /// must be set.
14954 bool CheckParameterPacksForExpansion(
14955 SourceLocation EllipsisLoc, SourceRange PatternRange,
14956 ArrayRef<UnexpandedParameterPack> Unexpanded,
14957 const MultiLevelTemplateArgumentList &TemplateArgs,
14958 bool FailOnPackProducingTemplates, bool &ShouldExpand,
14959 bool &RetainExpansion, UnsignedOrNone &NumExpansions,
14960 bool Diagnose = true);
14961
14962 /// Determine the number of arguments in the given pack expansion
14963 /// type.
14964 ///
14965 /// This routine assumes that the number of arguments in the expansion is
14966 /// consistent across all of the unexpanded parameter packs in its pattern.
14967 ///
14968 /// Returns an empty Optional if the type can't be expanded.
14969 UnsignedOrNone getNumArgumentsInExpansion(
14970 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
14971
14972 UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(
14973 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
14974 const MultiLevelTemplateArgumentList &TemplateArgs);
14975
14976 /// Determine whether the given declarator contains any unexpanded
14977 /// parameter packs.
14978 ///
14979 /// This routine is used by the parser to disambiguate function declarators
14980 /// with an ellipsis prior to the ')', e.g.,
14981 ///
14982 /// \code
14983 /// void f(T...);
14984 /// \endcode
14985 ///
14986 /// To determine whether we have an (unnamed) function parameter pack or
14987 /// a variadic function.
14988 ///
14989 /// \returns true if the declarator contains any unexpanded parameter packs,
14990 /// false otherwise.
14991 bool containsUnexpandedParameterPacks(Declarator &D);
14992
14993 /// Returns the pattern of the pack expansion for a template argument.
14994 ///
14995 /// \param OrigLoc The template argument to expand.
14996 ///
14997 /// \param Ellipsis Will be set to the location of the ellipsis.
14998 ///
14999 /// \param NumExpansions Will be set to the number of expansions that will
15000 /// be generated from this pack expansion, if known a priori.
15001 TemplateArgumentLoc
15002 getTemplateArgumentPackExpansionPattern(TemplateArgumentLoc OrigLoc,
15003 SourceLocation &Ellipsis,
15004 UnsignedOrNone &NumExpansions) const;
15005
15006 /// Given a template argument that contains an unexpanded parameter pack, but
15007 /// which has already been substituted, attempt to determine the number of
15008 /// elements that will be produced once this argument is fully-expanded.
15009 ///
15010 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
15011 /// avoid actually expanding the pack where possible.
15012 UnsignedOrNone getFullyPackExpandedSize(TemplateArgument Arg);
15013
15014 /// Called when an expression computing the size of a parameter pack
15015 /// is parsed.
15016 ///
15017 /// \code
15018 /// template<typename ...Types> struct count {
15019 /// static const unsigned value = sizeof...(Types);
15020 /// };
15021 /// \endcode
15022 ///
15023 //
15024 /// \param OpLoc The location of the "sizeof" keyword.
15025 /// \param Name The name of the parameter pack whose size will be determined.
15026 /// \param NameLoc The source location of the name of the parameter pack.
15027 /// \param RParenLoc The location of the closing parentheses.
15028 ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc,
15029 IdentifierInfo &Name,
15030 SourceLocation NameLoc,
15031 SourceLocation RParenLoc);
15032
15033 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
15034 SourceLocation EllipsisLoc,
15035 SourceLocation LSquareLoc, Expr *IndexExpr,
15036 SourceLocation RSquareLoc);
15037
15038 ExprResult BuildPackIndexingExpr(Expr *PackExpression,
15039 SourceLocation EllipsisLoc, Expr *IndexExpr,
15040 SourceLocation RSquareLoc,
15041 ArrayRef<Expr *> ExpandedExprs = {},
15042 bool FullySubstituted = false);
15043
15044 TemplateName ActOnPackIndexingTemplateName(TemplateName Pattern,
15045 SourceLocation NameLoc,
15046 Expr *IndexExpr);
15047
15048 TemplateName
15049 BuildPackIndexingTemplateName(TemplateName Pattern, Expr *IndexExpr,
15050 bool FullySubstituted = false,
15051 ArrayRef<TemplateName> Expansions = {});
15052
15053 TypeResult
15054 ActOnPackIndexingDeducedTemplateSpecializationType(TemplateName Name,
15055 SourceLocation NameLoc);
15056
15057 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
15058 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
15059 tok::TokenKind Operator,
15060 SourceLocation EllipsisLoc, Expr *RHS,
15061 SourceLocation RParenLoc);
15062 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
15063 SourceLocation LParenLoc, Expr *LHS,
15064 BinaryOperatorKind Operator,
15065 SourceLocation EllipsisLoc, Expr *RHS,
15066 SourceLocation RParenLoc,
15067 UnsignedOrNone NumExpansions);
15068 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
15069 BinaryOperatorKind Operator);
15070
15071 ///@}
15072
15073 //
15074 //
15075 // -------------------------------------------------------------------------
15076 //
15077 //
15078
15079 /// \name Constraints and Concepts
15080 /// Implementations are in SemaConcept.cpp
15081 ///@{
15082
15083public:
15084 ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI);
15085
15086 ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc,
15087 TypeSourceInfo *TSI);
15088
15089public:
15090 void PushSatisfactionStackEntry(const NamedDecl *D,
15091 const llvm::FoldingSetNodeID &ID) {
15092 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
15093 SatisfactionStack.emplace_back(Args&: Can, Args: ID);
15094 }
15095
15096 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
15097
15098 bool SatisfactionStackContains(const NamedDecl *D,
15099 const llvm::FoldingSetNodeID &ID) const {
15100 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
15101 return llvm::is_contained(Range: SatisfactionStack,
15102 Element: SatisfactionStackEntryTy{Can, ID});
15103 }
15104
15105 using SatisfactionStackEntryTy =
15106 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
15107
15108 // Resets the current SatisfactionStack for cases where we are instantiating
15109 // constraints as a 'side effect' of normal instantiation in a way that is not
15110 // indicative of recursive definition.
15111 class SatisfactionStackResetRAII {
15112 llvm::SmallVector<SatisfactionStackEntryTy, 10> BackupSatisfactionStack;
15113 Sema &SemaRef;
15114
15115 public:
15116 SatisfactionStackResetRAII(Sema &S) : SemaRef(S) {
15117 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
15118 }
15119
15120 ~SatisfactionStackResetRAII() {
15121 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
15122 }
15123
15124 SatisfactionStackResetRAII(const SatisfactionStackResetRAII &) = delete;
15125 SatisfactionStackResetRAII &
15126 operator=(const SatisfactionStackResetRAII &) = delete;
15127 };
15128
15129 void SwapSatisfactionStack(
15130 llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) {
15131 SatisfactionStack.swap(RHS&: NewSS);
15132 }
15133
15134 using ConstrainedDeclOrNestedRequirement =
15135 llvm::PointerUnion<const NamedDecl *,
15136 const concepts::NestedRequirement *>;
15137
15138 /// Check whether the given expression is a valid constraint expression.
15139 /// A diagnostic is emitted if it is not, false is returned, and
15140 /// PossibleNonPrimary will be set to true if the failure might be due to a
15141 /// non-primary expression being used as an atomic constraint.
15142 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
15143 bool *PossibleNonPrimary = nullptr,
15144 bool IsTrailingRequiresClause = false);
15145
15146 /// \brief Check whether the given list of constraint expressions are
15147 /// satisfied (as if in a 'conjunction') given template arguments.
15148 /// \param Template the template-like entity that triggered the constraints
15149 /// check (either a concept or a constrained entity).
15150 /// \param ConstraintExprs a list of constraint expressions, treated as if
15151 /// they were 'AND'ed together.
15152 /// \param TemplateArgLists the list of template arguments to substitute into
15153 /// the constraint expression.
15154 /// \param TemplateIDRange The source range of the template id that
15155 /// caused the constraints check.
15156 /// \param Satisfaction if true is returned, will contain details of the
15157 /// satisfaction, with enough information to diagnose an unsatisfied
15158 /// expression.
15159 /// \returns true if an error occurred and satisfaction could not be checked,
15160 /// false otherwise.
15161 bool CheckConstraintSatisfaction(
15162 ConstrainedDeclOrNestedRequirement Entity,
15163 ArrayRef<AssociatedConstraint> AssociatedConstraints,
15164 const MultiLevelTemplateArgumentList &TemplateArgLists,
15165 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
15166 const ConceptReference *TopLevelConceptId = nullptr,
15167 Expr **ConvertedExpr = nullptr);
15168
15169 /// Check whether the given function decl's trailing requires clause is
15170 /// satisfied, if any. Returns false and updates Satisfaction with the
15171 /// satisfaction verdict if successful, emits a diagnostic and returns true if
15172 /// an error occurred and satisfaction could not be determined.
15173 ///
15174 /// \returns true if an error occurred, false otherwise.
15175 bool CheckFunctionConstraints(const FunctionDecl *FD,
15176 ConstraintSatisfaction &Satisfaction,
15177 SourceLocation UsageLoc = SourceLocation(),
15178 bool ForOverloadResolution = false);
15179
15180 // Calculates whether two constraint expressions are equal irrespective of a
15181 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
15182 // 'New', which are the "source" of the constraint, since this is necessary
15183 // for figuring out the relative 'depth' of the constraint. The depth of the
15184 // 'primary template' and the 'instantiated from' templates aren't necessarily
15185 // the same, such as a case when one is a 'friend' defined in a class.
15186 bool AreConstraintExpressionsEqual(const NamedDecl *Old,
15187 const Expr *OldConstr,
15188 const TemplateCompareNewDeclInfo &New,
15189 const Expr *NewConstr);
15190
15191 // Calculates whether the friend function depends on an enclosing template for
15192 // the purposes of [temp.friend] p9.
15193 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
15194
15195 /// \brief Ensure that the given template arguments satisfy the constraints
15196 /// associated with the given template, emitting a diagnostic if they do not.
15197 ///
15198 /// \param Template The template to which the template arguments are being
15199 /// provided.
15200 ///
15201 /// \param TemplateArgs The converted, canonicalized template arguments.
15202 ///
15203 /// \param TemplateIDRange The source range of the template id that
15204 /// caused the constraints check.
15205 ///
15206 /// \returns true if the constrains are not satisfied or could not be checked
15207 /// for satisfaction, false if the constraints are satisfied.
15208 bool EnsureTemplateArgumentListConstraints(
15209 TemplateDecl *Template,
15210 const MultiLevelTemplateArgumentList &TemplateArgs,
15211 SourceRange TemplateIDRange);
15212
15213 bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
15214 FunctionDecl *Decl,
15215 ArrayRef<TemplateArgument> TemplateArgs,
15216 ConstraintSatisfaction &Satisfaction);
15217
15218 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15219 /// unsatisfied.
15220 /// \param First whether this is the first time an unsatisfied constraint is
15221 /// diagnosed for this error.
15222 void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
15223 SourceLocation Loc = {},
15224 bool First = true);
15225
15226 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15227 /// unsatisfied.
15228 void
15229 DiagnoseUnsatisfiedConstraint(const ConceptSpecializationExpr *ConstraintExpr,
15230 bool First = true);
15231
15232 void DiagnoseUnsatisfiedRequiresExpr(const RequiresExpr *RequiresExpr,
15233 bool First = true);
15234
15235 const NormalizedConstraint *getNormalizedAssociatedConstraints(
15236 ConstrainedDeclOrNestedRequirement Entity,
15237 ArrayRef<AssociatedConstraint> AssociatedConstraints);
15238
15239 /// \brief Check whether the given declaration's associated constraints are
15240 /// at least as constrained than another declaration's according to the
15241 /// partial ordering of constraints.
15242 ///
15243 /// \param Result If no error occurred, receives the result of true if D1 is
15244 /// at least constrained than D2, and false otherwise.
15245 ///
15246 /// \returns true if an error occurred, false otherwise.
15247 bool IsAtLeastAsConstrained(const NamedDecl *D1,
15248 MutableArrayRef<AssociatedConstraint> AC1,
15249 const NamedDecl *D2,
15250 MutableArrayRef<AssociatedConstraint> AC2,
15251 bool &Result);
15252
15253 /// If D1 was not at least as constrained as D2, but would've been if a pair
15254 /// of atomic constraints involved had been declared in a concept and not
15255 /// repeated in two separate places in code.
15256 /// \returns true if such a diagnostic was emitted, false otherwise.
15257 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(
15258 const NamedDecl *D1, ArrayRef<AssociatedConstraint> AC1,
15259 const NamedDecl *D2, ArrayRef<AssociatedConstraint> AC2);
15260
15261private:
15262 friend class ConstraintSatisfactionChecker;
15263 friend class SubstituteParameterMappings;
15264
15265 UnsignedOrNone EvaluateFoldExpandedConstraintSize(
15266 const Expr *Pattern, const MultiLevelTemplateArgumentList &MLTAL);
15267
15268 /// Cache the satisfaction of an atomic constraint.
15269 /// The key is based on the unsubstituted expression and the parameter
15270 /// mapping. This lets us not substituting the mapping more than once,
15271 /// which is (very!) expensive.
15272 llvm::DenseMap<llvm::FoldingSetNodeID,
15273 UnsubstitutedConstraintSatisfactionCacheResult>
15274 UnsubstitutedConstraintSatisfactionCache;
15275
15276 /// Cache the instantiation results of template parameter mappings within
15277 /// concepts. Substituting into normalized concepts can be extremely expensive
15278 /// due to the redundancy of template parameters. This cache is intended for
15279 /// use by TemplateInstantiator to avoid redundant semantic checking.
15280 llvm::DenseMap<llvm::FoldingSetNodeID, TemplateArgumentLoc>
15281 *CurrentCachedTemplateArgs = nullptr;
15282
15283 /// Caches pairs of template-like decls whose associated constraints were
15284 /// checked for subsumption and whether or not the first's constraints did in
15285 /// fact subsume the second's.
15286 llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
15287 SubsumptionCache;
15288 /// Caches the normal form of constraint expressions (and their pack
15289 /// substitution index). These are shared by e.g. the members of all
15290 /// specializations of a class template. If an error occurred while
15291 /// normalizing an expression, nullptr will be cached here.
15292 llvm::DenseMap<std::pair<const Expr *, unsigned>, NormalizedConstraint *>
15293 NormalizedConstraintExprCache;
15294
15295 /// Cache whether the associated constraint of a declaration
15296 /// is satisfied.
15297 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
15298 SatisfactionCache;
15299
15300 // The current stack of constraint satisfactions, so we can exit-early.
15301 llvm::SmallVector<SatisfactionStackEntryTy, 10> SatisfactionStack;
15302
15303 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
15304 /// LocalInstantiationScope of the current non-lambda function. For lambdas,
15305 /// use LambdaScopeForCallOperatorInstantiationRAII.
15306 bool
15307 SetupConstraintScope(FunctionDecl *FD,
15308 std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15309 const MultiLevelTemplateArgumentList &MLTAL,
15310 LocalInstantiationScope &Scope);
15311
15312 /// Used during constraint checking, sets up the constraint template argument
15313 /// lists, and calls SetupConstraintScope to set up the
15314 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
15315 std::optional<MultiLevelTemplateArgumentList>
15316 SetupConstraintCheckingTemplateArgumentsAndScope(
15317 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15318 LocalInstantiationScope &Scope);
15319
15320 ///@}
15321
15322 //
15323 //
15324 // -------------------------------------------------------------------------
15325 //
15326 //
15327
15328 /// \name Types
15329 /// Implementations are in SemaType.cpp
15330 ///@{
15331
15332public:
15333 /// A mapping that describes the nullability we've seen in each header file.
15334 FileNullabilityMap NullabilityMap;
15335
15336 static int getPrintable(int I) { return I; }
15337 static unsigned getPrintable(unsigned I) { return I; }
15338 static bool getPrintable(bool B) { return B; }
15339 static const char *getPrintable(const char *S) { return S; }
15340 static StringRef getPrintable(StringRef S) { return S; }
15341 static const std::string &getPrintable(const std::string &S) { return S; }
15342 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
15343 return II;
15344 }
15345 static DeclarationName getPrintable(DeclarationName N) { return N; }
15346 static QualType getPrintable(QualType T) { return T; }
15347 static SourceRange getPrintable(SourceRange R) { return R; }
15348 static SourceRange getPrintable(SourceLocation L) { return L; }
15349 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
15350 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange(); }
15351
15352 enum class CompleteTypeKind {
15353 /// Apply the normal rules for complete types. In particular,
15354 /// treat all sizeless types as incomplete.
15355 Normal,
15356
15357 /// Relax the normal rules for complete types so that they include
15358 /// sizeless built-in types.
15359 AcceptSizeless,
15360
15361 // FIXME: Eventually we should flip the default to Normal and opt in
15362 // to AcceptSizeless rather than opt out of it.
15363 Default = AcceptSizeless
15364 };
15365
15366 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
15367 const DeclSpec *DS = nullptr);
15368 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
15369 const DeclSpec *DS = nullptr);
15370
15371 /// Build a pointer type.
15372 ///
15373 /// \param T The type to which we'll be building a pointer.
15374 ///
15375 /// \param Loc The location of the entity whose type involves this
15376 /// pointer type or, if there is no such entity, the location of the
15377 /// type that will have pointer type.
15378 ///
15379 /// \param Entity The name of the entity that involves the pointer
15380 /// type, if known.
15381 ///
15382 /// \returns A suitable pointer type, if there are no
15383 /// errors. Otherwise, returns a NULL type.
15384 QualType BuildPointerType(QualType T, SourceLocation Loc,
15385 DeclarationName Entity);
15386
15387 /// Build a reference type.
15388 ///
15389 /// \param T The type to which we'll be building a reference.
15390 ///
15391 /// \param Loc The location of the entity whose type involves this
15392 /// reference type or, if there is no such entity, the location of the
15393 /// type that will have reference type.
15394 ///
15395 /// \param Entity The name of the entity that involves the reference
15396 /// type, if known.
15397 ///
15398 /// \returns A suitable reference type, if there are no
15399 /// errors. Otherwise, returns a NULL type.
15400 QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc,
15401 DeclarationName Entity);
15402
15403 /// Build an array type.
15404 ///
15405 /// \param T The type of each element in the array.
15406 ///
15407 /// \param ASM C99 array size modifier (e.g., '*', 'static').
15408 ///
15409 /// \param ArraySize Expression describing the size of the array.
15410 ///
15411 /// \param Brackets The range from the opening '[' to the closing ']'.
15412 ///
15413 /// \param Entity The name of the entity that involves the array
15414 /// type, if known.
15415 ///
15416 /// \returns A suitable array type, if there are no errors. Otherwise,
15417 /// returns a NULL type.
15418 QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize,
15419 unsigned Quals, SourceRange Brackets,
15420 DeclarationName Entity);
15421
15422 /// Diagnose an array of \p NumElements elements of type \p ElementType
15423 /// that is too large. Returns true if a diagnostic was emitted.
15424 bool checkArrayTooLarge(QualType ElementType, const llvm::APSInt &NumElements,
15425 SourceLocation Loc,
15426 SourceRange Range = SourceRange());
15427 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
15428
15429 /// Build an ext-vector type.
15430 ///
15431 /// Run the required checks for the extended vector type.
15432 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
15433 SourceLocation AttrLoc);
15434 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
15435 SourceLocation AttrLoc);
15436
15437 QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy,
15438 Expr *CountExpr,
15439 bool CountInBytes,
15440 bool OrNull);
15441
15442 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
15443 /// expression is uninstantiated. If instantiated it will apply the
15444 /// appropriate address space to the type. This function allows dependent
15445 /// template variables to be used in conjunction with the address_space
15446 /// attribute
15447 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
15448 SourceLocation AttrLoc);
15449
15450 /// Same as above, but constructs the AddressSpace index if not provided.
15451 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
15452 SourceLocation AttrLoc);
15453
15454 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
15455
15456 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
15457
15458 /// Build a function type.
15459 ///
15460 /// This routine checks the function type according to C++ rules and
15461 /// under the assumption that the result type and parameter types have
15462 /// just been instantiated from a template. It therefore duplicates
15463 /// some of the behavior of GetTypeForDeclarator, but in a much
15464 /// simpler form that is only suitable for this narrow use case.
15465 ///
15466 /// \param T The return type of the function.
15467 ///
15468 /// \param ParamTypes The parameter types of the function. This array
15469 /// will be modified to account for adjustments to the types of the
15470 /// function parameters.
15471 ///
15472 /// \param Loc The location of the entity whose type involves this
15473 /// function type or, if there is no such entity, the location of the
15474 /// type that will have function type.
15475 ///
15476 /// \param Entity The name of the entity that involves the function
15477 /// type, if known.
15478 ///
15479 /// \param EPI Extra information about the function type. Usually this will
15480 /// be taken from an existing function with the same prototype.
15481 ///
15482 /// \returns A suitable function type, if there are no errors. The
15483 /// unqualified type will always be a FunctionProtoType.
15484 /// Otherwise, returns a NULL type.
15485 QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes,
15486 SourceLocation Loc, DeclarationName Entity,
15487 const FunctionProtoType::ExtProtoInfo &EPI);
15488
15489 /// Build a member pointer type \c T Class::*.
15490 ///
15491 /// \param T the type to which the member pointer refers.
15492 /// \param Class the class type into which the member pointer points.
15493 /// \param Loc the location where this type begins
15494 /// \param Entity the name of the entity that will have this member pointer
15495 /// type
15496 ///
15497 /// \returns a member pointer type, if successful, or a NULL type if there was
15498 /// an error.
15499 QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS,
15500 CXXRecordDecl *Cls, SourceLocation Loc,
15501 DeclarationName Entity);
15502
15503 /// Build a block pointer type.
15504 ///
15505 /// \param T The type to which we'll be building a block pointer.
15506 ///
15507 /// \param Loc The source location, used for diagnostics.
15508 ///
15509 /// \param Entity The name of the entity that involves the block pointer
15510 /// type, if known.
15511 ///
15512 /// \returns A suitable block pointer type, if there are no
15513 /// errors. Otherwise, returns a NULL type.
15514 QualType BuildBlockPointerType(QualType T, SourceLocation Loc,
15515 DeclarationName Entity);
15516
15517 /// Build a paren type including \p T.
15518 QualType BuildParenType(QualType T);
15519 QualType BuildAtomicType(QualType T, SourceLocation Loc);
15520
15521 /// Build a Read-only Pipe type.
15522 ///
15523 /// \param T The type to which we'll be building a Pipe.
15524 ///
15525 /// \param Loc We do not use it for now.
15526 ///
15527 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15528 /// a NULL type.
15529 QualType BuildReadPipeType(QualType T, SourceLocation Loc);
15530
15531 /// Build a Write-only Pipe type.
15532 ///
15533 /// \param T The type to which we'll be building a Pipe.
15534 ///
15535 /// \param Loc We do not use it for now.
15536 ///
15537 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15538 /// a NULL type.
15539 QualType BuildWritePipeType(QualType T, SourceLocation Loc);
15540
15541 /// Build a bit-precise integer type.
15542 ///
15543 /// \param IsUnsigned Boolean representing the signedness of the type.
15544 ///
15545 /// \param BitWidth Size of this int type in bits, or an expression
15546 /// representing that.
15547 ///
15548 /// \param Loc Location of the keyword.
15549 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15550
15551 /// GetTypeForDeclarator - Convert the type for the specified
15552 /// declarator to Type instances.
15553 ///
15554 /// The result of this call will never be null, but the associated
15555 /// type may be a null type if there's an unrecoverable error.
15556 TypeSourceInfo *GetTypeForDeclarator(Declarator &D);
15557 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
15558
15559 /// Package the given type and TSI into a ParsedType.
15560 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
15561 static QualType GetTypeFromParser(ParsedType Ty,
15562 TypeSourceInfo **TInfo = nullptr);
15563
15564 TypeResult ActOnTypeName(Declarator &D);
15565
15566 // Check whether the size of array element of type \p EltTy is a multiple of
15567 // its alignment and return false if it isn't.
15568 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
15569
15570 void
15571 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15572 SourceLocation FallbackLoc,
15573 SourceLocation ConstQualLoc = SourceLocation(),
15574 SourceLocation VolatileQualLoc = SourceLocation(),
15575 SourceLocation RestrictQualLoc = SourceLocation(),
15576 SourceLocation AtomicQualLoc = SourceLocation(),
15577 SourceLocation UnalignedQualLoc = SourceLocation());
15578
15579 /// Retrieve the keyword associated
15580 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
15581
15582 /// Adjust the calling convention of a method to be the ABI default if it
15583 /// wasn't specified explicitly. This handles method types formed from
15584 /// function type typedefs and typename template arguments.
15585 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15586 bool IsCtorOrDtor, SourceLocation Loc);
15587
15588 // Check if there is an explicit attribute, but only look through parens.
15589 // The intent is to look for an attribute on the current declarator, but not
15590 // one that came from a typedef.
15591 bool hasExplicitCallingConv(QualType T);
15592
15593 /// Check whether a nullability type specifier can be added to the given
15594 /// type through some means not written in source (e.g. API notes).
15595 ///
15596 /// \param Type The type to which the nullability specifier will be
15597 /// added. On success, this type will be updated appropriately.
15598 ///
15599 /// \param Nullability The nullability specifier to add.
15600 ///
15601 /// \param DiagLoc The location to use for diagnostics.
15602 ///
15603 /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15604 /// array type (e.g., because it will decay to a pointer).
15605 ///
15606 /// \param OverrideExisting Whether to override an existing, locally-specified
15607 /// nullability specifier rather than complaining about the conflict.
15608 ///
15609 /// \returns true if nullability cannot be applied, false otherwise.
15610 bool CheckImplicitNullabilityTypeSpecifier(QualType &Type,
15611 NullabilityKind Nullability,
15612 SourceLocation DiagLoc,
15613 bool AllowArrayTypes,
15614 bool OverrideExisting);
15615
15616 /// Check whether the given variable declaration has a size that fits within
15617 /// the address space it is declared in. This issues a diagnostic if not.
15618 ///
15619 /// \param VD The variable declaration to check the size of.
15620 ///
15621 /// \param AS The address space to check the size of \p VD against.
15622 ///
15623 /// \returns true if the variable's size fits within the address space, false
15624 /// otherwise.
15625 bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS);
15626
15627 /// Get the type of expression E, triggering instantiation to complete the
15628 /// type if necessary -- that is, if the expression refers to a templated
15629 /// static data member of incomplete array type.
15630 ///
15631 /// May still return an incomplete type if instantiation was not possible or
15632 /// if the type is incomplete for a different reason. Use
15633 /// RequireCompleteExprType instead if a diagnostic is expected for an
15634 /// incomplete expression type.
15635 QualType getCompletedType(Expr *E);
15636
15637 void completeExprArrayBound(Expr *E);
15638
15639 /// Ensure that the type of the given expression is complete.
15640 ///
15641 /// This routine checks whether the expression \p E has a complete type. If
15642 /// the expression refers to an instantiable construct, that instantiation is
15643 /// performed as needed to complete its type. Furthermore
15644 /// Sema::RequireCompleteType is called for the expression's type (or in the
15645 /// case of a reference type, the referred-to type).
15646 ///
15647 /// \param E The expression whose type is required to be complete.
15648 /// \param Kind Selects which completeness rules should be applied.
15649 /// \param Diagnoser The object that will emit a diagnostic if the type is
15650 /// incomplete.
15651 ///
15652 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15653 /// otherwise.
15654 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
15655 TypeDiagnoser &Diagnoser);
15656 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15657
15658 template <typename... Ts>
15659 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15660 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15661 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
15662 }
15663
15664 // Returns the underlying type of a decltype with the given expression.
15665 QualType getDecltypeForExpr(Expr *E);
15666
15667 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
15668 /// If AsUnevaluated is false, E is treated as though it were an evaluated
15669 /// context, such as when building a type for decltype(auto).
15670 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15671
15672 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15673 SourceLocation Loc);
15674 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15675 SourceLocation Loc,
15676 bool FullySubstituted = false,
15677 ArrayRef<QualType> Expansions = {});
15678
15679 using UTTKind = UnaryTransformType::UTTKind;
15680 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
15681 SourceLocation Loc);
15682 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
15683 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
15684 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
15685 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
15686 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
15687 SourceLocation Loc);
15688 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
15689 SourceLocation Loc);
15690 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
15691 SourceLocation Loc);
15692
15693 QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc) {
15694 return BuiltinRemoveReference(BaseType, UKind: UTTKind::RemoveCVRef, Loc);
15695 }
15696
15697 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
15698 SourceLocation Loc);
15699 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
15700 SourceLocation Loc);
15701
15702 bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15703
15704 /// Ensure that the type T is a literal type.
15705 ///
15706 /// This routine checks whether the type @p T is a literal type. If @p T is an
15707 /// incomplete type, an attempt is made to complete it. If @p T is a literal
15708 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15709 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15710 /// it the type @p T), along with notes explaining why the type is not a
15711 /// literal type, and returns true.
15712 ///
15713 /// @param Loc The location in the source that the non-literal type
15714 /// diagnostic should refer to.
15715 ///
15716 /// @param T The type that this routine is examining for literalness.
15717 ///
15718 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15719 ///
15720 /// @returns @c true if @p T is not a literal type and a diagnostic was
15721 /// emitted, @c false otherwise.
15722 bool RequireLiteralType(SourceLocation Loc, QualType T,
15723 TypeDiagnoser &Diagnoser);
15724 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15725
15726 template <typename... Ts>
15727 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15728 const Ts &...Args) {
15729 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15730 return RequireLiteralType(Loc, T, Diagnoser);
15731 }
15732
15733 bool isCompleteType(SourceLocation Loc, QualType T,
15734 CompleteTypeKind Kind = CompleteTypeKind::Default) {
15735 return !RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser: nullptr);
15736 }
15737
15738 /// Ensure that the type T is a complete type.
15739 ///
15740 /// This routine checks whether the type @p T is complete in any
15741 /// context where a complete type is required. If @p T is a complete
15742 /// type, returns false. If @p T is a class template specialization,
15743 /// this routine then attempts to perform class template
15744 /// instantiation. If instantiation fails, or if @p T is incomplete
15745 /// and cannot be completed, issues the diagnostic @p diag (giving it
15746 /// the type @p T) and returns true.
15747 ///
15748 /// @param Loc The location in the source that the incomplete type
15749 /// diagnostic should refer to.
15750 ///
15751 /// @param T The type that this routine is examining for completeness.
15752 ///
15753 /// @param Kind Selects which completeness rules should be applied.
15754 ///
15755 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15756 /// @c false otherwise.
15757 bool RequireCompleteType(SourceLocation Loc, QualType T,
15758 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15759 bool RequireCompleteType(SourceLocation Loc, QualType T,
15760 CompleteTypeKind Kind, unsigned DiagID);
15761
15762 bool RequireCompleteType(SourceLocation Loc, QualType T,
15763 TypeDiagnoser &Diagnoser) {
15764 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, Diagnoser);
15765 }
15766 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15767 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, DiagID);
15768 }
15769
15770 template <typename... Ts>
15771 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15772 const Ts &...Args) {
15773 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15774 return RequireCompleteType(Loc, T, Diagnoser);
15775 }
15776
15777 /// Determine whether a declaration is visible to name lookup.
15778 bool isVisible(const NamedDecl *D) {
15779 return D->isUnconditionallyVisible() ||
15780 isAcceptableSlow(D, Kind: AcceptableKind::Visible);
15781 }
15782
15783 /// Determine whether a declaration is reachable.
15784 bool isReachable(const NamedDecl *D) {
15785 // All visible declarations are reachable.
15786 return D->isUnconditionallyVisible() ||
15787 isAcceptableSlow(D, Kind: AcceptableKind::Reachable);
15788 }
15789
15790 /// Determine whether a declaration is acceptable (visible/reachable).
15791 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
15792 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15793 }
15794
15795 /// Determine if \p D and \p Suggested have a structurally compatible
15796 /// layout as described in C11 6.2.7/1.
15797 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15798
15799 /// Determine if \p D has a visible definition. If not, suggest a declaration
15800 /// that should be made visible to expose the definition.
15801 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15802 bool OnlyNeedComplete = false);
15803 bool hasVisibleDefinition(const NamedDecl *D) {
15804 NamedDecl *Hidden;
15805 return hasVisibleDefinition(D: const_cast<NamedDecl *>(D), Suggested: &Hidden);
15806 }
15807 /// Determine if \p D has a definition which allows we redefine it in current
15808 /// TU. \p Suggested is the definition that should be made visible to expose
15809 /// the definition.
15810 bool isRedefinitionAllowedFor(NamedDecl *D, SourceLocation NewDefinitionLoc,
15811 NamedDecl **Suggested, bool &Visible);
15812 bool isRedefinitionAllowedFor(const NamedDecl *D, SourceLocation NewLoc,
15813 bool &Visible) {
15814 NamedDecl *Hidden;
15815 return isRedefinitionAllowedFor(D: const_cast<NamedDecl *>(D), NewDefinitionLoc: NewLoc, Suggested: &Hidden,
15816 Visible);
15817 }
15818
15819 /// Determine if \p D has a reachable definition. If not, suggest a
15820 /// declaration that should be made reachable to expose the definition.
15821 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15822 bool OnlyNeedComplete = false);
15823 bool hasReachableDefinition(NamedDecl *D) {
15824 NamedDecl *Hidden;
15825 return hasReachableDefinition(D, Suggested: &Hidden);
15826 }
15827
15828 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15829 AcceptableKind Kind,
15830 bool OnlyNeedComplete = false);
15831 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
15832 NamedDecl *Hidden;
15833 return hasAcceptableDefinition(D, Suggested: &Hidden, Kind);
15834 }
15835
15836 /// Determine if a definition at \p NewLoc coincides with \p PrevD.
15837 ///
15838 /// Including the same header as a non-modular and a modular allows to process
15839 /// its content twice despite guards against multiple inclusions. To handle
15840 /// such cases this method allows to detect if a currently-parsed decl is at
15841 /// the same location as an existing decl imported from a module.
15842 bool isFromSameSingleIncludeHeader(const Decl *PrevD, SourceLocation NewLoc);
15843
15844 /// Try to parse the conditional expression attached to an effect attribute
15845 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15846 /// optional on error.
15847 std::optional<FunctionEffectMode>
15848 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15849
15850 void ActOnCleanupAttr(Decl *D, const Attr *A);
15851 void ActOnInitPriorityAttr(Decl *D, const Attr *A);
15852
15853private:
15854 /// The implementation of RequireCompleteType
15855 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15856 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15857
15858 /// Nullability type specifiers.
15859 IdentifierInfo *Ident__Nonnull = nullptr;
15860 IdentifierInfo *Ident__Nullable = nullptr;
15861 IdentifierInfo *Ident__Nullable_result = nullptr;
15862 IdentifierInfo *Ident__Null_unspecified = nullptr;
15863
15864 ///@}
15865
15866 //
15867 //
15868 // -------------------------------------------------------------------------
15869 //
15870 //
15871
15872 /// \name FixIt Helpers
15873 /// Implementations are in SemaFixItUtils.cpp
15874 ///@{
15875
15876public:
15877 /// Get a string to suggest for zero-initialization of a type.
15878 std::string getFixItZeroInitializerForType(QualType T,
15879 SourceLocation Loc) const;
15880 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15881
15882 ///@}
15883
15884 //
15885 //
15886 // -------------------------------------------------------------------------
15887 //
15888 //
15889
15890 /// \name Function Effects
15891 /// Implementations are in SemaFunctionEffects.cpp
15892 ///@{
15893public:
15894 struct FunctionEffectDiff {
15895 enum class Kind { Added, Removed, ConditionMismatch };
15896
15897 FunctionEffect::Kind EffectKind;
15898 Kind DiffKind;
15899 std::optional<FunctionEffectWithCondition>
15900 Old; // Invalid when 'Kind' is 'Added'.
15901 std::optional<FunctionEffectWithCondition>
15902 New; // Invalid when 'Kind' is 'Removed'.
15903
15904 StringRef effectName() const {
15905 if (Old)
15906 return Old.value().Effect.name();
15907 return New.value().Effect.name();
15908 }
15909
15910 /// Describes the result of effects differing between a base class's virtual
15911 /// method and an overriding method in a subclass.
15912 enum class OverrideResult {
15913 NoAction,
15914 Warn,
15915 Merge // Merge missing effect from base to derived.
15916 };
15917
15918 /// Return true if adding or removing the effect as part of a type
15919 /// conversion should generate a diagnostic.
15920 bool shouldDiagnoseConversion(QualType SrcType,
15921 const FunctionEffectsRef &SrcFX,
15922 QualType DstType,
15923 const FunctionEffectsRef &DstFX) const;
15924
15925 /// Return true if adding or removing the effect in a redeclaration should
15926 /// generate a diagnostic.
15927 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
15928 const FunctionEffectsRef &OldFX,
15929 const FunctionDecl &NewFunction,
15930 const FunctionEffectsRef &NewFX) const;
15931
15932 /// Return true if adding or removing the effect in a C++ virtual method
15933 /// override should generate a diagnostic.
15934 OverrideResult shouldDiagnoseMethodOverride(
15935 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
15936 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
15937 };
15938
15939 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
15940 /// Caller should short-circuit by checking for equality first.
15941 FunctionEffectDiffVector(const FunctionEffectsRef &Old,
15942 const FunctionEffectsRef &New);
15943 };
15944
15945 /// All functions/lambdas/blocks which have bodies and which have a non-empty
15946 /// FunctionEffectsRef to be verified.
15947 SmallVector<const Decl *> DeclsWithEffectsToVerify;
15948
15949 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
15950 /// are all null.
15951 FunctionEffectKindSet AllEffectsToVerify;
15952
15953public:
15954 /// Warn and return true if adding a function effect to a set would create a
15955 /// conflict.
15956 bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX,
15957 const FunctionEffectWithCondition &EC,
15958 SourceLocation NewAttrLoc);
15959
15960 // Report a failure to merge function effects between declarations due to a
15961 // conflict.
15962 void
15963 diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs,
15964 SourceLocation NewLoc,
15965 SourceLocation OldLoc);
15966
15967 /// Inline checks from the start of maybeAddDeclWithEffects, to
15968 /// minimize performance impact on code not using effects.
15969 template <class FuncOrBlockDecl>
15970 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
15971 if (Context.hasAnyFunctionEffects())
15972 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
15973 maybeAddDeclWithEffects(D, FX);
15974 }
15975
15976 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
15977 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15978
15979 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
15980 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15981
15982 void performFunctionEffectAnalysis(TranslationUnitDecl *TU);
15983
15984 ///@}
15985
15986 //
15987 //
15988 // -------------------------------------------------------------------------
15989 //
15990 //
15991
15992 /// \name Expansion Statements
15993 /// Implementations are in SemaExpand.cpp
15994 ///@{
15995public:
15996 CXXExpansionStmtDecl *ActOnCXXExpansionStmtDecl(unsigned TemplateDepth,
15997 SourceLocation TemplateKWLoc);
15998
15999 CXXExpansionStmtDecl *
16000 BuildCXXExpansionStmtDecl(DeclContext *Ctx, SourceLocation TemplateKWLoc,
16001 NonTypeTemplateParmDecl *NTTP);
16002
16003 ExprResult ActOnCXXExpansionInitList(MultiExprArg SubExprs,
16004 SourceLocation LBraceLoc,
16005 SourceLocation RBraceLoc);
16006
16007 StmtResult ActOnCXXExpansionStmtPattern(
16008 CXXExpansionStmtDecl *ESD, Stmt *Init, Stmt *ExpansionVarStmt,
16009 Expr *ExpansionInitializer, SourceLocation LParenLoc,
16010 SourceLocation ColonLoc, SourceLocation RParenLoc,
16011 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps);
16012
16013 StmtResult FinishCXXExpansionStmt(Stmt *Expansion, Stmt *Body);
16014
16015 StmtResult BuildCXXEnumeratingExpansionStmtPattern(Decl *ESD, Stmt *Init,
16016 Stmt *ExpansionVar,
16017 SourceLocation LParenLoc,
16018 SourceLocation ColonLoc,
16019 SourceLocation RParenLoc);
16020
16021 StmtResult BuildNonEnumeratingCXXExpansionStmtPattern(
16022 CXXExpansionStmtDecl *ESD, Stmt *Init, DeclStmt *ExpansionVarStmt,
16023 Expr *ExpansionInitializer, SourceLocation LParenLoc,
16024 SourceLocation ColonLoc, SourceLocation RParenLoc,
16025 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
16026
16027 ExprResult BuildCXXExpansionSelectExpr(InitListExpr *Range, Expr *Idx);
16028
16029 std::optional<uint64_t>
16030 ComputeExpansionSize(CXXExpansionStmtPattern *Expansion);
16031 ///@}
16032};
16033
16034DeductionFailureInfo
16035MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK,
16036 sema::TemplateDeductionInfo &Info);
16037
16038/// Contains a late templated function.
16039/// Will be parsed at the end of the translation unit, used by Sema & Parser.
16040struct LateParsedTemplate {
16041 CachedTokens Toks;
16042 /// The template function declaration to be late parsed.
16043 Decl *D;
16044 /// Floating-point options in the point of definition.
16045 FPOptions FPO;
16046};
16047
16048template <>
16049void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
16050 PragmaMsStackAction Action,
16051 llvm::StringRef StackSlotLabel,
16052 AlignPackInfo Value);
16053
16054} // end namespace clang
16055
16056#endif
16057