1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/APINotes/APINotesManager.h"
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/ASTLambda.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/AttrIterator.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/DeclBase.h"
24#include "clang/AST/DeclCXX.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/DeclarationName.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprConcepts.h"
30#include "clang/AST/ExternalASTSource.h"
31#include "clang/AST/NestedNameSpecifier.h"
32#include "clang/AST/OperationKinds.h"
33#include "clang/AST/StmtCXX.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
36#include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h"
37#include "clang/Basic/AttrSubjectMatchRules.h"
38#include "clang/Basic/BuiltinTraits.h"
39#include "clang/Basic/Builtins.h"
40#include "clang/Basic/CapturedStmt.h"
41#include "clang/Basic/Cuda.h"
42#include "clang/Basic/DiagnosticSema.h"
43#include "clang/Basic/ExceptionSpecificationType.h"
44#include "clang/Basic/LLVM.h"
45#include "clang/Basic/Lambda.h"
46#include "clang/Basic/LangOptions.h"
47#include "clang/Basic/Module.h"
48#include "clang/Basic/OpenCLOptions.h"
49#include "clang/Basic/OperatorKinds.h"
50#include "clang/Basic/PartialDiagnostic.h"
51#include "clang/Basic/PragmaKinds.h"
52#include "clang/Basic/SourceLocation.h"
53#include "clang/Basic/Specifiers.h"
54#include "clang/Basic/StackExhaustionHandler.h"
55#include "clang/Basic/TemplateKinds.h"
56#include "clang/Basic/TokenKinds.h"
57#include "clang/Sema/AnalysisBasedWarnings.h"
58#include "clang/Sema/Attr.h"
59#include "clang/Sema/CleanupInfo.h"
60#include "clang/Sema/DeclSpec.h"
61#include "clang/Sema/ExternalSemaSource.h"
62#include "clang/Sema/IdentifierResolver.h"
63#include "clang/Sema/Ownership.h"
64#include "clang/Sema/ParsedAttr.h"
65#include "clang/Sema/Redeclaration.h"
66#include "clang/Sema/Scope.h"
67#include "clang/Sema/SemaBase.h"
68#include "clang/Sema/SemaConcept.h"
69#include "clang/Sema/TypoCorrection.h"
70#include "clang/Sema/Weak.h"
71#include "llvm/ADT/APInt.h"
72#include "llvm/ADT/ArrayRef.h"
73#include "llvm/ADT/BitmaskEnum.h"
74#include "llvm/ADT/DenseMap.h"
75#include "llvm/ADT/DenseSet.h"
76#include "llvm/ADT/FloatingPointMode.h"
77#include "llvm/ADT/FoldingSet.h"
78#include "llvm/ADT/MapVector.h"
79#include "llvm/ADT/PointerIntPair.h"
80#include "llvm/ADT/PointerUnion.h"
81#include "llvm/ADT/STLExtras.h"
82#include "llvm/ADT/STLForwardCompat.h"
83#include "llvm/ADT/STLFunctionalExtras.h"
84#include "llvm/ADT/SetVector.h"
85#include "llvm/ADT/SmallBitVector.h"
86#include "llvm/ADT/SmallPtrSet.h"
87#include "llvm/ADT/SmallSet.h"
88#include "llvm/ADT/SmallVector.h"
89#include "llvm/ADT/StringExtras.h"
90#include "llvm/ADT/StringMap.h"
91#include "llvm/ADT/TinyPtrVector.h"
92#include "llvm/Support/Allocator.h"
93#include "llvm/Support/Compiler.h"
94#include "llvm/Support/Error.h"
95#include "llvm/Support/ErrorHandling.h"
96#include <cassert>
97#include <climits>
98#include <cstddef>
99#include <cstdint>
100#include <deque>
101#include <functional>
102#include <iterator>
103#include <memory>
104#include <optional>
105#include <string>
106#include <tuple>
107#include <type_traits>
108#include <utility>
109#include <vector>
110
111namespace llvm {
112struct InlineAsmIdentifierInfo;
113} // namespace llvm
114
115namespace clang {
116class ADLResult;
117class APValue;
118struct ASTConstraintSatisfaction;
119class ASTConsumer;
120class ASTContext;
121class ASTDeclReader;
122class ASTMutationListener;
123class ASTReader;
124class ASTWriter;
125class CXXBasePath;
126class CXXBasePaths;
127class CXXFieldCollector;
128class CodeCompleteConsumer;
129enum class ComparisonCategoryType : unsigned char;
130class ConstraintSatisfaction;
131class DarwinSDKInfo;
132class DeclGroupRef;
133class DeducedTemplateArgument;
134struct DeductionFailureInfo;
135class DependentDiagnostic;
136class Designation;
137class IdentifierInfo;
138struct ImplicitAllocationArguments;
139class ImplicitConversionSequence;
140typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
141class InitializationKind;
142class InitializationSequence;
143class InitializedEntity;
144enum class LangAS : unsigned int;
145class LocalInstantiationScope;
146class LookupResult;
147class MangleNumberingContext;
148typedef ArrayRef<IdentifierLoc> ModuleIdPath;
149class ModuleLoader;
150class MultiLevelTemplateArgumentList;
151struct NormalizedConstraint;
152class ObjCInterfaceDecl;
153class ObjCMethodDecl;
154struct OverloadCandidate;
155enum class OverloadCandidateParamOrder : char;
156enum OverloadCandidateRewriteKind : unsigned;
157class OverloadCandidateSet;
158class Preprocessor;
159struct APINotesSelectorDiagnosticState;
160struct ResolvedAllocation;
161class SemaAMDGPU;
162class SemaARM;
163class SemaAVR;
164class SemaBPF;
165class SemaCodeCompletion;
166class SemaCUDA;
167class SemaDirectX;
168class SemaHLSL;
169class SemaHexagon;
170class SemaLoongArch;
171class SemaM68k;
172class SemaMIPS;
173class SemaMSP430;
174class SemaNVPTX;
175class SemaObjC;
176class SemaOpenACC;
177class SemaOpenCL;
178class SemaOpenMP;
179class SemaPPC;
180class SemaPseudoObject;
181class SemaRISCV;
182class SemaSPIRV;
183class SemaSYCL;
184class SemaSwift;
185class SemaSystemZ;
186class SemaWasm;
187class SemaX86;
188class StandardConversionSequence;
189class TemplateArgument;
190class TemplateArgumentLoc;
191class TemplateInstantiationCallback;
192class TemplatePartialOrderingContext;
193class TemplateSpecCandidateSet;
194class Token;
195class TypeConstraint;
196class TypoCorrectionConsumer;
197class UnresolvedSetImpl;
198class UnresolvedSetIterator;
199class VisibleDeclConsumer;
200
201namespace sema {
202class BlockScopeInfo;
203class Capture;
204class CapturedRegionScopeInfo;
205class CapturingScopeInfo;
206class CompoundScopeInfo;
207class DelayedDiagnostic;
208class DelayedDiagnosticPool;
209class FunctionScopeInfo;
210class LambdaScopeInfo;
211class SemaPPCallbacks;
212class TemplateDeductionInfo;
213} // namespace sema
214
215// AssignmentAction - This is used by all the assignment diagnostic functions
216// to represent what is actually causing the operation
217enum class AssignmentAction {
218 Assigning,
219 Passing,
220 Returning,
221 Converting,
222 Initializing,
223 Sending,
224 Casting,
225 Passing_CFAudited
226};
227
228// Inline capacity for type-aware, aligned, and unaligned allocation argument
229// list candidates.
230using AllocationArgumentSet = SmallVector<ImplicitAllocationArguments, 3>;
231
232namespace threadSafety {
233class BeforeSet;
234void threadSafetyCleanup(BeforeSet *Cache);
235} // namespace threadSafety
236
237// FIXME: No way to easily map from TemplateTypeParmTypes to
238// TemplateTypeParmDecls, so we have this horrible PointerUnion.
239typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *,
240 const TemplateSpecializationType *,
241 const SubstBuiltinTemplatePackType *>,
242 SourceLocation>
243 UnexpandedParameterPack;
244
245/// Describes whether we've seen any nullability information for the given
246/// file.
247struct FileNullability {
248 /// The first pointer declarator (of any pointer kind) in the file that does
249 /// not have a corresponding nullability annotation.
250 SourceLocation PointerLoc;
251
252 /// The end location for the first pointer declarator in the file. Used for
253 /// placing fix-its.
254 SourceLocation PointerEndLoc;
255
256 /// Which kind of pointer declarator we saw.
257 uint8_t PointerKind;
258
259 /// Whether we saw any type nullability annotations in the given file.
260 bool SawTypeNullability = false;
261};
262
263/// A mapping from file IDs to a record of whether we've seen nullability
264/// information in that file.
265class FileNullabilityMap {
266 /// A mapping from file IDs to the nullability information for each file ID.
267 llvm::DenseMap<FileID, FileNullability> Map;
268
269 /// A single-element cache based on the file ID.
270 struct {
271 FileID File;
272 FileNullability Nullability;
273 } Cache;
274
275public:
276 FileNullability &operator[](FileID file) {
277 // Check the single-element cache.
278 if (file == Cache.File)
279 return Cache.Nullability;
280
281 // It's not in the single-element cache; flush the cache if we have one.
282 if (!Cache.File.isInvalid()) {
283 Map[Cache.File] = Cache.Nullability;
284 }
285
286 // Pull this entry into the cache.
287 Cache.File = file;
288 Cache.Nullability = Map[file];
289 return Cache.Nullability;
290 }
291};
292
293/// Tracks expected type during expression parsing, for use in code completion.
294/// The type is tied to a particular token, all functions that update or consume
295/// the type take a start location of the token they are looking at as a
296/// parameter. This avoids updating the type on hot paths in the parser.
297class PreferredTypeBuilder {
298public:
299 PreferredTypeBuilder(ASTContext *Ctx, bool Enabled)
300 : Ctx(Ctx), Enabled(Enabled) {}
301
302 void enterCondition(Sema &S, SourceLocation Tok);
303 void enterReturn(Sema &S, SourceLocation Tok);
304 void enterVariableInit(SourceLocation Tok, Decl *D);
305 /// Handles e.g. BaseType{ .D = Tok...
306 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
307 const Designation &D);
308 /// Computing a type for the function argument may require running
309 /// overloading, so we postpone its computation until it is actually needed.
310 ///
311 /// Clients should be very careful when using this function, as it stores a
312 /// function_ref, clients should make sure all calls to get() with the same
313 /// location happen while function_ref is alive.
314 ///
315 /// The callback should also emit signature help as a side-effect, but only
316 /// if the completion point has been reached.
317 void enterFunctionArgument(SourceLocation Tok,
318 llvm::function_ref<QualType()> ComputeType);
319
320 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
321 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
322 SourceLocation OpLoc);
323 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
324 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
325 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
326 /// Handles all type casts, including C-style cast, C++ casts, etc.
327 void enterTypeCast(SourceLocation Tok, QualType CastType);
328
329 /// Get the expected type associated with this location, if any.
330 ///
331 /// If the location is a function argument, determining the expected type
332 /// involves considering all function overloads and the arguments so far.
333 /// In this case, signature help for these function overloads will be reported
334 /// as a side-effect (only if the completion point has been reached).
335 QualType get(SourceLocation Tok) const {
336 if (!Enabled || Tok != ExpectedLoc)
337 return QualType();
338 if (!Type.isNull())
339 return Type;
340 if (ComputeType)
341 return ComputeType();
342 return QualType();
343 }
344
345private:
346 ASTContext *Ctx;
347 bool Enabled;
348 /// Start position of a token for which we store expected type.
349 SourceLocation ExpectedLoc;
350 /// Expected type for a token starting at ExpectedLoc.
351 QualType Type;
352 /// A function to compute expected type at ExpectedLoc. It is only considered
353 /// if Type is null.
354 llvm::function_ref<QualType()> ComputeType;
355};
356
357struct SkipBodyInfo {
358 SkipBodyInfo() = default;
359 bool ShouldSkip = false;
360 bool CheckSameAsPrevious = false;
361 NamedDecl *Previous = nullptr;
362 NamedDecl *New = nullptr;
363};
364
365/// Describes the result of template argument deduction.
366///
367/// The TemplateDeductionResult enumeration describes the result of
368/// template argument deduction, as returned from
369/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
370/// structure provides additional information about the results of
371/// template argument deduction, e.g., the deduced template argument
372/// list (if successful) or the specific template parameters or
373/// deduced arguments that were involved in the failure.
374enum class TemplateDeductionResult {
375 /// Template argument deduction was successful.
376 Success = 0,
377 /// The declaration was invalid; do nothing.
378 Invalid,
379 /// Template argument deduction exceeded the maximum template
380 /// instantiation depth (which has already been diagnosed).
381 InstantiationDepth,
382 /// Template argument deduction did not deduce a value
383 /// for every template parameter.
384 Incomplete,
385 /// Template argument deduction did not deduce a value for every
386 /// expansion of an expanded template parameter pack.
387 IncompletePack,
388 /// Template argument deduction produced inconsistent
389 /// deduced values for the given template parameter.
390 Inconsistent,
391 /// Template argument deduction failed due to inconsistent
392 /// cv-qualifiers on a template parameter type that would
393 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
394 /// but were given a non-const "X".
395 Underqualified,
396 /// Substitution of the deduced template argument values
397 /// resulted in an error.
398 SubstitutionFailure,
399 /// After substituting deduced template arguments, a dependent
400 /// parameter type did not match the corresponding argument.
401 DeducedMismatch,
402 /// After substituting deduced template arguments, an element of
403 /// a dependent parameter type did not match the corresponding element
404 /// of the corresponding argument (when deducing from an initializer list).
405 DeducedMismatchNested,
406 /// A non-depnedent component of the parameter did not match the
407 /// corresponding component of the argument.
408 NonDeducedMismatch,
409 /// When performing template argument deduction for a function
410 /// template, there were too many call arguments.
411 TooManyArguments,
412 /// When performing template argument deduction for a function
413 /// template, there were too few call arguments.
414 TooFewArguments,
415 /// The explicitly-specified template arguments were not valid
416 /// template arguments for the given template.
417 InvalidExplicitArguments,
418 /// Checking non-dependent argument conversions failed.
419 NonDependentConversionFailure,
420 /// The deduced arguments did not satisfy the constraints associated
421 /// with the template.
422 ConstraintsNotSatisfied,
423 /// Deduction failed; that's all we know.
424 MiscellaneousDeductionFailure,
425 /// CUDA Target attributes do not match.
426 CUDATargetMismatch,
427 /// Some error which was already diagnosed.
428 AlreadyDiagnosed
429};
430
431/// The kind of conversion being performed.
432enum class CheckedConversionKind {
433 /// An implicit conversion.
434 Implicit,
435 /// A C-style cast.
436 CStyleCast,
437 /// A functional-style cast.
438 FunctionalCast,
439 /// A cast other than a C-style cast.
440 OtherCast,
441 /// A conversion for an operand of a builtin overloaded operator.
442 ForBuiltinOverloadedOp
443};
444
445enum class TagUseKind {
446 Reference, // Reference to a tag: 'struct foo *X;'
447 Declaration, // Fwd decl of a tag: 'struct foo;'
448 Definition, // Definition of a tag: 'struct foo { int X; } Y;'
449 Friend // Friend declaration: 'friend struct foo;'
450};
451
452/// Used with attributes/effects with a boolean condition, e.g. `nonblocking`.
453enum class FunctionEffectMode : uint8_t {
454 None, // effect is not present.
455 False, // effect(false).
456 True, // effect(true).
457 Dependent // effect(expr) where expr is dependent.
458};
459
460/// pragma clang section kind
461enum class PragmaClangSectionKind {
462 Invalid = 0,
463 BSS = 1,
464 Data = 2,
465 Rodata = 3,
466 Text = 4,
467 Relro = 5
468};
469
470enum class PragmaClangSectionAction { Set = 0, Clear = 1 };
471
472enum class PragmaOptionsAlignKind {
473 Native, // #pragma options align=native
474 Natural, // #pragma options align=natural
475 Packed, // #pragma options align=packed
476 Power, // #pragma options align=power
477 Mac68k, // #pragma options align=mac68k
478 Reset // #pragma options align=reset
479};
480
481enum class TUFragmentKind {
482 /// The global module fragment, between 'module;' and a module-declaration.
483 Global,
484 /// A normal translation unit fragment. For a non-module unit, this is the
485 /// entire translation unit. Otherwise, it runs from the module-declaration
486 /// to the private-module-fragment (if any) or the end of the TU (if not).
487 Normal,
488 /// The private module fragment, between 'module :private;' and the end of
489 /// the translation unit.
490 Private
491};
492
493enum class FormatStringType {
494 Scanf,
495 Printf,
496 NSString,
497 Strftime,
498 Strfmon,
499 Kprintf,
500 FreeBSDKPrintf,
501 OSTrace,
502 OSLog,
503 Unknown
504};
505
506// Used for emitting the right warning by DefaultVariadicArgumentPromotion
507enum class VariadicCallType {
508 Function,
509 Block,
510 Method,
511 Constructor,
512 DoesNotApply
513};
514
515enum class BuiltinCountedByRefKind {
516 Assignment,
517 Initializer,
518 FunctionArg,
519 ReturnArg,
520 ArraySubscript,
521 BinaryExpr,
522};
523
524// Contexts where using non-trivial C union types can be disallowed. This is
525// passed to err_non_trivial_c_union_in_invalid_context.
526enum class NonTrivialCUnionContext {
527 // Function parameter.
528 FunctionParam,
529 // Function return.
530 FunctionReturn,
531 // Default-initialized object.
532 DefaultInitializedObject,
533 // Variable with automatic storage duration.
534 AutoVar,
535 // Initializer expression that might copy from another object.
536 CopyInit,
537 // Assignment.
538 Assignment,
539 // Compound literal.
540 CompoundLiteral,
541 // Block capture.
542 BlockCapture,
543 // lvalue-to-rvalue conversion of volatile type.
544 LValueToRValueVolatile,
545};
546
547/// Describes the result of the name lookup and resolution performed
548/// by \c Sema::ClassifyName().
549enum class NameClassificationKind {
550 /// This name is not a type or template in this context, but might be
551 /// something else.
552 Unknown,
553 /// Classification failed; an error has been produced.
554 Error,
555 /// The name has been typo-corrected to a keyword.
556 Keyword,
557 /// The name was classified as a type.
558 Type,
559 /// The name was classified as a specific non-type, non-template
560 /// declaration. ActOnNameClassifiedAsNonType should be called to
561 /// convert the declaration to an expression.
562 NonType,
563 /// The name was classified as an ADL-only function name.
564 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
565 /// result to an expression.
566 UndeclaredNonType,
567 /// The name denotes a member of a dependent type that could not be
568 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
569 /// convert the result to an expression.
570 DependentNonType,
571 /// The name was classified as an overload set, and an expression
572 /// representing that overload set has been formed.
573 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
574 /// expression referencing the overload set.
575 OverloadSet,
576 /// The name was classified as a template whose specializations are types.
577 TypeTemplate,
578 /// The name was classified as a variable template name.
579 VarTemplate,
580 /// The name was classified as a function template name.
581 FunctionTemplate,
582 /// The name was classified as an ADL-only function template name.
583 UndeclaredTemplate,
584 /// The name was classified as a concept name.
585 Concept,
586};
587
588enum class PointerAuthDiscArgKind {
589 // Address discrimination argument of __ptrauth.
590 Addr,
591
592 // Extra discriminator argument of __ptrauth.
593 Extra,
594};
595
596/// Common ways to introduce type names without a tag for use in diagnostics.
597/// Keep in sync with err_tag_reference_non_tag.
598enum class NonTagKind {
599 NonStruct,
600 NonClass,
601 NonUnion,
602 NonEnum,
603 Typedef,
604 TypeAlias,
605 Template,
606 TypeAliasTemplate,
607 TemplateTemplateArgument,
608};
609
610enum class OffsetOfKind {
611 // Not parsing a type within __builtin_offsetof.
612 Outside,
613 // Parsing a type within __builtin_offsetof.
614 Builtin,
615 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
616 // To improve our diagnostic message.
617 Macro,
618};
619
620/// Describes the kind of merge to perform for availability
621/// attributes (including "deprecated", "unavailable", and "availability").
622enum class AvailabilityMergeKind {
623 /// Don't merge availability attributes at all.
624 None,
625 /// Merge availability attributes for a redeclaration, which requires
626 /// an exact match.
627 Redeclaration,
628 /// Merge availability attributes for an override, which requires
629 /// an exact match or a weakening of constraints.
630 Override,
631 /// Merge availability attributes for an implementation of
632 /// a protocol requirement.
633 ProtocolImplementation,
634 /// Merge availability attributes for an implementation of
635 /// an optional protocol requirement.
636 OptionalProtocolImplementation
637};
638
639enum class TrivialABIHandling {
640 /// The triviality of a method unaffected by "trivial_abi".
641 IgnoreTrivialABI,
642
643 /// The triviality of a method affected by "trivial_abi".
644 ConsiderTrivialABI
645};
646
647enum class TryCaptureKind { Implicit, ExplicitByVal, ExplicitByRef };
648
649enum class AllowFoldKind {
650 No,
651 Allow,
652};
653
654/// Context in which we're performing a usual arithmetic conversion.
655enum class ArithConvKind {
656 /// An arithmetic operation.
657 Arithmetic,
658 /// A bitwise operation.
659 BitwiseOp,
660 /// A comparison.
661 Comparison,
662 /// A conditional (?:) operator.
663 Conditional,
664 /// A compound assignment expression.
665 CompAssign,
666};
667
668// Used for determining in which context a type is allowed to be passed to a
669// vararg function.
670enum class VarArgKind {
671 Valid,
672 ValidInCXX11,
673 Undefined,
674 MSVCUndefined,
675 Invalid
676};
677
678/// AssignConvertType - All of the 'assignment' semantic checks return this
679/// enum to indicate whether the assignment was allowed. These checks are
680/// done for simple assignments, as well as initialization, return from
681/// function, argument passing, etc. The query is phrased in terms of a
682/// source and destination type.
683enum class AssignConvertType {
684 /// Compatible - the types are compatible according to the standard.
685 Compatible,
686
687 /// CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because
688 /// a void * can implicitly convert to another pointer type, which we
689 /// differentiate for better diagnostic behavior.
690 CompatibleVoidPtrToNonVoidPtr,
691
692 /// PointerToInt - The assignment converts a pointer to an int, which we
693 /// accept as an extension.
694 PointerToInt,
695
696 /// IntToPointer - The assignment converts an int to a pointer, which we
697 /// accept as an extension.
698 IntToPointer,
699
700 /// FunctionVoidPointer - The assignment is between a function pointer and
701 /// void*, which the standard doesn't allow, but we accept as an extension.
702 FunctionVoidPointer,
703
704 /// IncompatiblePointer - The assignment is between two pointers types that
705 /// are not compatible, but we accept them as an extension.
706 IncompatiblePointer,
707
708 /// IncompatibleFunctionPointer - The assignment is between two function
709 /// pointers types that are not compatible, but we accept them as an
710 /// extension.
711 IncompatibleFunctionPointer,
712
713 /// IncompatibleFunctionPointerStrict - The assignment is between two
714 /// function pointer types that are not identical, but are compatible,
715 /// unless compiled with -fsanitize=cfi, in which case the type mismatch
716 /// may trip an indirect call runtime check.
717 IncompatibleFunctionPointerStrict,
718
719 /// IncompatiblePointerSign - The assignment is between two pointers types
720 /// which point to integers which have a different sign, but are otherwise
721 /// identical. This is a subset of the above, but broken out because it's by
722 /// far the most common case of incompatible pointers.
723 IncompatiblePointerSign,
724
725 /// CompatiblePointerDiscardsQualifiers - The assignment discards
726 /// c/v/r qualifiers, which we accept as an extension.
727 CompatiblePointerDiscardsQualifiers,
728
729 /// IncompatiblePointerDiscardsQualifiers - The assignment
730 /// discards qualifiers that we don't permit to be discarded,
731 /// like address spaces.
732 IncompatiblePointerDiscardsQualifiers,
733
734 /// IncompatiblePointerDiscardsOverflowBehavior - The assignment
735 /// discards overflow behavior annotations between otherwise compatible
736 /// pointer types.
737 IncompatiblePointerDiscardsOverflowBehavior,
738
739 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
740 /// changes address spaces in nested pointer types which is not allowed.
741 /// For instance, converting __private int ** to __generic int ** is
742 /// illegal even though __private could be converted to __generic.
743 IncompatibleNestedPointerAddressSpaceMismatch,
744
745 /// IncompatibleNestedPointerQualifiers - The assignment is between two
746 /// nested pointer types, and the qualifiers other than the first two
747 /// levels differ e.g. char ** -> const char **, but we accept them as an
748 /// extension.
749 IncompatibleNestedPointerQualifiers,
750
751 /// IncompatibleVectors - The assignment is between two vector types that
752 /// have the same size, which we accept as an extension.
753 IncompatibleVectors,
754
755 /// IntToBlockPointer - The assignment converts an int to a block
756 /// pointer. We disallow this.
757 IntToBlockPointer,
758
759 /// IncompatibleBlockPointer - The assignment is between two block
760 /// pointers types that are not compatible.
761 IncompatibleBlockPointer,
762
763 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
764 /// id type and something else (that is incompatible with it). For example,
765 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
766 IncompatibleObjCQualifiedId,
767
768 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
769 /// object with __weak qualifier.
770 IncompatibleObjCWeakRef,
771
772 /// IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType
773 /// kinds, e.g., from __ob_trap to __ob_wrap or vice versa.
774 IncompatibleOBTKinds,
775
776 /// CompatibleOBTDiscards - Assignment discards overflow behavior
777 CompatibleOBTDiscards,
778
779 /// Incompatible - We reject this conversion outright, it is invalid to
780 /// represent it in the AST.
781 Incompatible
782};
783
784/// The scope in which to find allocation functions.
785enum class AllocationFunctionScope {
786 /// Only look for allocation functions in the global scope.
787 Global,
788 /// Only look for allocation functions in the scope of the
789 /// allocated class.
790 Class,
791 /// Look for allocation functions in both the global scope
792 /// and in the scope of the allocated class.
793 Both
794};
795
796/// Describes the result of an "if-exists" condition check.
797enum class IfExistsResult {
798 /// The symbol exists.
799 Exists,
800
801 /// The symbol does not exist.
802 DoesNotExist,
803
804 /// The name is a dependent name, so the results will differ
805 /// from one instantiation to the next.
806 Dependent,
807
808 /// An error occurred.
809 Error
810};
811
812enum class CorrectTypoKind {
813 NonError, // CorrectTypo used in a non error recovery situation.
814 ErrorRecovery // CorrectTypo used in normal error recovery.
815};
816
817enum class OverloadKind {
818 /// This is a legitimate overload: the existing declarations are
819 /// functions or function templates with different signatures.
820 Overload,
821
822 /// This is not an overload because the signature exactly matches
823 /// an existing declaration.
824 Match,
825
826 /// This is not an overload because the lookup results contain a
827 /// non-function.
828 NonFunction
829};
830
831/// Contexts in which a converted constant expression is required.
832enum class CCEKind {
833 CaseValue, ///< Expression in a case label.
834 Enumerator, ///< Enumerator value with fixed underlying type.
835 TemplateArg, ///< Value of a non-type template parameter.
836 TempArgStrict, ///< As above, but applies strict template checking
837 ///< rules.
838 ArrayBound, ///< Array bound in array declarator or new-expression.
839 ExplicitBool, ///< Condition in an explicit(bool) specifier.
840 Noexcept, ///< Condition in a noexcept(bool) specifier.
841 StaticAssertMessageSize, ///< Call to size() in a static assert
842 ///< message.
843 StaticAssertMessageData, ///< Call to data() in a static assert
844 ///< message.
845 PackIndex ///< Index of a pack indexing expression or specifier.
846};
847
848/// Enums for the diagnostics of target, target_version and target_clones.
849namespace DiagAttrParams {
850enum DiagType { Unsupported, Duplicate, Unknown };
851enum Specifier { None, CPU, Tune };
852enum AttrName { Target, TargetClones, TargetVersion };
853} // end namespace DiagAttrParams
854
855void inferNoReturnAttr(Sema &S, Decl *D);
856
857#ifdef __GNUC__
858#pragma GCC diagnostic push
859#pragma GCC diagnostic ignored "-Wattributes"
860#endif
861/// Sema - This implements semantic analysis and AST building for C.
862/// \nosubgrouping
863class Sema final : public SemaBase {
864#ifdef __GNUC__
865#pragma GCC diagnostic pop
866#endif
867 // Table of Contents
868 // -----------------
869 // 1. Semantic Analysis (Sema.cpp)
870 // 2. API Notes (SemaAPINotes.cpp)
871 // 3. C++ Access Control (SemaAccess.cpp)
872 // 4. Attributes (SemaAttr.cpp)
873 // 5. Availability Attribute Handling (SemaAvailability.cpp)
874 // 6. Bounds Safety (SemaBoundsSafety.cpp)
875 // 7. Casts (SemaCast.cpp)
876 // 8. Extra Semantic Checking (SemaChecking.cpp)
877 // 9. C++ Coroutines (SemaCoroutine.cpp)
878 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
879 // 11. Declarations (SemaDecl.cpp)
880 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
881 // 13. C++ Declarations (SemaDeclCXX.cpp)
882 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
883 // 15. Expressions (SemaExpr.cpp)
884 // 16. C++ Expressions (SemaExprCXX.cpp)
885 // 17. Member Access Expressions (SemaExprMember.cpp)
886 // 18. Initializers (SemaInit.cpp)
887 // 19. C++ Lambda Expressions (SemaLambda.cpp)
888 // 20. Name Lookup (SemaLookup.cpp)
889 // 21. Modules (SemaModule.cpp)
890 // 22. C++ Overloading (SemaOverload.cpp)
891 // 23. Statements (SemaStmt.cpp)
892 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
893 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
894 // 26. C++ Templates (SemaTemplate.cpp)
895 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
896 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
897 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
898 // 30. C++ Template Declaration Instantiation
899 // (SemaTemplateInstantiateDecl.cpp)
900 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
901 // 32. Constraints and Concepts (SemaConcept.cpp)
902 // 33. Types (SemaType.cpp)
903 // 34. FixIt Helpers (SemaFixItUtils.cpp)
904 // 35. Function Effects (SemaFunctionEffects.cpp)
905 // 36. C++ Expansion Statements (SemaExpand.cpp)
906
907 /// \name Semantic Analysis
908 /// Implementations are in Sema.cpp
909 ///@{
910
911public:
912 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
913 TranslationUnitKind TUKind = TU_Complete,
914 CodeCompleteConsumer *CompletionConsumer = nullptr);
915 ~Sema();
916
917 /// Perform initialization that occurs after the parser has been
918 /// initialized but before it parses anything.
919 void Initialize();
920
921 /// This virtual key function only exists to limit the emission of debug info
922 /// describing the Sema class. GCC and Clang only emit debug info for a class
923 /// with a vtable when the vtable is emitted. Sema is final and not
924 /// polymorphic, but the debug info size savings are so significant that it is
925 /// worth adding a vtable just to take advantage of this optimization.
926 LLVM_DECLARE_VIRTUAL_ANCHOR_FUNCTION();
927
928 const LangOptions &getLangOpts() const { return LangOpts; }
929 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
930 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
931
932 DiagnosticsEngine &getDiagnostics() const { return Diags; }
933 SourceManager &getSourceManager() const { return SourceMgr; }
934 Preprocessor &getPreprocessor() const { return PP; }
935 ASTContext &getASTContext() const { return Context; }
936 ASTConsumer &getASTConsumer() const { return Consumer; }
937 ASTMutationListener *getASTMutationListener() const;
938 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
939
940 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
941 StringRef Platform);
942 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
943
944 /// Registers an external source. If an external source already exists,
945 /// creates a multiplex external source and appends to it.
946 ///
947 ///\param[in] E - A non-null external sema source.
948 ///
949 void addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E);
950
951 /// Print out statistics about the semantic analysis.
952 void PrintStats() const;
953
954 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
955 /// guaranteed). Produces a warning if we're low on stack space and allocates
956 /// more in that case. Use this in code that may recurse deeply (for example,
957 /// in template instantiation) to avoid stack overflow.
958 void runWithSufficientStackSpace(SourceLocation Loc,
959 llvm::function_ref<void()> Fn);
960
961 /// Returns default addr space for method qualifiers.
962 LangAS getDefaultCXXMethodAddrSpace() const;
963
964 /// Load weak undeclared identifiers from the external source.
965 void LoadExternalWeakUndeclaredIdentifiers();
966
967 /// Load #pragma redefine_extname'd undeclared identifiers from the external
968 /// source.
969 void LoadExternalExtnameUndeclaredIdentifiers();
970
971 /// Determine if VD, which must be a variable or function, is an external
972 /// symbol that nonetheless can't be referenced from outside this translation
973 /// unit because its type has no linkage and it's not extern "C".
974 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
975
976 /// Determines whether the given source location is in the main file
977 /// and we're in a context where we should warn about unused entities.
978 bool isMainFileLoc(SourceLocation Loc) const;
979
980 /// Obtain a sorted list of functions that are undefined but ODR-used.
981 void getUndefinedButUsed(
982 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
983
984 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
985 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
986 /// Retrieves list of suspicious delete-expressions that will be checked at
987 /// the end of translation unit.
988 const llvm::MapVector<FieldDecl *, DeleteLocs> &
989 getMismatchingDeleteExpressions() const;
990
991 /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
992 /// This is closely coupled to the SemaDiagnosticBuilder class and
993 /// should not be used elsewhere.
994 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
995
996 void addImplicitTypedef(StringRef Name, QualType T);
997
998 /// Whether uncompilable error has occurred. This includes error happens
999 /// in deferred diagnostics.
1000 bool hasUncompilableErrorOccurred() const;
1001
1002 /// Looks through the macro-expansion chain for the given
1003 /// location, looking for a macro expansion with the given name.
1004 /// If one is found, returns true and sets the location to that
1005 /// expansion loc.
1006 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1007
1008 /// Calls \c Lexer::getLocForEndOfToken()
1009 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1010
1011 /// Calls \c Lexer::findNextToken() to find the next token, and if the
1012 /// locations of both ends of the token can be resolved it return that
1013 /// range; Otherwise it returns an invalid SourceRange.
1014 SourceRange getRangeForNextToken(
1015 SourceLocation Loc, bool IncludeMacros, bool IncludeComments,
1016 std::optional<tok::TokenKind> ExpectedToken = std::nullopt);
1017
1018 /// Retrieve the module loader associated with the preprocessor.
1019 ModuleLoader &getModuleLoader() const;
1020
1021 /// Invent a new identifier for parameters of abbreviated templates.
1022 IdentifierInfo *
1023 InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName,
1024 unsigned Index);
1025
1026 void emitAndClearUnusedLocalTypedefWarnings();
1027
1028 // Emit all deferred diagnostics.
1029 void emitDeferredDiags();
1030
1031 /// This is called before the very first declaration in the translation unit
1032 /// is parsed. Note that the ASTContext may have already injected some
1033 /// declarations.
1034 void ActOnStartOfTranslationUnit();
1035 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1036 /// translation unit when EOF is reached and all but the top-level scope is
1037 /// popped.
1038 void ActOnEndOfTranslationUnit();
1039 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1040
1041 /// Determines the active Scope associated with the given declaration
1042 /// context.
1043 ///
1044 /// This routine maps a declaration context to the active Scope object that
1045 /// represents that declaration context in the parser. It is typically used
1046 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1047 /// declarations) that injects a name for name-lookup purposes and, therefore,
1048 /// must update the Scope.
1049 ///
1050 /// \returns The scope corresponding to the given declaraion context, or NULL
1051 /// if no such scope is open.
1052 Scope *getScopeForContext(DeclContext *Ctx);
1053
1054 void PushFunctionScope();
1055 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1056 sema::LambdaScopeInfo *PushLambdaScope();
1057
1058 /// This is used to inform Sema what the current TemplateParameterDepth
1059 /// is during Parsing. Currently it is used to pass on the depth
1060 /// when parsing generic lambda 'auto' parameters.
1061 void RecordParsingTemplateParameterDepth(unsigned Depth);
1062
1063 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1064 RecordDecl *RD, CapturedRegionKind K,
1065 unsigned OpenMPCaptureLevel = 0);
1066
1067 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1068 /// time after they've been popped.
1069 class PoppedFunctionScopeDeleter {
1070 Sema *Self;
1071
1072 public:
1073 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1074 void operator()(sema::FunctionScopeInfo *Scope) const;
1075 };
1076
1077 using PoppedFunctionScopePtr =
1078 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1079
1080 /// Pop a function (or block or lambda or captured region) scope from the
1081 /// stack.
1082 ///
1083 /// \param WP The warning policy to use for CFG-based warnings, or null if
1084 /// such warnings should not be produced.
1085 /// \param D The declaration corresponding to this function scope, if
1086 /// producing CFG-based warnings.
1087 /// \param BlockType The type of the block expression, if D is a BlockDecl.
1088 PoppedFunctionScopePtr
1089 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1090 Decl *D = nullptr, QualType BlockType = QualType());
1091
1092 sema::FunctionScopeInfo *getEnclosingFunction() const;
1093
1094 void setFunctionHasBranchIntoScope();
1095 void setFunctionHasBranchProtectedScope();
1096 void setFunctionHasIndirectGoto();
1097 void setFunctionHasMustTail();
1098
1099 void PushCompoundScope(bool IsStmtExpr);
1100 void PopCompoundScope();
1101
1102 /// Determine whether any errors occurred within this function/method/
1103 /// block.
1104 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1105
1106 /// Retrieve the current block, if any.
1107 sema::BlockScopeInfo *getCurBlock();
1108
1109 /// Get the innermost lambda or block enclosing the current location, if any.
1110 /// This looks through intervening non-lambda, non-block scopes such as local
1111 /// functions.
1112 sema::CapturingScopeInfo *getEnclosingLambdaOrBlock() const;
1113
1114 /// Retrieve the current lambda scope info, if any.
1115 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1116 /// lambda scope info ignoring all inner capturing scopes that are not
1117 /// lambda scopes.
1118 sema::LambdaScopeInfo *
1119 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1120
1121 /// Retrieve the current generic lambda info, if any.
1122 sema::LambdaScopeInfo *getCurGenericLambda();
1123
1124 /// Retrieve the current captured region, if any.
1125 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1126
1127 void ActOnComment(SourceRange Comment);
1128
1129 /// Retrieve the parser's current scope.
1130 ///
1131 /// This routine must only be used when it is certain that semantic analysis
1132 /// and the parser are in precisely the same context, which is not the case
1133 /// when, e.g., we are performing any kind of template instantiation.
1134 /// Therefore, the only safe places to use this scope are in the parser
1135 /// itself and in routines directly invoked from the parser and *never* from
1136 /// template substitution or instantiation.
1137 Scope *getCurScope() const { return CurScope; }
1138
1139 IdentifierInfo *getSuperIdentifier() const;
1140
1141 DeclContext *getCurLexicalContext() const {
1142 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
1143 }
1144
1145 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1146 const FunctionDecl *FD = nullptr);
1147 SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
1148 const PartialDiagnostic &PD,
1149 const FunctionDecl *FD = nullptr) {
1150 return targetDiag(Loc, DiagID: PD.getDiagID(), FD) << PD;
1151 }
1152
1153 /// Check if the type is allowed to be used for the current target.
1154 void checkTypeSupport(QualType Ty, SourceLocation Loc,
1155 ValueDecl *D = nullptr);
1156
1157 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1158 /// cast. If there is already an implicit cast, merge into the existing one.
1159 /// If isLvalue, the result of the cast is an lvalue.
1160 ExprResult ImpCastExprToType(
1161 Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue,
1162 const CXXCastPath *BasePath = nullptr,
1163 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
1164
1165 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1166 /// to the conversion from scalar type ScalarTy to the Boolean type.
1167 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
1168
1169 /// If \p AllowLambda is true, treat lambda as function.
1170 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1171
1172 /// Returns a pointer to the innermost enclosing function, or nullptr if the
1173 /// current context is not inside a function. If \p AllowLambda is true,
1174 /// this can return the call operator of an enclosing lambda, otherwise
1175 /// lambdas are skipped when looking for an enclosing function.
1176 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1177
1178 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1179 /// the method decl for the method being parsed. If we're currently
1180 /// in a 'block', this returns the containing context.
1181 ObjCMethodDecl *getCurMethodDecl();
1182
1183 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1184 /// or C function we're in, otherwise return null. If we're currently
1185 /// in a 'block', this returns the containing context.
1186 NamedDecl *getCurFunctionOrMethodDecl() const;
1187
1188 /// Warn if we're implicitly casting from a _Nullable pointer type to a
1189 /// _Nonnull one.
1190 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
1191 SourceLocation Loc);
1192
1193 /// Warn when implicitly casting 0 to nullptr.
1194 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1195
1196 /// Warn when implicitly changing function effects.
1197 void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType,
1198 SourceLocation Loc);
1199
1200 /// makeUnavailableInSystemHeader - There is an error in the current
1201 /// context. If we're still in a system header, and we can plausibly
1202 /// make the relevant declaration unavailable instead of erroring, do
1203 /// so and return true.
1204 bool makeUnavailableInSystemHeader(SourceLocation loc,
1205 UnavailableAttr::ImplicitReason reason);
1206
1207 /// Retrieve a suitable printing policy for diagnostics.
1208 PrintingPolicy getPrintingPolicy() const {
1209 return getPrintingPolicy(Ctx: Context, PP);
1210 }
1211
1212 /// Retrieve a suitable printing policy for diagnostics.
1213 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1214 const Preprocessor &PP);
1215
1216 /// Scope actions.
1217 void ActOnTranslationUnitScope(Scope *S);
1218
1219 /// Determine whether \param D is function like (function or function
1220 /// template) for parsing.
1221 bool isDeclaratorFunctionLike(Declarator &D);
1222
1223 /// The maximum alignment, same as in llvm::Value. We duplicate them here
1224 /// because that allows us not to duplicate the constants in clang code,
1225 /// which we must to since we can't directly use the llvm constants.
1226 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1227 ///
1228 /// This is the greatest alignment value supported by load, store, and alloca
1229 /// instructions, and global values.
1230 static const unsigned MaxAlignmentExponent = 32;
1231 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1232
1233 /// Flag indicating whether or not to collect detailed statistics.
1234 bool CollectStats;
1235
1236 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1237
1238 /// Stack containing information about each of the nested
1239 /// function, block, and method scopes that are currently active.
1240 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
1241
1242 /// The index of the first FunctionScope that corresponds to the current
1243 /// context.
1244 unsigned FunctionScopesStart = 0;
1245
1246 /// Track the number of currently active capturing scopes.
1247 unsigned CapturingFunctionScopes = 0;
1248
1249 llvm::BumpPtrAllocator BumpAlloc;
1250
1251 /// The kind of translation unit we are processing.
1252 ///
1253 /// When we're processing a complete translation unit, Sema will perform
1254 /// end-of-translation-unit semantic tasks (such as creating
1255 /// initializers for tentative definitions in C) once parsing has
1256 /// completed. Modules and precompiled headers perform different kinds of
1257 /// checks.
1258 const TranslationUnitKind TUKind;
1259
1260 /// Translation Unit Scope - useful to Objective-C actions that need
1261 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1262 /// For example, user-defined classes, built-in "id" type, etc.
1263 Scope *TUScope;
1264
1265 void incrementMSManglingNumber() const {
1266 return CurScope->incrementMSManglingNumber();
1267 }
1268
1269 /// Try to recover by turning the given expression into a
1270 /// call. Returns true if recovery was attempted or an error was
1271 /// emitted; this may also leave the ExprResult invalid.
1272 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1273 bool ForceComplain = false,
1274 bool (*IsPlausibleResult)(QualType) = nullptr);
1275
1276 // Adds implicit lifetime bound attribute for implicit this to its
1277 // TypeSourceInfo.
1278 void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD);
1279
1280 /// Figure out if an expression could be turned into a call.
1281 ///
1282 /// Use this when trying to recover from an error where the programmer may
1283 /// have written just the name of a function instead of actually calling it.
1284 ///
1285 /// \param E - The expression to examine.
1286 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1287 /// with no arguments, this parameter is set to the type returned by such a
1288 /// call; otherwise, it is set to an empty QualType.
1289 /// \param OverloadSet - If the expression is an overloaded function
1290 /// name, this parameter is populated with the decls of the various
1291 /// overloads.
1292 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1293 UnresolvedSetImpl &NonTemplateOverloads);
1294
1295 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
1296 typedef OpaquePtr<TemplateName> TemplateTy;
1297 typedef OpaquePtr<QualType> TypeTy;
1298
1299 OpenCLOptions OpenCLFeatures;
1300 FPOptions CurFPFeatures;
1301
1302 const LangOptions &LangOpts;
1303 Preprocessor &PP;
1304 ASTContext &Context;
1305 ASTConsumer &Consumer;
1306 DiagnosticsEngine &Diags;
1307 SourceManager &SourceMgr;
1308 api_notes::APINotesManager APINotes;
1309
1310 std::unique_ptr<APINotesSelectorDiagnosticState> APINotesSelectorDiagnostics;
1311
1312 /// A RAII object to enter scope of a compound statement.
1313 class CompoundScopeRAII {
1314 public:
1315 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1316 S.ActOnStartOfCompoundStmt(IsStmtExpr);
1317 }
1318
1319 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1320 CompoundScopeRAII(const CompoundScopeRAII &) = delete;
1321 CompoundScopeRAII &operator=(const CompoundScopeRAII &) = delete;
1322
1323 private:
1324 Sema &S;
1325 };
1326
1327 /// An RAII helper that pops function a function scope on exit.
1328 struct FunctionScopeRAII {
1329 Sema &S;
1330 bool Active;
1331 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
1332 ~FunctionScopeRAII() {
1333 if (Active)
1334 S.PopFunctionScopeInfo();
1335 }
1336 void disable() { Active = false; }
1337 };
1338
1339 sema::FunctionScopeInfo *getCurFunction() const {
1340 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1341 }
1342
1343 /// Worker object for performing CFG-based warnings.
1344 sema::AnalysisBasedWarnings AnalysisWarnings;
1345 threadSafety::BeforeSet *ThreadSafetyDeclCache;
1346
1347 /// Callback to the parser to parse templated functions when needed.
1348 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1349 LateTemplateParserCB *LateTemplateParser;
1350 void *OpaqueParser;
1351
1352 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
1353 LateTemplateParser = LTP;
1354 OpaqueParser = P;
1355 }
1356
1357 /// Callback to the parser to parse a type expressed as a string.
1358 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1359 ParseTypeFromStringCallback;
1360
1361 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1362 /// This is used as part of a hack to omit that class from ADL results.
1363 DeclarationName VAListTagName;
1364
1365 /// Is the last error level diagnostic immediate. This is used to determined
1366 /// whether the next info diagnostic should be immediate.
1367 bool IsLastErrorImmediate = true;
1368
1369 /// Track if we're currently analyzing overflow behavior types in assignment
1370 /// context.
1371 bool InOverflowBehaviorAssignmentContext = false;
1372
1373 class DelayedDiagnostics;
1374
1375 class DelayedDiagnosticsState {
1376 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1377 friend class Sema::DelayedDiagnostics;
1378 };
1379 typedef DelayedDiagnosticsState ParsingDeclState;
1380 typedef DelayedDiagnosticsState ProcessingContextState;
1381
1382 /// A class which encapsulates the logic for delaying diagnostics
1383 /// during parsing and other processing.
1384 class DelayedDiagnostics {
1385 /// The current pool of diagnostics into which delayed
1386 /// diagnostics should go.
1387 sema::DelayedDiagnosticPool *CurPool = nullptr;
1388
1389 public:
1390 DelayedDiagnostics() = default;
1391
1392 /// Adds a delayed diagnostic.
1393 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1394
1395 /// Determines whether diagnostics should be delayed.
1396 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1397
1398 /// Returns the current delayed-diagnostics pool.
1399 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1400
1401 /// Enter a new scope. Access and deprecation diagnostics will be
1402 /// collected in this pool.
1403 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
1404 DelayedDiagnosticsState state;
1405 state.SavedPool = CurPool;
1406 CurPool = &pool;
1407 return state;
1408 }
1409
1410 /// Leave a delayed-diagnostic state that was previously pushed.
1411 /// Do not emit any of the diagnostics. This is performed as part
1412 /// of the bookkeeping of popping a pool "properly".
1413 void popWithoutEmitting(DelayedDiagnosticsState state) {
1414 CurPool = state.SavedPool;
1415 }
1416
1417 /// Enter a new scope where access and deprecation diagnostics are
1418 /// not delayed.
1419 DelayedDiagnosticsState pushUndelayed() {
1420 DelayedDiagnosticsState state;
1421 state.SavedPool = CurPool;
1422 CurPool = nullptr;
1423 return state;
1424 }
1425
1426 /// Undo a previous pushUndelayed().
1427 void popUndelayed(DelayedDiagnosticsState state) {
1428 assert(CurPool == nullptr);
1429 CurPool = state.SavedPool;
1430 }
1431 } DelayedDiagnostics;
1432
1433 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
1434 return DelayedDiagnostics.push(pool);
1435 }
1436
1437 /// Diagnostics that are emitted only if we discover that the given function
1438 /// must be codegen'ed. Because handling these correctly adds overhead to
1439 /// compilation, this is currently only used for offload languages like CUDA,
1440 /// OpenMP, and SYCL.
1441 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1442
1443 /// CurContext - This is the current declaration context of parsing.
1444 DeclContext *CurContext;
1445
1446 SemaAMDGPU &AMDGPU() {
1447 assert(AMDGPUPtr);
1448 return *AMDGPUPtr;
1449 }
1450
1451 SemaARM &ARM() {
1452 assert(ARMPtr);
1453 return *ARMPtr;
1454 }
1455
1456 SemaAVR &AVR() {
1457 assert(AVRPtr);
1458 return *AVRPtr;
1459 }
1460
1461 SemaBPF &BPF() {
1462 assert(BPFPtr);
1463 return *BPFPtr;
1464 }
1465
1466 SemaCodeCompletion &CodeCompletion() {
1467 assert(CodeCompletionPtr);
1468 return *CodeCompletionPtr;
1469 }
1470
1471 SemaCUDA &CUDA() {
1472 assert(CUDAPtr);
1473 return *CUDAPtr;
1474 }
1475
1476 SemaDirectX &DirectX() {
1477 assert(DirectXPtr);
1478 return *DirectXPtr;
1479 }
1480
1481 SemaHLSL &HLSL() {
1482 assert(HLSLPtr);
1483 return *HLSLPtr;
1484 }
1485
1486 SemaHexagon &Hexagon() {
1487 assert(HexagonPtr);
1488 return *HexagonPtr;
1489 }
1490
1491 SemaLoongArch &LoongArch() {
1492 assert(LoongArchPtr);
1493 return *LoongArchPtr;
1494 }
1495
1496 SemaM68k &M68k() {
1497 assert(M68kPtr);
1498 return *M68kPtr;
1499 }
1500
1501 SemaMIPS &MIPS() {
1502 assert(MIPSPtr);
1503 return *MIPSPtr;
1504 }
1505
1506 SemaMSP430 &MSP430() {
1507 assert(MSP430Ptr);
1508 return *MSP430Ptr;
1509 }
1510
1511 SemaNVPTX &NVPTX() {
1512 assert(NVPTXPtr);
1513 return *NVPTXPtr;
1514 }
1515
1516 SemaObjC &ObjC() {
1517 assert(ObjCPtr);
1518 return *ObjCPtr;
1519 }
1520
1521 SemaOpenACC &OpenACC() {
1522 assert(OpenACCPtr);
1523 return *OpenACCPtr;
1524 }
1525
1526 SemaOpenCL &OpenCL() {
1527 assert(OpenCLPtr);
1528 return *OpenCLPtr;
1529 }
1530
1531 SemaOpenMP &OpenMP() {
1532 assert(OpenMPPtr && "SemaOpenMP is dead");
1533 return *OpenMPPtr;
1534 }
1535
1536 SemaPPC &PPC() {
1537 assert(PPCPtr);
1538 return *PPCPtr;
1539 }
1540
1541 SemaPseudoObject &PseudoObject() {
1542 assert(PseudoObjectPtr);
1543 return *PseudoObjectPtr;
1544 }
1545
1546 SemaRISCV &RISCV() {
1547 assert(RISCVPtr);
1548 return *RISCVPtr;
1549 }
1550
1551 SemaSPIRV &SPIRV() {
1552 assert(SPIRVPtr);
1553 return *SPIRVPtr;
1554 }
1555
1556 SemaSYCL &SYCL() {
1557 assert(SYCLPtr);
1558 return *SYCLPtr;
1559 }
1560
1561 SemaSwift &Swift() {
1562 assert(SwiftPtr);
1563 return *SwiftPtr;
1564 }
1565
1566 SemaSystemZ &SystemZ() {
1567 assert(SystemZPtr);
1568 return *SystemZPtr;
1569 }
1570
1571 SemaWasm &Wasm() {
1572 assert(WasmPtr);
1573 return *WasmPtr;
1574 }
1575
1576 SemaX86 &X86() {
1577 assert(X86Ptr);
1578 return *X86Ptr;
1579 }
1580
1581 /// Source of additional semantic information.
1582 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
1583
1584protected:
1585 friend class Parser;
1586 friend class InitializationSequence;
1587 friend class ASTReader;
1588 friend class ASTDeclReader;
1589 friend class ASTWriter;
1590
1591private:
1592 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1593 bool WarnedDarwinSDKInfoMissing = false;
1594
1595 StackExhaustionHandler StackHandler;
1596
1597 Sema(const Sema &) = delete;
1598 void operator=(const Sema &) = delete;
1599
1600 /// The handler for the FileChanged preprocessor events.
1601 ///
1602 /// Used for diagnostics that implement custom semantic analysis for #include
1603 /// directives, like -Wpragma-pack.
1604 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1605
1606 /// The parser's current scope.
1607 ///
1608 /// The parser maintains this state here.
1609 Scope *CurScope;
1610
1611 mutable IdentifierInfo *Ident_super;
1612
1613 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1614 std::unique_ptr<SemaARM> ARMPtr;
1615 std::unique_ptr<SemaAVR> AVRPtr;
1616 std::unique_ptr<SemaBPF> BPFPtr;
1617 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1618 std::unique_ptr<SemaCUDA> CUDAPtr;
1619 std::unique_ptr<SemaDirectX> DirectXPtr;
1620 std::unique_ptr<SemaHLSL> HLSLPtr;
1621 std::unique_ptr<SemaHexagon> HexagonPtr;
1622 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1623 std::unique_ptr<SemaM68k> M68kPtr;
1624 std::unique_ptr<SemaMIPS> MIPSPtr;
1625 std::unique_ptr<SemaMSP430> MSP430Ptr;
1626 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1627 std::unique_ptr<SemaObjC> ObjCPtr;
1628 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1629 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1630 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1631 std::unique_ptr<SemaPPC> PPCPtr;
1632 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1633 std::unique_ptr<SemaRISCV> RISCVPtr;
1634 std::unique_ptr<SemaSPIRV> SPIRVPtr;
1635 std::unique_ptr<SemaSYCL> SYCLPtr;
1636 std::unique_ptr<SemaSwift> SwiftPtr;
1637 std::unique_ptr<SemaSystemZ> SystemZPtr;
1638 std::unique_ptr<SemaWasm> WasmPtr;
1639 std::unique_ptr<SemaX86> X86Ptr;
1640
1641 ///@}
1642
1643 //
1644 //
1645 // -------------------------------------------------------------------------
1646 //
1647 //
1648
1649 /// \name API Notes
1650 /// Implementations are in SemaAPINotes.cpp
1651 ///@{
1652
1653public:
1654 /// Map any API notes provided for this declaration to attributes on the
1655 /// declaration.
1656 ///
1657 /// Triggered by declaration-attribute processing.
1658 void ProcessAPINotes(Decl *D);
1659 /// Apply the 'Nullability:' annotation to the specified declaration
1660 void ApplyNullability(Decl *D, NullabilityKind Nullability);
1661 /// Apply the 'Type:' annotation to the specified declaration
1662 void ApplyAPINotesType(Decl *D, StringRef TypeString);
1663
1664 /// Diagnose exact API notes selectors that were not matched by any
1665 /// declaration processed in this translation unit.
1666 void DiagnoseUnusedAPINotesSelectors();
1667
1668 /// Whether APINotes should be gathered for all applicable Swift language
1669 /// versions, without being applied. Leaving clients of the current module
1670 /// to select and apply the correct version.
1671 bool captureSwiftVersionIndependentAPINotes() {
1672 return APINotes.captureVersionIndependentSwift();
1673 }
1674 ///@}
1675
1676 //
1677 //
1678 // -------------------------------------------------------------------------
1679 //
1680 //
1681
1682 /// \name C++ Access Control
1683 /// Implementations are in SemaAccess.cpp
1684 ///@{
1685
1686public:
1687 enum AccessResult {
1688 AR_accessible,
1689 AR_inaccessible,
1690 AR_dependent,
1691 AR_delayed
1692 };
1693
1694 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1695 /// Returns true on error (when the previous member decl access specifier
1696 /// is different from the new member decl access specifier).
1697 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1698 NamedDecl *PrevMemberDecl,
1699 AccessSpecifier LexicalAS);
1700
1701 /// Perform access-control checking on a previously-unresolved member
1702 /// access which has now been resolved to a member.
1703 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
1704 DeclAccessPair FoundDecl);
1705 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
1706 DeclAccessPair FoundDecl);
1707
1708 /// Checks access to an overloaded operator new or delete.
1709 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
1710 SourceRange PlacementRange,
1711 CXXRecordDecl *NamingClass,
1712 DeclAccessPair FoundDecl,
1713 bool Diagnose = true);
1714
1715 /// Checks access to a constructor.
1716 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1717 DeclAccessPair FoundDecl,
1718 const InitializedEntity &Entity,
1719 bool IsCopyBindingRefToTemp = false);
1720
1721 /// Checks access to a constructor.
1722 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1723 DeclAccessPair FoundDecl,
1724 const InitializedEntity &Entity,
1725 const PartialDiagnostic &PDiag);
1726 AccessResult CheckDestructorAccess(SourceLocation Loc,
1727 CXXDestructorDecl *Dtor,
1728 const PartialDiagnostic &PDiag,
1729 QualType objectType = QualType());
1730
1731 /// Checks access to the target of a friend declaration.
1732 AccessResult CheckFriendAccess(NamedDecl *D);
1733
1734 /// Checks access to a member.
1735 AccessResult CheckMemberAccess(SourceLocation UseLoc,
1736 CXXRecordDecl *NamingClass,
1737 DeclAccessPair Found);
1738
1739 /// Checks implicit access to a member in a structured binding.
1740 AccessResult
1741 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
1742 CXXRecordDecl *DecomposedClass,
1743 DeclAccessPair Field);
1744 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1745 const SourceRange &,
1746 DeclAccessPair FoundDecl);
1747
1748 /// Checks access to an overloaded member operator, including
1749 /// conversion operators.
1750 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1751 Expr *ArgExpr,
1752 DeclAccessPair FoundDecl);
1753 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1754 ArrayRef<Expr *> ArgExprs,
1755 DeclAccessPair FoundDecl);
1756 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
1757 DeclAccessPair FoundDecl);
1758
1759 /// Checks access for a hierarchy conversion.
1760 ///
1761 /// \param ForceCheck true if this check should be performed even if access
1762 /// control is disabled; some things rely on this for semantics
1763 /// \param ForceUnprivileged true if this check should proceed as if the
1764 /// context had no special privileges
1765 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base,
1766 QualType Derived, const CXXBasePath &Path,
1767 unsigned DiagID, bool ForceCheck = false,
1768 bool ForceUnprivileged = false);
1769
1770 AccessResult CheckBaseClassAccess(
1771 SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1772 const CXXBasePath &Path, unsigned DiagID,
1773 llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1774 bool ForceCheck = false, bool ForceUnprivileged = false);
1775
1776 /// Checks access to all the declarations in the given result set.
1777 void CheckLookupAccess(const LookupResult &R);
1778
1779 /// Checks access to Target from the given class. The check will take access
1780 /// specifiers into account, but no member access expressions and such.
1781 ///
1782 /// \param Target the declaration to check if it can be accessed
1783 /// \param NamingClass the class in which the lookup was started.
1784 /// \param BaseType type of the left side of member access expression.
1785 /// \p BaseType and \p NamingClass are used for C++ access control.
1786 /// Depending on the lookup case, they should be set to the following:
1787 /// - lhs.target (member access without a qualifier):
1788 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1789 /// - lhs.X::target (member access with a qualifier):
1790 /// BaseType is the type of 'lhs', NamingClass is 'X'
1791 /// - X::target (qualified lookup without member access):
1792 /// BaseType is null, NamingClass is 'X'.
1793 /// - target (unqualified lookup).
1794 /// BaseType is null, NamingClass is the parent class of 'target'.
1795 /// \return true if the Target is accessible from the Class, false otherwise.
1796 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1797 QualType BaseType);
1798
1799 /// Is the given member accessible for the purposes of deciding whether to
1800 /// define a special member function as deleted?
1801 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1802 DeclAccessPair Found, QualType ObjectType,
1803 SourceLocation Loc,
1804 const PartialDiagnostic &Diag);
1805 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1806 DeclAccessPair Found,
1807 QualType ObjectType) {
1808 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1809 Loc: SourceLocation(), Diag: PDiag());
1810 }
1811
1812 void HandleDependentAccessCheck(
1813 const DependentDiagnostic &DD,
1814 const MultiLevelTemplateArgumentList &TemplateArgs);
1815 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
1816
1817 ///@}
1818
1819 //
1820 //
1821 // -------------------------------------------------------------------------
1822 //
1823 //
1824
1825 /// \name Attributes
1826 /// Implementations are in SemaAttr.cpp
1827 ///@{
1828
1829public:
1830 /// Controls member pointer representation format under the MS ABI.
1831 LangOptions::PragmaMSPointersToMembersKind
1832 MSPointerToMemberRepresentationMethod;
1833
1834 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1835
1836 /// Source location for newly created implicit MSInheritanceAttrs
1837 SourceLocation ImplicitMSInheritanceAttrLoc;
1838
1839 struct PragmaClangSection {
1840 std::string SectionName;
1841 bool Valid = false;
1842 SourceLocation PragmaLocation;
1843 };
1844
1845 PragmaClangSection PragmaClangBSSSection;
1846 PragmaClangSection PragmaClangDataSection;
1847 PragmaClangSection PragmaClangRodataSection;
1848 PragmaClangSection PragmaClangRelroSection;
1849 PragmaClangSection PragmaClangTextSection;
1850
1851 enum PragmaMsStackAction {
1852 PSK_Reset = 0x0, // #pragma ()
1853 PSK_Set = 0x1, // #pragma (value)
1854 PSK_Push = 0x2, // #pragma (push[, id])
1855 PSK_Pop = 0x4, // #pragma (pop[, id])
1856 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1857 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1858 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1859 };
1860
1861 struct PragmaPackInfo {
1862 PragmaMsStackAction Action;
1863 StringRef SlotLabel;
1864 Token Alignment;
1865 };
1866
1867 // #pragma pack and align.
1868 class AlignPackInfo {
1869 public:
1870 // `Native` represents default align mode, which may vary based on the
1871 // platform.
1872 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1873
1874 // #pragma pack info constructor
1875 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1876 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1877 assert(Num == PackNumber && "The pack number has been truncated.");
1878 }
1879
1880 // #pragma align info constructor
1881 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
1882 : PackAttr(false), AlignMode(M),
1883 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1884
1885 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1886
1887 AlignPackInfo() : AlignPackInfo(Native, false) {}
1888
1889 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1890 // integer encoding for it. This should only be passed to
1891 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1892 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
1893 std::uint32_t Encoding{};
1894 if (Info.IsXLStack())
1895 Encoding |= IsXLMask;
1896
1897 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1898
1899 if (Info.IsPackAttr())
1900 Encoding |= PackAttrMask;
1901
1902 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1903
1904 return Encoding;
1905 }
1906
1907 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1908 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1909 AlignPackInfo::Mode M =
1910 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1911 int PackNumber = (Encoding & PackNumMask) >> 4;
1912
1913 if (Encoding & PackAttrMask)
1914 return AlignPackInfo(M, PackNumber, IsXL);
1915
1916 return AlignPackInfo(M, IsXL);
1917 }
1918
1919 bool IsPackAttr() const { return PackAttr; }
1920
1921 bool IsAlignAttr() const { return !PackAttr; }
1922
1923 Mode getAlignMode() const { return AlignMode; }
1924
1925 unsigned getPackNumber() const { return PackNumber; }
1926
1927 bool IsPackSet() const {
1928 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1929 // attriute on a decl.
1930 return PackNumber != UninitPackVal && PackNumber != 0;
1931 }
1932
1933 bool IsXLStack() const { return XLStack; }
1934
1935 bool operator==(const AlignPackInfo &Info) const {
1936 return std::tie(args: AlignMode, args: PackNumber, args: PackAttr, args: XLStack) ==
1937 std::tie(args: Info.AlignMode, args: Info.PackNumber, args: Info.PackAttr,
1938 args: Info.XLStack);
1939 }
1940
1941 bool operator!=(const AlignPackInfo &Info) const {
1942 return !(*this == Info);
1943 }
1944
1945 private:
1946 /// \brief True if this is a pragma pack attribute,
1947 /// not a pragma align attribute.
1948 bool PackAttr;
1949
1950 /// \brief The alignment mode that is in effect.
1951 Mode AlignMode;
1952
1953 /// \brief The pack number of the stack.
1954 unsigned char PackNumber;
1955
1956 /// \brief True if it is a XL #pragma align/pack stack.
1957 bool XLStack;
1958
1959 /// \brief Uninitialized pack value.
1960 static constexpr unsigned char UninitPackVal = -1;
1961
1962 // Masks to encode and decode an AlignPackInfo.
1963 static constexpr uint32_t IsXLMask{0x0000'0001};
1964 static constexpr uint32_t AlignModeMask{0x0000'0006};
1965 static constexpr uint32_t PackAttrMask{0x00000'0008};
1966 static constexpr uint32_t PackNumMask{0x0000'01F0};
1967 };
1968
1969 template <typename ValueType> struct PragmaStack {
1970 struct Slot {
1971 llvm::StringRef StackSlotLabel;
1972 ValueType Value;
1973 SourceLocation PragmaLocation;
1974 SourceLocation PragmaPushLocation;
1975 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
1976 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
1977 : StackSlotLabel(StackSlotLabel), Value(Value),
1978 PragmaLocation(PragmaLocation),
1979 PragmaPushLocation(PragmaPushLocation) {}
1980 };
1981
1982 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
1983 llvm::StringRef StackSlotLabel, ValueType Value) {
1984 if (Action == PSK_Reset) {
1985 CurrentValue = DefaultValue;
1986 CurrentPragmaLocation = PragmaLocation;
1987 return;
1988 }
1989 if (Action & PSK_Push)
1990 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
1991 PragmaLocation);
1992 else if (Action & PSK_Pop) {
1993 if (!StackSlotLabel.empty()) {
1994 // If we've got a label, try to find it and jump there.
1995 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
1996 return x.StackSlotLabel == StackSlotLabel;
1997 });
1998 // If we found the label so pop from there.
1999 if (I != Stack.rend()) {
2000 CurrentValue = I->Value;
2001 CurrentPragmaLocation = I->PragmaLocation;
2002 Stack.erase(std::prev(I.base()), Stack.end());
2003 }
2004 } else if (!Stack.empty()) {
2005 // We do not have a label, just pop the last entry.
2006 CurrentValue = Stack.back().Value;
2007 CurrentPragmaLocation = Stack.back().PragmaLocation;
2008 Stack.pop_back();
2009 }
2010 }
2011 if (Action & PSK_Set) {
2012 CurrentValue = Value;
2013 CurrentPragmaLocation = PragmaLocation;
2014 }
2015 }
2016
2017 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
2018 // method body to restore the stacks on exit, so it works like this:
2019 //
2020 // struct S {
2021 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
2022 // void Method {}
2023 // #pragma <name>(pop, InternalPragmaSlot)
2024 // };
2025 //
2026 // It works even with #pragma vtordisp, although MSVC doesn't support
2027 // #pragma vtordisp(push [, id], n)
2028 // syntax.
2029 //
2030 // Push / pop a named sentinel slot.
2031 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
2032 assert((Action == PSK_Push || Action == PSK_Pop) &&
2033 "Can only push / pop #pragma stack sentinels!");
2034 Act(PragmaLocation: CurrentPragmaLocation, Action, StackSlotLabel: Label, Value: CurrentValue);
2035 }
2036
2037 // Constructors.
2038 explicit PragmaStack(const ValueType &Default)
2039 : DefaultValue(Default), CurrentValue(Default) {}
2040
2041 bool hasValue() const { return CurrentValue != DefaultValue; }
2042
2043 SmallVector<Slot, 2> Stack;
2044 ValueType DefaultValue; // Value used for PSK_Reset action.
2045 ValueType CurrentValue;
2046 SourceLocation CurrentPragmaLocation;
2047 };
2048 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2049 // we shouldn't do so if they're in a module).
2050
2051 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2052 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
2053 ///
2054 /// 0: Suppress all vtordisps
2055 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2056 /// structors
2057 /// 2: Always insert vtordisps to support RTTI on partially constructed
2058 /// objects
2059 PragmaStack<MSVtorDispMode> VtorDispStack;
2060 PragmaStack<AlignPackInfo> AlignPackStack;
2061 // The current #pragma align/pack values and locations at each #include.
2062 struct AlignPackIncludeState {
2063 AlignPackInfo CurrentValue;
2064 SourceLocation CurrentPragmaLocation;
2065 bool HasNonDefaultValue, ShouldWarnOnInclude;
2066 };
2067 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
2068 // Segment #pragmas.
2069 PragmaStack<StringLiteral *> DataSegStack;
2070 PragmaStack<StringLiteral *> BSSSegStack;
2071 PragmaStack<StringLiteral *> ConstSegStack;
2072 PragmaStack<StringLiteral *> CodeSegStack;
2073
2074 // #pragma strict_gs_check.
2075 PragmaStack<bool> StrictGuardStackCheckStack;
2076
2077 // This stack tracks the current state of Sema.CurFPFeatures.
2078 PragmaStack<FPOptionsOverride> FpPragmaStack;
2079 FPOptionsOverride CurFPFeatureOverrides() {
2080 FPOptionsOverride result;
2081 if (!FpPragmaStack.hasValue()) {
2082 result = FPOptionsOverride();
2083 } else {
2084 result = FpPragmaStack.CurrentValue;
2085 }
2086 return result;
2087 }
2088
2089 enum PragmaSectionKind {
2090 PSK_DataSeg,
2091 PSK_BSSSeg,
2092 PSK_ConstSeg,
2093 PSK_CodeSeg,
2094 };
2095
2096 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2097 // Actions should be performed only if we enter / exit a C++ method body.
2098 class PragmaStackSentinelRAII {
2099 public:
2100 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2101 ~PragmaStackSentinelRAII();
2102 PragmaStackSentinelRAII(const PragmaStackSentinelRAII &) = delete;
2103 PragmaStackSentinelRAII &
2104 operator=(const PragmaStackSentinelRAII &) = delete;
2105
2106 private:
2107 Sema &S;
2108 StringRef SlotLabel;
2109 bool ShouldAct;
2110 };
2111
2112 /// Last section used with #pragma init_seg.
2113 StringLiteral *CurInitSeg;
2114 SourceLocation CurInitSegLoc;
2115
2116 /// Sections used with #pragma alloc_text.
2117 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2118
2119 /// VisContext - Manages the stack for \#pragma GCC visibility.
2120 void *VisContext; // Really a "PragmaVisStack*"
2121
2122 /// This an attribute introduced by \#pragma clang attribute.
2123 struct PragmaAttributeEntry {
2124 SourceLocation Loc;
2125 ParsedAttr *Attribute;
2126 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
2127 bool IsUsed;
2128 };
2129
2130 /// A push'd group of PragmaAttributeEntries.
2131 struct PragmaAttributeGroup {
2132 /// The location of the push attribute.
2133 SourceLocation Loc;
2134 /// The namespace of this push group.
2135 const IdentifierInfo *Namespace;
2136 SmallVector<PragmaAttributeEntry, 2> Entries;
2137 };
2138
2139 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
2140
2141 /// The declaration that is currently receiving an attribute from the
2142 /// #pragma attribute stack.
2143 const Decl *PragmaAttributeCurrentTargetDecl;
2144
2145 /// This represents the last location of a "#pragma clang optimize off"
2146 /// directive if such a directive has not been closed by an "on" yet. If
2147 /// optimizations are currently "on", this is set to an invalid location.
2148 SourceLocation OptimizeOffPragmaLocation;
2149
2150 /// Get the location for the currently active "\#pragma clang optimize
2151 /// off". If this location is invalid, then the state of the pragma is "on".
2152 SourceLocation getOptimizeOffPragmaLocation() const {
2153 return OptimizeOffPragmaLocation;
2154 }
2155
2156 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2157 /// whether the optimizations in the list passed to the pragma should be
2158 /// turned off or on. This boolean is true by default because command line
2159 /// options are honored when `#pragma optimize("", on)`.
2160 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2161 bool MSPragmaOptimizeIsOn = true;
2162
2163 /// Set of no-builtin functions listed by \#pragma function.
2164 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
2165
2166 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2167 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2168 void AddAlignmentAttributesForRecord(RecordDecl *RD);
2169
2170 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2171 void AddMsStructLayoutForRecord(RecordDecl *RD);
2172
2173 /// Add gsl::Pointer attribute to std::container::iterator
2174 /// \param ND The declaration that introduces the name
2175 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2176 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2177
2178 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2179 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
2180
2181 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2182 void inferLifetimeBoundAttribute(FunctionDecl *FD);
2183
2184 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2185 void inferLifetimeCaptureByAttribute(FunctionDecl *FD);
2186
2187 /// Add [[gsl::Pointer]] attributes for std:: types.
2188 void inferGslPointerAttribute(TypedefNameDecl *TD);
2189
2190 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2191 StringRef ParamName);
2192 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2193 // can be the name of a function parameter, we need to parse the function
2194 // declaration and rest of the parameters before processesing 'X'. Therefore
2195 // do this lazily instead of processing while parsing the annotation itself.
2196 void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD);
2197
2198 /// Add _Nullable attributes for std:: types.
2199 void inferNullableClassAttribute(CXXRecordDecl *CRD);
2200
2201 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2202 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
2203 PragmaClangSectionAction Action,
2204 PragmaClangSectionKind SecKind,
2205 StringRef SecName);
2206
2207 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2208 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
2209 SourceLocation PragmaLoc);
2210
2211 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2212 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2213 StringRef SlotLabel, Expr *Alignment);
2214
2215 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2216 /// (unless they are value dependent or type dependent). Returns false
2217 /// and emits a diagnostic if one or more of the arguments could not be
2218 /// folded into a constant.
2219 bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
2220 MutableArrayRef<Expr *> Args);
2221
2222 enum class PragmaAlignPackDiagnoseKind {
2223 NonDefaultStateAtInclude,
2224 ChangedStateAtExit
2225 };
2226
2227 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
2228 SourceLocation IncludeLoc);
2229 void DiagnoseUnterminatedPragmaAlignPack();
2230
2231 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2232 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
2233
2234 /// ActOnPragmaMSComment - Called on well formed
2235 /// \#pragma comment(kind, "arg").
2236 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
2237 StringRef Arg);
2238
2239 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2240 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2241 StringRef Value);
2242
2243 /// Are precise floating point semantics currently enabled?
2244 bool isPreciseFPEnabled() {
2245 return !CurFPFeatures.getAllowFPReassociate() &&
2246 !CurFPFeatures.getNoSignedZero() &&
2247 !CurFPFeatures.getAllowReciprocal() &&
2248 !CurFPFeatures.getAllowApproxFunc();
2249 }
2250
2251 void ActOnPragmaFPEvalMethod(SourceLocation Loc,
2252 LangOptions::FPEvalMethodKind Value);
2253
2254 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2255 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2256 PragmaFloatControlKind Value);
2257
2258 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2259 /// pointers_to_members(representation method[, general purpose
2260 /// representation]).
2261 void ActOnPragmaMSPointersToMembers(
2262 LangOptions::PragmaMSPointersToMembersKind Kind,
2263 SourceLocation PragmaLoc);
2264
2265 /// Called on well formed \#pragma vtordisp().
2266 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2267 SourceLocation PragmaLoc, MSVtorDispMode Value);
2268
2269 bool UnifySection(StringRef SectionName, int SectionFlags,
2270 NamedDecl *TheDecl);
2271 bool UnifySection(StringRef SectionName, int SectionFlags,
2272 SourceLocation PragmaSectionLocation);
2273
2274 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2275 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2276 PragmaMsStackAction Action,
2277 llvm::StringRef StackSlotLabel,
2278 StringLiteral *SegmentName, llvm::StringRef PragmaName);
2279
2280 /// Called on well formed \#pragma section().
2281 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2282 StringLiteral *SegmentName);
2283
2284 /// Called on well-formed \#pragma init_seg().
2285 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2286 StringLiteral *SegmentName);
2287
2288 /// Called on well-formed \#pragma alloc_text().
2289 void ActOnPragmaMSAllocText(
2290 SourceLocation PragmaLocation, StringRef Section,
2291 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2292 &Functions);
2293
2294 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2295 /// strict_gs_check.
2296 void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
2297 PragmaMsStackAction Action,
2298 bool Value);
2299
2300 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2301 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2302 SourceLocation PragmaLoc);
2303
2304 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
2305 SourceLocation PragmaLoc,
2306 attr::ParsedSubjectMatchRuleSet Rules);
2307 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
2308 const IdentifierInfo *Namespace);
2309
2310 /// Called on well-formed '\#pragma clang attribute pop'.
2311 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
2312 const IdentifierInfo *Namespace);
2313
2314 /// Adds the attributes that have been specified using the
2315 /// '\#pragma clang attribute push' directives to the given declaration.
2316 void AddPragmaAttributes(Scope *S, Decl *D);
2317
2318 using InstantiationContextDiagFuncRef =
2319 llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
2320 auto getDefaultDiagFunc() {
2321 return [this](SourceLocation Loc, PartialDiagnostic PD) {
2322 // This bypasses a lot of the filters in the diag engine, as it's
2323 // to be used to attach notes to diagnostics which have already
2324 // been filtered through.
2325 DiagnosticBuilder Builder(Diags.Report(Loc, DiagID: PD.getDiagID()));
2326 PD.Emit(DB: Builder);
2327 };
2328 }
2329
2330 void PrintPragmaAttributeInstantiationPoint(
2331 InstantiationContextDiagFuncRef DiagFunc);
2332 void PrintPragmaAttributeInstantiationPoint() {
2333 PrintPragmaAttributeInstantiationPoint(DiagFunc: getDefaultDiagFunc());
2334 }
2335
2336 void DiagnoseUnterminatedPragmaAttribute();
2337
2338 /// Called on well formed \#pragma clang optimize.
2339 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2340
2341 /// #pragma optimize("[optimization-list]", on | off).
2342 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2343
2344 /// Call on well formed \#pragma function.
2345 void
2346 ActOnPragmaMSFunction(SourceLocation Loc,
2347 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2348
2349 NamedDecl *lookupExternCFunctionOrVariable(IdentifierInfo *IdentId,
2350 SourceLocation NameLoc,
2351 Scope *curScope);
2352
2353 /// Information from a C++ #pragma export, for a symbol that we
2354 /// haven't seen the declaration for yet.
2355 struct PendingPragmaInfo {
2356 SourceLocation NameLoc;
2357 bool Used;
2358 };
2359
2360 llvm::DenseMap<IdentifierInfo *, PendingPragmaInfo> PendingExportedNames;
2361
2362 /// ActonPragmaExport - called on well-formed '\#pragma export'.
2363 void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc,
2364 Scope *curScope);
2365
2366 /// Only called on function definitions; if there is a pragma in scope
2367 /// with the effect of a range-based optnone, consider marking the function
2368 /// with attribute optnone.
2369 void AddRangeBasedOptnone(FunctionDecl *FD);
2370
2371 /// Only called on function definitions; if there is a `#pragma alloc_text`
2372 /// that decides which code section the function should be in, add
2373 /// attribute section to the function.
2374 void AddSectionMSAllocText(FunctionDecl *FD);
2375
2376 /// Adds the 'optnone' attribute to the function declaration if there
2377 /// are no conflicts; Loc represents the location causing the 'optnone'
2378 /// attribute to be added (usually because of a pragma).
2379 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
2380
2381 /// Only called on function definitions; if there is a MSVC #pragma optimize
2382 /// in scope, consider changing the function's attributes based on the
2383 /// optimization list passed to the pragma.
2384 void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
2385
2386 /// Only called on function definitions; if there is a pragma in scope
2387 /// with the effect of a range-based no_builtin, consider marking the function
2388 /// with attribute no_builtin.
2389 void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
2390
2391 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2392 /// add an appropriate visibility attribute.
2393 void AddPushedVisibilityAttribute(Decl *RD);
2394
2395 /// FreeVisContext - Deallocate and null out VisContext.
2396 void FreeVisContext();
2397
2398 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2399 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2400 SourceLocation PragmaLoc);
2401
2402 /// ActOnPragmaFPContract - Called on well formed
2403 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2404 /// \#pragma clang fp contract
2405 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
2406
2407 /// Called on well formed
2408 /// \#pragma clang fp reassociate
2409 /// or
2410 /// \#pragma clang fp reciprocal
2411 void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind,
2412 bool IsEnabled);
2413
2414 /// ActOnPragmaFenvAccess - Called on well formed
2415 /// \#pragma STDC FENV_ACCESS
2416 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2417
2418 /// ActOnPragmaCXLimitedRange - Called on well formed
2419 /// \#pragma STDC CX_LIMITED_RANGE
2420 void ActOnPragmaCXLimitedRange(SourceLocation Loc,
2421 LangOptions::ComplexRangeKind Range);
2422
2423 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2424 void ActOnPragmaFPExceptions(SourceLocation Loc,
2425 LangOptions::FPExceptionModeKind);
2426
2427 /// Called to set constant rounding mode for floating point operations.
2428 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2429
2430 /// Called to set exception behavior for floating point operations.
2431 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
2432
2433 /// PushNamespaceVisibilityAttr - Note that we've entered a
2434 /// namespace with a visibility attribute.
2435 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2436 SourceLocation Loc);
2437
2438 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2439 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2440 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2441
2442 /// Handles semantic checking for features that are common to all attributes,
2443 /// such as checking whether a parameter was properly specified, or the
2444 /// correct number of arguments were passed, etc. Returns true if the
2445 /// attribute has been diagnosed.
2446 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2447 bool SkipArgCountCheck = false);
2448 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2449 bool SkipArgCountCheck = false);
2450
2451 ///@}
2452
2453 //
2454 //
2455 // -------------------------------------------------------------------------
2456 //
2457 //
2458
2459 /// \name Availability Attribute Handling
2460 /// Implementations are in SemaAvailability.cpp
2461 ///@{
2462
2463public:
2464 /// Issue any -Wunguarded-availability warnings in \c FD
2465 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
2466
2467 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2468
2469 /// Retrieve the current function, if any, that should be analyzed for
2470 /// potential availability violations.
2471 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2472
2473 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
2474 const ObjCInterfaceDecl *UnknownObjCClass,
2475 bool ObjCPropertyAccess,
2476 bool AvoidPartialAvailabilityChecks,
2477 ObjCInterfaceDecl *ClassReceiver);
2478
2479 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs);
2480
2481 std::pair<AvailabilityResult, const NamedDecl *>
2482 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2483 ObjCInterfaceDecl *ClassReceiver);
2484 ///@}
2485
2486 //
2487 //
2488 // -------------------------------------------------------------------------
2489 //
2490 //
2491
2492 /// \name Bounds Safety
2493 /// Implementations are in SemaBoundsSafety.cpp
2494 ///@{
2495public:
2496 /// Check if applying the specified attribute variant from the "counted by"
2497 /// family of attributes to FieldDecl \p FD is semantically valid. If
2498 /// semantically invalid diagnostics will be emitted explaining the problems.
2499 ///
2500 /// \param FD The FieldDecl to apply the attribute to
2501 /// \param E The count expression on the attribute
2502 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2503 /// attributes. If the false the attribute is from
2504 /// "counted_by" family of attributes.
2505 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2506 /// of attributes. If false the attribute does not have the
2507 /// suffix.
2508 ///
2509 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2510 /// \p CountInBytes and \p OrNull both being true indicates the
2511 /// `counted_by_or_null` attribute.
2512 ///
2513 /// \returns false iff semantically valid.
2514 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2515 bool OrNull);
2516
2517 /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2518 /// `__counted_by_or_null` pointer type \param LHSTy.
2519 ///
2520 /// \param LHSTy The type being assigned to. Checks will only be performed if
2521 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2522 /// \param RHSExpr The expression being assigned from.
2523 /// \param Action The type assignment being performed
2524 /// \param Loc The SourceLocation to use for error diagnostics
2525 /// \param Assignee The ValueDecl being assigned. This is used to compute
2526 /// the name of the assignee. If the assignee isn't known this can
2527 /// be set to nullptr.
2528 /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2529 /// Assignee to compute the name of the assignee use the fully
2530 /// qualified name, otherwise use the unqualified name.
2531 ///
2532 /// \returns True iff no diagnostic where emitted, false otherwise.
2533 bool BoundsSafetyCheckAssignmentToCountAttrPtr(
2534 QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2535 SourceLocation Loc, const ValueDecl *Assignee,
2536 bool ShowFullyQualifiedAssigneeName);
2537
2538 /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2539 /// pointer.
2540 ///
2541 /// \param Entity The entity being initialized
2542 /// \param Kind The kind of initialization being performed
2543 /// \param Action The type assignment being performed
2544 /// \param LHSTy The type being assigned to. Checks will only be performed if
2545 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2546 /// \param RHSExpr The expression being used for initialization.
2547 ///
2548 /// \returns True iff no diagnostic where emitted, false otherwise.
2549 bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity,
2550 const InitializationKind &Kind,
2551 AssignmentAction Action,
2552 QualType LHSType, Expr *RHSExpr);
2553
2554 /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2555 /// or counted_by_or_null pointers in \param E.
2556 ///
2557 /// \param E the expression to check
2558 ///
2559 /// \returns True iff no diagnostic where emitted, false otherwise.
2560 bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E);
2561 ///@}
2562
2563 //
2564 //
2565 // -------------------------------------------------------------------------
2566 //
2567 //
2568
2569 /// \name Casts
2570 /// Implementations are in SemaCast.cpp
2571 ///@{
2572
2573public:
2574 static bool isCast(CheckedConversionKind CCK) {
2575 return CCK == CheckedConversionKind::CStyleCast ||
2576 CCK == CheckedConversionKind::FunctionalCast ||
2577 CCK == CheckedConversionKind::OtherCast;
2578 }
2579
2580 /// ActOnCXXNamedCast - Parse
2581 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2582 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2583 SourceLocation LAngleBracketLoc, Declarator &D,
2584 SourceLocation RAngleBracketLoc,
2585 SourceLocation LParenLoc, Expr *E,
2586 SourceLocation RParenLoc);
2587
2588 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2589 TypeSourceInfo *Ty, Expr *E,
2590 SourceRange AngleBrackets, SourceRange Parens);
2591
2592 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
2593 ExprResult Operand,
2594 SourceLocation RParenLoc);
2595
2596 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
2597 Expr *Operand, SourceLocation RParenLoc);
2598
2599 // Checks that reinterpret casts don't have undefined behavior.
2600 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2601 bool IsDereference, SourceRange Range);
2602
2603 // Checks that the vector type should be initialized from a scalar
2604 // by splatting the value rather than populating a single element.
2605 // This is the case for AltiVecVector types as well as with
2606 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2607 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2608
2609 // Checks if the -faltivec-src-compat=gcc option is specified.
2610 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2611 // treated the same way as they are when trying to initialize
2612 // these vectors on gcc (an error is emitted).
2613 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
2614 QualType SrcTy);
2615
2616 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
2617 SourceLocation RParenLoc, Expr *Op);
2618
2619 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
2620 SourceLocation LParenLoc,
2621 Expr *CastExpr,
2622 SourceLocation RParenLoc);
2623
2624 ///@}
2625
2626 //
2627 //
2628 // -------------------------------------------------------------------------
2629 //
2630 //
2631
2632 /// \name Extra Semantic Checking
2633 /// Implementations are in SemaChecking.cpp
2634 ///@{
2635
2636public:
2637 /// Used to change context to isConstantEvaluated without pushing a heavy
2638 /// ExpressionEvaluationContextRecord object.
2639 bool isConstantEvaluatedOverride = false;
2640
2641 bool isConstantEvaluatedContext() const {
2642 return currentEvaluationContext().isConstantEvaluated() ||
2643 isConstantEvaluatedOverride;
2644 }
2645
2646 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
2647 unsigned ByteNo) const;
2648
2649 enum FormatArgumentPassingKind {
2650 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2651 FAPK_Variadic, // values to format are passed as variadic arguments
2652 FAPK_VAList, // values to format are passed in a va_list
2653 FAPK_Elsewhere, // values to format are not passed to this function
2654 };
2655
2656 // Used to grab the relevant information from a FormatAttr and a
2657 // FunctionDeclaration.
2658 struct FormatStringInfo {
2659 unsigned FormatIdx;
2660 unsigned FirstDataArg;
2661 FormatArgumentPassingKind ArgPassingKind;
2662 };
2663
2664 /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2665 /// populate the FormatStringInfo parameter with the attribute's correct
2666 /// format_idx and firstDataArg. Returns true when the format fits the
2667 /// function and the FormatStringInfo has been populated.
2668 static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2669 unsigned FirstArg, FormatStringInfo *FSI);
2670 static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2671 bool HasImplicitThisParam, bool IsVariadic,
2672 FormatStringInfo *FSI);
2673
2674 // Used by C++ template instantiation.
2675 ExprResult BuiltinShuffleVector(CallExpr *TheCall);
2676
2677 /// ConvertVectorExpr - Handle __builtin_convertvector
2678 ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2679 SourceLocation BuiltinLoc,
2680 SourceLocation RParenLoc);
2681
2682 static StringRef GetFormatStringTypeName(FormatStringType FST);
2683 static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2684 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2685 static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2686
2687 bool FormatStringHasSArg(const StringLiteral *FExpr);
2688
2689 /// Check for comparisons of floating-point values using == and !=. Issue a
2690 /// warning if the comparison is not likely to do what the programmer
2691 /// intended.
2692 void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2693 const Expr *RHS, BinaryOperatorKind Opcode);
2694
2695 /// Register a magic integral constant to be used as a type tag.
2696 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2697 uint64_t MagicValue, QualType Type,
2698 bool LayoutCompatible, bool MustBeNull);
2699
2700 struct TypeTagData {
2701 TypeTagData() {}
2702
2703 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
2704 : Type(Type), LayoutCompatible(LayoutCompatible),
2705 MustBeNull(MustBeNull) {}
2706
2707 QualType Type;
2708
2709 /// If true, \c Type should be compared with other expression's types for
2710 /// layout-compatibility.
2711 LLVM_PREFERRED_TYPE(bool)
2712 unsigned LayoutCompatible : 1;
2713 LLVM_PREFERRED_TYPE(bool)
2714 unsigned MustBeNull : 1;
2715 };
2716
2717 /// A pair of ArgumentKind identifier and magic value. This uniquely
2718 /// identifies the magic value.
2719 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2720
2721 /// Diagnoses the current set of gathered accesses. This happens at the end of
2722 /// each expression evaluation context. Diagnostics are emitted only for
2723 /// accesses gathered in the current evaluation context.
2724 void DiagnoseMisalignedMembers();
2725
2726 /// This function checks if the expression is in the sef of potentially
2727 /// misaligned members and it is converted to some pointer type T with lower
2728 /// or equal alignment requirements. If so it removes it. This is used when
2729 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2730 /// void*).
2731 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2732
2733 /// Returns true if `From` is a function or pointer to a function with the
2734 /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2735 /// function without this attribute.
2736 bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2737
2738 /// This function calls Action when it determines that E designates a
2739 /// misaligned member due to the packed attribute. This is used to emit
2740 /// local diagnostics like in reference binding.
2741 void RefersToMemberWithReducedAlignment(
2742 Expr *E,
2743 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2744 Action);
2745
2746 enum class AtomicArgumentOrder { API, AST };
2747 ExprResult
2748 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2749 SourceLocation RParenLoc, MultiExprArg Args,
2750 AtomicExpr::AtomicOp Op,
2751 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
2752
2753 /// Check to see if a given expression could have '.c_str()' called on it.
2754 bool hasCStrMethod(const Expr *E);
2755
2756 /// Diagnose pointers that are always non-null.
2757 /// \param E the expression containing the pointer
2758 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2759 /// compared to a null pointer
2760 /// \param IsEqual True when the comparison is equal to a null pointer
2761 /// \param Range Extra SourceRange to highlight in the diagnostic
2762 void DiagnoseAlwaysNonNullPointer(Expr *E,
2763 Expr::NullPointerConstantKind NullType,
2764 bool IsEqual, SourceRange Range);
2765
2766 /// CheckParmsForFunctionDef - Check that the parameters of the given
2767 /// function are appropriate for the definition of a function. This
2768 /// takes care of any checks that cannot be performed on the
2769 /// declaration itself, e.g., that the types of each of the function
2770 /// parameters are complete.
2771 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2772 bool CheckParameterNames);
2773
2774 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2775 /// pointer cast increases the alignment requirements.
2776 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2777
2778 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2779 /// to weak/__unsafe_unretained type.
2780 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2781
2782 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2783 /// to weak/__unsafe_unretained expression.
2784 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2785
2786 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2787 /// statement as a \p Body, and it is located on the same line.
2788 ///
2789 /// This helps prevent bugs due to typos, such as:
2790 /// if (condition);
2791 /// do_stuff();
2792 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2793 unsigned DiagID);
2794
2795 /// Warn if a for/while loop statement \p S, which is followed by
2796 /// \p PossibleBody, has a suspicious null statement as a body.
2797 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2798
2799 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2800 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2801 SourceLocation OpLoc);
2802
2803 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2804 bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
2805 const TypeSourceInfo *Derived);
2806
2807 /// CheckFunctionCall - Check a direct function call for various correctness
2808 /// and safety properties not strictly enforced by the C type system.
2809 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2810 const FunctionProtoType *Proto);
2811
2812 enum class EltwiseBuiltinArgTyRestriction {
2813 None,
2814 FloatTy,
2815 IntegerTy,
2816 SignedIntOrFloatTy,
2817 };
2818
2819 /// \param FPOnly restricts the arguments to floating-point types.
2820 std::optional<QualType>
2821 BuiltinVectorMath(CallExpr *TheCall,
2822 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2823 EltwiseBuiltinArgTyRestriction::None);
2824 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2825
2826 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2827 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2828
2829 /// Handles the checks for format strings, non-POD arguments to vararg
2830 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2831 /// attributes and AArch64 SME attributes.
2832 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2833 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2834 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2835 VariadicCallType CallType);
2836
2837 /// Verify that two format strings (as understood by attribute(format) and
2838 /// attribute(format_matches) are compatible. If they are incompatible,
2839 /// diagnostics are emitted with the assumption that \c
2840 /// AuthoritativeFormatString is correct and
2841 /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2842 /// diagnostics will point to it and a note will refer to \c
2843 /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2844 bool
2845 CheckFormatStringsCompatible(FormatStringType FST,
2846 const StringLiteral *AuthoritativeFormatString,
2847 const StringLiteral *TestedFormatString,
2848 const Expr *FunctionCallArg = nullptr);
2849
2850 /// Verify that one format string (as understood by attribute(format)) is
2851 /// self-consistent; for instance, that it doesn't have multiple positional
2852 /// arguments referring to the same argument in incompatible ways. Diagnose
2853 /// if it isn't.
2854 bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str);
2855
2856 /// \brief Enforce the bounds of a TCB
2857 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2858 /// directly calls other functions in the same TCB as marked by the
2859 /// enforce_tcb and enforce_tcb_leaf attributes.
2860 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2861 const NamedDecl *Callee);
2862
2863 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2864
2865 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2866 /// TheCall is a constant expression.
2867 bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
2868 llvm::APSInt &Result);
2869
2870 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2871 /// TheCall is a constant expression in the range [Low, High].
2872 bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
2873 int High, bool RangeIsError = true);
2874
2875 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2876 /// TheCall is a constant expression is a multiple of Num..
2877 bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
2878 unsigned Multiple);
2879
2880 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2881 /// constant expression representing a power of 2.
2882 bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum);
2883
2884 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2885 /// a constant expression representing an arbitrary byte value shifted left by
2886 /// a multiple of 8 bits.
2887 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
2888 unsigned ArgBits);
2889
2890 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2891 /// TheCall is a constant expression representing either a shifted byte value,
2892 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2893 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2894 /// Arm MVE intrinsics.
2895 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum,
2896 unsigned ArgBits);
2897
2898 /// Checks that a call expression's argument count is at least the desired
2899 /// number. This is useful when doing custom type-checking on a variadic
2900 /// function. Returns true on error.
2901 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2902
2903 /// Checks that a call expression's argument count is at most the desired
2904 /// number. This is useful when doing custom type-checking on a variadic
2905 /// function. Returns true on error.
2906 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
2907
2908 /// Checks that a call expression's argument count is in the desired range.
2909 /// This is useful when doing custom type-checking on a variadic function.
2910 /// Returns true on error.
2911 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
2912 unsigned MaxArgCount);
2913
2914 /// Checks that a call expression's argument count is the desired number.
2915 /// This is useful when doing custom type-checking. Returns true on error.
2916 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
2917
2918 /// Returns true if the argument consists of one contiguous run of 1s with any
2919 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
2920 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
2921 /// since all 1s are not contiguous.
2922 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2923
2924 void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
2925 bool *ICContext = nullptr,
2926 bool IsListInit = false);
2927
2928 /// Check for overflow behavior type related implicit conversion diagnostics.
2929 /// Returns true if OBT-related diagnostic was issued, false otherwise.
2930 bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
2931 SourceLocation CC);
2932
2933 bool
2934 BuiltinElementwiseTernaryMath(CallExpr *TheCall,
2935 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2936 EltwiseBuiltinArgTyRestriction::FloatTy);
2937 bool PrepareBuiltinElementwiseMathOneArgCall(
2938 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
2939 EltwiseBuiltinArgTyRestriction::None);
2940
2941private:
2942 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2943 const ArraySubscriptExpr *ASE = nullptr,
2944 bool AllowOnePastEnd = true, bool IndexNegated = false);
2945 void CheckArrayAccess(const Expr *E);
2946
2947 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2948 const FunctionProtoType *Proto);
2949
2950 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2951 /// such as function pointers returned from functions.
2952 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
2953
2954 /// CheckConstructorCall - Check a constructor call for correctness and safety
2955 /// properties not enforced by the C type system.
2956 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
2957 ArrayRef<const Expr *> Args,
2958 const FunctionProtoType *Proto, SourceLocation Loc);
2959
2960 /// Warn if a pointer or reference argument passed to a function points to an
2961 /// object that is less aligned than the parameter. This can happen when
2962 /// creating a typedef with a lower alignment than the original type and then
2963 /// calling functions defined in terms of the original type.
2964 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
2965 StringRef ParamName, QualType ArgTy, QualType ParamTy);
2966
2967 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
2968
2969 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2970 CallExpr *TheCall);
2971
2972 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2973 CallExpr *TheCall);
2974
2975 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
2976
2977 /// Argument-value fortify checks for libc functions that are not builtins,
2978 /// dispatched by name (e.g. umask). Diagnostics belong to -Wfortify-source.
2979 void checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall);
2980
2981 /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
2982 /// or '__builtin_c23_va_start' for validity. Emit an error and return true
2983 /// on failure; return false on success.
2984 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
2985 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
2986
2987 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2988 /// friends. This is declared to take (...), so we have to check everything.
2989 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
2990
2991 /// BuiltinSemaBuiltinFPClassification - Handle functions like
2992 /// __builtin_isnan and friends. This is declared to take (...), so we have
2993 /// to check everything.
2994 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
2995 unsigned BuiltinID);
2996
2997 /// Perform semantic analysis for a call to __builtin_complex.
2998 bool BuiltinComplex(CallExpr *TheCall);
2999 bool BuiltinOSLogFormat(CallExpr *TheCall);
3000
3001 /// BuiltinPrefetch - Handle __builtin_prefetch.
3002 /// This is declared to take (const void*, ...) and can take two
3003 /// optional constant int args.
3004 bool BuiltinPrefetch(CallExpr *TheCall);
3005
3006 /// Handle __builtin_alloca_with_align. This is declared
3007 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3008 /// than 8.
3009 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
3010
3011 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
3012 bool BuiltinArithmeticFence(CallExpr *TheCall);
3013
3014 /// BuiltinAssume - Handle __assume (MS Extension).
3015 /// __assume does not evaluate its arguments, and should warn if its argument
3016 /// has side effects.
3017 bool BuiltinAssume(CallExpr *TheCall);
3018
3019 /// Handle __builtin_assume_aligned. This is declared
3020 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3021 bool BuiltinAssumeAligned(CallExpr *TheCall);
3022
3023 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3024 /// This checks that the target supports __builtin_longjmp and
3025 /// that val is a constant 1.
3026 bool BuiltinLongjmp(CallExpr *TheCall);
3027
3028 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3029 /// This checks that the target supports __builtin_setjmp.
3030 bool BuiltinSetjmp(CallExpr *TheCall);
3031
3032 /// We have a call to a function like __sync_fetch_and_add, which is an
3033 /// overloaded function based on the pointer type of its first argument.
3034 /// The main BuildCallExpr routines have already promoted the types of
3035 /// arguments because all of these calls are prototyped as void(...).
3036 ///
3037 /// This function goes through and does final semantic checking for these
3038 /// builtins, as well as generating any warnings.
3039 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
3040
3041 /// BuiltinNontemporalOverloaded - We have a call to
3042 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3043 /// overloaded function based on the pointer type of its last argument.
3044 ///
3045 /// This function goes through and does final semantic checking for these
3046 /// builtins.
3047 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
3048 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
3049 AtomicExpr::AtomicOp Op);
3050
3051 /// \param FPOnly restricts the arguments to floating-point types.
3052 bool BuiltinElementwiseMath(CallExpr *TheCall,
3053 EltwiseBuiltinArgTyRestriction ArgTyRestr =
3054 EltwiseBuiltinArgTyRestriction::None);
3055 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
3056
3057 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
3058
3059 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
3060 BuiltinCountedByRefKind K);
3061 bool BuiltinCountedByRef(CallExpr *TheCall);
3062
3063 // Matrix builtin handling.
3064 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
3065 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
3066 ExprResult CallResult);
3067 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
3068 ExprResult CallResult);
3069
3070 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3071 /// functions) for correct use of format strings.
3072 /// Returns true if a format string has been fully checked.
3073 bool CheckFormatArguments(const FormatAttr *Format,
3074 ArrayRef<const Expr *> Args, bool IsCXXMember,
3075 VariadicCallType CallType, SourceLocation Loc,
3076 SourceRange Range,
3077 llvm::SmallBitVector &CheckedVarArgs);
3078 bool CheckFormatString(const FormatMatchesAttr *Format,
3079 ArrayRef<const Expr *> Args, bool IsCXXMember,
3080 VariadicCallType CallType, SourceLocation Loc,
3081 SourceRange Range,
3082 llvm::SmallBitVector &CheckedVarArgs);
3083 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3084 FormatArgumentPassingKind FAPK,
3085 StringLiteral *ReferenceFormatString,
3086 unsigned format_idx, unsigned firstDataArg,
3087 FormatStringType Type, VariadicCallType CallType,
3088 SourceLocation Loc, SourceRange range,
3089 llvm::SmallBitVector &CheckedVarArgs);
3090
3091 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3092
3093 /// Warn when using the wrong abs() function.
3094 void CheckAbsoluteValueFunction(const CallExpr *Call,
3095 const FunctionDecl *FDecl);
3096
3097 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3098
3099 /// Check for dangerous or invalid arguments to memset().
3100 ///
3101 /// This issues warnings on known problematic, dangerous or unspecified
3102 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3103 /// function calls.
3104 ///
3105 /// \param Call The call expression to diagnose.
3106 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3107 IdentifierInfo *FnName);
3108
3109 bool CheckSizeofMemaccessArgument(const Expr *SizeOfArg, const Expr *Dest,
3110 IdentifierInfo *FnName);
3111 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3112 // be the size of the source, instead of the destination.
3113 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3114
3115 // Warn on anti-patterns as the 'size' argument to strncat.
3116 // The correct size argument should look like following:
3117 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3118 void CheckStrncatArguments(const CallExpr *Call,
3119 const IdentifierInfo *FnName);
3120
3121 /// Alerts the user that they are attempting to free a non-malloc'd object.
3122 void CheckFreeArguments(const CallExpr *E);
3123
3124 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3125 SourceLocation ReturnLoc, bool isObjCMethod = false,
3126 const AttrVec *Attrs = nullptr,
3127 const FunctionDecl *FD = nullptr);
3128
3129 /// Diagnoses "dangerous" implicit conversions within the given
3130 /// expression (which is a full expression). Implements -Wconversion
3131 /// and -Wsign-compare.
3132 ///
3133 /// \param CC the "context" location of the implicit conversion, i.e.
3134 /// the most location of the syntactic entity requiring the implicit
3135 /// conversion
3136 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3137
3138 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3139 /// Input argument E is a logical expression.
3140 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
3141
3142 /// Diagnose when expression is an integer constant expression and its
3143 /// evaluation results in integer overflow
3144 void CheckForIntOverflow(const Expr *E);
3145 void CheckUnsequencedOperations(const Expr *E);
3146
3147 /// Perform semantic checks on a completed expression. This will either
3148 /// be a full-expression or a default argument expression.
3149 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3150 bool IsConstexpr = false);
3151
3152 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3153 Expr *Init);
3154
3155 /// A map from magic value to type information.
3156 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3157 TypeTagForDatatypeMagicValues;
3158
3159 /// Peform checks on a call of a function with argument_with_type_tag
3160 /// or pointer_with_type_tag attributes.
3161 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3162 const ArrayRef<const Expr *> ExprArgs,
3163 SourceLocation CallSiteLoc);
3164
3165 /// Check if we are taking the address of a packed field
3166 /// as this may be a problem if the pointer value is dereferenced.
3167 void CheckAddressOfPackedMember(Expr *rhs);
3168
3169 /// Helper class that collects misaligned member designations and
3170 /// their location info for delayed diagnostics.
3171 struct MisalignedMember {
3172 Expr *E;
3173 RecordDecl *RD;
3174 ValueDecl *MD;
3175 CharUnits Alignment;
3176
3177 MisalignedMember() : E(), RD(), MD() {}
3178 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3179 CharUnits Alignment)
3180 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
3181 explicit MisalignedMember(Expr *E)
3182 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3183
3184 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3185 };
3186
3187 /// Adds an expression to the set of gathered misaligned members.
3188 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3189 CharUnits Alignment);
3190 ///@}
3191
3192 //
3193 //
3194 // -------------------------------------------------------------------------
3195 //
3196 //
3197
3198 /// \name C++ Coroutines
3199 /// Implementations are in SemaCoroutine.cpp
3200 ///@{
3201
3202public:
3203 /// The C++ "std::coroutine_traits" template, which is defined in
3204 /// \<coroutine_traits>
3205 ClassTemplateDecl *StdCoroutineTraitsCache;
3206
3207 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
3208 StringRef Keyword);
3209 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3210 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3211 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
3212
3213 ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
3214 ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
3215 UnresolvedLookupExpr *Lookup);
3216 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3217 Expr *Awaiter, bool IsImplicit = false);
3218 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3219 UnresolvedLookupExpr *Lookup);
3220 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
3221 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
3222 bool IsImplicit = false);
3223 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
3224 bool buildCoroutineParameterMoves(SourceLocation Loc);
3225 VarDecl *buildCoroutinePromise(SourceLocation Loc);
3226 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
3227
3228 // As a clang extension, enforces that a non-coroutine function must be marked
3229 // with [[clang::coro_wrapper]] if it returns a type marked with
3230 // [[clang::coro_return_type]].
3231 // Expects that FD is not a coroutine.
3232 void CheckCoroutineWrapper(FunctionDecl *FD);
3233 /// Lookup 'coroutine_traits' in std namespace and std::experimental
3234 /// namespace. The namespace found is recorded in Namespace.
3235 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
3236 SourceLocation FuncLoc);
3237 /// Check that the expression co_await promise.final_suspend() shall not be
3238 /// potentially-throwing.
3239 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3240
3241 ///@}
3242
3243 //
3244 //
3245 // -------------------------------------------------------------------------
3246 //
3247 //
3248
3249 /// \name C++ Scope Specifiers
3250 /// Implementations are in SemaCXXScopeSpec.cpp
3251 ///@{
3252
3253public:
3254 // Marks SS invalid if it represents an incomplete type.
3255 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
3256 // Complete an enum decl, maybe without a scope spec.
3257 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
3258 CXXScopeSpec *SS = nullptr);
3259
3260 /// Compute the DeclContext that is associated with the given type.
3261 ///
3262 /// \param T the type for which we are attempting to find a DeclContext.
3263 ///
3264 /// \returns the declaration context represented by the type T,
3265 /// or NULL if the declaration context cannot be computed (e.g., because it is
3266 /// dependent and not the current instantiation).
3267 DeclContext *computeDeclContext(QualType T);
3268
3269 /// Compute the DeclContext that is associated with the given
3270 /// scope specifier.
3271 ///
3272 /// \param SS the C++ scope specifier as it appears in the source
3273 ///
3274 /// \param EnteringContext when true, we will be entering the context of
3275 /// this scope specifier, so we can retrieve the declaration context of a
3276 /// class template or class template partial specialization even if it is
3277 /// not the current instantiation.
3278 ///
3279 /// \returns the declaration context represented by the scope specifier @p SS,
3280 /// or NULL if the declaration context cannot be computed (e.g., because it is
3281 /// dependent and not the current instantiation).
3282 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
3283 bool EnteringContext = false);
3284 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
3285
3286 /// If the given nested name specifier refers to the current
3287 /// instantiation, return the declaration that corresponds to that
3288 /// current instantiation (C++0x [temp.dep.type]p1).
3289 ///
3290 /// \param NNS a dependent nested name specifier.
3291 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier NNS);
3292
3293 /// The parser has parsed a global nested-name-specifier '::'.
3294 ///
3295 /// \param CCLoc The location of the '::'.
3296 ///
3297 /// \param SS The nested-name-specifier, which will be updated in-place
3298 /// to reflect the parsed nested-name-specifier.
3299 ///
3300 /// \returns true if an error occurred, false otherwise.
3301 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
3302
3303 /// The parser has parsed a '__super' nested-name-specifier.
3304 ///
3305 /// \param SuperLoc The location of the '__super' keyword.
3306 ///
3307 /// \param ColonColonLoc The location of the '::'.
3308 ///
3309 /// \param SS The nested-name-specifier, which will be updated in-place
3310 /// to reflect the parsed nested-name-specifier.
3311 ///
3312 /// \returns true if an error occurred, false otherwise.
3313 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
3314 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3315
3316 /// Determines whether the given declaration is an valid acceptable
3317 /// result for name lookup of a nested-name-specifier.
3318 /// \param SD Declaration checked for nested-name-specifier.
3319 /// \param IsExtension If not null and the declaration is accepted as an
3320 /// extension, the pointed variable is assigned true.
3321 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
3322 bool *CanCorrect = nullptr);
3323
3324 /// If the given nested-name-specifier begins with a bare identifier
3325 /// (e.g., Base::), perform name lookup for that identifier as a
3326 /// nested-name-specifier within the given scope, and return the result of
3327 /// that name lookup.
3328 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier NNS);
3329
3330 /// Keeps information about an identifier in a nested-name-spec.
3331 ///
3332 struct NestedNameSpecInfo {
3333 /// The type of the object, if we're parsing nested-name-specifier in
3334 /// a member access expression.
3335 ParsedType ObjectType;
3336
3337 /// The identifier preceding the '::'.
3338 IdentifierInfo *Identifier;
3339
3340 /// The location of the identifier.
3341 SourceLocation IdentifierLoc;
3342
3343 /// The location of the '::'.
3344 SourceLocation CCLoc;
3345
3346 /// Creates info object for the most typical case.
3347 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3348 SourceLocation ColonColonLoc,
3349 ParsedType ObjectType = ParsedType())
3350 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
3351 CCLoc(ColonColonLoc) {}
3352
3353 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3354 SourceLocation ColonColonLoc, QualType ObjectType)
3355 : ObjectType(ParsedType::make(P: ObjectType)), Identifier(II),
3356 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3357 };
3358
3359 /// Build a new nested-name-specifier for "identifier::", as described
3360 /// by ActOnCXXNestedNameSpecifier.
3361 ///
3362 /// \param S Scope in which the nested-name-specifier occurs.
3363 /// \param IdInfo Parser information about an identifier in the
3364 /// nested-name-spec.
3365 /// \param EnteringContext If true, enter the context specified by the
3366 /// nested-name-specifier.
3367 /// \param SS Optional nested name specifier preceding the identifier.
3368 /// \param ScopeLookupResult Provides the result of name lookup within the
3369 /// scope of the nested-name-specifier that was computed at template
3370 /// definition time.
3371 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3372 /// error recovery and what kind of recovery is performed.
3373 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3374 /// are allowed. The bool value pointed by this parameter is set to
3375 /// 'true' if the identifier is treated as if it was followed by ':',
3376 /// not '::'.
3377 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3378 ///
3379 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3380 /// that it contains an extra parameter \p ScopeLookupResult, which provides
3381 /// the result of name lookup within the scope of the nested-name-specifier
3382 /// that was computed at template definition time.
3383 ///
3384 /// If ErrorRecoveryLookup is true, then this call is used to improve error
3385 /// recovery. This means that it should not emit diagnostics, it should
3386 /// just return true on failure. It also means it should only return a valid
3387 /// scope if it *knows* that the result is correct. It should not return in a
3388 /// dependent context, for example. Nor will it extend \p SS with the scope
3389 /// specifier.
3390 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3391 bool EnteringContext, CXXScopeSpec &SS,
3392 NamedDecl *ScopeLookupResult,
3393 bool ErrorRecoveryLookup,
3394 bool *IsCorrectedToColon = nullptr,
3395 bool OnlyNamespace = false);
3396
3397 /// The parser has parsed a nested-name-specifier 'identifier::'.
3398 ///
3399 /// \param S The scope in which this nested-name-specifier occurs.
3400 ///
3401 /// \param IdInfo Parser information about an identifier in the
3402 /// nested-name-spec.
3403 ///
3404 /// \param EnteringContext Whether we're entering the context nominated by
3405 /// this nested-name-specifier.
3406 ///
3407 /// \param SS The nested-name-specifier, which is both an input
3408 /// parameter (the nested-name-specifier before this type) and an
3409 /// output parameter (containing the full nested-name-specifier,
3410 /// including this new type).
3411 ///
3412 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3413 /// are allowed. The bool value pointed by this parameter is set to 'true'
3414 /// if the identifier is treated as if it was followed by ':', not '::'.
3415 ///
3416 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3417 ///
3418 /// \returns true if an error occurred, false otherwise.
3419 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3420 bool EnteringContext, CXXScopeSpec &SS,
3421 bool *IsCorrectedToColon = nullptr,
3422 bool OnlyNamespace = false);
3423
3424 /// The parser has parsed a nested-name-specifier
3425 /// 'template[opt] template-name < template-args >::'.
3426 ///
3427 /// \param S The scope in which this nested-name-specifier occurs.
3428 ///
3429 /// \param SS The nested-name-specifier, which is both an input
3430 /// parameter (the nested-name-specifier before this type) and an
3431 /// output parameter (containing the full nested-name-specifier,
3432 /// including this new type).
3433 ///
3434 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3435 /// \param TemplateName the template name.
3436 /// \param TemplateNameLoc The location of the template name.
3437 /// \param LAngleLoc The location of the opening angle bracket ('<').
3438 /// \param TemplateArgs The template arguments.
3439 /// \param RAngleLoc The location of the closing angle bracket ('>').
3440 /// \param CCLoc The location of the '::'.
3441 ///
3442 /// \param EnteringContext Whether we're entering the context of the
3443 /// nested-name-specifier.
3444 ///
3445 ///
3446 /// \returns true if an error occurred, false otherwise.
3447 bool ActOnCXXNestedNameSpecifier(
3448 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3449 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3450 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3451 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3452
3453 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS,
3454 SourceLocation ColonColonLoc);
3455
3456 bool ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS,
3457 const DeclSpec &DS,
3458 SourceLocation ColonColonLoc,
3459 QualType Type);
3460
3461 /// IsInvalidUnlessNestedName - This method is used for error recovery
3462 /// purposes to determine whether the specified identifier is only valid as
3463 /// a nested name specifier, for example a namespace name. It is
3464 /// conservatively correct to always return false from this method.
3465 ///
3466 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3467 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3468 NestedNameSpecInfo &IdInfo,
3469 bool EnteringContext);
3470
3471 /// Given a C++ nested-name-specifier, produce an annotation value
3472 /// that the parser can use later to reconstruct the given
3473 /// nested-name-specifier.
3474 ///
3475 /// \param SS A nested-name-specifier.
3476 ///
3477 /// \returns A pointer containing all of the information in the
3478 /// nested-name-specifier \p SS.
3479 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3480
3481 /// Given an annotation pointer for a nested-name-specifier, restore
3482 /// the nested-name-specifier structure.
3483 ///
3484 /// \param Annotation The annotation pointer, produced by
3485 /// \c SaveNestedNameSpecifierAnnotation().
3486 ///
3487 /// \param AnnotationRange The source range corresponding to the annotation.
3488 ///
3489 /// \param SS The nested-name-specifier that will be updated with the contents
3490 /// of the annotation pointer.
3491 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3492 SourceRange AnnotationRange,
3493 CXXScopeSpec &SS);
3494
3495 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3496
3497 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3498 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3499 /// After this method is called, according to [C++ 3.4.3p3], names should be
3500 /// looked up in the declarator-id's scope, until the declarator is parsed and
3501 /// ActOnCXXExitDeclaratorScope is called.
3502 /// The 'SS' should be a non-empty valid CXXScopeSpec.
3503 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
3504
3505 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3506 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3507 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3508 /// Used to indicate that names should revert to being looked up in the
3509 /// defining scope.
3510 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3511
3512 ///@}
3513
3514 //
3515 //
3516 // -------------------------------------------------------------------------
3517 //
3518 //
3519
3520 /// \name Declarations
3521 /// Implementations are in SemaDecl.cpp
3522 ///@{
3523
3524public:
3525 IdentifierResolver IdResolver;
3526
3527 /// The index of the first InventedParameterInfo that refers to the current
3528 /// context.
3529 unsigned InventedParameterInfosStart = 0;
3530
3531 /// A RAII object to temporarily push a declaration context.
3532 class ContextRAII {
3533 private:
3534 Sema &S;
3535 DeclContext *SavedContext;
3536 ProcessingContextState SavedContextState;
3537 QualType SavedCXXThisTypeOverride;
3538 unsigned SavedFunctionScopesStart;
3539 unsigned SavedInventedParameterInfosStart;
3540
3541 public:
3542 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3543 : S(S), SavedContext(S.CurContext),
3544 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3545 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3546 SavedFunctionScopesStart(S.FunctionScopesStart),
3547 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3548 assert(ContextToPush && "pushing null context");
3549 S.CurContext = ContextToPush;
3550 if (NewThisContext)
3551 S.CXXThisTypeOverride = QualType();
3552 // Any saved FunctionScopes do not refer to this context.
3553 S.FunctionScopesStart = S.FunctionScopes.size();
3554 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3555 }
3556
3557 void pop() {
3558 if (!SavedContext)
3559 return;
3560 S.CurContext = SavedContext;
3561 S.DelayedDiagnostics.popUndelayed(state: SavedContextState);
3562 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3563 S.FunctionScopesStart = SavedFunctionScopesStart;
3564 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3565 SavedContext = nullptr;
3566 }
3567
3568 ~ContextRAII() { pop(); }
3569 ContextRAII(const ContextRAII &) = delete;
3570 ContextRAII &operator=(const ContextRAII &) = delete;
3571 };
3572
3573 void DiagnoseInvalidJumps(Stmt *Body);
3574
3575 /// The function definitions which were renamed as part of typo-correction
3576 /// to match their respective declarations. We want to keep track of them
3577 /// to ensure that we don't emit a "redefinition" error if we encounter a
3578 /// correctly named definition after the renamed definition.
3579 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
3580
3581 /// A cache of the flags available in enumerations with the flag_enum
3582 /// attribute.
3583 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3584
3585 /// A cache of enumerator values for enums checked by -Wassign-enum.
3586 llvm::DenseMap<const EnumDecl *, llvm::SmallVector<llvm::APSInt>>
3587 AssignEnumCache;
3588
3589 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3590 /// declared. Rare. May alias another identifier, declared or undeclared.
3591 ///
3592 /// For aliases, the target identifier is used as a key for eventual
3593 /// processing when the target is declared. For the single-identifier form,
3594 /// the sole identifier is used as the key. Each entry is a `SetVector`
3595 /// (ordered by parse order) of aliases (identified by the alias name) in case
3596 /// of multiple aliases to the same undeclared identifier.
3597 llvm::MapVector<
3598 IdentifierInfo *,
3599 llvm::SetVector<
3600 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
3601 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3602 WeakUndeclaredIdentifiers;
3603
3604 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3605 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3606 /// to define functions that occur in multiple standards to call the version
3607 /// in the currently selected standard.
3608 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>
3609 ExtnameUndeclaredIdentifiers;
3610
3611 /// Set containing all typedefs that are likely unused.
3612 llvm::SmallPtrSet<const TypedefNameDecl *, 4>
3613 UnusedLocalTypedefNameCandidates;
3614
3615 /// Store UnusedLocalTypedefNameCandidates in \p Sorted in a deterministic
3616 /// order.
3617 void getSortedUnusedLocalTypedefNameCandidates(
3618 SmallVectorImpl<const TypedefNameDecl *> &Sorted) const;
3619
3620 typedef LazyVector<const DeclaratorDecl *,
3621 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
3622 UnusedFileScopedDeclsType;
3623
3624 /// The set of file scoped decls seen so far that have not been used
3625 /// and must warn if not used. Only contains the first declaration.
3626 UnusedFileScopedDeclsType UnusedFileScopedDecls;
3627
3628 typedef LazyVector<VarDecl *, &ExternalSemaSource::ReadTentativeDefinitions,
3629 2, 2>
3630 TentativeDefinitionsType;
3631
3632 /// All the tentative definitions encountered in the TU.
3633 TentativeDefinitionsType TentativeDefinitions;
3634
3635 /// All the external declarations encoutered and used in the TU.
3636 SmallVector<DeclaratorDecl *, 4> ExternalDeclarations;
3637
3638 /// Generally null except when we temporarily switch decl contexts,
3639 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3640 DeclContext *OriginalLexicalContext;
3641
3642 /// Is the module scope we are in a C++ Header Unit?
3643 bool currentModuleIsHeaderUnit() const {
3644 return ModuleScopes.empty() ? false
3645 : ModuleScopes.back().Module->isHeaderUnit();
3646 }
3647
3648 /// Get the module owning an entity.
3649 Module *getOwningModule(const Decl *Entity) {
3650 return Entity->getOwningModule();
3651 }
3652
3653 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3654
3655 enum class DiagCtorKind { None, Implicit, Typename };
3656 /// Returns the TypeDeclType for the given type declaration,
3657 /// as ASTContext::getTypeDeclType would, but
3658 /// performs the required semantic checks for name lookup of said entity.
3659 void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD,
3660 SourceLocation NameLoc);
3661
3662 /// If the identifier refers to a type name within this scope,
3663 /// return the declaration of that type.
3664 ///
3665 /// This routine performs ordinary name lookup of the identifier II
3666 /// within the given scope, with optional C++ scope specifier SS, to
3667 /// determine whether the name refers to a type. If so, returns an
3668 /// opaque pointer (actually a QualType) corresponding to that
3669 /// type. Otherwise, returns NULL.
3670 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
3671 Scope *S, CXXScopeSpec *SS = nullptr,
3672 bool isClassName = false, bool HasTrailingDot = false,
3673 ParsedType ObjectType = nullptr,
3674 bool IsCtorOrDtorName = false,
3675 bool WantNontrivialTypeSourceInfo = false,
3676 bool IsClassTemplateDeductionContext = true,
3677 ImplicitTypenameContext AllowImplicitTypename =
3678 ImplicitTypenameContext::No,
3679 IdentifierInfo **CorrectedII = nullptr);
3680
3681 /// isTagName() - This method is called *for error recovery purposes only*
3682 /// to determine if the specified name is a valid tag name ("struct foo"). If
3683 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3684 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3685 /// diagnose cases in C where the user forgot to specify the tag.
3686 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
3687
3688 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3689 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3690 /// then downgrade the missing typename error to a warning.
3691 /// This is needed for MSVC compatibility; Example:
3692 /// @code
3693 /// template<class T> class A {
3694 /// public:
3695 /// typedef int TYPE;
3696 /// };
3697 /// template<class T> class B : public A<T> {
3698 /// public:
3699 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3700 /// };
3701 /// @endcode
3702 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3703 void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc,
3704 Scope *S, CXXScopeSpec *SS,
3705 ParsedType &SuggestedType,
3706 bool IsTemplateName = false);
3707
3708 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3709 /// type name has failed in a dependent context. In these situations, we
3710 /// automatically form a DependentTypeName that will retry lookup in a related
3711 /// scope during instantiation.
3712 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
3713 SourceLocation NameLoc,
3714 bool IsTemplateTypeArg);
3715
3716 class NameClassification {
3717 NameClassificationKind Kind;
3718 union {
3719 ExprResult Expr;
3720 NamedDecl *NonTypeDecl;
3721 TemplateName Template;
3722 ParsedType Type;
3723 };
3724
3725 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3726
3727 public:
3728 NameClassification(ParsedType Type)
3729 : Kind(NameClassificationKind::Type), Type(Type) {}
3730
3731 NameClassification(const IdentifierInfo *Keyword)
3732 : Kind(NameClassificationKind::Keyword) {}
3733
3734 static NameClassification Error() {
3735 return NameClassification(NameClassificationKind::Error);
3736 }
3737
3738 static NameClassification Unknown() {
3739 return NameClassification(NameClassificationKind::Unknown);
3740 }
3741
3742 static NameClassification OverloadSet(ExprResult E) {
3743 NameClassification Result(NameClassificationKind::OverloadSet);
3744 Result.Expr = E;
3745 return Result;
3746 }
3747
3748 static NameClassification NonType(NamedDecl *D) {
3749 NameClassification Result(NameClassificationKind::NonType);
3750 Result.NonTypeDecl = D;
3751 return Result;
3752 }
3753
3754 static NameClassification UndeclaredNonType() {
3755 return NameClassification(NameClassificationKind::UndeclaredNonType);
3756 }
3757
3758 static NameClassification DependentNonType() {
3759 return NameClassification(NameClassificationKind::DependentNonType);
3760 }
3761
3762 static NameClassification TypeTemplate(TemplateName Name) {
3763 NameClassification Result(NameClassificationKind::TypeTemplate);
3764 Result.Template = Name;
3765 return Result;
3766 }
3767
3768 static NameClassification VarTemplate(TemplateName Name) {
3769 NameClassification Result(NameClassificationKind::VarTemplate);
3770 Result.Template = Name;
3771 return Result;
3772 }
3773
3774 static NameClassification FunctionTemplate(TemplateName Name) {
3775 NameClassification Result(NameClassificationKind::FunctionTemplate);
3776 Result.Template = Name;
3777 return Result;
3778 }
3779
3780 static NameClassification Concept(TemplateName Name) {
3781 NameClassification Result(NameClassificationKind::Concept);
3782 Result.Template = Name;
3783 return Result;
3784 }
3785
3786 static NameClassification UndeclaredTemplate(TemplateName Name) {
3787 NameClassification Result(NameClassificationKind::UndeclaredTemplate);
3788 Result.Template = Name;
3789 return Result;
3790 }
3791
3792 NameClassificationKind getKind() const { return Kind; }
3793
3794 ExprResult getExpression() const {
3795 assert(Kind == NameClassificationKind::OverloadSet);
3796 return Expr;
3797 }
3798
3799 ParsedType getType() const {
3800 assert(Kind == NameClassificationKind::Type);
3801 return Type;
3802 }
3803
3804 NamedDecl *getNonTypeDecl() const {
3805 assert(Kind == NameClassificationKind::NonType);
3806 return NonTypeDecl;
3807 }
3808
3809 TemplateName getTemplateName() const {
3810 assert(Kind == NameClassificationKind::TypeTemplate ||
3811 Kind == NameClassificationKind::FunctionTemplate ||
3812 Kind == NameClassificationKind::VarTemplate ||
3813 Kind == NameClassificationKind::Concept ||
3814 Kind == NameClassificationKind::UndeclaredTemplate);
3815 return Template;
3816 }
3817
3818 TemplateNameKind getTemplateNameKind() const {
3819 switch (Kind) {
3820 case NameClassificationKind::TypeTemplate:
3821 return TNK_Type_template;
3822 case NameClassificationKind::FunctionTemplate:
3823 return TNK_Function_template;
3824 case NameClassificationKind::VarTemplate:
3825 return TNK_Var_template;
3826 case NameClassificationKind::Concept:
3827 return TNK_Concept_template;
3828 case NameClassificationKind::UndeclaredTemplate:
3829 return TNK_Undeclared_template;
3830 default:
3831 llvm_unreachable("unsupported name classification.");
3832 }
3833 }
3834 };
3835
3836 /// Perform name lookup on the given name, classifying it based on
3837 /// the results of name lookup and the following token.
3838 ///
3839 /// This routine is used by the parser to resolve identifiers and help direct
3840 /// parsing. When the identifier cannot be found, this routine will attempt
3841 /// to correct the typo and classify based on the resulting name.
3842 ///
3843 /// \param S The scope in which we're performing name lookup.
3844 ///
3845 /// \param SS The nested-name-specifier that precedes the name.
3846 ///
3847 /// \param Name The identifier. If typo correction finds an alternative name,
3848 /// this pointer parameter will be updated accordingly.
3849 ///
3850 /// \param NameLoc The location of the identifier.
3851 ///
3852 /// \param NextToken The token following the identifier. Used to help
3853 /// disambiguate the name.
3854 ///
3855 /// \param CCC The correction callback, if typo correction is desired.
3856 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3857 IdentifierInfo *&Name, SourceLocation NameLoc,
3858 const Token &NextToken,
3859 CorrectionCandidateCallback *CCC = nullptr);
3860
3861 /// Act on the result of classifying a name as an undeclared (ADL-only)
3862 /// non-type declaration.
3863 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
3864 SourceLocation NameLoc);
3865 /// Act on the result of classifying a name as an undeclared member of a
3866 /// dependent base class.
3867 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
3868 IdentifierInfo *Name,
3869 SourceLocation NameLoc,
3870 bool IsAddressOfOperand);
3871 /// Act on the result of classifying a name as a specific non-type
3872 /// declaration.
3873 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
3874 NamedDecl *Found,
3875 SourceLocation NameLoc,
3876 const Token &NextToken);
3877 /// Act on the result of classifying a name as an overload set.
3878 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
3879
3880 /// Describes the detailed kind of a template name. Used in diagnostics.
3881 enum class TemplateNameKindForDiagnostics {
3882 ClassTemplate,
3883 FunctionTemplate,
3884 VarTemplate,
3885 AliasTemplate,
3886 TemplateTemplateParam,
3887 Concept,
3888 DependentTemplate
3889 };
3890 TemplateNameKindForDiagnostics
3891 getTemplateNameKindForDiagnostics(TemplateName Name);
3892
3893 /// Determine whether it's plausible that E was intended to be a
3894 /// template-name.
3895 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
3896 if (!getLangOpts().CPlusPlus || E.isInvalid())
3897 return false;
3898 Dependent = false;
3899 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E.get()))
3900 return !DRE->hasExplicitTemplateArgs();
3901 if (auto *ME = dyn_cast<MemberExpr>(Val: E.get()))
3902 return !ME->hasExplicitTemplateArgs();
3903 Dependent = true;
3904 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(Val: E.get()))
3905 return !DSDRE->hasExplicitTemplateArgs();
3906 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(Val: E.get()))
3907 return !DSME->hasExplicitTemplateArgs();
3908 // Any additional cases recognized here should also be handled by
3909 // diagnoseExprIntendedAsTemplateName.
3910 return false;
3911 }
3912
3913 void warnOnReservedIdentifier(const NamedDecl *D);
3914 void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D);
3915
3916 void ProcessPragmaExport(DeclaratorDecl *newDecl);
3917
3918 Decl *ActOnDeclarator(Scope *S, Declarator &D);
3919
3920 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
3921 MultiTemplateParamsArg TemplateParameterLists);
3922
3923 /// Attempt to fold a variable-sized type to a constant-sized type, returning
3924 /// true if we were successful.
3925 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T,
3926 SourceLocation Loc,
3927 unsigned FailedFoldDiagID);
3928
3929 /// Register the given locally-scoped extern "C" declaration so
3930 /// that it can be found later for redeclarations. We include any extern "C"
3931 /// declaration that is not visible in the translation unit here, not just
3932 /// function-scope declarations.
3933 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
3934
3935 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3936 /// If T is the name of a class, then each of the following shall have a
3937 /// name different from T:
3938 /// - every static data member of class T;
3939 /// - every member function of class T
3940 /// - every member of class T that is itself a type;
3941 /// \returns true if the declaration name violates these rules.
3942 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
3943
3944 /// Diagnose a declaration whose declarator-id has the given
3945 /// nested-name-specifier.
3946 ///
3947 /// \param SS The nested-name-specifier of the declarator-id.
3948 ///
3949 /// \param DC The declaration context to which the nested-name-specifier
3950 /// resolves.
3951 ///
3952 /// \param Name The name of the entity being declared.
3953 ///
3954 /// \param Loc The location of the name of the entity being declared.
3955 ///
3956 /// \param IsMemberSpecialization Whether we are declaring a member
3957 /// specialization.
3958 ///
3959 /// \param TemplateId The template-id, if any.
3960 ///
3961 /// \returns true if we cannot safely recover from this error, false
3962 /// otherwise.
3963 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3964 DeclarationName Name, SourceLocation Loc,
3965 TemplateIdAnnotation *TemplateId,
3966 bool IsMemberSpecialization);
3967
3968 bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range);
3969
3970 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
3971
3972 bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind,
3973 unsigned &IntVal);
3974
3975 /// Diagnose function specifiers on a declaration of an identifier that
3976 /// does not identify a function.
3977 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
3978
3979 /// Return the declaration shadowed by the given typedef \p D, or null
3980 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3981 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
3982 const LookupResult &R);
3983
3984 /// Return the declaration shadowed by the given variable \p D, or null
3985 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3986 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
3987
3988 /// Return the declaration shadowed by the given variable \p D, or null
3989 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3990 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
3991 const LookupResult &R);
3992 /// Diagnose variable or built-in function shadowing. Implements
3993 /// -Wshadow.
3994 ///
3995 /// This method is called whenever a VarDecl is added to a "useful"
3996 /// scope.
3997 ///
3998 /// \param ShadowedDecl the declaration that is shadowed by the given variable
3999 /// \param R the lookup of the name
4000 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
4001 const LookupResult &R);
4002
4003 /// Check -Wshadow without the advantage of a previous lookup.
4004 void CheckShadow(Scope *S, VarDecl *D);
4005
4006 /// Warn if 'E', which is an expression that is about to be modified, refers
4007 /// to a shadowing declaration.
4008 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
4009
4010 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
4011 /// when these variables are captured by the lambda.
4012 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
4013
4014 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
4015 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4016 TypedefNameDecl *NewTD);
4017 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
4018 NamedDecl *ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4019 TypeSourceInfo *TInfo,
4020 LookupResult &Previous);
4021
4022 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4023 /// declares a typedef-name, either using the 'typedef' type specifier or via
4024 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4025 NamedDecl *ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D,
4026 LookupResult &Previous, bool &Redeclaration);
4027 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4028 TypeSourceInfo *TInfo,
4029 LookupResult &Previous,
4030 MultiTemplateParamsArg TemplateParamLists,
4031 bool &AddToScope,
4032 ArrayRef<BindingDecl *> Bindings = {});
4033
4034private:
4035 // Perform a check on an AsmLabel to verify its consistency and emit
4036 // diagnostics in case of an error.
4037 void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
4038 TypeSourceInfo *TInfo, VarDecl *);
4039
4040public:
4041 /// Perform semantic checking on a newly-created variable
4042 /// declaration.
4043 ///
4044 /// This routine performs all of the type-checking required for a
4045 /// variable declaration once it has been built. It is used both to
4046 /// check variables after they have been parsed and their declarators
4047 /// have been translated into a declaration, and to check variables
4048 /// that have been instantiated from a template.
4049 ///
4050 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4051 ///
4052 /// Returns true if the variable declaration is a redeclaration.
4053 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
4054 void CheckVariableDeclarationType(VarDecl *NewVD);
4055 void CheckCompleteVariableDeclaration(VarDecl *VD);
4056
4057 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4058 TypeSourceInfo *TInfo,
4059 LookupResult &Previous,
4060 MultiTemplateParamsArg TemplateParamLists,
4061 bool &AddToScope);
4062
4063 /// Attach the ABI tag a standard calling convention variant requires, as an
4064 /// implicit abi_tag attribute. Call this once the function type is final.
4065 void addImplicitCallingConvAbiTag(FunctionDecl *FD);
4066
4067 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4068 /// and if so, check that it's a valid override and remember it.
4069 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
4070
4071 /// Perform semantic checking of a new function declaration.
4072 ///
4073 /// Performs semantic analysis of the new function declaration
4074 /// NewFD. This routine performs all semantic checking that does not
4075 /// require the actual declarator involved in the declaration, and is
4076 /// used both for the declaration of functions as they are parsed
4077 /// (called via ActOnDeclarator) and for the declaration of functions
4078 /// that have been instantiated via C++ template instantiation (called
4079 /// via InstantiateDecl).
4080 ///
4081 /// \param IsMemberSpecialization whether this new function declaration is
4082 /// a member specialization (that replaces any definition provided by the
4083 /// previous declaration).
4084 ///
4085 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4086 ///
4087 /// \returns true if the function declaration is a redeclaration.
4088 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4089 LookupResult &Previous,
4090 bool IsMemberSpecialization, bool DeclIsDefn);
4091
4092 /// Checks if the new declaration declared in dependent context must be
4093 /// put in the same redeclaration chain as the specified declaration.
4094 ///
4095 /// \param D Declaration that is checked.
4096 /// \param PrevDecl Previous declaration found with proper lookup method for
4097 /// the same declaration name.
4098 /// \returns True if D must be added to the redeclaration chain which PrevDecl
4099 /// belongs to.
4100 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4101
4102 /// Determines if we can perform a correct type check for \p D as a
4103 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4104 /// best-effort check.
4105 ///
4106 /// \param NewD The new declaration.
4107 /// \param OldD The old declaration.
4108 /// \param NewT The portion of the type of the new declaration to check.
4109 /// \param OldT The portion of the type of the old declaration to check.
4110 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4111 QualType NewT, QualType OldT);
4112 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4113 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4114
4115 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4116 /// containing class. Otherwise it will return implicit SectionAttr if the
4117 /// function is a definition and there is an active value on CodeSegStack
4118 /// (from the current #pragma code-seg value).
4119 ///
4120 /// \param FD Function being declared.
4121 /// \param IsDefinition Whether it is a definition or just a declaration.
4122 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4123 /// nullptr if no attribute should be added.
4124 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4125 bool IsDefinition);
4126
4127 /// Common checks for a parameter-declaration that should apply to both
4128 /// function parameters and non-type template parameters.
4129 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4130
4131 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4132 /// to introduce parameters into function prototype scope.
4133 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4134 SourceLocation ExplicitThisLoc = {});
4135
4136 /// Synthesizes a variable for a parameter arising from a
4137 /// typedef.
4138 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4139 QualType T);
4140 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4141 SourceLocation NameLoc,
4142 const IdentifierInfo *Name, QualType T,
4143 TypeSourceInfo *TSInfo, StorageClass SC);
4144
4145 /// Emit diagnostics if the initializer or any of its explicit or
4146 /// implicitly-generated subexpressions require copying or
4147 /// default-initializing a type that is or contains a C union type that is
4148 /// non-trivial to copy or default-initialize.
4149 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4150
4151 // These flags are passed to checkNonTrivialCUnion.
4152 enum NonTrivialCUnionKind {
4153 NTCUK_Init = 0x1,
4154 NTCUK_Destruct = 0x2,
4155 NTCUK_Copy = 0x4,
4156 };
4157
4158 /// Emit diagnostics if a non-trivial C union type or a struct that contains
4159 /// a non-trivial C union is used in an invalid context.
4160 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
4161 NonTrivialCUnionContext UseContext,
4162 unsigned NonTrivialKind);
4163
4164 /// Certain globally-unique variables might be accidentally duplicated if
4165 /// built into multiple shared libraries with hidden visibility. This can
4166 /// cause problems if the variable is mutable, its initialization is
4167 /// effectful, or its address is taken.
4168 bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl);
4169 void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl);
4170
4171 /// AddInitializerToDecl - Adds the initializer Init to the
4172 /// declaration dcl. If DirectInit is true, this is C++ direct
4173 /// initialization rather than copy initialization.
4174 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4175 void ActOnUninitializedDecl(Decl *dcl);
4176
4177 /// ActOnInitializerError - Given that there was an error parsing an
4178 /// initializer for the given declaration, try to at least re-establish
4179 /// invariants such as whether a variable's type is either dependent or
4180 /// complete.
4181 void ActOnInitializerError(Decl *Dcl);
4182
4183 void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt);
4184 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
4185 IdentifierInfo *Ident,
4186 ParsedAttributes &Attrs);
4187
4188 /// Check if VD needs to be dllexport/dllimport due to being in a
4189 /// dllexport/import function.
4190 void CheckStaticLocalForDllExport(VarDecl *VD);
4191 void CheckThreadLocalForLargeAlignment(VarDecl *VD);
4192
4193 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4194 /// any semantic actions necessary after any initializer has been attached.
4195 void FinalizeDeclaration(Decl *D);
4196 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4197 ArrayRef<Decl *> Group);
4198
4199 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4200 /// group, performing any necessary semantic checking.
4201 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
4202
4203 /// Should be called on all declarations that might have attached
4204 /// documentation comments.
4205 void ActOnDocumentableDecl(Decl *D);
4206 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
4207
4208 enum class FnBodyKind {
4209 /// C++26 [dcl.fct.def.general]p1
4210 /// function-body:
4211 /// ctor-initializer[opt] compound-statement
4212 /// function-try-block
4213 Other,
4214 /// = default ;
4215 Default,
4216 /// deleted-function-body
4217 ///
4218 /// deleted-function-body:
4219 /// = delete ;
4220 /// = delete ( unevaluated-string ) ;
4221 Delete
4222 };
4223
4224 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4225 SourceLocation LocAfterDecls);
4226 void CheckForFunctionRedefinition(
4227 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4228 SkipBodyInfo *SkipBody = nullptr);
4229 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
4230 MultiTemplateParamsArg TemplateParamLists,
4231 SkipBodyInfo *SkipBody = nullptr,
4232 FnBodyKind BodyKind = FnBodyKind::Other);
4233 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
4234 SkipBodyInfo *SkipBody = nullptr,
4235 FnBodyKind BodyKind = FnBodyKind::Other);
4236 void applyFunctionAttributesBeforeParsingBody(Decl *FD);
4237
4238 /// Determine whether we can delay parsing the body of a function or
4239 /// function template until it is used, assuming we don't care about emitting
4240 /// code for that function.
4241 ///
4242 /// This will be \c false if we may need the body of the function in the
4243 /// middle of parsing an expression (where it's impractical to switch to
4244 /// parsing a different function), for instance, if it's constexpr in C++11
4245 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4246 bool canDelayFunctionBody(const Declarator &D);
4247
4248 /// Determine whether we can skip parsing the body of a function
4249 /// definition, assuming we don't care about analyzing its body or emitting
4250 /// code for that function.
4251 ///
4252 /// This will be \c false only if we may need the body of the function in
4253 /// order to parse the rest of the program (for instance, if it is
4254 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4255 bool canSkipFunctionBody(Decl *D);
4256
4257 /// Given the set of return statements within a function body,
4258 /// compute the variables that are subject to the named return value
4259 /// optimization.
4260 ///
4261 /// Each of the variables that is subject to the named return value
4262 /// optimization will be marked as NRVO variables in the AST, and any
4263 /// return statement that has a marked NRVO variable as its NRVO candidate can
4264 /// use the named return value optimization.
4265 ///
4266 /// This function applies a very simplistic algorithm for NRVO: if every
4267 /// return statement in the scope of a variable has the same NRVO candidate,
4268 /// that candidate is an NRVO variable.
4269 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
4270
4271 /// Performs semantic analysis at the end of a function body.
4272 ///
4273 /// \param RetainFunctionScopeInfo If \c true, the client is responsible for
4274 /// releasing the associated \p FunctionScopeInfo. This is useful when
4275 /// building e.g. LambdaExprs.
4276 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body,
4277 bool IsInstantiation = false,
4278 bool RetainFunctionScopeInfo = false);
4279 Decl *ActOnSkippedFunctionBody(Decl *Decl);
4280 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
4281
4282 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4283 /// attribute for which parsing is delayed.
4284 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
4285
4286 /// Diagnose any unused parameters in the given sequence of
4287 /// ParmVarDecl pointers.
4288 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
4289
4290 /// Diagnose whether the size of parameters or return value of a
4291 /// function or obj-c method definition is pass-by-value and larger than a
4292 /// specified threshold.
4293 void
4294 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
4295 QualType ReturnTy, NamedDecl *D);
4296
4297 Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc,
4298 SourceLocation RParenLoc);
4299
4300 TopLevelStmtDecl *ActOnStartTopLevelStmtDecl(Scope *S);
4301 void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement);
4302
4303 void ActOnPopScope(SourceLocation Loc, Scope *S);
4304
4305 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4306 /// no declarator (e.g. "struct foo;") is parsed.
4307 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4308 const ParsedAttributesView &DeclAttrs,
4309 RecordDecl *&AnonRecord);
4310
4311 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4312 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4313 /// parameters to cope with template friend declarations.
4314 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4315 const ParsedAttributesView &DeclAttrs,
4316 MultiTemplateParamsArg TemplateParams,
4317 bool IsExplicitInstantiation,
4318 RecordDecl *&AnonRecord,
4319 SourceLocation EllipsisLoc = {});
4320
4321 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4322 /// anonymous structure or union. Anonymous unions are a C++ feature
4323 /// (C++ [class.union]) and a C11 feature; anonymous structures
4324 /// are a C11 feature and GNU C++ extension.
4325 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4326 RecordDecl *Record,
4327 const PrintingPolicy &Policy);
4328
4329 /// Called once it is known whether
4330 /// a tag declaration is an anonymous union or struct.
4331 void ActOnDefinedDeclarationSpecifier(Decl *D);
4332
4333 /// Emit diagnostic warnings for placeholder members.
4334 /// We can only do that after the class is fully constructed,
4335 /// as anonymous union/structs can insert placeholders
4336 /// in their parent scope (which might be a Record).
4337 void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record);
4338
4339 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4340 /// Microsoft C anonymous structure.
4341 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4342 /// Example:
4343 ///
4344 /// struct A { int a; };
4345 /// struct B { struct A; int b; };
4346 ///
4347 /// void foo() {
4348 /// B var;
4349 /// var.a = 3;
4350 /// }
4351 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4352 RecordDecl *Record);
4353
4354 /// Given a non-tag type declaration, returns an enum useful for indicating
4355 /// what kind of non-tag type this is.
4356 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4357
4358 /// Determine whether a tag with a given kind is acceptable
4359 /// as a redeclaration of the given tag declaration.
4360 ///
4361 /// \returns true if the new tag kind is acceptable, false otherwise.
4362 bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag,
4363 bool isDefinition, SourceLocation NewTagLoc,
4364 const IdentifierInfo *Name);
4365
4366 /// This is invoked when we see 'struct foo' or 'struct {'. In the
4367 /// former case, Name will be non-null. In the later case, Name will be null.
4368 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4369 /// a reference/declaration/definition of a tag.
4370 ///
4371 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4372 /// trailing-type-specifier) other than one in an alias-declaration.
4373 ///
4374 /// \param SkipBody If non-null, will be set to indicate if the caller should
4375 /// skip the definition of this tag and treat it as if it were a declaration.
4376 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4377 SourceLocation KWLoc, CXXScopeSpec &SS,
4378 IdentifierInfo *Name, SourceLocation NameLoc,
4379 const ParsedAttributesView &Attr, AccessSpecifier AS,
4380 SourceLocation ModulePrivateLoc,
4381 MultiTemplateParamsArg TemplateParameterLists,
4382 bool &OwnedDecl, bool &IsDependent,
4383 SourceLocation ScopedEnumKWLoc,
4384 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4385 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4386 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4387
4388 /// ActOnField - Each field of a C struct/union is passed into this in order
4389 /// to create a FieldDecl object for it.
4390 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4391 Declarator &D, Expr *BitfieldWidth);
4392
4393 /// HandleField - Analyze a field of a C struct or a C++ data member.
4394 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4395 Declarator &D, Expr *BitfieldWidth,
4396 InClassInitStyle InitStyle, AccessSpecifier AS);
4397
4398 /// Build a new FieldDecl and check its well-formedness.
4399 ///
4400 /// This routine builds a new FieldDecl given the fields name, type,
4401 /// record, etc. \p PrevDecl should refer to any previous declaration
4402 /// with the same name and in the same scope as the field to be
4403 /// created.
4404 ///
4405 /// \returns a new FieldDecl.
4406 ///
4407 /// \todo The Declarator argument is a hack. It will be removed once
4408 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4409 TypeSourceInfo *TInfo, RecordDecl *Record,
4410 SourceLocation Loc, bool Mutable,
4411 Expr *BitfieldWidth, InClassInitStyle InitStyle,
4412 SourceLocation TSSL, AccessSpecifier AS,
4413 NamedDecl *PrevDecl, Declarator *D = nullptr);
4414
4415 bool CheckNontrivialField(FieldDecl *FD);
4416
4417 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4418 /// class and class extensions. For every class \@interface and class
4419 /// extension \@interface, if the last ivar is a bitfield of any type,
4420 /// then add an implicit `char :0` ivar to the end of that interface.
4421 void ActOnLastBitfield(SourceLocation DeclStart,
4422 SmallVectorImpl<Decl *> &AllIvarDecls);
4423
4424 // This is used for both record definitions and ObjC interface declarations.
4425 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4426 ArrayRef<Decl *> Fields, SourceLocation LBrac,
4427 SourceLocation RBrac, const ParsedAttributesView &AttrList);
4428
4429 /// ActOnTagStartDefinition - Invoked when we have entered the
4430 /// scope of a tag's definition (e.g., for an enumeration, class,
4431 /// struct, or union).
4432 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4433
4434 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4435 /// Differently from C++, actually parse the body and reject / error out
4436 /// in case of a structural mismatch.
4437 bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4438
4439 typedef void *SkippedDefinitionContext;
4440
4441 /// Invoked when we enter a tag definition that we're skipping.
4442 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
4443
4444 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4445 /// C++ record definition's base-specifiers clause and are starting its
4446 /// member declarations.
4447 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
4448 SourceLocation FinalLoc,
4449 bool IsFinalSpelledSealed,
4450 bool IsAbstract,
4451 SourceLocation LBraceLoc);
4452
4453 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4454 /// the definition of a tag (enumeration, class, struct, or union).
4455 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
4456 SourceRange BraceRange);
4457
4458 ASTContext::CXXRecordDeclRelocationInfo
4459 CheckCXX2CRelocatable(const clang::CXXRecordDecl *D);
4460
4461 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
4462
4463 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4464 /// error parsing the definition of a tag.
4465 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
4466
4467 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
4468 EnumConstantDecl *LastEnumConst,
4469 SourceLocation IdLoc, IdentifierInfo *Id,
4470 Expr *val);
4471
4472 /// Check that this is a valid underlying type for an enum declaration.
4473 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
4474
4475 /// Check whether this is a valid redeclaration of a previous enumeration.
4476 /// \return true if the redeclaration was invalid.
4477 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4478 QualType EnumUnderlyingTy, bool IsFixed,
4479 const EnumDecl *Prev);
4480
4481 /// Determine whether the body of an anonymous enumeration should be skipped.
4482 /// \param II The name of the first enumerator.
4483 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
4484 SourceLocation IILoc);
4485
4486 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4487 SourceLocation IdLoc, IdentifierInfo *Id,
4488 const ParsedAttributesView &Attrs,
4489 SourceLocation EqualLoc, Expr *Val,
4490 SkipBodyInfo *SkipBody = nullptr);
4491 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4492 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4493 const ParsedAttributesView &Attr);
4494
4495 /// Set the current declaration context until it gets popped.
4496 void PushDeclContext(Scope *S, DeclContext *DC);
4497 void PopDeclContext();
4498
4499 /// EnterDeclaratorContext - Used when we must lookup names in the context
4500 /// of a declarator's nested name specifier.
4501 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
4502 void ExitDeclaratorContext(Scope *S);
4503
4504 /// Enter a template parameter scope, after it's been associated with a
4505 /// particular DeclContext. Causes lookup within the scope to chain through
4506 /// enclosing contexts in the correct order.
4507 void EnterTemplatedContext(Scope *S, DeclContext *DC);
4508
4509 /// Push the parameters of D, which must be a function, into scope.
4510 void ActOnReenterFunctionContext(Scope *S, Decl *D);
4511 void ActOnExitFunctionContext();
4512
4513 /// Add this decl to the scope shadowed decl chains.
4514 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4515
4516 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4517 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4518 /// true if 'D' belongs to the given declaration context.
4519 ///
4520 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4521 /// enclosing namespace set of the context, rather than contained
4522 /// directly within it.
4523 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4524 bool AllowInlineNamespace = false) const;
4525
4526 /// Determine whether a tag-like declaration found by lookup can be
4527 /// redeclared in the given scope. If lookup found a using-shadow, also
4528 /// consider the scope of the declaration named by the using-shadow.
4529 bool isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx,
4530 Scope *S = nullptr,
4531 bool AllowInlineNamespace = false) const;
4532
4533 /// Finds the scope corresponding to the given decl context, if it
4534 /// happens to be an enclosing scope. Otherwise return NULL.
4535 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
4536
4537 /// Subroutines of ActOnDeclarator().
4538 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4539 TypeSourceInfo *TInfo);
4540 bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New);
4541
4542 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4543 void mergeDeclAttributes(
4544 NamedDecl *New, Decl *Old,
4545 AvailabilityMergeKind AMK = AvailabilityMergeKind::Redeclaration);
4546
4547 /// CheckAttributesOnDeducedType - Calls Sema functions for attributes that
4548 /// requires the type to be deduced.
4549 void CheckAttributesOnDeducedType(Decl *D);
4550
4551 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4552 /// same name and scope as a previous declaration 'Old'. Figure out
4553 /// how to resolve this situation, merging decls or emitting
4554 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4555 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
4556 LookupResult &OldDecls);
4557
4558 /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4559 /// definition visible.
4560 /// This method performs any necessary cleanup on the parser state to discard
4561 /// child nodes from newly parsed decl we are retiring.
4562 void CleanupMergedEnum(Scope *S, Decl *New);
4563
4564 /// MergeFunctionDecl - We just parsed a function 'New' from
4565 /// declarator D which has the same name and scope as a previous
4566 /// declaration 'Old'. Figure out how to resolve this situation,
4567 /// merging decls or emitting diagnostics as appropriate.
4568 ///
4569 /// In C++, New and Old must be declarations that are not
4570 /// overloaded. Use IsOverload to determine whether New and Old are
4571 /// overloaded, and to select the Old declaration that New should be
4572 /// merged with.
4573 ///
4574 /// Returns true if there was an error, false otherwise.
4575 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
4576 bool MergeTypeWithOld, bool NewDeclIsDefn);
4577
4578 /// Completes the merge of two function declarations that are
4579 /// known to be compatible.
4580 ///
4581 /// This routine handles the merging of attributes and other
4582 /// properties of function declarations from the old declaration to
4583 /// the new declaration, once we know that New is in fact a
4584 /// redeclaration of Old.
4585 ///
4586 /// \returns false
4587 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4588 Scope *S, bool MergeTypeWithOld);
4589 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
4590
4591 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4592 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4593 /// situation, merging decls or emitting diagnostics as appropriate.
4594 ///
4595 /// Tentative definition rules (C99 6.9.2p2) are checked by
4596 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4597 /// definitions here, since the initializer hasn't been attached.
4598 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
4599
4600 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4601 /// scope as a previous declaration 'Old'. Figure out how to merge their
4602 /// types, emitting diagnostics as appropriate.
4603 ///
4604 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4605 /// back to here in AddInitializerToDecl. We can't check them before the
4606 /// initializer is attached.
4607 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4608
4609 /// We've just determined that \p Old and \p New both appear to be definitions
4610 /// of the same variable. Either diagnose or fix the problem.
4611 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4612 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
4613
4614 /// Filters out lookup results that don't fall within the given scope
4615 /// as determined by isDeclInScope.
4616 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4617 bool ConsiderLinkage, bool AllowInlineNamespace);
4618
4619 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4620 /// have compatible owning modules.
4621 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4622
4623 /// [module.interface]p6:
4624 /// A redeclaration of an entity X is implicitly exported if X was introduced
4625 /// by an exported declaration; otherwise it shall not be exported.
4626 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4627
4628 /// A wrapper function for checking the semantic restrictions of
4629 /// a redeclaration within a module.
4630 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4631
4632 /// Check the redefinition in C++20 Modules.
4633 ///
4634 /// [basic.def.odr]p14:
4635 /// For any definable item D with definitions in multiple translation units,
4636 /// - if D is a non-inline non-templated function or variable, or
4637 /// - if the definitions in different translation units do not satisfy the
4638 /// following requirements,
4639 /// the program is ill-formed; a diagnostic is required only if the
4640 /// definable item is attached to a named module and a prior definition is
4641 /// reachable at the point where a later definition occurs.
4642 /// - Each such definition shall not be attached to a named module
4643 /// ([module.unit]).
4644 /// - Each such definition shall consist of the same sequence of tokens, ...
4645 /// ...
4646 ///
4647 /// Return true if the redefinition is not allowed. Return false otherwise.
4648 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4649
4650 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4651
4652 /// If it's a file scoped decl that must warn if not used, keep track
4653 /// of it.
4654 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4655
4656 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4657 DiagReceiverTy;
4658
4659 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4660 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
4661 DiagReceiverTy DiagReceiver);
4662 void DiagnoseUnusedDecl(const NamedDecl *ND);
4663
4664 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4665 /// unless they are marked attr(unused).
4666 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4667
4668 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4669 /// variable.
4670 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4671
4672 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4673 /// from S, where a non-field would be declared. This routine copes
4674 /// with the difference between C and C++ scoping rules in structs and
4675 /// unions. For example, the following code is well-formed in C but
4676 /// ill-formed in C++:
4677 /// @code
4678 /// struct S6 {
4679 /// enum { BAR } e;
4680 /// };
4681 ///
4682 /// void test_S6() {
4683 /// struct S6 a;
4684 /// a.e = BAR;
4685 /// }
4686 /// @endcode
4687 /// For the declaration of BAR, this routine will return a different
4688 /// scope. The scope S will be the scope of the unnamed enumeration
4689 /// within S6. In C++, this routine will return the scope associated
4690 /// with S6, because the enumeration's scope is a transparent
4691 /// context but structures can contain non-field names. In C, this
4692 /// routine will return the translation unit scope, since the
4693 /// enumeration's scope is a transparent context and structures cannot
4694 /// contain non-field names.
4695 Scope *getNonFieldDeclScope(Scope *S);
4696
4697 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4698 SourceLocation Loc);
4699
4700 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4701 /// file scope. lazily create a decl for it. ForRedeclaration is true
4702 /// if we're creating this built-in in anticipation of redeclaring the
4703 /// built-in.
4704 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4705 bool ForRedeclaration, SourceLocation Loc);
4706
4707 /// Get the outermost AttributedType node that sets a calling convention.
4708 /// Valid types should not have multiple attributes with different CCs.
4709 const AttributedType *getCallingConvAttributedType(QualType T) const;
4710
4711 /// GetNameForDeclarator - Determine the full declaration name for the
4712 /// given Declarator.
4713 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
4714
4715 /// Retrieves the declaration name from a parsed unqualified-id.
4716 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
4717
4718 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4719 /// we are currently parsing the initializer.
4720 llvm::SmallPtrSet<const Decl *, 4> ParsingInitForAutoVars;
4721
4722 /// Look for a locally scoped extern "C" declaration by the given name.
4723 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
4724
4725 void deduceOpenCLAddressSpace(VarDecl *decl);
4726 void deduceHLSLAddressSpace(VarDecl *decl);
4727
4728 /// Adjust the \c DeclContext for a function or variable that might be a
4729 /// function-local external declaration.
4730 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
4731
4732 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4733
4734 /// Checks if the variant/multiversion functions are compatible.
4735 bool areMultiversionVariantFunctionsCompatible(
4736 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4737 const PartialDiagnostic &NoProtoDiagID,
4738 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4739 const PartialDiagnosticAt &NoSupportDiagIDAt,
4740 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4741 bool ConstexprSupported, bool CLinkageMayDiffer);
4742
4743 /// type checking declaration initializers (C99 6.7.8)
4744 bool CheckForConstantInitializer(
4745 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4746
4747 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
4748 QualType Type, TypeSourceInfo *TSI,
4749 SourceRange Range, bool DirectInit,
4750 Expr *Init);
4751
4752 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
4753 Expr *Init);
4754
4755 sema::LambdaScopeInfo *RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator);
4756
4757 // Heuristically tells if the function is `get_return_object` member of a
4758 // coroutine promise_type by matching the function name.
4759 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4760 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4761
4762 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4763 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4764 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4765 Scope *S);
4766
4767 /// If this function is a C++ replaceable global allocation function
4768 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4769 /// adds any function attributes that we know a priori based on the standard.
4770 ///
4771 /// We need to check for duplicate attributes both here and where user-written
4772 /// attributes are applied to declarations.
4773 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4774 FunctionDecl *FD);
4775
4776 /// Adds any function attributes that we know a priori based on
4777 /// the declaration of this function.
4778 ///
4779 /// These attributes can apply both to implicitly-declared builtins
4780 /// (like __builtin___printf_chk) or to library-declared functions
4781 /// like NSLog or printf.
4782 ///
4783 /// We need to check for duplicate attributes both here and where user-written
4784 /// attributes are applied to declarations.
4785 void AddKnownFunctionAttributes(FunctionDecl *FD);
4786
4787 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4788 /// the correct width, and that the field type is valid.
4789 /// Returns false on success.
4790 ExprResult VerifyBitField(SourceLocation FieldLoc,
4791 const IdentifierInfo *FieldName, QualType FieldTy,
4792 bool IsMsStruct, Expr *BitWidth);
4793
4794 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4795 /// enum. If AllowMask is true, then we also allow the complement of a valid
4796 /// value, to be used as a mask.
4797 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4798 bool AllowMask) const;
4799
4800 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4801 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4802 SourceLocation WeakNameLoc);
4803
4804 /// ActOnPragmaRedefineExtname - Called on well formed
4805 /// \#pragma redefine_extname oldname newname.
4806 void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName,
4807 IdentifierInfo *AliasName,
4808 SourceLocation PragmaLoc,
4809 SourceLocation WeakNameLoc,
4810 SourceLocation AliasNameLoc);
4811
4812 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4813 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4814 SourceLocation PragmaLoc,
4815 SourceLocation WeakNameLoc,
4816 SourceLocation AliasNameLoc);
4817
4818 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4819 enum class FunctionEmissionStatus {
4820 Emitted,
4821 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4822 OMPDiscarded, // Discarded due to OpenMP hostness
4823 TemplateDiscarded, // Discarded due to uninstantiated templates
4824 Unknown,
4825 };
4826 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4827 bool Final = false);
4828
4829 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4830 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4831
4832 /// Function or variable declarations to be checked for whether the deferred
4833 /// diagnostics should be emitted.
4834 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
4835
4836private:
4837 /// Map of current shadowing declarations to shadowed declarations. Warn if
4838 /// it looks like the user is trying to modify the shadowing declaration.
4839 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4840
4841 // We need this to handle
4842 //
4843 // typedef struct {
4844 // void *foo() { return 0; }
4845 // } A;
4846 //
4847 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4848 // for example. If 'A', foo will have external linkage. If we have '*A',
4849 // foo will have no linkage. Since we can't know until we get to the end
4850 // of the typedef, this function finds out if D might have non-external
4851 // linkage. Callers should verify at the end of the TU if it D has external
4852 // linkage or not.
4853 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4854
4855#include "clang/Sema/AttrIsTypeDependent.inc"
4856
4857 ///@}
4858
4859 //
4860 //
4861 // -------------------------------------------------------------------------
4862 //
4863 //
4864
4865 /// \name Declaration Attribute Handling
4866 /// Implementations are in SemaDeclAttr.cpp
4867 ///@{
4868
4869public:
4870 /// Describes the kind of priority given to an availability attribute.
4871 ///
4872 /// The sum of priorities deteremines the final priority of the attribute.
4873 /// The final priority determines how the attribute will be merged.
4874 /// An attribute with a lower priority will always remove higher priority
4875 /// attributes for the specified platform when it is being applied. An
4876 /// attribute with a higher priority will not be applied if the declaration
4877 /// already has an availability attribute with a lower priority for the
4878 /// specified platform. The final prirority values are not expected to match
4879 /// the values in this enumeration, but instead should be treated as a plain
4880 /// integer value. This enumeration just names the priority weights that are
4881 /// used to calculate that final vaue.
4882 enum AvailabilityPriority : int {
4883 /// The availability attribute was specified explicitly next to the
4884 /// declaration.
4885 AP_Explicit = 0,
4886
4887 /// The availability attribute was applied using '#pragma clang attribute'.
4888 AP_PragmaClangAttribute = 1,
4889
4890 /// The availability attribute for a specific platform was inferred from
4891 /// an availability attribute for another platform.
4892 AP_InferredFromOtherPlatform = 2,
4893
4894 /// The availability attribute was inferred from an 'anyAppleOS'
4895 /// availability attribute.
4896 AP_InferredFromAnyAppleOS = 3,
4897
4898 /// The availability attribute was inferred from an 'anyAppleOS'
4899 /// availability attribute that was applied using '#pragma clang attribute'.
4900 /// This has the lowest priority.
4901 AP_PragmaClangAttribute_InferredFromAnyAppleOS = 4
4902 };
4903
4904 /// Describes the reason a calling convention specification was ignored, used
4905 /// for diagnostics.
4906 enum class CallingConventionIgnoredReason {
4907 ForThisTarget = 0,
4908 VariadicFunction,
4909 ConstructorDestructor,
4910 BuiltinFunction
4911 };
4912
4913 /// A helper function to provide Attribute Location for the Attr types
4914 /// AND the ParsedAttr.
4915 template <typename AttrInfo>
4916 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
4917 getAttrLoc(const AttrInfo &AL) {
4918 return AL.getLocation();
4919 }
4920 SourceLocation getAttrLoc(const AttributeCommonInfo &CI);
4921
4922 /// If Expr is a valid integer constant, get the value of the integer
4923 /// expression and return success or failure. May output an error.
4924 ///
4925 /// Negative argument is implicitly converted to unsigned, unless
4926 /// \p StrictlyUnsigned is true.
4927 template <typename AttrInfo>
4928 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
4929 unsigned Idx = UINT_MAX,
4930 bool StrictlyUnsigned = false) {
4931 std::optional<llvm::APSInt> I = llvm::APSInt(32);
4932 if (Expr->isTypeDependent() ||
4933 !(I = Expr->getIntegerConstantExpr(Ctx: Context))) {
4934 if (Idx != UINT_MAX)
4935 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
4936 << &AI << Idx << AANT_ArgumentIntegerConstant
4937 << Expr->getSourceRange();
4938 else
4939 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
4940 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
4941 return false;
4942 }
4943
4944 if (!I->isIntN(N: 32)) {
4945 Diag(Loc: Expr->getExprLoc(), DiagID: diag::err_ice_too_large)
4946 << toString(I: *I, Radix: 10, Signed: false) << 32 << /* Unsigned */ 1;
4947 return false;
4948 }
4949
4950 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
4951 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
4952 << &AI << /*non-negative*/ 1;
4953 return false;
4954 }
4955
4956 Val = (uint32_t)I->getZExtValue();
4957 return true;
4958 }
4959
4960 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
4961 /// \#pragma weak during processing of other Decls.
4962 /// I couldn't figure out a clean way to generate these in-line, so
4963 /// we store them here and handle separately -- which is a hack.
4964 /// It would be best to refactor this.
4965 SmallVector<Decl *, 2> WeakTopLevelDecl;
4966
4967 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
4968 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
4969
4970 typedef LazyVector<TypedefNameDecl *, &ExternalSemaSource::ReadExtVectorDecls,
4971 2, 2>
4972 ExtVectorDeclsType;
4973
4974 /// ExtVectorDecls - This is a list all the extended vector types. This allows
4975 /// us to associate a raw vector type with one of the ext_vector type names.
4976 /// This is only necessary for issuing pretty diagnostics.
4977 ExtVectorDeclsType ExtVectorDecls;
4978
4979 /// Check if the argument \p E is a ASCII string literal. If not emit an error
4980 /// and return false, otherwise set \p Str to the value of the string literal
4981 /// and return true.
4982 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
4983 const Expr *E, StringRef &Str,
4984 SourceLocation *ArgLocation = nullptr);
4985
4986 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
4987 /// If not emit an error and return false. If the argument is an identifier it
4988 /// will emit an error with a fixit hint and treat it as if it was a string
4989 /// literal.
4990 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4991 StringRef &Str,
4992 SourceLocation *ArgLocation = nullptr);
4993
4994 /// Determine if type T is a valid subject for a nonnull and similar
4995 /// attributes. Dependent types are considered valid so they can be checked
4996 /// during instantiation time. By default, we look through references (the
4997 /// behavior used by nonnull), but if the second parameter is true, then we
4998 /// treat a reference type as valid.
4999 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
5000
5001 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
5002 /// declaration.
5003 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5004 Expr *OE);
5005
5006 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
5007 /// declaration.
5008 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
5009 Expr *ParamExpr);
5010
5011 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
5012 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
5013
5014 AvailabilityAttr *
5015 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
5016 const IdentifierInfo *Platform, bool Implicit,
5017 VersionTuple Introduced, VersionTuple Deprecated,
5018 VersionTuple Obsoleted, bool IsUnavailable,
5019 StringRef Message, bool IsStrict, StringRef Replacement,
5020 AvailabilityMergeKind AMK, int Priority,
5021 const IdentifierInfo *IIEnvironment,
5022 const IdentifierInfo *InferredPlatformII = nullptr);
5023
5024 AvailabilityAttr *mergeAndInferAvailabilityAttr(
5025 NamedDecl *D, const AttributeCommonInfo &CI,
5026 const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced,
5027 VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable,
5028 StringRef Message, bool IsStrict, StringRef Replacement,
5029 AvailabilityMergeKind AMK, int Priority,
5030 const IdentifierInfo *IIEnvironment,
5031 const IdentifierInfo *InferredPlatformII);
5032
5033 TypeVisibilityAttr *
5034 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5035 TypeVisibilityAttr::VisibilityType Vis);
5036 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5037 VisibilityAttr::VisibilityType Vis);
5038 void mergeVisibilityType(Decl *D, SourceLocation Loc,
5039 VisibilityAttr::VisibilityType Type);
5040 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
5041 StringRef Name);
5042
5043 /// Used to implement to perform semantic checking on
5044 /// attribute((section("foo"))) specifiers.
5045 ///
5046 /// In this case, "foo" is passed in to be checked. If the section
5047 /// specifier is invalid, return an Error that indicates the problem.
5048 ///
5049 /// This is a simple quality of implementation feature to catch errors
5050 /// and give good diagnostics in cases when the assembler or code generator
5051 /// would otherwise reject the section specifier.
5052 llvm::Error isValidSectionSpecifier(StringRef Str);
5053 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
5054 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
5055 StringRef Name);
5056
5057 // Check for things we'd like to warn about. Multiversioning issues are
5058 // handled later in the process, once we know how many exist.
5059 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
5060
5061 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
5062 StringRef NewUserDiagnostic);
5063 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
5064 const IdentifierInfo *Format, int FormatIdx,
5065 int FirstArg);
5066 FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
5067 const AttributeCommonInfo &CI,
5068 const IdentifierInfo *Format,
5069 int FormatIdx,
5070 StringLiteral *FormatStr);
5071 ModularFormatAttr *mergeModularFormatAttr(Decl *D,
5072 const AttributeCommonInfo &CI,
5073 const IdentifierInfo *ModularImplFn,
5074 StringRef ImplName,
5075 MutableArrayRef<StringRef> Aspects);
5076
5077 PersonalityAttr *mergePersonalityAttr(Decl *D, FunctionDecl *Routine,
5078 const AttributeCommonInfo &CI);
5079
5080 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5081 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5082 bool IsPackExpansion);
5083 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
5084 bool IsPackExpansion);
5085
5086 /// AddAlignValueAttr - Adds an align_value attribute to a particular
5087 /// declaration.
5088 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
5089
5090 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
5091 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
5092 MutableArrayRef<Expr *> Args);
5093 Attr *CreateAnnotationAttr(const ParsedAttr &AL);
5094
5095 bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range,
5096 bool BestCase,
5097 MSInheritanceModel SemanticSpelling);
5098
5099 void CheckAlignasUnderalignment(Decl *D);
5100
5101 /// AddModeAttr - Adds a mode attribute to a particular declaration.
5102 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
5103 const IdentifierInfo *Name, bool InInstantiation = false);
5104 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
5105 const AttributeCommonInfo &CI,
5106 const IdentifierInfo *Ident);
5107 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
5108 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
5109 const AttributeCommonInfo &CI);
5110 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
5111 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
5112 const InternalLinkageAttr &AL);
5113
5114 /// Check validaty of calling convention attribute \p attr. If \p FD
5115 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
5116 /// target. Otherwise, it is specified by \p CFT.
5117 bool CheckCallingConvAttr(
5118 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
5119 CUDAFunctionTarget CFT = CUDAFunctionTarget::InvalidTarget);
5120
5121 /// Checks a regparm attribute, returning true if it is ill-formed and
5122 /// otherwise setting numParams to the appropriate value.
5123 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
5124
5125 /// Create a CUDALaunchBoundsAttr attribute. By default, the function only
5126 /// supports nvptx target architectures and skips MaxBlocks if it is previous
5127 /// to sm_90. Use \p IgnoreArch to skip the architecture check.
5128 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
5129 Expr *MaxThreads,
5130 Expr *MinBlocks, Expr *MaxBlocks,
5131 bool IgnoreArch = false);
5132
5133 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
5134 /// declaration.
5135 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5136 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
5137
5138 /// Add a cluster_dims attribute to a particular declaration.
5139 CUDAClusterDimsAttr *createClusterDimsAttr(const AttributeCommonInfo &CI,
5140 Expr *X, Expr *Y, Expr *Z);
5141 void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
5142 Expr *Y, Expr *Z);
5143 /// Add a no_cluster attribute to a particular declaration.
5144 void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI);
5145
5146 enum class RetainOwnershipKind { NS, CF, OS };
5147
5148 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5149 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5150
5151 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5152
5153 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5154 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5155 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5156 const AttributeCommonInfo &CI,
5157 bool BestCase,
5158 MSInheritanceModel Model);
5159
5160 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5161 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5162 const EnforceTCBLeafAttr &AL);
5163
5164 /// Helper for delayed processing TransparentUnion or
5165 /// BPFPreserveAccessIndexAttr attribute.
5166 void ProcessDeclAttributeDelayed(Decl *D,
5167 const ParsedAttributesView &AttrList);
5168
5169 // Options for ProcessDeclAttributeList().
5170 struct ProcessDeclAttributeOptions {
5171 ProcessDeclAttributeOptions()
5172 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
5173
5174 ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
5175 ProcessDeclAttributeOptions Result = *this;
5176 Result.IncludeCXX11Attributes = Val;
5177 return Result;
5178 }
5179
5180 ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
5181 ProcessDeclAttributeOptions Result = *this;
5182 Result.IgnoreTypeAttributes = Val;
5183 return Result;
5184 }
5185
5186 // Should C++11 attributes be processed?
5187 bool IncludeCXX11Attributes;
5188
5189 // Should any type attributes encountered be ignored?
5190 // If this option is false, a diagnostic will be emitted for any type
5191 // attributes of a kind that does not "slide" from the declaration to
5192 // the decl-specifier-seq.
5193 bool IgnoreTypeAttributes;
5194 };
5195
5196 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5197 /// attribute list to the specified decl, ignoring any type attributes.
5198 void ProcessDeclAttributeList(Scope *S, Decl *D,
5199 const ParsedAttributesView &AttrList,
5200 const ProcessDeclAttributeOptions &Options =
5201 ProcessDeclAttributeOptions());
5202
5203 /// Annotation attributes are the only attributes allowed after an access
5204 /// specifier.
5205 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5206 const ParsedAttributesView &AttrList);
5207
5208 /// checkUnusedDeclAttributes - Given a declarator which is not being
5209 /// used to build a declaration, complain about any decl attributes
5210 /// which might be lying around on it.
5211 void checkUnusedDeclAttributes(Declarator &D);
5212
5213 void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5214
5215 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5216 /// \#pragma weak needs a non-definition decl and source may not have one.
5217 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
5218 SourceLocation Loc);
5219
5220 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5221 /// applied to it, possibly with an alias.
5222 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5223
5224 void ProcessPragmaWeak(Scope *S, Decl *D);
5225 // Decl attributes - this routine is the top level dispatcher.
5226 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5227
5228 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5229
5230 /// Given a set of delayed diagnostics, re-emit them as if they had
5231 /// been delayed in the current context instead of in the given pool.
5232 /// Essentially, this just moves them to the current pool.
5233 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5234
5235 /// Check that the type is a plain record with one field being a pointer
5236 /// type and the other field being an integer. This matches the common
5237 /// implementation of std::span or sized_allocation_t in P0901R11.
5238 bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty);
5239
5240 /// Check if IdxExpr is a valid parameter index for a function or
5241 /// instance method D. May output an error.
5242 ///
5243 /// \returns true if IdxExpr is a valid index.
5244 template <typename AttrInfo>
5245 bool checkFunctionOrMethodParameterIndex(
5246 const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5247 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5248 bool CanIndexVariadicArguments = false) {
5249 assert(isFunctionOrMethodOrBlockForAttrSubject(D));
5250
5251 // In C++ the implicit 'this' function parameter also counts.
5252 // Parameters are counted from one.
5253 bool HP = hasFunctionProto(D);
5254 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
5255 bool IV = HP && isFunctionOrMethodVariadic(D);
5256 unsigned NumParams =
5257 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
5258
5259 std::optional<llvm::APSInt> IdxInt;
5260 if (IdxExpr->isTypeDependent() ||
5261 !(IdxInt = IdxExpr->getIntegerConstantExpr(Ctx: Context))) {
5262 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5263 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5264 << IdxExpr->getSourceRange();
5265 return false;
5266 }
5267
5268 constexpr unsigned Limit = 1 << ParamIdx::IdxBitWidth;
5269 unsigned IdxSource = IdxInt->getLimitedValue(Limit);
5270 if (IdxSource < 1 || IdxSource == Limit ||
5271 ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5272 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5273 << &AI << AttrArgNum << IdxExpr->getSourceRange();
5274 return false;
5275 }
5276 if (HasImplicitThisParam && !CanIndexImplicitThis) {
5277 if (IdxSource == 1) {
5278 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5279 << &AI << IdxExpr->getSourceRange();
5280 return false;
5281 }
5282 }
5283
5284 Idx = ParamIdx(IdxSource, D);
5285 return true;
5286 }
5287
5288 ///@}
5289
5290 //
5291 //
5292 // -------------------------------------------------------------------------
5293 //
5294 //
5295
5296 /// \name C++ Declarations
5297 /// Implementations are in SemaDeclCXX.cpp
5298 ///@{
5299
5300public:
5301 void CheckDelegatingCtorCycles();
5302
5303 /// Called before parsing a function declarator belonging to a function
5304 /// declaration.
5305 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
5306 unsigned TemplateParameterDepth);
5307
5308 /// Called after parsing a function declarator belonging to a function
5309 /// declaration.
5310 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
5311
5312 // Act on C++ namespaces
5313 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5314 SourceLocation NamespaceLoc,
5315 SourceLocation IdentLoc, IdentifierInfo *Ident,
5316 SourceLocation LBrace,
5317 const ParsedAttributesView &AttrList,
5318 UsingDirectiveDecl *&UsingDecl, bool IsNested);
5319
5320 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5321 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5322 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5323
5324 NamespaceDecl *getStdNamespace() const;
5325
5326 /// Retrieve the special "std" namespace, which may require us to
5327 /// implicitly define the namespace.
5328 NamespaceDecl *getOrCreateStdNamespace();
5329
5330 CXXRecordDecl *getStdBadAlloc() const;
5331 EnumDecl *getStdAlignValT() const;
5332
5333 TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const;
5334 FunctionDecl *BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl,
5335 QualType AllocType, SourceLocation);
5336
5337 ValueDecl *tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
5338 const IdentifierInfo *MemberOrBase);
5339
5340 enum class ComparisonCategoryUsage {
5341 /// The '<=>' operator was used in an expression and a builtin operator
5342 /// was selected.
5343 OperatorInExpression,
5344 /// A defaulted 'operator<=>' needed the comparison category. This
5345 /// typically only applies to 'std::strong_ordering', due to the implicit
5346 /// fallback return value.
5347 DefaultedOperator,
5348 /// A builtin needed 'std::strong_ordering' (eg. '__builtin_type_order').
5349 Builtin,
5350 };
5351
5352 /// Lookup the specified comparison category types in the standard
5353 /// library, an check the VarDecls possibly returned by the operator<=>
5354 /// builtins for that type.
5355 ///
5356 /// \return The type of the comparison category type corresponding to the
5357 /// specified Kind, or a null type if an error occurs
5358 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5359 SourceLocation Loc,
5360 ComparisonCategoryUsage Usage);
5361
5362 /// Tests whether Ty is an instance of std::initializer_list and, if
5363 /// it is and Element is not NULL, assigns the element type to Element.
5364 bool isStdInitializerList(QualType Ty, QualType *Element);
5365
5366 /// Tests whether Ty is an instance of std::type_identity and, if
5367 /// it is and TypeArgument is not NULL, assigns the element type to Element.
5368 /// If MalformedDecl is not null, and type_identity was ruled out due to being
5369 /// incorrectly structured despite having the correct name, the faulty Decl
5370 /// will be assigned to MalformedDecl.
5371 bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5372 const Decl **MalformedDecl = nullptr);
5373
5374 /// Looks for the std::initializer_list template and instantiates it
5375 /// with Element, or emits an error if it's not found.
5376 ///
5377 /// \returns The instantiated template, or null on error.
5378 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5379
5380 /// Looks for the std::type_identity template and instantiates it
5381 /// with Type, or returns a null type if type_identity has not been declared
5382 ///
5383 /// \returns The instantiated template, or null if std::type_identity is not
5384 /// declared
5385 QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc);
5386
5387 /// Determine whether Ctor is an initializer-list constructor, as
5388 /// defined in [dcl.init.list]p2.
5389 bool isInitListConstructor(const FunctionDecl *Ctor);
5390
5391 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5392 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5393 SourceLocation IdentLoc,
5394 IdentifierInfo *NamespcName,
5395 const ParsedAttributesView &AttrList);
5396
5397 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5398
5399 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5400 SourceLocation AliasLoc, IdentifierInfo *Alias,
5401 CXXScopeSpec &SS, SourceLocation IdentLoc,
5402 IdentifierInfo *Ident);
5403
5404 /// Remove decls we can't actually see from a lookup being used to declare
5405 /// shadow using decls.
5406 ///
5407 /// \param S - The scope of the potential shadow decl
5408 /// \param Previous - The lookup of a potential shadow decl's name.
5409 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5410
5411 /// Hides a using shadow declaration. This is required by the current
5412 /// using-decl implementation when a resolvable using declaration in a
5413 /// class is followed by a declaration which would hide or override
5414 /// one or more of the using decl's targets; for example:
5415 ///
5416 /// struct Base { void foo(int); };
5417 /// struct Derived : Base {
5418 /// using Base::foo;
5419 /// void foo(int);
5420 /// };
5421 ///
5422 /// The governing language is C++03 [namespace.udecl]p12:
5423 ///
5424 /// When a using-declaration brings names from a base class into a
5425 /// derived class scope, member functions in the derived class
5426 /// override and/or hide member functions with the same name and
5427 /// parameter types in a base class (rather than conflicting).
5428 ///
5429 /// There are two ways to implement this:
5430 /// (1) optimistically create shadow decls when they're not hidden
5431 /// by existing declarations, or
5432 /// (2) don't create any shadow decls (or at least don't make them
5433 /// visible) until we've fully parsed/instantiated the class.
5434 /// The problem with (1) is that we might have to retroactively remove
5435 /// a shadow decl, which requires several O(n) operations because the
5436 /// decl structures are (very reasonably) not designed for removal.
5437 /// (2) avoids this but is very fiddly and phase-dependent.
5438 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5439
5440 /// Determines whether to create a using shadow decl for a particular
5441 /// decl, given the set of decls existing prior to this using lookup.
5442 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5443 const LookupResult &PreviousDecls,
5444 UsingShadowDecl *&PrevShadow);
5445
5446 /// Builds a shadow declaration corresponding to a 'using' declaration.
5447 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5448 NamedDecl *Target,
5449 UsingShadowDecl *PrevDecl);
5450
5451 /// Checks that the given using declaration is not an invalid
5452 /// redeclaration. Note that this is checking only for the using decl
5453 /// itself, not for any ill-formedness among the UsingShadowDecls.
5454 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5455 bool HasTypenameKeyword,
5456 const CXXScopeSpec &SS,
5457 SourceLocation NameLoc,
5458 const LookupResult &Previous);
5459
5460 /// Checks that the given nested-name qualifier used in a using decl
5461 /// in the current context is appropriately related to the current
5462 /// scope. If an error is found, diagnoses it and returns true.
5463 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5464 /// the result of that lookup. UD is likewise nullptr, except when we have an
5465 /// already-populated UsingDecl whose shadow decls contain the same
5466 /// information (i.e. we're instantiating a UsingDecl with non-dependent
5467 /// scope).
5468 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5469 const CXXScopeSpec &SS,
5470 const DeclarationNameInfo &NameInfo,
5471 SourceLocation NameLoc,
5472 const LookupResult *R = nullptr,
5473 const UsingDecl *UD = nullptr);
5474
5475 /// Builds a using declaration.
5476 ///
5477 /// \param IsInstantiation - Whether this call arises from an
5478 /// instantiation of an unresolved using declaration. We treat
5479 /// the lookup differently for these declarations.
5480 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5481 SourceLocation UsingLoc,
5482 bool HasTypenameKeyword,
5483 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5484 DeclarationNameInfo NameInfo,
5485 SourceLocation EllipsisLoc,
5486 const ParsedAttributesView &AttrList,
5487 bool IsInstantiation, bool IsUsingIfExists);
5488 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
5489 SourceLocation UsingLoc,
5490 SourceLocation EnumLoc,
5491 SourceLocation NameLoc,
5492 TypeSourceInfo *EnumType, EnumDecl *ED);
5493 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5494 ArrayRef<NamedDecl *> Expansions);
5495
5496 /// Additional checks for a using declaration referring to a constructor name.
5497 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5498
5499 /// Given a derived-class using shadow declaration for a constructor and the
5500 /// correspnding base class constructor, find or create the implicit
5501 /// synthesized derived class constructor to use for this initialization.
5502 CXXConstructorDecl *
5503 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5504 ConstructorUsingShadowDecl *DerivedShadow);
5505
5506 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5507 SourceLocation UsingLoc,
5508 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5509 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5510 const ParsedAttributesView &AttrList);
5511 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
5512 SourceLocation UsingLoc,
5513 SourceLocation EnumLoc, SourceRange TyLoc,
5514 const IdentifierInfo &II, ParsedType Ty,
5515 const CXXScopeSpec &SS);
5516 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5517 MultiTemplateParamsArg TemplateParams,
5518 SourceLocation UsingLoc, UnqualifiedId &Name,
5519 const ParsedAttributesView &AttrList,
5520 TypeResult Type, Decl *DeclFromDeclSpec);
5521
5522 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5523 /// including handling of its default argument expressions.
5524 ///
5525 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5526 ExprResult BuildCXXConstructExpr(
5527 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5528 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5529 bool HadMultipleCandidates, bool IsListInitialization,
5530 bool IsStdInitListInitialization, bool RequiresZeroInit,
5531 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5532
5533 /// Build a CXXConstructExpr whose constructor has already been resolved if
5534 /// it denotes an inherited constructor.
5535 ExprResult BuildCXXConstructExpr(
5536 SourceLocation ConstructLoc, QualType DeclInitType,
5537 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5538 bool HadMultipleCandidates, bool IsListInitialization,
5539 bool IsStdInitListInitialization, bool RequiresZeroInit,
5540 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5541
5542 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5543 // the constructor can be elidable?
5544 ExprResult BuildCXXConstructExpr(
5545 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5546 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5547 bool HadMultipleCandidates, bool IsListInitialization,
5548 bool IsStdInitListInitialization, bool RequiresZeroInit,
5549 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5550
5551 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr,
5552 SourceLocation InitLoc);
5553 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD,
5554 const InitializedEntity &Entity,
5555 Expr *InitExpr,
5556 SourceLocation InitLoc);
5557
5558 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5559 /// constructed variable.
5560 void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit);
5561
5562 /// Helper class that collects exception specifications for
5563 /// implicitly-declared special member functions.
5564 class ImplicitExceptionSpecification {
5565 // Pointer to allow copying
5566 Sema *Self;
5567 // We order exception specifications thus:
5568 // noexcept is the most restrictive, but is only used in C++11.
5569 // throw() comes next.
5570 // Then a throw(collected exceptions)
5571 // Finally no specification, which is expressed as noexcept(false).
5572 // throw(...) is used instead if any called function uses it.
5573 ExceptionSpecificationType ComputedEST;
5574 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5575 SmallVector<QualType, 4> Exceptions;
5576
5577 void ClearExceptions() {
5578 ExceptionsSeen.clear();
5579 Exceptions.clear();
5580 }
5581
5582 public:
5583 explicit ImplicitExceptionSpecification(Sema &Self)
5584 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5585 if (!Self.getLangOpts().CPlusPlus11)
5586 ComputedEST = EST_DynamicNone;
5587 }
5588
5589 /// Get the computed exception specification type.
5590 ExceptionSpecificationType getExceptionSpecType() const {
5591 assert(!isComputedNoexcept(ComputedEST) &&
5592 "noexcept(expr) should not be a possible result");
5593 return ComputedEST;
5594 }
5595
5596 /// The number of exceptions in the exception specification.
5597 unsigned size() const { return Exceptions.size(); }
5598
5599 /// The set of exceptions in the exception specification.
5600 const QualType *data() const { return Exceptions.data(); }
5601
5602 /// Integrate another called method into the collected data.
5603 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5604
5605 /// Integrate an invoked expression into the collected data.
5606 void CalledExpr(Expr *E) { CalledStmt(S: E); }
5607
5608 /// Integrate an invoked statement into the collected data.
5609 void CalledStmt(Stmt *S);
5610
5611 /// Overwrite an EPI's exception specification with this
5612 /// computed exception specification.
5613 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5614 FunctionProtoType::ExceptionSpecInfo ESI;
5615 ESI.Type = getExceptionSpecType();
5616 if (ESI.Type == EST_Dynamic) {
5617 ESI.Exceptions = Exceptions;
5618 } else if (ESI.Type == EST_None) {
5619 /// C++11 [except.spec]p14:
5620 /// The exception-specification is noexcept(false) if the set of
5621 /// potential exceptions of the special member function contains "any"
5622 ESI.Type = EST_NoexceptFalse;
5623 ESI.NoexceptExpr =
5624 Self->ActOnCXXBoolLiteral(OpLoc: SourceLocation(), Kind: tok::kw_false).get();
5625 }
5626 return ESI;
5627 }
5628 };
5629
5630 /// Evaluate the implicit exception specification for a defaulted
5631 /// special member function.
5632 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5633
5634 /// Check the given exception-specification and update the
5635 /// exception specification information with the results.
5636 void checkExceptionSpecification(bool IsTopLevel,
5637 ExceptionSpecificationType EST,
5638 ArrayRef<ParsedType> DynamicExceptions,
5639 ArrayRef<SourceRange> DynamicExceptionRanges,
5640 Expr *NoexceptExpr,
5641 SmallVectorImpl<QualType> &Exceptions,
5642 FunctionProtoType::ExceptionSpecInfo &ESI);
5643
5644 /// Add an exception-specification to the given member or friend function
5645 /// (or function template). The exception-specification was parsed
5646 /// after the function itself was declared.
5647 void actOnDelayedExceptionSpecification(
5648 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5649 ArrayRef<ParsedType> DynamicExceptions,
5650 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5651
5652 class InheritedConstructorInfo;
5653
5654 /// Determine if a special member function should have a deleted
5655 /// definition when it is defaulted.
5656 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
5657 InheritedConstructorInfo *ICI = nullptr,
5658 bool Diagnose = false);
5659
5660 /// Produce notes explaining why a defaulted function was defined as deleted.
5661 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5662
5663 /// Declare the implicit default constructor for the given class.
5664 ///
5665 /// \param ClassDecl The class declaration into which the implicit
5666 /// default constructor will be added.
5667 ///
5668 /// \returns The implicitly-declared default constructor.
5669 CXXConstructorDecl *
5670 DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl);
5671
5672 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5673 /// defining this constructor as the default constructor.
5674 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5675 CXXConstructorDecl *Constructor);
5676
5677 /// Declare the implicit destructor for the given class.
5678 ///
5679 /// \param ClassDecl The class declaration into which the implicit
5680 /// destructor will be added.
5681 ///
5682 /// \returns The implicitly-declared destructor.
5683 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5684
5685 /// DefineImplicitDestructor - Checks for feasibility of
5686 /// defining this destructor as the default destructor.
5687 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5688 CXXDestructorDecl *Destructor);
5689
5690 /// Build an exception spec for destructors that don't have one.
5691 ///
5692 /// C++11 says that user-defined destructors with no exception spec get one
5693 /// that looks as if the destructor was implicitly declared.
5694 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5695
5696 /// Define the specified inheriting constructor.
5697 void DefineInheritingConstructor(SourceLocation UseLoc,
5698 CXXConstructorDecl *Constructor);
5699
5700 /// Declare the implicit copy constructor for the given class.
5701 ///
5702 /// \param ClassDecl The class declaration into which the implicit
5703 /// copy constructor will be added.
5704 ///
5705 /// \returns The implicitly-declared copy constructor.
5706 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5707
5708 /// DefineImplicitCopyConstructor - Checks for feasibility of
5709 /// defining this constructor as the copy constructor.
5710 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5711 CXXConstructorDecl *Constructor);
5712
5713 /// Declare the implicit move constructor for the given class.
5714 ///
5715 /// \param ClassDecl The Class declaration into which the implicit
5716 /// move constructor will be added.
5717 ///
5718 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5719 /// declared.
5720 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5721
5722 /// DefineImplicitMoveConstructor - Checks for feasibility of
5723 /// defining this constructor as the move constructor.
5724 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5725 CXXConstructorDecl *Constructor);
5726
5727 /// Declare the implicit copy assignment operator for the given class.
5728 ///
5729 /// \param ClassDecl The class declaration into which the implicit
5730 /// copy assignment operator will be added.
5731 ///
5732 /// \returns The implicitly-declared copy assignment operator.
5733 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5734
5735 /// Defines an implicitly-declared copy assignment operator.
5736 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5737 CXXMethodDecl *MethodDecl);
5738
5739 /// Declare the implicit move assignment operator for the given class.
5740 ///
5741 /// \param ClassDecl The Class declaration into which the implicit
5742 /// move assignment operator will be added.
5743 ///
5744 /// \returns The implicitly-declared move assignment operator, or NULL if it
5745 /// wasn't declared.
5746 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5747
5748 /// Defines an implicitly-declared move assignment operator.
5749 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5750 CXXMethodDecl *MethodDecl);
5751
5752 /// Check a completed declaration of an implicit special member.
5753 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5754
5755 /// Determine whether the given function is an implicitly-deleted
5756 /// special member function.
5757 bool isImplicitlyDeleted(FunctionDecl *FD);
5758
5759 /// Check whether 'this' shows up in the type of a static member
5760 /// function after the (naturally empty) cv-qualifier-seq would be.
5761 ///
5762 /// \returns true if an error occurred.
5763 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5764
5765 /// Whether this' shows up in the exception specification of a static
5766 /// member function.
5767 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5768
5769 /// Check whether 'this' shows up in the attributes of the given
5770 /// static member function.
5771 ///
5772 /// \returns true if an error occurred.
5773 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5774
5775 bool CheckImmediateEscalatingFunctionDefinition(
5776 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5777
5778 void DiagnoseImmediateEscalatingReason(FunctionDecl *FD);
5779
5780 /// Given a constructor and the set of arguments provided for the
5781 /// constructor, convert the arguments and add any required default arguments
5782 /// to form a proper call to this constructor.
5783 ///
5784 /// \returns true if an error occurred, false otherwise.
5785 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5786 QualType DeclInitType, MultiExprArg ArgsPtr,
5787 SourceLocation Loc,
5788 SmallVectorImpl<Expr *> &ConvertedArgs,
5789 bool AllowExplicit = false,
5790 bool IsListInitialization = false);
5791
5792 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5793 /// initializer for the declaration 'Dcl'.
5794 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5795 /// static data member of class X, names should be looked up in the scope of
5796 /// class X.
5797 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5798
5799 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5800 /// initializer for the declaration 'Dcl'.
5801 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5802
5803 /// Define the "body" of the conversion from a lambda object to a
5804 /// function pointer.
5805 ///
5806 /// This routine doesn't actually define a sensible body; rather, it fills
5807 /// in the initialization expression needed to copy the lambda object into
5808 /// the block, and IR generation actually generates the real body of the
5809 /// block pointer conversion.
5810 void
5811 DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc,
5812 CXXConversionDecl *Conv);
5813
5814 /// Define the "body" of the conversion from a lambda object to a
5815 /// block pointer.
5816 ///
5817 /// This routine doesn't actually define a sensible body; rather, it fills
5818 /// in the initialization expression needed to copy the lambda object into
5819 /// the block, and IR generation actually generates the real body of the
5820 /// block pointer conversion.
5821 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5822 CXXConversionDecl *Conv);
5823
5824 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5825 /// linkage specification, including the language and (if present)
5826 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5827 /// language string literal. LBraceLoc, if valid, provides the location of
5828 /// the '{' brace. Otherwise, this linkage specification does not
5829 /// have any braces.
5830 Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5831 Expr *LangStr, SourceLocation LBraceLoc);
5832
5833 /// ActOnFinishLinkageSpecification - Complete the definition of
5834 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5835 /// valid, it's the position of the closing '}' brace in a linkage
5836 /// specification that uses braces.
5837 Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec,
5838 SourceLocation RBraceLoc);
5839
5840 //===--------------------------------------------------------------------===//
5841 // C++ Classes
5842 //
5843
5844 /// Get the class that is directly named by the current context. This is the
5845 /// class for which an unqualified-id in this scope could name a constructor
5846 /// or destructor.
5847 ///
5848 /// If the scope specifier denotes a class, this will be that class.
5849 /// If the scope specifier is empty, this will be the class whose
5850 /// member-specification we are currently within. Otherwise, there
5851 /// is no such class.
5852 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
5853
5854 /// isCurrentClassName - Determine whether the identifier II is the
5855 /// name of the class type currently being defined. In the case of
5856 /// nested classes, this will only return true if II is the name of
5857 /// the innermost class.
5858 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5859 const CXXScopeSpec *SS = nullptr);
5860
5861 /// Determine whether the identifier II is a typo for the name of
5862 /// the class type currently being defined. If so, update it to the identifier
5863 /// that should have been used.
5864 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5865
5866 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5867 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
5868 SourceLocation ColonLoc,
5869 const ParsedAttributesView &Attrs);
5870
5871 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5872 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5873 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
5874 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
5875 /// present (but parsing it has been deferred).
5876 NamedDecl *
5877 ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
5878 MultiTemplateParamsArg TemplateParameterLists,
5879 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5880 InClassInitStyle InitStyle);
5881
5882 /// Enter a new C++ default initializer scope. After calling this, the
5883 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
5884 /// parsing or instantiating the initializer failed.
5885 void ActOnStartCXXInClassMemberInitializer();
5886
5887 /// This is invoked after parsing an in-class initializer for a
5888 /// non-static C++ class member, and after instantiating an in-class
5889 /// initializer in a class template. Such actions are deferred until the class
5890 /// is complete.
5891 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5892 SourceLocation EqualLoc,
5893 ExprResult Init);
5894
5895 /// Handle a C++ member initializer using parentheses syntax.
5896 MemInitResult
5897 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
5898 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
5899 const DeclSpec &DS, SourceLocation IdLoc,
5900 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
5901 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
5902
5903 /// Handle a C++ member initializer using braced-init-list syntax.
5904 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
5905 CXXScopeSpec &SS,
5906 IdentifierInfo *MemberOrBase,
5907 ParsedType TemplateTypeTy,
5908 const DeclSpec &DS, SourceLocation IdLoc,
5909 Expr *InitList, SourceLocation EllipsisLoc);
5910
5911 /// Handle a C++ member initializer.
5912 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
5913 CXXScopeSpec &SS,
5914 IdentifierInfo *MemberOrBase,
5915 ParsedType TemplateTypeTy,
5916 const DeclSpec &DS, SourceLocation IdLoc,
5917 Expr *Init, SourceLocation EllipsisLoc);
5918
5919 MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init,
5920 SourceLocation IdLoc);
5921
5922 MemInitResult BuildBaseInitializer(QualType BaseType,
5923 TypeSourceInfo *BaseTInfo, Expr *Init,
5924 CXXRecordDecl *ClassDecl,
5925 SourceLocation EllipsisLoc);
5926
5927 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
5928 CXXRecordDecl *ClassDecl);
5929
5930 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5931 CXXCtorInitializer *Initializer);
5932
5933 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5934 ArrayRef<CXXCtorInitializer *> Initializers = {});
5935
5936 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5937 /// mark all the non-trivial destructors of its members and bases as
5938 /// referenced.
5939 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5940 CXXRecordDecl *Record);
5941
5942 /// Mark destructors of virtual bases of this class referenced. In the Itanium
5943 /// C++ ABI, this is done when emitting a destructor for any non-abstract
5944 /// class. In the Microsoft C++ ABI, this is done any time a class's
5945 /// destructor is referenced.
5946 void MarkVirtualBaseDestructorsReferenced(
5947 SourceLocation Location, CXXRecordDecl *ClassDecl,
5948 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
5949 nullptr);
5950
5951 /// Do semantic checks to allow the complete destructor variant to be emitted
5952 /// when the destructor is defined in another translation unit. In the Itanium
5953 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
5954 /// can be emitted in separate TUs. To emit the complete variant, run a subset
5955 /// of the checks performed when emitting a regular destructor.
5956 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
5957 CXXDestructorDecl *Dtor);
5958
5959 /// The list of classes whose vtables have been used within
5960 /// this translation unit, and the source locations at which the
5961 /// first use occurred.
5962 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
5963
5964 /// The list of vtables that are required but have not yet been
5965 /// materialized.
5966 SmallVector<VTableUse, 16> VTableUses;
5967
5968 /// The set of classes whose vtables have been used within
5969 /// this translation unit, and a bit that will be true if the vtable is
5970 /// required to be emitted (otherwise, it should be emitted only if needed
5971 /// by code generation).
5972 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5973
5974 /// Load any externally-stored vtable uses.
5975 void LoadExternalVTableUses();
5976
5977 /// Note that the vtable for the given class was used at the
5978 /// given location.
5979 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5980 bool DefinitionRequired = false);
5981
5982 /// Mark the exception specifications of all virtual member functions
5983 /// in the given class as needed.
5984 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5985 const CXXRecordDecl *RD);
5986
5987 /// MarkVirtualMembersReferenced - Will mark all members of the given
5988 /// CXXRecordDecl referenced.
5989 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
5990 bool ConstexprOnly = false);
5991
5992 /// Define all of the vtables that have been used in this
5993 /// translation unit and reference any virtual members used by those
5994 /// vtables.
5995 ///
5996 /// \returns true if any work was done, false otherwise.
5997 bool DefineUsedVTables();
5998
5999 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6000 /// special functions, such as the default constructor, copy
6001 /// constructor, or destructor, to the given C++ class (C++
6002 /// [special]p1). This routine can only be executed just before the
6003 /// definition of the class is complete.
6004 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
6005
6006 /// ActOnMemInitializers - Handle the member initializers for a constructor.
6007 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
6008 ArrayRef<CXXCtorInitializer *> MemInits,
6009 bool AnyErrors);
6010
6011 /// Check class-level dllimport/dllexport attribute. The caller must
6012 /// ensure that referenceDLLExportedClassMethods is called some point later
6013 /// when all outer classes of Class are complete.
6014 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
6015 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
6016
6017 void referenceDLLExportedClassMethods();
6018
6019 /// Perform propagation of DLL attributes from a derived class to a
6020 /// templated base class for MS compatibility.
6021 void propagateDLLAttrToBaseClassTemplate(
6022 CXXRecordDecl *Class, Attr *ClassAttr,
6023 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6024 SourceLocation BaseLoc);
6025
6026 /// Perform semantic checks on a class definition that has been
6027 /// completing, introducing implicitly-declared members, checking for
6028 /// abstract types, etc.
6029 ///
6030 /// \param S The scope in which the class was parsed. Null if we didn't just
6031 /// parse a class definition.
6032 /// \param Record The completed class.
6033 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
6034
6035 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6036 /// conditions that are needed for the attribute to have an effect.
6037 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6038
6039 /// Check that VTable Pointer authentication is only being set on the first
6040 /// first instantiation of the vtable
6041 void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD);
6042
6043 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6044 Decl *TagDecl, SourceLocation LBrac,
6045 SourceLocation RBrac,
6046 const ParsedAttributesView &AttrList);
6047
6048 /// Perform any semantic analysis which needs to be delayed until all
6049 /// pending class member declarations have been parsed.
6050 void ActOnFinishCXXMemberDecls();
6051 void ActOnFinishCXXNonNestedClass();
6052
6053 /// This is used to implement the constant expression evaluation part of the
6054 /// attribute enable_if extension. There is nothing in standard C++ which
6055 /// would require reentering parameters.
6056 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6057 unsigned ActOnReenterTemplateScope(Decl *Template,
6058 llvm::function_ref<Scope *()> EnterScope);
6059 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6060
6061 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6062 /// parsing a top-level (non-nested) C++ class, and we are now
6063 /// parsing those parts of the given Method declaration that could
6064 /// not be parsed earlier (C++ [class.mem]p2), such as default
6065 /// arguments. This action should enter the scope of the given
6066 /// Method declaration as if we had just parsed the qualified method
6067 /// name. However, it should not bring the parameters into scope;
6068 /// that will be performed by ActOnDelayedCXXMethodParameter.
6069 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6070 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6071 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6072
6073 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6074 /// processing the delayed method declaration for Method. The method
6075 /// declaration is now considered finished. There may be a separate
6076 /// ActOnStartOfFunctionDef action later (not necessarily
6077 /// immediately!) for this method, if it was also defined inside the
6078 /// class body.
6079 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6080 void ActOnFinishDelayedMemberInitializers(Decl *Record);
6081
6082 enum class StringEvaluationContext { StaticAssert = 0, Asm = 1 };
6083
6084 bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
6085 StringEvaluationContext EvalContext,
6086 bool ErrorOnInvalidMessage);
6087 bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
6088 StringEvaluationContext EvalContext,
6089 bool ErrorOnInvalidMessage);
6090
6091 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6092 Expr *AssertExpr, Expr *AssertMessageExpr,
6093 SourceLocation RParenLoc);
6094 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6095 Expr *AssertExpr, Expr *AssertMessageExpr,
6096 SourceLocation RParenLoc, bool Failed);
6097
6098 /// Try to print more useful information about a failed static_assert
6099 /// with expression \E
6100 void DiagnoseStaticAssertDetails(const Expr *E);
6101
6102 /// If E represents a built-in type trait, or a known standard type trait,
6103 /// try to print more information about why the type type-trait failed.
6104 /// This assumes we already evaluated the expression to a false boolean value.
6105 void DiagnoseTypeTraitDetails(const Expr *E);
6106
6107 /// Handle a friend type declaration. This works in tandem with
6108 /// ActOnTag.
6109 ///
6110 /// Notes on friend class templates:
6111 ///
6112 /// We generally treat friend class declarations as if they were
6113 /// declaring a class. So, for example, the elaborated type specifier
6114 /// in a friend declaration is required to obey the restrictions of a
6115 /// class-head (i.e. no typedefs in the scope chain), template
6116 /// parameters are required to match up with simple template-ids, &c.
6117 /// However, unlike when declaring a template specialization, it's
6118 /// okay to refer to a template specialization without an empty
6119 /// template parameter declaration, e.g.
6120 /// friend class A<T>::B<unsigned>;
6121 /// We permit this as a special case; if there are any template
6122 /// parameters present at all, require proper matching, i.e.
6123 /// template <> template \<class T> friend class A<int>::B;
6124 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6125 MultiTemplateParamsArg TemplateParams,
6126 SourceLocation EllipsisLoc);
6127 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6128 MultiTemplateParamsArg TemplateParams);
6129
6130 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6131 /// the well-formedness of the constructor declarator @p D with type @p
6132 /// R. If there are any errors in the declarator, this routine will
6133 /// emit diagnostics and set the invalid bit to true. In any case, the type
6134 /// will be updated to reflect a well-formed type for the constructor and
6135 /// returned.
6136 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6137 StorageClass &SC);
6138
6139 /// CheckConstructor - Checks a fully-formed constructor for
6140 /// well-formedness, issuing any diagnostics required. Returns true if
6141 /// the constructor declarator is invalid.
6142 void CheckConstructor(CXXConstructorDecl *Constructor);
6143
6144 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6145 /// the well-formednes of the destructor declarator @p D with type @p
6146 /// R. If there are any errors in the declarator, this routine will
6147 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6148 /// will be updated to reflect a well-formed type for the destructor and
6149 /// returned.
6150 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6151 StorageClass &SC);
6152
6153 /// CheckDestructor - Checks a fully-formed destructor definition for
6154 /// well-formedness, issuing any diagnostics required. Returns true
6155 /// on error.
6156 bool CheckDestructor(CXXDestructorDecl *Destructor);
6157
6158 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6159 /// well-formednes of the conversion function declarator @p D with
6160 /// type @p R. If there are any errors in the declarator, this routine
6161 /// will emit diagnostics and return true. Otherwise, it will return
6162 /// false. Either way, the type @p R will be updated to reflect a
6163 /// well-formed type for the conversion operator.
6164 void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC);
6165
6166 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6167 /// the declaration of the given C++ conversion function. This routine
6168 /// is responsible for recording the conversion function in the C++
6169 /// class, if possible.
6170 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6171
6172 /// Check the validity of a declarator that we parsed for a deduction-guide.
6173 /// These aren't actually declarators in the grammar, so we need to check that
6174 /// the user didn't specify any pieces that are not part of the
6175 /// deduction-guide grammar. Return true on invalid deduction-guide.
6176 bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6177 StorageClass &SC);
6178
6179 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6180
6181 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6182 CXXSpecialMemberKind CSM,
6183 SourceLocation DefaultLoc);
6184 void CheckDelayedMemberExceptionSpecs();
6185
6186 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6187 DefaultedComparisonKind DCK);
6188 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6189 FunctionDecl *Spaceship);
6190 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6191 DefaultedComparisonKind DCK);
6192
6193 void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name,
6194 QualType R, bool IsLambda,
6195 DeclContext *DC = nullptr);
6196 void CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
6197 DeclarationName Name, QualType R);
6198 void CheckExplicitObjectLambda(Declarator &D);
6199
6200 //===--------------------------------------------------------------------===//
6201 // C++ Derived Classes
6202 //
6203
6204 /// Check the validity of a C++ base class specifier.
6205 ///
6206 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6207 /// and returns NULL otherwise.
6208 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6209 SourceRange SpecifierRange, bool Virtual,
6210 AccessSpecifier Access,
6211 TypeSourceInfo *TInfo,
6212 SourceLocation EllipsisLoc);
6213
6214 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6215 /// one entry in the base class list of a class specifier, for
6216 /// example:
6217 /// class foo : public bar, virtual private baz {
6218 /// 'public bar' and 'virtual private baz' are each base-specifiers.
6219 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6220 const ParsedAttributesView &Attrs, bool Virtual,
6221 AccessSpecifier Access, ParsedType basetype,
6222 SourceLocation BaseLoc,
6223 SourceLocation EllipsisLoc);
6224
6225 /// Performs the actual work of attaching the given base class
6226 /// specifiers to a C++ class.
6227 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6228 MutableArrayRef<CXXBaseSpecifier *> Bases);
6229
6230 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6231 /// class, after checking whether there are any duplicate base
6232 /// classes.
6233 void ActOnBaseSpecifiers(Decl *ClassDecl,
6234 MutableArrayRef<CXXBaseSpecifier *> Bases);
6235
6236 /// Determine whether the type \p Derived is a C++ class that is
6237 /// derived from the type \p Base.
6238 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6239 CXXRecordDecl *Base, CXXBasePaths &Paths);
6240 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6241 CXXRecordDecl *Base);
6242 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6243 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6244 CXXBasePaths &Paths);
6245
6246 // FIXME: I don't like this name.
6247 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6248
6249 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6250 SourceLocation Loc, SourceRange Range,
6251 CXXCastPath *BasePath = nullptr,
6252 bool IgnoreAccess = false);
6253
6254 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6255 /// conversion (where Derived and Base are class types) is
6256 /// well-formed, meaning that the conversion is unambiguous (and
6257 /// that all of the base classes are accessible). Returns true
6258 /// and emits a diagnostic if the code is ill-formed, returns false
6259 /// otherwise. Loc is the location where this routine should point to
6260 /// if there is an error, and Range is the source range to highlight
6261 /// if there is an error.
6262 ///
6263 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6264 /// diagnostic for the respective type of error will be suppressed, but the
6265 /// check for ill-formed code will still be performed.
6266 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6267 unsigned InaccessibleBaseID,
6268 unsigned AmbiguousBaseConvID,
6269 SourceLocation Loc, SourceRange Range,
6270 DeclarationName Name, CXXCastPath *BasePath,
6271 bool IgnoreAccess = false);
6272
6273 /// Builds a string representing ambiguous paths from a
6274 /// specific derived class to different subobjects of the same base
6275 /// class.
6276 ///
6277 /// This function builds a string that can be used in error messages
6278 /// to show the different paths that one can take through the
6279 /// inheritance hierarchy to go from the derived class to different
6280 /// subobjects of a base class. The result looks something like this:
6281 /// @code
6282 /// struct D -> struct B -> struct A
6283 /// struct D -> struct C -> struct A
6284 /// @endcode
6285 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6286
6287 bool CheckOverridingFunctionAttributes(CXXMethodDecl *New,
6288 const CXXMethodDecl *Old);
6289
6290 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6291 /// covariant, according to C++ [class.virtual]p5.
6292 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6293 const CXXMethodDecl *Old);
6294
6295 // Check that the overriding method has no explicit object parameter.
6296 bool CheckExplicitObjectOverride(CXXMethodDecl *New,
6297 const CXXMethodDecl *Old);
6298
6299 /// Mark the given method pure.
6300 ///
6301 /// \param Method the method to be marked pure.
6302 ///
6303 /// \param InitRange the source range that covers the "0" initializer.
6304 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6305
6306 /// CheckOverrideControl - Check C++11 override control semantics.
6307 void CheckOverrideControl(NamedDecl *D);
6308
6309 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6310 /// not used in the declaration of an overriding method.
6311 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
6312
6313 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6314 /// function overrides a virtual member function marked 'final', according to
6315 /// C++11 [class.virtual]p4.
6316 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6317 const CXXMethodDecl *Old);
6318
6319 enum AbstractDiagSelID {
6320 AbstractNone = -1,
6321 AbstractReturnType,
6322 AbstractParamType,
6323 AbstractVariableType,
6324 AbstractFieldType,
6325 AbstractIvarType,
6326 AbstractSynthesizedIvarType,
6327 AbstractArrayType
6328 };
6329
6330 struct TypeDiagnoser;
6331
6332 bool isAbstractType(SourceLocation Loc, QualType T);
6333 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6334 TypeDiagnoser &Diagnoser);
6335 template <typename... Ts>
6336 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6337 const Ts &...Args) {
6338 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6339 return RequireNonAbstractType(Loc, T, Diagnoser);
6340 }
6341
6342 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6343
6344 //===--------------------------------------------------------------------===//
6345 // C++ Overloaded Operators [C++ 13.5]
6346 //
6347
6348 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6349 /// of this overloaded operator is well-formed. If so, returns false;
6350 /// otherwise, emits appropriate diagnostics and returns true.
6351 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6352
6353 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6354 /// of this literal operator function is well-formed. If so, returns
6355 /// false; otherwise, emits appropriate diagnostics and returns true.
6356 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6357
6358 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6359 /// found in an explicit(bool) specifier.
6360 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
6361
6362 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6363 /// Returns true if the explicit specifier is now resolved.
6364 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
6365
6366 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6367 /// C++ if/switch/while/for statement.
6368 /// e.g: "if (int x = f()) {...}"
6369 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
6370
6371 // Emitting members of dllexported classes is delayed until the class
6372 // (including field initializers) is fully parsed.
6373 SmallVector<CXXRecordDecl *, 4> DelayedDllExportClasses;
6374 SmallVector<CXXMethodDecl *, 4> DelayedDllExportMemberFunctions;
6375
6376 /// Merge the exception specifications of two variable declarations.
6377 ///
6378 /// This is called when there's a redeclaration of a VarDecl. The function
6379 /// checks if the redeclaration might have an exception specification and
6380 /// validates compatibility and merges the specs if necessary.
6381 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
6382
6383 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6384 /// function, once we already know that they have the same
6385 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6386 /// error, false otherwise.
6387 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
6388
6389 /// Helpers for dealing with blocks and functions.
6390 void CheckCXXDefaultArguments(FunctionDecl *FD);
6391
6392 /// CheckExtraCXXDefaultArguments - Check for any extra default
6393 /// arguments in the declarator, which is not a function declaration
6394 /// or definition and therefore is not permitted to have default
6395 /// arguments. This routine should be invoked for every declarator
6396 /// that is not a function declaration or definition.
6397 void CheckExtraCXXDefaultArguments(Declarator &D);
6398
6399 /// Perform semantic analysis for the variable declaration that
6400 /// occurs within a C++ catch clause, returning the newly-created
6401 /// variable.
6402 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
6403 SourceLocation StartLoc,
6404 SourceLocation IdLoc,
6405 const IdentifierInfo *Id);
6406
6407 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6408 /// handler.
6409 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
6410
6411 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
6412
6413 /// Handle a friend tag declaration where the scope specifier was
6414 /// templated.
6415 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6416 unsigned TagSpec, SourceLocation TagLoc,
6417 CXXScopeSpec &SS, IdentifierInfo *Name,
6418 SourceLocation NameLoc,
6419 SourceLocation EllipsisLoc,
6420 const ParsedAttributesView &Attr,
6421 MultiTemplateParamsArg TempParamLists,
6422 TemplateIdAnnotation *TemplateId);
6423
6424 bool CheckDependentFriend(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc,
6425 ArrayRef<TemplateParameterList *> TPLs,
6426 bool IsInstantiation);
6427
6428 bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc,
6429 NestedNameSpecifierLoc NNSLoc);
6430
6431 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
6432 SourceLocation DeclStart, Declarator &D,
6433 Expr *BitfieldWidth,
6434 InClassInitStyle InitStyle,
6435 AccessSpecifier AS,
6436 const ParsedAttr &MSPropertyAttr);
6437
6438 /// Diagnose why the specified class does not have a trivial special member of
6439 /// the given kind.
6440 void DiagnoseNontrivial(const CXXRecordDecl *Record,
6441 CXXSpecialMemberKind CSM);
6442
6443 /// Determine whether a defaulted or deleted special member function is
6444 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6445 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6446 bool SpecialMemberIsTrivial(
6447 CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
6448 TrivialABIHandling TAH = TrivialABIHandling::IgnoreTrivialABI,
6449 bool Diagnose = false);
6450
6451 /// Handle a C++11 empty-declaration and attribute-declaration.
6452 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
6453 SourceLocation SemiLoc);
6454
6455 enum class CheckConstexprKind {
6456 /// Diagnose issues that are non-constant or that are extensions.
6457 Diagnose,
6458 /// Identify whether this function satisfies the formal rules for constexpr
6459 /// functions in the current lanugage mode (with no extensions).
6460 CheckValid
6461 };
6462
6463 // Check whether a function declaration satisfies the requirements of a
6464 // constexpr function definition or a constexpr constructor definition. If so,
6465 // return true. If not, produce appropriate diagnostics (unless asked not to
6466 // by Kind) and return false.
6467 //
6468 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6469 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
6470 CheckConstexprKind Kind);
6471
6472 /// Diagnose methods which overload virtual methods in a base class
6473 /// without overriding any.
6474 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
6475
6476 /// Check if a method overloads virtual methods in a base class without
6477 /// overriding any.
6478 void
6479 FindHiddenVirtualMethods(CXXMethodDecl *MD,
6480 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6481 void
6482 NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6483 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6484
6485 /// ActOnParamDefaultArgument - Check whether the default argument
6486 /// provided for a function parameter is well-formed. If so, attach it
6487 /// to the parameter declaration.
6488 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6489 Expr *defarg);
6490
6491 /// ActOnParamUnparsedDefaultArgument - We've seen a default
6492 /// argument for a function parameter, but we can't parse it yet
6493 /// because we're inside a class definition. Note that this default
6494 /// argument will be parsed later.
6495 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
6496 SourceLocation ArgLoc);
6497
6498 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6499 /// the default argument for the parameter param failed.
6500 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
6501 Expr *DefaultArg);
6502 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6503 SourceLocation EqualLoc);
6504 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6505 SourceLocation EqualLoc);
6506
6507 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6508 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6509 StringLiteral *Message = nullptr);
6510 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
6511
6512 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6513 StringLiteral *DeletedMessage = nullptr);
6514 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
6515 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
6516 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
6517
6518 NamedDecl *
6519 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
6520 MultiTemplateParamsArg TemplateParamLists);
6521 void DiagPlaceholderVariableDefinition(SourceLocation Loc);
6522 bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
6523 RecordDecl *ClassDecl,
6524 const IdentifierInfo *Name);
6525
6526 UnsignedOrNone GetDecompositionElementCount(QualType DecompType,
6527 SourceLocation Loc);
6528 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
6529
6530 /// Stack containing information needed when in C++2a an 'auto' is encountered
6531 /// in a function declaration parameter type specifier in order to invent a
6532 /// corresponding template parameter in the enclosing abbreviated function
6533 /// template. This information is also present in LambdaScopeInfo, stored in
6534 /// the FunctionScopes stack.
6535 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
6536
6537 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6538 std::unique_ptr<CXXFieldCollector> FieldCollector;
6539
6540 typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType;
6541 /// Set containing all declared private fields that are not used.
6542 NamedDeclSetType UnusedPrivateFields;
6543
6544 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 8> RecordDeclSetTy;
6545
6546 /// PureVirtualClassDiagSet - a set of class declarations which we have
6547 /// emitted a list of pure virtual functions. Used to prevent emitting the
6548 /// same list more than once.
6549 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6550
6551 typedef LazyVector<CXXConstructorDecl *,
6552 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
6553 DelegatingCtorDeclsType;
6554
6555 /// All the delegating constructors seen so far in the file, used for
6556 /// cycle detection at the end of the TU.
6557 DelegatingCtorDeclsType DelegatingCtorDecls;
6558
6559 /// The C++ "std" namespace, where the standard library resides.
6560 LazyDeclPtr StdNamespace;
6561
6562 /// The C++ "std::initializer_list" template, which is defined in
6563 /// \<initializer_list>.
6564 ClassTemplateDecl *StdInitializerList;
6565
6566 /// The C++ "std::type_identity" template, which is defined in
6567 /// \<type_traits>.
6568 ClassTemplateDecl *StdTypeIdentity;
6569
6570 // Contains the locations of the beginning of unparsed default
6571 // argument locations.
6572 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6573
6574 /// UndefinedInternals - all the used, undefined objects which require a
6575 /// definition in this translation unit.
6576 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6577
6578 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6579 SpecialMemberDecl;
6580
6581 /// The C++ special members which we are currently in the process of
6582 /// declaring. If this process recursively triggers the declaration of the
6583 /// same special member, we should act as if it is not yet declared.
6584 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
6585
6586 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
6587
6588 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6589
6590 typedef ProcessingContextState ParsingClassState;
6591 ParsingClassState PushParsingClass() {
6592 ParsingClassDepth++;
6593 return DelayedDiagnostics.pushUndelayed();
6594 }
6595 void PopParsingClass(ParsingClassState state) {
6596 ParsingClassDepth--;
6597 DelayedDiagnostics.popUndelayed(state);
6598 }
6599
6600 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
6601 CXXScopeSpec &SS,
6602 ParsedType TemplateTypeTy,
6603 IdentifierInfo *MemberOrBase);
6604
6605private:
6606 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6607 QualType ResultTy,
6608 ArrayRef<QualType> Args);
6609 // Helper for ActOnFields to check for all function pointer members.
6610 bool EntirelyFunctionPointers(const RecordDecl *Record);
6611
6612 // A cache representing if we've fully checked the various comparison category
6613 // types stored in ASTContext. The bit-index corresponds to the integer value
6614 // of a ComparisonCategoryType enumerator.
6615 llvm::SmallBitVector FullyCheckedComparisonCategories;
6616
6617 /// Check if there is a field shadowing.
6618 void CheckShadowInheritedFields(const SourceLocation &Loc,
6619 DeclarationName FieldName,
6620 const CXXRecordDecl *RD,
6621 bool DeclIsField = true);
6622
6623 ///@}
6624
6625 //
6626 //
6627 // -------------------------------------------------------------------------
6628 //
6629 //
6630
6631 /// \name C++ Exception Specifications
6632 /// Implementations are in SemaExceptionSpec.cpp
6633 ///@{
6634
6635public:
6636 /// All the overriding functions seen during a class definition
6637 /// that had their exception spec checks delayed, plus the overridden
6638 /// function.
6639 SmallVector<std::pair<const CXXMethodDecl *, const CXXMethodDecl *>, 2>
6640 DelayedOverridingExceptionSpecChecks;
6641
6642 /// All the function redeclarations seen during a class definition that had
6643 /// their exception spec checks delayed, plus the prior declaration they
6644 /// should be checked against. Except during error recovery, the new decl
6645 /// should always be a friend declaration, as that's the only valid way to
6646 /// redeclare a special member before its class is complete.
6647 SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 2>
6648 DelayedEquivalentExceptionSpecChecks;
6649
6650 /// Determine if we're in a case where we need to (incorrectly) eagerly
6651 /// parse an exception specification to work around a libstdc++ bug.
6652 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6653
6654 /// Check the given noexcept-specifier, convert its expression, and compute
6655 /// the appropriate ExceptionSpecificationType.
6656 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6657 ExceptionSpecificationType &EST);
6658
6659 CanThrowResult canThrow(const Stmt *E);
6660 /// Determine whether the callee of a particular function call can throw.
6661 /// E, D and Loc are all optional.
6662 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6663 SourceLocation Loc = SourceLocation());
6664 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
6665 const FunctionProtoType *FPT);
6666 void UpdateExceptionSpec(FunctionDecl *FD,
6667 const FunctionProtoType::ExceptionSpecInfo &ESI);
6668
6669 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6670 /// exception specification. Incomplete types, or pointers to incomplete types
6671 /// other than void are not allowed.
6672 ///
6673 /// \param[in,out] T The exception type. This will be decayed to a pointer
6674 /// type
6675 /// when the input is an array or a function type.
6676 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
6677
6678 /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6679 /// pointer to member to a function with an exception specification. This
6680 /// means that it is invalid to add another level of indirection.
6681 bool CheckDistantExceptionSpec(QualType T);
6682 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
6683
6684 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6685 /// exception specifications. Exception specifications are equivalent if
6686 /// they allow exactly the same set of exception types. It does not matter how
6687 /// that is achieved. See C++ [except.spec]p2.
6688 bool CheckEquivalentExceptionSpec(const FunctionProtoType *Old,
6689 SourceLocation OldLoc,
6690 const FunctionProtoType *New,
6691 SourceLocation NewLoc);
6692 bool CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
6693 const PartialDiagnostic &NoteID,
6694 const FunctionProtoType *Old,
6695 SourceLocation OldLoc,
6696 const FunctionProtoType *New,
6697 SourceLocation NewLoc);
6698 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6699
6700 /// CheckExceptionSpecSubset - Check whether the second function type's
6701 /// exception specification is a subset (or equivalent) of the first function
6702 /// type. This is used by override and pointer assignment checks.
6703 bool CheckExceptionSpecSubset(
6704 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6705 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6706 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6707 SourceLocation SuperLoc, const FunctionProtoType *Subset,
6708 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6709
6710 /// CheckParamExceptionSpec - Check if the parameter and return types of the
6711 /// two functions have equivalent exception specs. This is part of the
6712 /// assignment and override compatibility check. We do not check the
6713 /// parameters of parameter function pointers recursively, as no sane
6714 /// programmer would even be able to write such a function type.
6715 bool CheckParamExceptionSpec(
6716 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6717 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6718 SourceLocation TargetLoc, const FunctionProtoType *Source,
6719 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6720
6721 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6722
6723 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6724 /// spec is a subset of base spec.
6725 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6726 const CXXMethodDecl *Old);
6727
6728 ///@}
6729
6730 //
6731 //
6732 // -------------------------------------------------------------------------
6733 //
6734 //
6735
6736 /// \name Expressions
6737 /// Implementations are in SemaExpr.cpp
6738 ///@{
6739
6740public:
6741 /// Describes how the expressions currently being parsed are
6742 /// evaluated at run-time, if at all.
6743 enum class ExpressionEvaluationContext {
6744 /// The current expression and its subexpressions occur within an
6745 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6746 /// \c sizeof, where the type of the expression may be significant but
6747 /// no code will be generated to evaluate the value of the expression at
6748 /// run time.
6749 Unevaluated,
6750
6751 /// The current expression occurs within a braced-init-list within
6752 /// an unevaluated operand. This is mostly like a regular unevaluated
6753 /// context, except that we still instantiate constexpr functions that are
6754 /// referenced here so that we can perform narrowing checks correctly.
6755 UnevaluatedList,
6756
6757 /// The current expression occurs within a discarded statement.
6758 /// This behaves largely similarly to an unevaluated operand in preventing
6759 /// definitions from being required, but not in other ways.
6760 DiscardedStatement,
6761
6762 /// The current expression occurs within an unevaluated
6763 /// operand that unconditionally permits abstract references to
6764 /// fields, such as a SIZE operator in MS-style inline assembly.
6765 UnevaluatedAbstract,
6766
6767 /// The current context is "potentially evaluated" in C++11 terms,
6768 /// but the expression is evaluated at compile-time (like the values of
6769 /// cases in a switch statement).
6770 ConstantEvaluated,
6771
6772 /// In addition of being constant evaluated, the current expression
6773 /// occurs in an immediate function context - either a consteval function
6774 /// or a consteval if statement.
6775 ImmediateFunctionContext,
6776
6777 /// The current expression is potentially evaluated at run time,
6778 /// which means that code may be generated to evaluate the value of the
6779 /// expression at run time.
6780 PotentiallyEvaluated,
6781
6782 /// The current expression is potentially evaluated, but any
6783 /// declarations referenced inside that expression are only used if
6784 /// in fact the current expression is used.
6785 ///
6786 /// This value is used when parsing default function arguments, for which
6787 /// we would like to provide diagnostics (e.g., passing non-POD arguments
6788 /// through varargs) but do not want to mark declarations as "referenced"
6789 /// until the default argument is used.
6790 PotentiallyEvaluatedIfUsed
6791 };
6792
6793 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6794 /// to a variable (constant) that may or may not be odr-used in this Expr, and
6795 /// we won't know until all lvalue-to-rvalue and discarded value conversions
6796 /// have been applied to all subexpressions of the enclosing full expression.
6797 /// This is cleared at the end of each full expression.
6798 using MaybeODRUseExprSet = llvm::SmallSetVector<Expr *, 4>;
6799 MaybeODRUseExprSet MaybeODRUseExprs;
6800
6801 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6802
6803 /// Data structure used to record current or nested
6804 /// expression evaluation contexts.
6805 struct ExpressionEvaluationContextRecord {
6806 /// The expression evaluation context.
6807 ExpressionEvaluationContext Context;
6808
6809 /// Whether the enclosing context needed a cleanup.
6810 CleanupInfo ParentCleanup;
6811
6812 /// The number of active cleanup objects when we entered
6813 /// this expression evaluation context.
6814 unsigned NumCleanupObjects;
6815
6816 MaybeODRUseExprSet SavedMaybeODRUseExprs;
6817
6818 /// The lambdas that are present within this context, if it
6819 /// is indeed an unevaluated context.
6820 SmallVector<LambdaExpr *, 2> Lambdas;
6821
6822 /// The declaration that provides context for lambda expressions
6823 /// and block literals if the normal declaration context does not
6824 /// suffice, e.g., in a default function argument.
6825 Decl *ManglingContextDecl;
6826
6827 /// Declaration for initializer if one is currently being
6828 /// parsed. Used when an expression has a possibly unreachable
6829 /// diagnostic to reference the declaration as a whole.
6830 VarDecl *DeclForInitializer = nullptr;
6831
6832 /// If we are processing a decltype type, a set of call expressions
6833 /// for which we have deferred checking the completeness of the return type.
6834 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
6835
6836 /// If we are processing a decltype type, a set of temporary binding
6837 /// expressions for which we have deferred checking the destructor.
6838 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
6839
6840 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
6841
6842 /// Expressions appearing as the LHS of a volatile assignment in this
6843 /// context. We produce a warning for these when popping the context if
6844 /// they are not discarded-value expressions nor unevaluated operands.
6845 SmallVector<Expr *, 2> VolatileAssignmentLHSs;
6846
6847 /// Set of candidates for starting an immediate invocation.
6848 llvm::SmallVector<ImmediateInvocationCandidate, 4>
6849 ImmediateInvocationCandidates;
6850
6851 /// Set of DeclRefExprs referencing a consteval function when used in a
6852 /// context not already known to be immediately invoked.
6853 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
6854
6855 /// P2718R0 - Lifetime extension in range-based for loops.
6856 /// MaterializeTemporaryExprs in for-range-init expressions which need to
6857 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
6858 /// InLifetimeExtendingContext is true.
6859 SmallVector<MaterializeTemporaryExpr *, 8> ForRangeLifetimeExtendTemps;
6860
6861 /// Small set of gathered accesses to potentially misaligned members
6862 /// due to the packed attribute.
6863 SmallVector<MisalignedMember, 4> MisalignedMembers;
6864
6865 /// \brief Describes whether we are in an expression constext which we have
6866 /// to handle differently.
6867 enum ExpressionKind {
6868 EK_Decltype,
6869 EK_TemplateArgument,
6870 EK_AttrArgument,
6871 EK_VariableInit,
6872 EK_Other
6873 } ExprContext;
6874
6875 // A context can be nested in both a discarded statement context and
6876 // an immediate function context, so they need to be tracked independently.
6877 bool InDiscardedStatement;
6878 bool InImmediateFunctionContext;
6879 bool InImmediateEscalatingFunctionContext;
6880
6881 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
6882
6883 // We are in a constant context, but we also allow
6884 // non constant expressions, for example for array bounds (which may be
6885 // VLAs).
6886 bool InConditionallyConstantEvaluateContext = false;
6887
6888 /// Whether we are currently in a context in which all temporaries must be
6889 /// lifetime-extended, even if they're not bound to a reference (for
6890 /// example, in a for-range initializer).
6891 bool InLifetimeExtendingContext = false;
6892
6893 /// Whether evaluating an expression for a switch case label.
6894 bool IsCaseExpr = false;
6895
6896 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
6897 bool RebuildDefaultArgOrDefaultInit = false;
6898
6899 // When evaluating immediate functions in the initializer of a default
6900 // argument or default member initializer, this is the declaration whose
6901 // default initializer is being evaluated and the location of the call
6902 // or constructor definition.
6903 struct InitializationContext {
6904 InitializationContext(SourceLocation Loc, ValueDecl *Decl,
6905 DeclContext *Context)
6906 : Loc(Loc), Decl(Decl), Context(Context) {
6907 assert(Decl && Context && "invalid initialization context");
6908 }
6909
6910 SourceLocation Loc;
6911 ValueDecl *Decl = nullptr;
6912 DeclContext *Context = nullptr;
6913 };
6914 std::optional<InitializationContext> DelayedDefaultInitializationContext;
6915
6916 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
6917 unsigned NumCleanupObjects,
6918 CleanupInfo ParentCleanup,
6919 Decl *ManglingContextDecl,
6920 ExpressionKind ExprContext)
6921 : Context(Context), ParentCleanup(ParentCleanup),
6922 NumCleanupObjects(NumCleanupObjects),
6923 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
6924 InDiscardedStatement(false), InImmediateFunctionContext(false),
6925 InImmediateEscalatingFunctionContext(false) {}
6926
6927 bool isUnevaluated() const {
6928 return Context == ExpressionEvaluationContext::Unevaluated ||
6929 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
6930 Context == ExpressionEvaluationContext::UnevaluatedList;
6931 }
6932
6933 bool isPotentiallyEvaluated() const {
6934 return Context == ExpressionEvaluationContext::PotentiallyEvaluated ||
6935 Context ==
6936 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed ||
6937 Context == ExpressionEvaluationContext::ConstantEvaluated;
6938 }
6939
6940 bool isConstantEvaluated() const {
6941 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
6942 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
6943 }
6944
6945 bool isImmediateFunctionContext() const {
6946 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
6947 (Context == ExpressionEvaluationContext::DiscardedStatement &&
6948 InImmediateFunctionContext) ||
6949 // C++23 [expr.const]p14:
6950 // An expression or conversion is in an immediate function
6951 // context if it is potentially evaluated and either:
6952 // * its innermost enclosing non-block scope is a function
6953 // parameter scope of an immediate function, or
6954 // * its enclosing statement is enclosed by the compound-
6955 // statement of a consteval if statement.
6956 (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
6957 InImmediateFunctionContext);
6958 }
6959
6960 bool isDiscardedStatementContext() const {
6961 return Context == ExpressionEvaluationContext::DiscardedStatement ||
6962 ((Context ==
6963 ExpressionEvaluationContext::ImmediateFunctionContext ||
6964 isPotentiallyEvaluated()) &&
6965 InDiscardedStatement);
6966 }
6967 };
6968
6969 const ExpressionEvaluationContextRecord &currentEvaluationContext() const {
6970 assert(!ExprEvalContexts.empty() &&
6971 "Must be in an expression evaluation context");
6972 return ExprEvalContexts.back();
6973 }
6974
6975 ExpressionEvaluationContextRecord &currentEvaluationContext() {
6976 assert(!ExprEvalContexts.empty() &&
6977 "Must be in an expression evaluation context");
6978 return ExprEvalContexts.back();
6979 }
6980
6981 ExpressionEvaluationContextRecord &parentEvaluationContext() {
6982 assert(ExprEvalContexts.size() >= 2 &&
6983 "Must be in an expression evaluation context");
6984 return ExprEvalContexts[ExprEvalContexts.size() - 2];
6985 }
6986
6987 const ExpressionEvaluationContextRecord &parentEvaluationContext() const {
6988 return const_cast<Sema *>(this)->parentEvaluationContext();
6989 }
6990
6991 bool isAttrContext() const {
6992 return ExprEvalContexts.back().ExprContext ==
6993 ExpressionEvaluationContextRecord::ExpressionKind::EK_AttrArgument;
6994 }
6995
6996 /// Increment when we find a reference; decrement when we find an ignored
6997 /// assignment. Ultimately the value is 0 if every reference is an ignored
6998 /// assignment.
6999 ///
7000 /// Uses canonical VarDecl as key so in-class decls and out-of-class defs of
7001 /// static data members get tracked as a single entry.
7002 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
7003
7004 /// Used to control the generation of ExprWithCleanups.
7005 CleanupInfo Cleanup;
7006
7007 /// ExprCleanupObjects - This is the stack of objects requiring
7008 /// cleanup that are created by the current full expression.
7009 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
7010
7011 /// Determine whether the use of this declaration is valid, without
7012 /// emitting diagnostics.
7013 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
7014 // A version of DiagnoseUseOfDecl that should be used if overload resolution
7015 // has been used to find this declaration, which means we don't have to bother
7016 // checking the trailing requires clause.
7017 bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) {
7018 return DiagnoseUseOfDecl(
7019 D, Locs: Loc, /*UnknownObjCClass=*/UnknownObjCClass: nullptr, /*ObjCPropertyAccess=*/ObjCPropertyAccess: false,
7020 /*AvoidPartialAvailabilityChecks=*/AvoidPartialAvailabilityChecks: false, /*ClassReceiver=*/ClassReceiver: nullptr,
7021 /*SkipTrailingRequiresClause=*/SkipTrailingRequiresClause: true);
7022 }
7023
7024 /// Determine whether the use of this declaration is valid, and
7025 /// emit any corresponding diagnostics.
7026 ///
7027 /// This routine diagnoses various problems with referencing
7028 /// declarations that can occur when using a declaration. For example,
7029 /// it might warn if a deprecated or unavailable declaration is being
7030 /// used, or produce an error (and return true) if a C++0x deleted
7031 /// function is being used.
7032 ///
7033 /// \returns true if there was an error (this declaration cannot be
7034 /// referenced), false otherwise.
7035 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
7036 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
7037 bool ObjCPropertyAccess = false,
7038 bool AvoidPartialAvailabilityChecks = false,
7039 ObjCInterfaceDecl *ClassReceiver = nullptr,
7040 bool SkipTrailingRequiresClause = false);
7041
7042 /// Emit a note explaining that this function is deleted.
7043 void NoteDeletedFunction(FunctionDecl *FD);
7044
7045 /// DiagnoseSentinelCalls - This routine checks whether a call or
7046 /// message-send is to a declaration with the sentinel attribute, and
7047 /// if so, it checks that the requirements of the sentinel are
7048 /// satisfied.
7049 void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
7050 ArrayRef<Expr *> Args);
7051
7052 void PushExpressionEvaluationContext(
7053 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
7054 ExpressionEvaluationContextRecord::ExpressionKind Type =
7055 ExpressionEvaluationContextRecord::EK_Other);
7056
7057 void PushExpressionEvaluationContextForFunction(
7058 ExpressionEvaluationContext NewContext, FunctionDecl *FD);
7059
7060 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
7061 void PushExpressionEvaluationContext(
7062 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
7063 ExpressionEvaluationContextRecord::ExpressionKind Type =
7064 ExpressionEvaluationContextRecord::EK_Other);
7065 void PopExpressionEvaluationContext();
7066
7067 void DiscardCleanupsInEvaluationContext();
7068
7069 ExprResult TransformToPotentiallyEvaluated(Expr *E);
7070 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
7071 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
7072
7073 /// Check whether E, which is either a discarded-value expression or an
7074 /// unevaluated operand, is a simple-assignment to a volatlie-qualified
7075 /// lvalue, and if so, remove it from the list of volatile-qualified
7076 /// assignments that we are going to warn are deprecated.
7077 void CheckUnusedVolatileAssignment(Expr *E);
7078
7079 ExprResult ActOnConstantExpression(ExprResult Res);
7080
7081 // Functions for marking a declaration referenced. These functions also
7082 // contain the relevant logic for marking if a reference to a function or
7083 // variable is an odr-use (in the C++11 sense). There are separate variants
7084 // for expressions referring to a decl; these exist because odr-use marking
7085 // needs to be delayed for some constant variables when we build one of the
7086 // named expressions.
7087 //
7088 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
7089 // should usually be true. This only needs to be set to false if the lack of
7090 // odr-use cannot be determined from the current context (for instance,
7091 // because the name denotes a virtual function and was written without an
7092 // explicit nested-name-specifier).
7093 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
7094
7095 /// Mark a function referenced, and check whether it is odr-used
7096 /// (C++ [basic.def.odr]p2, C99 6.9p3)
7097 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
7098 bool MightBeOdrUse = true);
7099
7100 /// Mark a variable referenced, and check whether it is odr-used
7101 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
7102 /// used directly for normal expressions referring to VarDecl.
7103 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
7104
7105 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7106 ///
7107 /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7108 /// be handled with care if the DeclRefExpr is not newly-created.
7109 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7110
7111 /// Perform reference-marking and odr-use handling for a MemberExpr.
7112 void MarkMemberReferenced(MemberExpr *E);
7113
7114 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7115 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
7116 void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc,
7117 unsigned CapturingScopeIndex);
7118
7119 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
7120 void CleanupVarDeclMarking();
7121
7122 /// Try to capture the given variable.
7123 ///
7124 /// \param Var The variable to capture.
7125 ///
7126 /// \param Loc The location at which the capture occurs.
7127 ///
7128 /// \param Kind The kind of capture, which may be implicit (for either a
7129 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7130 ///
7131 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7132 /// an explicit lambda capture.
7133 ///
7134 /// \param BuildAndDiagnose Whether we are actually supposed to add the
7135 /// captures or diagnose errors. If false, this routine merely check whether
7136 /// the capture can occur without performing the capture itself or complaining
7137 /// if the variable cannot be captured.
7138 ///
7139 /// \param CaptureType Will be set to the type of the field used to capture
7140 /// this variable in the innermost block or lambda. Only valid when the
7141 /// variable can be captured.
7142 ///
7143 /// \param DeclRefType Will be set to the type of a reference to the capture
7144 /// from within the current scope. Only valid when the variable can be
7145 /// captured.
7146 ///
7147 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7148 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7149 /// This is useful when enclosing lambdas must speculatively capture
7150 /// variables that may or may not be used in certain specializations of
7151 /// a nested generic lambda.
7152 ///
7153 /// \returns true if an error occurred (i.e., the variable cannot be
7154 /// captured) and false if the capture succeeded.
7155 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7156 TryCaptureKind Kind, SourceLocation EllipsisLoc,
7157 bool BuildAndDiagnose, QualType &CaptureType,
7158 QualType &DeclRefType,
7159 const unsigned *const FunctionScopeIndexToStopAt);
7160
7161 /// Try to capture the given variable.
7162 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7163 TryCaptureKind Kind = TryCaptureKind::Implicit,
7164 SourceLocation EllipsisLoc = SourceLocation());
7165
7166 /// Checks if the variable must be captured.
7167 bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc);
7168
7169 /// Given a variable, determine the type that a reference to that
7170 /// variable will have in the given scope.
7171 QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc);
7172
7173 /// Mark all of the declarations referenced within a particular AST node as
7174 /// referenced. Used when template instantiation instantiates a non-dependent
7175 /// type -- entities referenced by the type are now referenced.
7176 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
7177
7178 /// Mark any declarations that appear within this expression or any
7179 /// potentially-evaluated subexpressions as "referenced".
7180 ///
7181 /// \param SkipLocalVariables If true, don't mark local variables as
7182 /// 'referenced'.
7183 /// \param StopAt Subexpressions that we shouldn't recurse into.
7184 void MarkDeclarationsReferencedInExpr(Expr *E,
7185 bool SkipLocalVariables = false,
7186 ArrayRef<const Expr *> StopAt = {});
7187
7188 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7189 /// conversion.
7190 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7191
7192 /// Conditionally issue a diagnostic based on the statements's reachability
7193 /// analysis.
7194 ///
7195 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7196 /// the function body is parsed, and then do a basic reachability analysis to
7197 /// determine if the statement is reachable. If it is unreachable, the
7198 /// diagnostic will not be emitted.
7199 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7200 const PartialDiagnostic &PD);
7201
7202 /// Conditionally issue a diagnostic based on the current
7203 /// evaluation context.
7204 ///
7205 /// \param Statement If Statement is non-null, delay reporting the
7206 /// diagnostic until the function body is parsed, and then do a basic
7207 /// reachability analysis to determine if the statement is reachable.
7208 /// If it is unreachable, the diagnostic will not be emitted.
7209 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7210 const PartialDiagnostic &PD);
7211 /// Similar, but diagnostic is only produced if all the specified statements
7212 /// are reachable.
7213 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7214 const PartialDiagnostic &PD);
7215
7216 // Primary Expressions.
7217 SourceRange getExprRange(Expr *E) const;
7218
7219 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7220 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7221 bool HasTrailingLParen, bool IsAddressOfOperand,
7222 CorrectionCandidateCallback *CCC = nullptr,
7223 bool IsInlineAsmIdentifier = false);
7224
7225 /// Decomposes the given name into a DeclarationNameInfo, its location, and
7226 /// possibly a list of template arguments.
7227 ///
7228 /// If this produces template arguments, it is permitted to call
7229 /// DecomposeTemplateName.
7230 ///
7231 /// This actually loses a lot of source location information for
7232 /// non-standard name kinds; we should consider preserving that in
7233 /// some way.
7234 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7235 TemplateArgumentListInfo &Buffer,
7236 DeclarationNameInfo &NameInfo,
7237 const TemplateArgumentListInfo *&TemplateArgs);
7238
7239 /// Diagnose a lookup that found results in an enclosing class during error
7240 /// recovery. This usually indicates that the results were found in a
7241 /// dependent base class that could not be searched as part of a template
7242 /// definition. Always issues a diagnostic (though this may be only a warning
7243 /// in MS compatibility mode).
7244 ///
7245 /// Return \c true if the error is unrecoverable, or \c false if the caller
7246 /// should attempt to recover using these lookup results.
7247 bool DiagnoseDependentMemberLookup(const LookupResult &R);
7248
7249 /// Diagnose an empty lookup.
7250 ///
7251 /// \return false if new lookup candidates were found
7252 bool
7253 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7254 CorrectionCandidateCallback &CCC,
7255 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7256 ArrayRef<Expr *> Args = {},
7257 DeclContext *LookupCtx = nullptr);
7258
7259 /// If \p D cannot be odr-used in the current expression evaluation context,
7260 /// return a reason explaining why. Otherwise, return NOUR_None.
7261 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
7262
7263 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7264 SourceLocation Loc,
7265 const CXXScopeSpec *SS = nullptr);
7266 DeclRefExpr *
7267 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7268 const DeclarationNameInfo &NameInfo,
7269 const CXXScopeSpec *SS = nullptr,
7270 NamedDecl *FoundD = nullptr,
7271 SourceLocation TemplateKWLoc = SourceLocation(),
7272 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7273
7274 /// BuildDeclRefExpr - Build an expression that references a
7275 /// declaration that does not require a closure capture.
7276 DeclRefExpr *
7277 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7278 const DeclarationNameInfo &NameInfo,
7279 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7280 SourceLocation TemplateKWLoc = SourceLocation(),
7281 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7282
7283 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7284 bool HasTrailingLParen);
7285
7286 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7287 /// declaration name, generally during template instantiation.
7288 /// There's a large number of things which don't need to be done along
7289 /// this path.
7290 ExprResult BuildQualifiedDeclarationNameExpr(
7291 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7292 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7293
7294 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7295 bool NeedsADL,
7296 bool AcceptInvalidDecl = false);
7297
7298 /// Complete semantic analysis for a reference to the given declaration.
7299 ExprResult BuildDeclarationNameExpr(
7300 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7301 NamedDecl *FoundD = nullptr,
7302 const TemplateArgumentListInfo *TemplateArgs = nullptr,
7303 bool AcceptInvalidDecl = false);
7304
7305 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7306 // where Tokens representing function local predefined macros (such as
7307 // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7308 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7309
7310 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7311 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7312 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7313
7314 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7315
7316 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7317 ExprResult ActOnCharacterConstant(const Token &Tok,
7318 Scope *UDLScope = nullptr);
7319 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7320 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7321 MultiExprArg Val);
7322 ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7323 unsigned NumUserSpecifiedExprs,
7324 SourceLocation InitLoc,
7325 SourceLocation LParenLoc,
7326 SourceLocation RParenLoc);
7327
7328 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7329 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle
7330 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7331 /// from multiple tokens. However, the common case is that StringToks points
7332 /// to one string.
7333 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7334 Scope *UDLScope = nullptr);
7335
7336 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7337
7338 /// ControllingExprOrType is either an opaque pointer coming out of a
7339 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7340 /// into two so we don't take a void *, but that's awkward because one of
7341 /// the operands is either a ParsedType or an Expr *, which doesn't lend
7342 /// itself to generic code very well.
7343 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7344 SourceLocation DefaultLoc,
7345 SourceLocation RParenLoc,
7346 bool PredicateIsExpr,
7347 void *ControllingExprOrType,
7348 ArrayRef<ParsedType> ArgTypes,
7349 ArrayRef<Expr *> ArgExprs);
7350 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7351 /// it'd be better to split this interface into two so we don't take a
7352 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7353 /// isn't a trivial change.
7354 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7355 SourceLocation DefaultLoc,
7356 SourceLocation RParenLoc,
7357 bool PredicateIsExpr,
7358 void *ControllingExprOrType,
7359 ArrayRef<TypeSourceInfo *> Types,
7360 ArrayRef<Expr *> Exprs);
7361
7362 // Binary/Unary Operators. 'Tok' is the token for the operator.
7363 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7364 Expr *InputExpr, bool IsAfterAmp = false);
7365 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7366 Expr *Input, bool IsAfterAmp = false);
7367
7368 /// Unary Operators. 'Tok' is the token for the operator.
7369 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7370 Expr *Input, bool IsAfterAmp = false);
7371
7372 /// Determine whether the given expression is a qualified member
7373 /// access expression, of a form that could be turned into a pointer to member
7374 /// with the address-of operator.
7375 bool isQualifiedMemberAccess(Expr *E);
7376 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7377 const Expr *Op,
7378 const CXXMethodDecl *MD);
7379
7380 /// CheckAddressOfOperand - The operand of & must be either a function
7381 /// designator or an lvalue designating an object. If it is an lvalue, the
7382 /// object cannot be declared with storage class register or be a bit field.
7383 /// Note: The usual conversions are *not* applied to the operand of the &
7384 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7385 /// In C++, the operand might be an overloaded function name, in which case
7386 /// we allow the '&' but retain the overloaded-function type.
7387 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7388
7389 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7390 /// _Alignas(type-name) .
7391 /// [dcl.align] An alignment-specifier of the form
7392 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7393 ///
7394 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7395 /// _Alignas(_Alignof(type-name)).
7396 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7397 SourceLocation OpLoc, SourceRange R);
7398 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7399 SourceLocation OpLoc, SourceRange R);
7400
7401 /// Build a sizeof or alignof expression given a type operand.
7402 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7403 SourceLocation OpLoc,
7404 UnaryExprOrTypeTrait ExprKind,
7405 SourceRange R);
7406
7407 /// Build a sizeof or alignof expression given an expression
7408 /// operand.
7409 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7410 UnaryExprOrTypeTrait ExprKind);
7411
7412 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7413 /// expr and the same for @c alignof and @c __alignof
7414 /// Note that the ArgRange is invalid if isType is false.
7415 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7416 UnaryExprOrTypeTrait ExprKind,
7417 bool IsType, void *TyOrEx,
7418 SourceRange ArgRange);
7419
7420 /// Check for operands with placeholder types and complain if found.
7421 /// Returns ExprError() if there was an error and no recovery was possible.
7422 ExprResult CheckPlaceholderExpr(Expr *E);
7423 bool CheckVecStepExpr(Expr *E);
7424
7425 /// Check the constraints on expression operands to unary type expression
7426 /// and type traits.
7427 ///
7428 /// Completes any types necessary and validates the constraints on the operand
7429 /// expression. The logic mostly mirrors the type-based overload, but may
7430 /// modify the expression as it completes the type for that expression through
7431 /// template instantiation, etc.
7432 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
7433
7434 /// Check the constraints on operands to unary expression and type
7435 /// traits.
7436 ///
7437 /// This will complete any types necessary, and validate the various
7438 /// constraints on those operands.
7439 ///
7440 /// The UsualUnaryConversions() function is *not* called by this routine.
7441 /// C99 6.3.2.1p[2-4] all state:
7442 /// Except when it is the operand of the sizeof operator ...
7443 ///
7444 /// C++ [expr.sizeof]p4
7445 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7446 /// standard conversions are not applied to the operand of sizeof.
7447 ///
7448 /// This policy is followed for all of the unary trait expressions.
7449 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7450 SourceRange ExprRange,
7451 UnaryExprOrTypeTrait ExprKind,
7452 StringRef KWName);
7453
7454 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7455 tok::TokenKind Kind, Expr *Input);
7456
7457 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7458 MultiExprArg ArgExprs,
7459 SourceLocation RLoc);
7460 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7461 Expr *Idx, SourceLocation RLoc);
7462
7463 ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx,
7464 SourceLocation RBLoc);
7465
7466 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7467 Expr *ColumnIdx,
7468 SourceLocation RBLoc);
7469
7470 /// ConvertArgumentsForCall - Converts the arguments specified in
7471 /// Args/NumArgs to the parameter types of the function FDecl with
7472 /// function prototype Proto. Call is the call expression itself, and
7473 /// Fn is the function expression. For a C++ member function, this
7474 /// routine does not attempt to convert the object argument. Returns
7475 /// true if the call is ill-formed.
7476 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7477 const FunctionProtoType *Proto,
7478 ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7479 bool ExecConfig = false);
7480
7481 /// CheckStaticArrayArgument - If the given argument corresponds to a static
7482 /// array parameter, check that it is non-null, and that if it is formed by
7483 /// array-to-pointer decay, the underlying array is sufficiently large.
7484 ///
7485 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7486 /// the array type derivation, then for each call to the function, the value
7487 /// of the corresponding actual argument shall provide access to the first
7488 /// element of an array with at least as many elements as specified by the
7489 /// size expression.
7490 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7491 const Expr *ArgExpr);
7492
7493 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7494 /// This provides the location of the left/right parens and a list of comma
7495 /// locations.
7496 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7497 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7498 Expr *ExecConfig = nullptr);
7499
7500 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7501 /// This provides the location of the left/right parens and a list of comma
7502 /// locations.
7503 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7504 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7505 Expr *ExecConfig = nullptr,
7506 bool IsExecConfig = false,
7507 bool AllowRecovery = false);
7508
7509 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7510 // with the specified CallArgs
7511 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7512 MultiExprArg CallArgs);
7513
7514 using ADLCallKind = CallExpr::ADLCallKind;
7515
7516 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7517 /// i.e. an expression not of \p OverloadTy. The expression should
7518 /// unary-convert to an expression of function-pointer or
7519 /// block-pointer type.
7520 ///
7521 /// \param NDecl the declaration being called, if available
7522 ExprResult
7523 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7524 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7525 Expr *Config = nullptr, bool IsExecConfig = false,
7526 ADLCallKind UsesADL = ADLCallKind::NotADL);
7527
7528 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D,
7529 ParsedType &Ty, SourceLocation RParenLoc,
7530 Expr *CastExpr);
7531
7532 /// Prepares for a scalar cast, performing all the necessary stages
7533 /// except the final cast and returning the kind required.
7534 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
7535
7536 /// Build an altivec or OpenCL literal.
7537 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
7538 SourceLocation RParenLoc, Expr *E,
7539 TypeSourceInfo *TInfo);
7540
7541 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7542 /// the ParenListExpr into a sequence of comma binary operators.
7543 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
7544
7545 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7546 SourceLocation RParenLoc, Expr *InitExpr);
7547
7548 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
7549 TypeSourceInfo *TInfo,
7550 SourceLocation RParenLoc,
7551 Expr *LiteralExpr);
7552
7553 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7554 SourceLocation RBraceLoc);
7555
7556 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7557 SourceLocation RBraceLoc, bool IsExplicit);
7558
7559 /// Binary Operators. 'Tok' is the token for the operator.
7560 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind,
7561 Expr *LHSExpr, Expr *RHSExpr);
7562 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7563 Expr *LHSExpr, Expr *RHSExpr,
7564 bool ForFoldExpression = false);
7565
7566 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7567 /// operator @p Opc at location @c TokLoc. This routine only supports
7568 /// built-in operations; ActOnBinOp handles overloaded operators.
7569 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
7570 Expr *LHSExpr, Expr *RHSExpr,
7571 bool ForFoldExpression = false);
7572 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7573 UnresolvedSetImpl &Functions);
7574
7575 /// Look for instances where it is likely the comma operator is confused with
7576 /// another operator. There is an explicit list of acceptable expressions for
7577 /// the left hand side of the comma operator, otherwise emit a warning.
7578 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7579
7580 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7581 /// in the case of a the GNU conditional expr extension.
7582 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
7583 SourceLocation ColonLoc, Expr *CondExpr,
7584 Expr *LHSExpr, Expr *RHSExpr);
7585
7586 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7587 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
7588 LabelDecl *TheDecl);
7589
7590 void ActOnStartStmtExpr();
7591 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7592 SourceLocation RPLoc);
7593 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
7594 SourceLocation RPLoc, unsigned TemplateDepth);
7595 // Handle the final expression in a statement expression.
7596 ExprResult ActOnStmtExprResult(ExprResult E);
7597 void ActOnStmtExprError();
7598
7599 /// __builtin_offsetof(type, a.b[123][456].c)
7600 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
7601 TypeSourceInfo *TInfo,
7602 const Designation &Desig,
7603 SourceLocation RParenLoc);
7604 ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
7605 SourceLocation TypeLoc,
7606 ParsedType ParsedArgTy,
7607 const Designation &Desig,
7608 SourceLocation RParenLoc);
7609
7610 // __builtin_choose_expr(constExpr, expr1, expr2)
7611 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7612 Expr *LHSExpr, Expr *RHSExpr,
7613 SourceLocation RPLoc);
7614
7615 // __builtin_va_arg(expr, type)
7616 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
7617 SourceLocation RPLoc);
7618 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
7619 TypeSourceInfo *TInfo, SourceLocation RPLoc);
7620
7621 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7622 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7623 ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind,
7624 SourceLocation BuiltinLoc,
7625 SourceLocation RPLoc);
7626
7627 // #embed
7628 ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
7629 StringLiteral *BinaryData, StringRef FileName);
7630
7631 // Build a potentially resolved SourceLocExpr.
7632 ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
7633 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7634 DeclContext *ParentContext);
7635
7636 // __null
7637 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
7638
7639 bool CheckCaseExpression(Expr *E);
7640
7641 //===------------------------- "Block" Extension ------------------------===//
7642
7643 /// ActOnBlockStart - This callback is invoked when a block literal is
7644 /// started.
7645 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7646
7647 /// ActOnBlockArguments - This callback allows processing of block arguments.
7648 /// If there are no arguments, this is still invoked.
7649 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7650 Scope *CurScope);
7651
7652 /// ActOnBlockError - If there is an error parsing a block, this callback
7653 /// is invoked to pop the information about the block from the action impl.
7654 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7655
7656 /// ActOnBlockStmtExpr - This is called when the body of a block statement
7657 /// literal was successfully completed. ^(int x){...}
7658 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
7659 Scope *CurScope);
7660
7661 //===---------------------------- Clang Extensions ----------------------===//
7662
7663 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7664 /// provided arguments.
7665 ///
7666 /// __builtin_convertvector( value, dst type )
7667 ///
7668 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7669 SourceLocation BuiltinLoc,
7670 SourceLocation RParenLoc);
7671
7672 //===---------------------------- OpenCL Features -----------------------===//
7673
7674 /// Parse a __builtin_astype expression.
7675 ///
7676 /// __builtin_astype( value, dst type )
7677 ///
7678 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7679 SourceLocation BuiltinLoc,
7680 SourceLocation RParenLoc);
7681
7682 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7683 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
7684 SourceLocation BuiltinLoc,
7685 SourceLocation RParenLoc);
7686
7687 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7688 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
7689 ArrayRef<Expr *> SubExprs,
7690 QualType T = QualType());
7691
7692 /// Cast a base object to a member's actual type.
7693 ///
7694 /// There are two relevant checks:
7695 ///
7696 /// C++ [class.access.base]p7:
7697 ///
7698 /// If a class member access operator [...] is used to access a non-static
7699 /// data member or non-static member function, the reference is ill-formed
7700 /// if the left operand [...] cannot be implicitly converted to a pointer to
7701 /// the naming class of the right operand.
7702 ///
7703 /// C++ [expr.ref]p7:
7704 ///
7705 /// If E2 is a non-static data member or a non-static member function, the
7706 /// program is ill-formed if the class of which E2 is directly a member is
7707 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7708 ///
7709 /// Note that the latter check does not consider access; the access of the
7710 /// "real" base class is checked as appropriate when checking the access of
7711 /// the member name.
7712 ExprResult PerformObjectMemberConversion(Expr *From,
7713 NestedNameSpecifier Qualifier,
7714 NamedDecl *FoundDecl,
7715 NamedDecl *Member);
7716
7717 /// CheckCallReturnType - Checks that a call expression's return type is
7718 /// complete. Returns true on failure. The location passed in is the location
7719 /// that best represents the call.
7720 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7721 CallExpr *CE, FunctionDecl *FD);
7722
7723 /// Emit a warning for all pending noderef expressions that we recorded.
7724 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
7725
7726private:
7727 /// Shared logic for building default member initializer which used in a
7728 /// constructor or an aggregate initialization.
7729 ///
7730 ///
7731 /// The caller enters that evaluation context and decides whether the result
7732 /// is finished as a full-expression. \p NestedDefaultChecking and
7733 /// \p NeedRebuild have to be sampled before entering it.
7734 ExprResult BuildCXXDefaultInitInternal(SourceLocation Loc, FieldDecl *Field,
7735 const InitializedEntity &Entity,
7736 bool NestedDefaultChecking,
7737 bool NeedRebuild);
7738
7739public:
7740 ExprResult BuildCXXCtorDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
7741 ExprResult
7742 BuildCXXAggregateDefaultInitExpr(SourceLocation Loc, FieldDecl *Field,
7743 const InitializedEntity &MemberEntity);
7744
7745 /// Instantiate or parse a C++ default argument expression as necessary.
7746 /// Return true on error.
7747 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7748 ParmVarDecl *Param, Expr *Init = nullptr,
7749 bool SkipImmediateInvocations = true);
7750
7751 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7752 /// the default expr if needed.
7753 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7754 ParmVarDecl *Param, Expr *Init = nullptr);
7755
7756 /// Wrap the expression in a ConstantExpr if it is a potential immediate
7757 /// invocation.
7758 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
7759
7760 void MarkExpressionAsImmediateEscalating(Expr *E);
7761
7762 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7763 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7764
7765 /// Abstract base class used for diagnosing integer constant
7766 /// expression violations.
7767 class VerifyICEDiagnoser {
7768 public:
7769 bool Suppress;
7770
7771 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) {}
7772
7773 virtual SemaDiagnosticBuilder
7774 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7775 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7776 SourceLocation Loc) = 0;
7777 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
7778 virtual ~VerifyICEDiagnoser() {}
7779 };
7780
7781 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7782 /// and reports the appropriate diagnostics. Returns false on success.
7783 /// Can optionally return the value of the expression.
7784 ExprResult
7785 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7786 VerifyICEDiagnoser &Diagnoser,
7787 AllowFoldKind CanFold = AllowFoldKind::No);
7788 ExprResult
7789 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7790 unsigned DiagID,
7791 AllowFoldKind CanFold = AllowFoldKind::No);
7792 ExprResult
7793 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7794 AllowFoldKind CanFold = AllowFoldKind::No);
7795 ExprResult
7796 VerifyIntegerConstantExpression(Expr *E,
7797 AllowFoldKind CanFold = AllowFoldKind::No) {
7798 return VerifyIntegerConstantExpression(E, Result: nullptr, CanFold);
7799 }
7800
7801 /// DiagnoseAssignmentAsCondition - Given that an expression is
7802 /// being used as a boolean condition, warn if it's an assignment.
7803 void DiagnoseAssignmentAsCondition(Expr *E);
7804
7805 /// Redundant parentheses over an equality comparison can indicate
7806 /// that the user intended an assignment used as condition.
7807 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7808
7809 class FullExprArg {
7810 public:
7811 FullExprArg() : E(nullptr) {}
7812 FullExprArg(Sema &actions) : E(nullptr) {}
7813
7814 ExprResult release() { return E; }
7815
7816 Expr *get() const { return E; }
7817
7818 Expr *operator->() { return E; }
7819
7820 private:
7821 // FIXME: No need to make the entire Sema class a friend when it's just
7822 // Sema::MakeFullExpr that needs access to the constructor below.
7823 friend class Sema;
7824
7825 explicit FullExprArg(Expr *expr) : E(expr) {}
7826
7827 Expr *E;
7828 };
7829
7830 FullExprArg MakeFullExpr(Expr *Arg) {
7831 return MakeFullExpr(Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation());
7832 }
7833 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
7834 return FullExprArg(
7835 ActOnFinishFullExpr(Expr: Arg, CC, /*DiscardedValue*/ DiscardedValue: false).get());
7836 }
7837 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
7838 ExprResult FE =
7839 ActOnFinishFullExpr(Expr: Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation(),
7840 /*DiscardedValue*/ DiscardedValue: true);
7841 return FullExprArg(FE.get());
7842 }
7843
7844 class ConditionResult {
7845 Decl *ConditionVar;
7846 ExprResult Condition;
7847 bool Invalid;
7848 std::optional<bool> KnownValue;
7849
7850 friend class Sema;
7851 ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
7852 bool IsConstexpr)
7853 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
7854 if (IsConstexpr && Condition.get()) {
7855 if (std::optional<llvm::APSInt> Val =
7856 Condition.get()->getIntegerConstantExpr(Ctx: S.Context)) {
7857 KnownValue = !!(*Val);
7858 }
7859 }
7860 }
7861 explicit ConditionResult(bool Invalid)
7862 : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
7863 KnownValue(std::nullopt) {}
7864
7865 public:
7866 ConditionResult() : ConditionResult(false) {}
7867 bool isInvalid() const { return Invalid; }
7868 std::pair<VarDecl *, Expr *> get() const {
7869 return std::make_pair(x: cast_or_null<VarDecl>(Val: ConditionVar),
7870 y: Condition.get());
7871 }
7872 std::optional<bool> getKnownValue() const { return KnownValue; }
7873 };
7874 static ConditionResult ConditionError() { return ConditionResult(true); }
7875
7876 /// CheckBooleanCondition - Diagnose problems involving the use of
7877 /// the given expression as a boolean condition (e.g. in an if
7878 /// statement). Also performs the standard function and array
7879 /// decays, possibly changing the input variable.
7880 ///
7881 /// \param Loc - A location associated with the condition, e.g. the
7882 /// 'if' keyword.
7883 /// \return true iff there were any errors
7884 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
7885 bool IsConstexpr = false);
7886
7887 enum class ConditionKind {
7888 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
7889 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
7890 Switch ///< An integral condition for a 'switch' statement.
7891 };
7892
7893 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
7894 ConditionKind CK, bool MissingOK = false);
7895
7896 QualType CheckConditionalOperands( // C99 6.5.15
7897 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
7898 ExprObjectKind &OK, SourceLocation QuestionLoc);
7899
7900 /// Emit a specialized diagnostic when one expression is a null pointer
7901 /// constant and the other is not a pointer. Returns true if a diagnostic is
7902 /// emitted.
7903 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7904 SourceLocation QuestionLoc);
7905
7906 /// type checking for vector binary operators.
7907 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7908 SourceLocation Loc, bool IsCompAssign,
7909 bool AllowBothBool, bool AllowBoolConversion,
7910 bool AllowBoolOperation, bool ReportInvalid);
7911
7912 /// Return a signed ext_vector_type that is of identical size and number of
7913 /// elements. For floating point vectors, return an integer type of identical
7914 /// size and number of elements. In the non ext_vector_type case, search from
7915 /// the largest type to the smallest type to avoid cases where long long ==
7916 /// long, where long gets picked over long long.
7917 QualType GetSignedVectorType(QualType V);
7918 QualType GetSignedSizelessVectorType(QualType V);
7919
7920 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7921 /// operates on extended vector types. Instead of producing an IntTy result,
7922 /// like a scalar comparison, a vector comparison produces a vector of integer
7923 /// types.
7924 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7925 SourceLocation Loc,
7926 BinaryOperatorKind Opc);
7927 QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7928 SourceLocation Loc,
7929 BinaryOperatorKind Opc);
7930 QualType CheckMatrixCompareOperands(ExprResult &LHS, ExprResult &RHS,
7931 SourceLocation Loc,
7932 BinaryOperatorKind Opc);
7933 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7934 SourceLocation Loc,
7935 BinaryOperatorKind Opc);
7936 QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7937 SourceLocation Loc,
7938 BinaryOperatorKind Opc);
7939 // type checking for sizeless vector binary operators.
7940 QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
7941 SourceLocation Loc, bool IsCompAssign,
7942 ArithConvKind OperationKind);
7943
7944 /// Type checking for matrix binary operators.
7945 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
7946 SourceLocation Loc,
7947 bool IsCompAssign);
7948 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
7949 SourceLocation Loc, bool IsCompAssign);
7950
7951 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
7952 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
7953 /// VLST) allowed?
7954 ///
7955 /// This will also return false if the two given types do not make sense from
7956 /// the perspective of SVE bitcasts.
7957 bool isValidSveBitcast(QualType srcType, QualType destType);
7958
7959 /// Are the two types matrix types and do they have the same dimensions i.e.
7960 /// do they have the same number of rows and the same number of columns?
7961 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
7962
7963 bool areVectorTypesSameSize(QualType srcType, QualType destType);
7964
7965 /// Are the two types lax-compatible vector types? That is, given
7966 /// that one of them is a vector, do they have equal storage sizes,
7967 /// where the storage size is the number of elements times the element
7968 /// size?
7969 ///
7970 /// This will also return false if either of the types is neither a
7971 /// vector nor a real type.
7972 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
7973
7974 /// Is this a legal conversion between two types, one of which is
7975 /// known to be a vector type?
7976 bool isLaxVectorConversion(QualType srcType, QualType destType);
7977
7978 // This returns true if at least one of the types is an altivec vector.
7979 bool anyAltivecTypes(QualType srcType, QualType destType);
7980
7981 // type checking C++ declaration initializers (C++ [dcl.init]).
7982
7983 /// Check a cast of an unknown-any type. We intentionally only
7984 /// trigger this for C-style casts.
7985 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
7986 Expr *CastExpr, CastKind &CastKind,
7987 ExprValueKind &VK, CXXCastPath &Path);
7988
7989 /// Force an expression with unknown-type to an expression of the
7990 /// given type.
7991 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
7992
7993 /// Type-check an expression that's being passed to an
7994 /// __unknown_anytype parameter.
7995 ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result,
7996 QualType &paramType);
7997
7998 // CheckMatrixCast - Check type constraints for matrix casts.
7999 // We allow casting between matrixes of the same dimensions i.e. when they
8000 // have the same number of rows and column. Returns true if the cast is
8001 // invalid.
8002 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8003 CastKind &Kind);
8004
8005 // CheckVectorCast - check type constraints for vectors.
8006 // Since vectors are an extension, there are no C standard reference for this.
8007 // We allow casting between vectors and integer datatypes of the same size.
8008 // returns true if the cast is invalid
8009 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8010 CastKind &Kind);
8011
8012 /// Prepare `SplattedExpr` for a vector splat operation, adding
8013 /// implicit casts if necessary.
8014 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8015
8016 /// Prepare `SplattedExpr` for a matrix splat operation, adding
8017 /// implicit casts if necessary.
8018 ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr);
8019
8020 // CheckExtVectorCast - check type constraints for extended vectors.
8021 // Since vectors are an extension, there are no C standard reference for this.
8022 // We allow casting between vectors and integer datatypes of the same size,
8023 // or vectors and the element type of that vector.
8024 // returns the cast expr
8025 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8026 CastKind &Kind);
8027
8028 QualType PreferredConditionType(ConditionKind K) const {
8029 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
8030 }
8031
8032 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
8033 // functions and arrays to their respective pointers (C99 6.3.2.1), and
8034 // promotes floating-piont types according to the language semantics.
8035 ExprResult UsualUnaryConversions(Expr *E);
8036
8037 // UsualUnaryFPConversions - promotes floating-point types according to the
8038 // current language semantics.
8039 ExprResult UsualUnaryFPConversions(Expr *E);
8040
8041 /// CallExprUnaryConversions - a special case of an unary conversion
8042 /// performed on a function designator of a call expression.
8043 ExprResult CallExprUnaryConversions(Expr *E);
8044
8045 // DefaultFunctionArrayConversion - converts functions and arrays
8046 // to their respective pointers (C99 6.3.2.1).
8047 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8048
8049 // DefaultFunctionArrayLvalueConversion - converts functions and
8050 // arrays to their respective pointers and performs the
8051 // lvalue-to-rvalue conversion.
8052 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8053 bool Diagnose = true);
8054
8055 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8056 // the operand. This function is a no-op if the operand has a function type
8057 // or an array type.
8058 ExprResult DefaultLvalueConversion(Expr *E);
8059
8060 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8061 // do not have a prototype. Integer promotions are performed on each
8062 // argument, and arguments that have type float are promoted to double.
8063 ExprResult DefaultArgumentPromotion(Expr *E);
8064
8065 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8066 const FunctionProtoType *Proto,
8067 Expr *Fn);
8068
8069 /// Determine the degree of POD-ness for an expression.
8070 /// Incomplete types are considered POD, since this check can be performed
8071 /// when we're in an unevaluated context.
8072 VarArgKind isValidVarArgType(const QualType &Ty);
8073
8074 /// Check to see if the given expression is a valid argument to a variadic
8075 /// function, issuing a diagnostic if not.
8076 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8077
8078 /// GatherArgumentsForCall - Collector argument expressions for various
8079 /// form of call prototypes.
8080 bool GatherArgumentsForCall(
8081 SourceLocation CallLoc, FunctionDecl *FDecl,
8082 const FunctionProtoType *Proto, unsigned FirstParam,
8083 ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs,
8084 VariadicCallType CallType = VariadicCallType::DoesNotApply,
8085 bool AllowExplicit = false, bool IsListInitialization = false);
8086
8087 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8088 // will create a runtime trap if the resulting type is not a POD type.
8089 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8090 FunctionDecl *FDecl);
8091
8092 // Check that the usual arithmetic conversions can be performed on this pair
8093 // of expressions that might be of enumeration type.
8094 void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc,
8095 ArithConvKind ACK);
8096
8097 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8098 // operands and then handles various conversions that are common to binary
8099 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8100 // routine returns the first non-arithmetic type found. The client is
8101 // responsible for emitting appropriate error diagnostics.
8102 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8103 SourceLocation Loc, ArithConvKind ACK);
8104
8105 bool IsAssignConvertCompatible(AssignConvertType ConvTy) {
8106 switch (ConvTy) {
8107 default:
8108 return false;
8109 case AssignConvertType::Compatible:
8110 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
8111 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
8112 return true;
8113 }
8114 llvm_unreachable("impossible");
8115 }
8116
8117 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8118 /// assignment conversion type specified by ConvTy. This returns true if the
8119 /// conversion was invalid or false if the conversion was accepted.
8120 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc,
8121 QualType DstType, QualType SrcType,
8122 Expr *SrcExpr, AssignmentAction Action,
8123 bool *Complained = nullptr);
8124
8125 /// CheckAssignmentConstraints - Perform type checking for assignment,
8126 /// argument passing, variable initialization, and function return values.
8127 /// C99 6.5.16.
8128 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8129 QualType LHSType,
8130 QualType RHSType);
8131
8132 /// Check assignment constraints and optionally prepare for a conversion of
8133 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8134 /// is true.
8135 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8136 ExprResult &RHS, CastKind &Kind,
8137 bool ConvertRHS = true);
8138
8139 /// Check assignment constraints for an assignment of RHS to LHSType.
8140 ///
8141 /// \param LHSType The destination type for the assignment.
8142 /// \param RHS The source expression for the assignment.
8143 /// \param Diagnose If \c true, diagnostics may be produced when checking
8144 /// for assignability. If a diagnostic is produced, \p RHS will be
8145 /// set to ExprError(). Note that this function may still return
8146 /// without producing a diagnostic, even for an invalid assignment.
8147 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8148 /// in an audited Core Foundation API and does not need to be checked
8149 /// for ARC retain issues.
8150 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8151 /// conversions necessary to perform the assignment. If \c false,
8152 /// \p Diagnose must also be \c false.
8153 AssignConvertType CheckSingleAssignmentConstraints(
8154 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8155 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8156
8157 // If the lhs type is a transparent union, check whether we
8158 // can initialize the transparent union with the given expression.
8159 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8160 ExprResult &RHS);
8161
8162 /// the following "Check" methods will return a valid/converted QualType
8163 /// or a null QualType (indicating an error diagnostic was issued).
8164
8165 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8166 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8167 ExprResult &RHS);
8168
8169 /// Diagnose cases where a scalar was implicitly converted to a vector and
8170 /// diagnose the underlying types. Otherwise, diagnose the error
8171 /// as invalid vector logical operands for non-C++ cases.
8172 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8173 ExprResult &RHS);
8174
8175 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8176 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8177 BinaryOperatorKind Opc);
8178 QualType CheckRemainderOperands( // C99 6.5.5
8179 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8180 bool IsCompAssign = false);
8181 QualType CheckAdditionOperands( // C99 6.5.6
8182 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8183 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8184 QualType CheckSubtractionOperands( // C99 6.5.6
8185 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8186 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8187 QualType CheckShiftOperands( // C99 6.5.7
8188 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8189 BinaryOperatorKind Opc, bool IsCompAssign = false);
8190 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
8191 QualType CheckCompareOperands( // C99 6.5.8/9
8192 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8193 BinaryOperatorKind Opc);
8194 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8195 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8196 BinaryOperatorKind Opc);
8197 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8198 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8199 BinaryOperatorKind Opc);
8200 // CheckAssignmentOperands is used for both simple and compound assignment.
8201 // For simple assignment, pass both expressions and a null converted type.
8202 // For compound assignment, pass both expressions and the converted type.
8203 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8204 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8205 BinaryOperatorKind Opc);
8206
8207 /// To be used for checking whether the arguments being passed to
8208 /// function exceeds the number of parameters expected for it.
8209 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8210 bool PartialOverloading = false) {
8211 // We check whether we're just after a comma in code-completion.
8212 if (NumArgs > 0 && PartialOverloading)
8213 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8214 return NumArgs > NumParams;
8215 }
8216
8217 /// Whether the AST is currently being rebuilt to correct immediate
8218 /// invocations. Immediate invocation candidates and references to consteval
8219 /// functions aren't tracked when this is set.
8220 bool RebuildingImmediateInvocation = false;
8221
8222 bool isAlwaysConstantEvaluatedContext() const {
8223 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8224 return (Ctx.isConstantEvaluated() || isConstantEvaluatedOverride) &&
8225 !Ctx.InConditionallyConstantEvaluateContext;
8226 }
8227
8228 /// Determines whether we are currently in a context that
8229 /// is not evaluated as per C++ [expr] p5.
8230 bool isUnevaluatedContext() const {
8231 return currentEvaluationContext().isUnevaluated();
8232 }
8233
8234 bool isImmediateFunctionContext() const {
8235 return currentEvaluationContext().isImmediateFunctionContext();
8236 }
8237
8238 bool isInLifetimeExtendingContext() const {
8239 return currentEvaluationContext().InLifetimeExtendingContext;
8240 }
8241
8242 bool needsRebuildOfDefaultArgOrInit() const {
8243 return currentEvaluationContext().RebuildDefaultArgOrDefaultInit;
8244 }
8245
8246 bool isCheckingDefaultArgumentOrInitializer() const {
8247 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8248 return (Ctx.Context ==
8249 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) ||
8250 Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer;
8251 }
8252
8253 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8254 InnermostDeclarationWithDelayedImmediateInvocations() const {
8255 assert(!ExprEvalContexts.empty() &&
8256 "Must be in an expression evaluation context");
8257 for (const auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8258 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8259 Ctx.DelayedDefaultInitializationContext)
8260 return Ctx.DelayedDefaultInitializationContext;
8261 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8262 Ctx.isUnevaluated())
8263 break;
8264 }
8265 return std::nullopt;
8266 }
8267
8268 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8269 OutermostDeclarationWithDelayedImmediateInvocations() const {
8270 assert(!ExprEvalContexts.empty() &&
8271 "Must be in an expression evaluation context");
8272 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8273 for (auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8274 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8275 !Ctx.DelayedDefaultInitializationContext && Res)
8276 break;
8277 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8278 Ctx.isUnevaluated())
8279 break;
8280 Res = Ctx.DelayedDefaultInitializationContext;
8281 }
8282 return Res;
8283 }
8284
8285 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8286 /// SelfAssigned when inside a CXXMethodDecl.
8287 const FieldDecl *
8288 getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
8289
8290 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
8291
8292 template <typename... Ts>
8293 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
8294 const Ts &...Args) {
8295 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8296 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8297 }
8298
8299 template <typename... Ts>
8300 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8301 const Ts &...Args) {
8302 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8303 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
8304 }
8305
8306 /// Abstract class used to diagnose incomplete types.
8307 struct TypeDiagnoser {
8308 TypeDiagnoser() {}
8309
8310 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
8311 virtual ~TypeDiagnoser() {}
8312 };
8313
8314 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8315 protected:
8316 unsigned DiagID;
8317 std::tuple<const Ts &...> Args;
8318
8319 template <std::size_t... Is>
8320 void emit(const SemaDiagnosticBuilder &DB,
8321 std::index_sequence<Is...>) const {
8322 // Apply all tuple elements to the builder in order.
8323 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8324 (void)Dummy;
8325 }
8326
8327 public:
8328 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8329 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8330 assert(DiagID != 0 && "no diagnostic for type diagnoser");
8331 }
8332
8333 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8334 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8335 emit(DB, std::index_sequence_for<Ts...>());
8336 DB << T;
8337 }
8338 };
8339
8340 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8341 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8342 /// For example, a diagnostic with no other parameters would generally have
8343 /// the form "...%select{incomplete|sizeless}0 type %1...".
8344 template <typename... Ts>
8345 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
8346 public:
8347 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8348 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8349
8350 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8351 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8352 this->emit(DB, std::index_sequence_for<Ts...>());
8353 DB << T->isSizelessType() << T;
8354 }
8355 };
8356
8357 /// Check an argument list for placeholders that we won't try to
8358 /// handle later.
8359 bool CheckArgsForPlaceholders(MultiExprArg args);
8360
8361 /// The C++ "std::source_location::__impl" struct, defined in
8362 /// \<source_location>.
8363 RecordDecl *StdSourceLocationImplDecl;
8364
8365 /// A stack of expression evaluation contexts.
8366 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
8367
8368 // Set of failed immediate invocations to avoid double diagnosing.
8369 llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
8370
8371 /// List of SourceLocations where 'self' is implicitly retained inside a
8372 /// block.
8373 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
8374 ImplicitlyRetainedSelfLocs;
8375
8376 /// Do an explicit extend of the given block pointer if we're in ARC.
8377 void maybeExtendBlockObject(ExprResult &E);
8378
8379 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8380 SourceLocation LocationOfExcessPrecisionNotSatisfied;
8381 void DiagnosePrecisionLossInComplexDivision();
8382
8383private:
8384 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8385
8386 /// Methods for marking which expressions involve dereferencing a pointer
8387 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8388 /// they are parsed, meaning that a noderef pointer may not be accessed. For
8389 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8390 /// `*p`, but need to check that `address of` is called on it. This requires
8391 /// keeping a container of all pending expressions and checking if the address
8392 /// of them are eventually taken.
8393 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8394 void CheckAddressOfNoDeref(const Expr *E);
8395
8396 ///@}
8397
8398 //
8399 //
8400 // -------------------------------------------------------------------------
8401 //
8402 //
8403
8404 /// \name C++ Expressions
8405 /// Implementations are in SemaExprCXX.cpp
8406 ///@{
8407
8408public:
8409 /// The C++ "std::bad_alloc" class, which is defined by the C++
8410 /// standard library.
8411 LazyDeclPtr StdBadAlloc;
8412
8413 /// The C++ "std::align_val_t" enum class, which is defined by the C++
8414 /// standard library.
8415 LazyDeclPtr StdAlignValT;
8416
8417 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
8418 RecordDecl *CXXTypeInfoDecl;
8419
8420 /// A flag to remember whether the implicit forms of operator new and delete
8421 /// have been declared.
8422 bool GlobalNewDeleteDeclared;
8423
8424 /// Delete-expressions to be analyzed at the end of translation unit
8425 ///
8426 /// This list contains class members, and locations of delete-expressions
8427 /// that could not be proven as to whether they mismatch with new-expression
8428 /// used in initializer of the field.
8429 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8430
8431 /// Handle the result of the special case name lookup for inheriting
8432 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8433 /// constructor names in member using declarations, even if 'X' is not the
8434 /// name of the corresponding type.
8435 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
8436 SourceLocation NameLoc,
8437 const IdentifierInfo &Name);
8438
8439 ParsedType getConstructorName(const IdentifierInfo &II,
8440 SourceLocation NameLoc, Scope *S,
8441 CXXScopeSpec &SS, bool EnteringContext);
8442 ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc,
8443 Scope *S, CXXScopeSpec &SS,
8444 ParsedType ObjectType, bool EnteringContext);
8445
8446 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
8447 ParsedType ObjectType);
8448
8449 /// Build a C++ typeid expression with a type operand.
8450 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8451 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8452
8453 /// Build a C++ typeid expression with an expression operand.
8454 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8455 Expr *Operand, SourceLocation RParenLoc);
8456
8457 /// ActOnCXXTypeid - Parse typeid( something ).
8458 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
8459 bool isType, void *TyOrExpr,
8460 SourceLocation RParenLoc);
8461
8462 /// Build a Microsoft __uuidof expression with a type operand.
8463 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8464 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8465
8466 /// Build a Microsoft __uuidof expression with an expression operand.
8467 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8468 Expr *Operand, SourceLocation RParenLoc);
8469
8470 /// ActOnCXXUuidof - Parse __uuidof( something ).
8471 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
8472 bool isType, void *TyOrExpr,
8473 SourceLocation RParenLoc);
8474
8475 //// ActOnCXXThis - Parse 'this' pointer.
8476 ExprResult ActOnCXXThis(SourceLocation Loc);
8477
8478 /// Check whether the type of 'this' is valid in the current context.
8479 bool CheckCXXThisType(SourceLocation Loc, QualType Type);
8480
8481 /// Build a CXXThisExpr and mark it referenced in the current context.
8482 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8483 void MarkThisReferenced(CXXThisExpr *This);
8484
8485 /// Try to retrieve the type of the 'this' pointer.
8486 ///
8487 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8488 QualType getCurrentThisType();
8489
8490 /// When non-NULL, the C++ 'this' expression is allowed despite the
8491 /// current context not being a non-static member function. In such cases,
8492 /// this provides the type used for 'this'.
8493 QualType CXXThisTypeOverride;
8494
8495 /// RAII object used to temporarily allow the C++ 'this' expression
8496 /// to be used, with the given qualifiers on the current class type.
8497 class CXXThisScopeRAII {
8498 Sema &S;
8499 QualType OldCXXThisTypeOverride;
8500 bool Enabled;
8501
8502 public:
8503 /// Introduce a new scope where 'this' may be allowed (when enabled),
8504 /// using the given declaration (which is either a class template or a
8505 /// class) along with the given qualifiers.
8506 /// along with the qualifiers placed on '*this'.
8507 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8508 bool Enabled = true);
8509
8510 ~CXXThisScopeRAII();
8511 CXXThisScopeRAII(const CXXThisScopeRAII &) = delete;
8512 CXXThisScopeRAII &operator=(const CXXThisScopeRAII &) = delete;
8513 };
8514
8515 /// Make sure the value of 'this' is actually available in the current
8516 /// context, if it is a potentially evaluated context.
8517 ///
8518 /// \param Loc The location at which the capture of 'this' occurs.
8519 ///
8520 /// \param Explicit Whether 'this' is explicitly captured in a lambda
8521 /// capture list.
8522 ///
8523 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8524 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8525 /// This is useful when enclosing lambdas must speculatively capture
8526 /// 'this' that may or may not be used in certain specializations of
8527 /// a nested generic lambda (depending on whether the name resolves to
8528 /// a non-static member function or a static function).
8529 /// \return returns 'true' if failed, 'false' if success.
8530 bool CheckCXXThisCapture(
8531 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8532 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8533 bool ByCopy = false);
8534
8535 /// Determine whether the given type is the type of *this that is used
8536 /// outside of the body of a member function for a type that is currently
8537 /// being defined.
8538 bool isThisOutsideMemberFunctionBody(QualType BaseType);
8539
8540 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8541 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
8542
8543 /// Build a boolean-typed literal expression.
8544 ExprResult BuildBoolLiteral(SourceLocation Loc, bool Value);
8545
8546 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8547 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
8548
8549 //// ActOnCXXThrow - Parse throw expressions.
8550 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
8551 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
8552 bool IsThrownVarInScope);
8553
8554 /// CheckCXXThrowOperand - Validate the operand of a throw.
8555 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8556
8557 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8558 /// Can be interpreted either as function-style casting ("int(x)")
8559 /// or class type construction ("ClassType(x,y,z)")
8560 /// or creation of a value-initialized type ("int()").
8561 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
8562 SourceLocation LParenOrBraceLoc,
8563 MultiExprArg Exprs,
8564 SourceLocation RParenOrBraceLoc,
8565 bool ListInitialization);
8566
8567 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
8568 SourceLocation LParenLoc,
8569 MultiExprArg Exprs,
8570 SourceLocation RParenLoc,
8571 bool ListInitialization);
8572
8573 /// Parsed a C++ 'new' expression (C++ 5.3.4).
8574 ///
8575 /// E.g.:
8576 /// @code new (memory) int[size][4] @endcode
8577 /// or
8578 /// @code ::new Foo(23, "hello") @endcode
8579 ///
8580 /// \param StartLoc The first location of the expression.
8581 /// \param UseGlobal True if 'new' was prefixed with '::'.
8582 /// \param PlacementLParen Opening paren of the placement arguments.
8583 /// \param PlacementArgs Placement new arguments.
8584 /// \param PlacementRParen Closing paren of the placement arguments.
8585 /// \param TypeIdParens If the type is in parens, the source range.
8586 /// \param D The type to be allocated, as well as array dimensions.
8587 /// \param Initializer The initializing expression or initializer-list, or
8588 /// null if there is none.
8589 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8590 SourceLocation PlacementLParen,
8591 MultiExprArg PlacementArgs,
8592 SourceLocation PlacementRParen,
8593 SourceRange TypeIdParens, Declarator &D,
8594 Expr *Initializer);
8595 ExprResult
8596 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8597 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8598 SourceRange TypeIdParens, QualType AllocType,
8599 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8600 SourceRange DirectInitRange, Expr *Initializer);
8601
8602 /// Determine whether \p FD is an aligned allocation or deallocation
8603 /// function that is unavailable.
8604 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
8605
8606 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8607 /// function that is unavailable.
8608 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
8609 SourceLocation Loc);
8610
8611 /// Checks that a type is suitable as the allocated type
8612 /// in a new-expression.
8613 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8614 SourceRange R);
8615
8616 /// Finds the overloads of operator new and delete that are appropriate
8617 /// for the allocation.
8618 std::optional<ResolvedAllocation> FindAllocationFunctions(
8619 SourceLocation StartLoc, SourceRange Range,
8620 AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope,
8621 QualType AllocType, bool IsArray, const ImplicitAllocationParameters &IAP,
8622 MultiExprArg PlaceArgs, bool Diagnose = true);
8623
8624 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8625 /// delete. These are:
8626 /// @code
8627 /// // C++03:
8628 /// void* operator new(std::size_t) throw(std::bad_alloc);
8629 /// void* operator new[](std::size_t) throw(std::bad_alloc);
8630 /// void operator delete(void *) throw();
8631 /// void operator delete[](void *) throw();
8632 /// // C++11:
8633 /// void* operator new(std::size_t);
8634 /// void* operator new[](std::size_t);
8635 /// void operator delete(void *) noexcept;
8636 /// void operator delete[](void *) noexcept;
8637 /// // C++1y:
8638 /// void* operator new(std::size_t);
8639 /// void* operator new[](std::size_t);
8640 /// void operator delete(void *) noexcept;
8641 /// void operator delete[](void *) noexcept;
8642 /// void operator delete(void *, std::size_t) noexcept;
8643 /// void operator delete[](void *, std::size_t) noexcept;
8644 /// @endcode
8645 /// Note that the placement and nothrow forms of new are *not* implicitly
8646 /// declared. Their use requires including \<new\>.
8647 void DeclareGlobalNewDelete();
8648 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
8649 ArrayRef<QualType> Params);
8650
8651 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
8652 DeclarationName Name, FunctionDecl *&Operator,
8653 ImplicitDeallocationParameters,
8654 bool Diagnose = true);
8655 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
8656 ImplicitDeallocationParameters,
8657 DeclarationName Name,
8658 bool Diagnose = true);
8659 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
8660 CXXRecordDecl *RD,
8661 bool Diagnose,
8662 bool LookForGlobal,
8663 DeclarationName Name);
8664
8665 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8666 /// @code ::delete ptr; @endcode
8667 /// or
8668 /// @code delete [] ptr; @endcode
8669 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8670 bool ArrayForm, Expr *Operand);
8671 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
8672 bool IsDelete, bool CallCanBeVirtual,
8673 bool WarnOnNonAbstractTypes,
8674 SourceLocation DtorLoc);
8675
8676 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
8677 Expr *Operand, SourceLocation RParen);
8678 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8679 SourceLocation RParen);
8680
8681 ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base,
8682 SourceLocation OpLoc,
8683 tok::TokenKind OpKind,
8684 ParsedType &ObjectType,
8685 bool &MayBePseudoDestructor);
8686
8687 ExprResult BuildPseudoDestructorExpr(
8688 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8689 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8690 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8691
8692 ExprResult ActOnPseudoDestructorExpr(
8693 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8694 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8695 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8696
8697 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
8698 SourceLocation OpLoc,
8699 tok::TokenKind OpKind,
8700 SourceLocation TildeLoc,
8701 const DeclSpec &DS);
8702
8703 /// MaybeCreateExprWithCleanups - If the current full-expression
8704 /// requires any cleanups, surround it with a ExprWithCleanups node.
8705 /// Otherwise, just returns the passed-in expression.
8706 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
8707 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
8708 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
8709
8710 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8711 return ActOnFinishFullExpr(
8712 Expr, CC: Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8713 }
8714 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
8715 bool DiscardedValue, bool IsConstexpr = false,
8716 bool IsTemplateArgument = false);
8717 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
8718
8719 /// Process the expression contained within a decltype. For such expressions,
8720 /// certain semantic checks on temporaries are delayed until this point, and
8721 /// are omitted for the 'topmost' call in the decltype expression. If the
8722 /// topmost call bound a temporary, strip that temporary off the expression.
8723 ExprResult ActOnDecltypeExpression(Expr *E);
8724
8725 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8726 bool IsUDSuffix);
8727
8728 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
8729
8730 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8731 SourceLocation StmtLoc,
8732 ConditionKind CK);
8733
8734 /// Check the use of the given variable as a C++ condition in an if,
8735 /// while, do-while, or switch statement.
8736 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
8737 SourceLocation StmtLoc, ConditionKind CK);
8738
8739 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8740 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8741
8742 /// Helper function to determine whether this is the (deprecated) C++
8743 /// conversion from a string literal to a pointer to non-const char or
8744 /// non-const wchar_t (for narrow and wide string literals,
8745 /// respectively).
8746 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8747
8748 /// PerformImplicitConversion - Perform an implicit conversion of the
8749 /// expression From to the type ToType using the pre-computed implicit
8750 /// conversion sequence ICS. Returns the converted
8751 /// expression. Action is the kind of conversion we're performing,
8752 /// used in the error message.
8753 ExprResult PerformImplicitConversion(
8754 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8755 AssignmentAction Action,
8756 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
8757
8758 /// PerformImplicitConversion - Perform an implicit conversion of the
8759 /// expression From to the type ToType by following the standard
8760 /// conversion sequence SCS. Returns the converted
8761 /// expression. Flavor is the context in which we're performing this
8762 /// conversion, for use in error messages.
8763 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8764 const StandardConversionSequence &SCS,
8765 AssignmentAction Action,
8766 CheckedConversionKind CCK);
8767
8768 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8769
8770 /// Parsed one of the type trait support pseudo-functions.
8771 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8772 ArrayRef<ParsedType> Args,
8773 SourceLocation RParenLoc);
8774 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8775 ArrayRef<TypeSourceInfo *> Args,
8776 SourceLocation RParenLoc);
8777
8778 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8779 /// pseudo-functions.
8780 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8781 ParsedType LhsTy, Expr *DimExpr,
8782 SourceLocation RParen);
8783
8784 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8785 TypeSourceInfo *TSInfo, Expr *DimExpr,
8786 SourceLocation RParen);
8787
8788 /// ActOnExpressionTrait - Parsed one of the unary type trait support
8789 /// pseudo-functions.
8790 ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8791 Expr *Queried, SourceLocation RParen);
8792
8793 ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8794 Expr *Queried, SourceLocation RParen);
8795
8796 QualType CheckPointerToMemberOperands( // C++ 5.5
8797 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc,
8798 bool isIndirect);
8799 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
8800 ExprResult &RHS,
8801 SourceLocation QuestionLoc);
8802
8803 //// Determines if a type is trivially relocatable
8804 /// according to the C++26 rules.
8805 // FIXME: This is in Sema because it requires
8806 // overload resolution, can we move to ASTContext?
8807 bool IsCXXTriviallyRelocatableType(QualType T);
8808 bool IsCXXTriviallyRelocatableType(const CXXRecordDecl &RD);
8809
8810 /// Check the operands of ?: under C++ semantics.
8811 ///
8812 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8813 /// extension. In this case, LHS == Cond. (But they're not aliases.)
8814 ///
8815 /// This function also implements GCC's vector extension and the
8816 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8817 /// permit the use of a?b:c where the type of a is that of a integer vector
8818 /// with the same number of elements and size as the vectors of b and c. If
8819 /// one of either b or c is a scalar it is implicitly converted to match the
8820 /// type of the vector. Otherwise the expression is ill-formed. If both b and
8821 /// c are scalars, then b and c are checked and converted to the type of a if
8822 /// possible.
8823 ///
8824 /// The expressions are evaluated differently for GCC's and OpenCL's
8825 /// extensions. For the GCC extension, the ?: operator is evaluated as
8826 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8827 /// For the OpenCL extensions, the ?: operator is evaluated as
8828 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
8829 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
8830 QualType CXXCheckConditionalOperands( // C++ 5.16
8831 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8832 ExprObjectKind &OK, SourceLocation questionLoc);
8833
8834 /// Find a merged pointer type and convert the two expressions to it.
8835 ///
8836 /// This finds the composite pointer type for \p E1 and \p E2 according to
8837 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8838 /// it. It does not emit diagnostics (FIXME: that's not true if \p
8839 /// ConvertArgs is \c true).
8840 ///
8841 /// \param Loc The location of the operator requiring these two expressions to
8842 /// be converted to the composite pointer type.
8843 ///
8844 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
8845 /// type.
8846 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8847 bool ConvertArgs = true);
8848 QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1,
8849 ExprResult &E2, bool ConvertArgs = true) {
8850 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8851 QualType Composite =
8852 FindCompositePointerType(Loc, E1&: E1Tmp, E2&: E2Tmp, ConvertArgs);
8853 E1 = E1Tmp;
8854 E2 = E2Tmp;
8855 return Composite;
8856 }
8857
8858 /// MaybeBindToTemporary - If the passed in expression has a record type with
8859 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
8860 /// it simply returns the passed in expression.
8861 ExprResult MaybeBindToTemporary(Expr *E);
8862
8863 /// IgnoredValueConversions - Given that an expression's result is
8864 /// syntactically ignored, perform any conversions that are
8865 /// required.
8866 ExprResult IgnoredValueConversions(Expr *E);
8867
8868 ExprResult CheckUnevaluatedOperand(Expr *E);
8869
8870 IfExistsResult
8871 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
8872 const DeclarationNameInfo &TargetNameInfo);
8873
8874 IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S,
8875 SourceLocation KeywordLoc,
8876 bool IsIfExists, CXXScopeSpec &SS,
8877 UnqualifiedId &Name);
8878
8879 RequiresExprBodyDecl *
8880 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8881 ArrayRef<ParmVarDecl *> LocalParameters,
8882 Scope *BodyScope);
8883 void ActOnFinishRequiresExpr();
8884 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8885 concepts::Requirement *ActOnTypeRequirement(SourceLocation TypenameKWLoc,
8886 CXXScopeSpec &SS,
8887 SourceLocation NameLoc,
8888 const IdentifierInfo *TypeName,
8889 TemplateIdAnnotation *TemplateId);
8890 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8891 SourceLocation NoexceptLoc);
8892 concepts::Requirement *ActOnCompoundRequirement(
8893 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8894 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8895 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8896 concepts::ExprRequirement *BuildExprRequirement(
8897 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8898 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8899 concepts::ExprRequirement *BuildExprRequirement(
8900 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8901 bool IsSatisfied, SourceLocation NoexceptLoc,
8902 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8903 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8904 concepts::TypeRequirement *BuildTypeRequirement(
8905 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8906 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8907 concepts::NestedRequirement *
8908 BuildNestedRequirement(StringRef InvalidConstraintEntity,
8909 const ASTConstraintSatisfaction &Satisfaction);
8910 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8911 RequiresExprBodyDecl *Body,
8912 SourceLocation LParenLoc,
8913 ArrayRef<ParmVarDecl *> LocalParameters,
8914 SourceLocation RParenLoc,
8915 ArrayRef<concepts::Requirement *> Requirements,
8916 SourceLocation ClosingBraceLoc);
8917
8918private:
8919 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
8920 bool IsDelete);
8921
8922 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8923 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8924 bool DeleteWasArrayForm);
8925
8926 std::optional<AllocationArgumentSet>
8927 resolveAllocationArguments(LookupResult &R,
8928 const ImplicitAllocationParameters &,
8929 ArrayRef<Expr *> PlacementArguments);
8930
8931 // Attempts to construct the type identity argument for the call to a
8932 // type aware operator new. Returns null on failure.
8933 Expr *tryGetTypeIdentityArgument(QualType Type, SourceLocation);
8934
8935 Expr *AllocationSizeExpr = nullptr;
8936 Expr *AllocationAlignmentExpr = nullptr;
8937 llvm::DenseMap<QualType, Expr *> AllocationTypeIdentityArguments;
8938
8939 ///@}
8940
8941 //
8942 //
8943 // -------------------------------------------------------------------------
8944 //
8945 //
8946
8947 /// \name Member Access Expressions
8948 /// Implementations are in SemaExprMember.cpp
8949 ///@{
8950
8951public:
8952 /// Check whether an expression might be an implicit class member access.
8953 bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R,
8954 bool IsAddressOfOperand);
8955
8956 /// Builds an expression which might be an implicit member expression.
8957 ExprResult BuildPossibleImplicitMemberExpr(
8958 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
8959 const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
8960
8961 /// Builds an implicit member access expression. The current context
8962 /// is known to be an instance method, and the given unqualified lookup
8963 /// set is known to contain only instance members, at least one of which
8964 /// is from an appropriate type.
8965 ExprResult
8966 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8967 LookupResult &R,
8968 const TemplateArgumentListInfo *TemplateArgs,
8969 bool IsDefiniteInstance, const Scope *S);
8970
8971 ExprResult ActOnDependentMemberExpr(
8972 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
8973 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8974 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
8975 const TemplateArgumentListInfo *TemplateArgs);
8976
8977 /// The main callback when the parser finds something like
8978 /// expression . [nested-name-specifier] identifier
8979 /// expression -> [nested-name-specifier] identifier
8980 /// where 'identifier' encompasses a fairly broad spectrum of
8981 /// possibilities, including destructor and operator references.
8982 ///
8983 /// \param OpKind either tok::arrow or tok::period
8984 /// \param ObjCImpDecl the current Objective-C \@implementation
8985 /// decl; this is an ugly hack around the fact that Objective-C
8986 /// \@implementations aren't properly put in the context chain
8987 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
8988 tok::TokenKind OpKind, CXXScopeSpec &SS,
8989 SourceLocation TemplateKWLoc,
8990 UnqualifiedId &Member, Decl *ObjCImpDecl);
8991
8992 MemberExpr *
8993 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
8994 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
8995 ValueDecl *Member, DeclAccessPair FoundDecl,
8996 bool HadMultipleCandidates,
8997 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
8998 ExprValueKind VK, ExprObjectKind OK,
8999 const TemplateArgumentListInfo *TemplateArgs = nullptr);
9000
9001 // Check whether the declarations we found through a nested-name
9002 // specifier in a member expression are actually members of the base
9003 // type. The restriction here is:
9004 //
9005 // C++ [expr.ref]p2:
9006 // ... In these cases, the id-expression shall name a
9007 // member of the class or of one of its base classes.
9008 //
9009 // So it's perfectly legitimate for the nested-name specifier to name
9010 // an unrelated class, and for us to find an overload set including
9011 // decls from classes which are not superclasses, as long as the decl
9012 // we actually pick through overload resolution is from a superclass.
9013 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
9014 const CXXScopeSpec &SS,
9015 const LookupResult &R);
9016
9017 // This struct is for use by ActOnMemberAccess to allow
9018 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
9019 // changing the access operator from a '.' to a '->' (to see if that is the
9020 // change needed to fix an error about an unknown member, e.g. when the class
9021 // defines a custom operator->).
9022 struct ActOnMemberAccessExtraArgs {
9023 Scope *S;
9024 UnqualifiedId &Id;
9025 Decl *ObjCImpDecl;
9026 };
9027
9028 ExprResult BuildMemberReferenceExpr(
9029 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
9030 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9031 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9032 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
9033 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9034
9035 ExprResult
9036 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
9037 bool IsArrow, const CXXScopeSpec &SS,
9038 SourceLocation TemplateKWLoc,
9039 NamedDecl *FirstQualifierInScope, LookupResult &R,
9040 const TemplateArgumentListInfo *TemplateArgs,
9041 const Scope *S, bool SuppressQualifierCheck = false,
9042 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9043
9044 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
9045 SourceLocation OpLoc,
9046 const CXXScopeSpec &SS, FieldDecl *Field,
9047 DeclAccessPair FoundDecl,
9048 const DeclarationNameInfo &MemberNameInfo);
9049
9050 /// Perform conversions on the LHS of a member access expression.
9051 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
9052
9053 ExprResult BuildAnonymousStructUnionMemberReference(
9054 const CXXScopeSpec &SS, SourceLocation nameLoc,
9055 IndirectFieldDecl *indirectField,
9056 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none),
9057 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
9058
9059private:
9060 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
9061
9062 ///@}
9063
9064 //
9065 //
9066 // -------------------------------------------------------------------------
9067 //
9068 //
9069
9070 /// \name Initializers
9071 /// Implementations are in SemaInit.cpp
9072 ///@{
9073
9074public:
9075 /// Stack of types that correspond to the parameter entities that are
9076 /// currently being copy-initialized. Can be empty.
9077 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
9078
9079 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
9080 AggregateDeductionCandidates;
9081
9082 bool IsStringInit(Expr *Init, const ArrayType *AT);
9083
9084 /// Determine whether we can perform aggregate initialization for the purposes
9085 /// of overload resolution.
9086 bool CanPerformAggregateInitializationForOverloadResolution(
9087 const InitializedEntity &Entity, InitListExpr *From);
9088
9089 ExprResult ActOnDesignatedInitializer(Designation &Desig,
9090 SourceLocation EqualOrColonLoc,
9091 bool GNUSyntax, ExprResult Init);
9092
9093 /// Check that the lifetime of the initializer (and its subobjects) is
9094 /// sufficient for initializing the entity, and perform lifetime extension
9095 /// (when permitted) if not.
9096 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
9097
9098 MaterializeTemporaryExpr *
9099 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
9100 bool BoundToLvalueReference);
9101
9102 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9103 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9104 /// we don't have xvalues there.
9105 ExprResult TemporaryMaterializationConversion(Expr *E);
9106
9107 ExprResult PerformQualificationConversion(
9108 Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
9109 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
9110
9111 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
9112 ExprResult Init);
9113 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
9114 SourceLocation EqualLoc, ExprResult Init,
9115 bool TopLevelOfInitList = false,
9116 bool AllowExplicit = false);
9117
9118 QualType DeduceTemplateSpecializationFromInitializer(
9119 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9120 const InitializationKind &Kind, MultiExprArg Init);
9121
9122 ///@}
9123
9124 //
9125 //
9126 // -------------------------------------------------------------------------
9127 //
9128 //
9129
9130 /// \name C++ Lambda Expressions
9131 /// Implementations are in SemaLambda.cpp
9132 ///@{
9133
9134public:
9135 /// Create a new lambda closure type.
9136 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
9137 TypeSourceInfo *Info,
9138 unsigned LambdaDependencyKind,
9139 LambdaCaptureDefault CaptureDefault);
9140
9141 /// Number lambda for linkage purposes if necessary.
9142 void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method,
9143 std::optional<CXXRecordDecl::LambdaNumbering>
9144 NumberingOverride = std::nullopt);
9145
9146 /// Endow the lambda scope info with the relevant properties.
9147 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9148 SourceRange IntroducerRange,
9149 LambdaCaptureDefault CaptureDefault,
9150 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9151 bool Mutable);
9152
9153 CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange,
9154 CXXRecordDecl *Class);
9155
9156 void AddTemplateParametersToLambdaCallOperator(
9157 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9158 TemplateParameterList *TemplateParams);
9159
9160 void
9161 CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc,
9162 SourceLocation CallOperatorLoc,
9163 const AssociatedConstraint &TrailingRequiresClause,
9164 TypeSourceInfo *MethodTyInfo,
9165 ConstexprSpecKind ConstexprKind, StorageClass SC,
9166 ArrayRef<ParmVarDecl *> Params,
9167 bool HasExplicitResultType);
9168
9169 /// Returns true if the explicit object parameter was invalid.
9170 bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method,
9171 SourceLocation CallLoc);
9172
9173 /// Perform initialization analysis of the init-capture and perform
9174 /// any implicit conversions such as an lvalue-to-rvalue conversion if
9175 /// not being used to initialize a reference.
9176 ParsedType actOnLambdaInitCaptureInitialization(
9177 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9178 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9179 return ParsedType::make(P: buildLambdaInitCaptureInitialization(
9180 Loc, ByRef, EllipsisLoc, NumExpansions: std::nullopt, Id,
9181 DirectInit: InitKind != LambdaCaptureInitKind::CopyInit, Init));
9182 }
9183 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
9184 SourceLocation EllipsisLoc,
9185 UnsignedOrNone NumExpansions,
9186 IdentifierInfo *Id,
9187 bool DirectInit, Expr *&Init);
9188
9189 /// Create a dummy variable within the declcontext of the lambda's
9190 /// call operator, for name lookup purposes for a lambda init capture.
9191 ///
9192 /// CodeGen handles emission of lambda captures, ignoring these dummy
9193 /// variables appropriately.
9194 VarDecl *createLambdaInitCaptureVarDecl(
9195 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9196 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9197
9198 /// Add an init-capture to a lambda scope.
9199 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9200
9201 /// Note that we have finished the explicit captures for the
9202 /// given lambda.
9203 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
9204
9205 /// Deduce a block or lambda's return type based on the return
9206 /// statements present in the body.
9207 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
9208
9209 /// Once the Lambdas capture are known, we can start to create the closure,
9210 /// call operator method, and keep track of the captures.
9211 /// We do the capture lookup here, but they are not actually captured until
9212 /// after we know what the qualifiers of the call operator are.
9213 void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
9214 Scope *CurContext);
9215
9216 /// This is called after parsing the explicit template parameter list
9217 /// on a lambda (if it exists) in C++2a.
9218 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
9219 SourceLocation LAngleLoc,
9220 ArrayRef<NamedDecl *> TParams,
9221 SourceLocation RAngleLoc,
9222 ExprResult RequiresClause);
9223
9224 void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
9225 SourceLocation MutableLoc);
9226
9227 void ActOnLambdaClosureParameters(
9228 Scope *LambdaScope,
9229 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo);
9230
9231 /// ActOnStartOfLambdaDefinition - This is called just before we start
9232 /// parsing the body of a lambda; it analyzes the explicit captures and
9233 /// arguments, and sets up various data-structures for the body of the
9234 /// lambda.
9235 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
9236 Declarator &ParamInfo, const DeclSpec &DS);
9237
9238 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9239 /// is invoked to pop the information about the lambda.
9240 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9241 bool IsInstantiation = false);
9242
9243 /// ActOnLambdaExpr - This is called when the body of a lambda expression
9244 /// was successfully completed.
9245 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body);
9246
9247 /// Does copying/destroying the captured variable have side effects?
9248 bool CaptureHasSideEffects(const sema::Capture &From);
9249
9250 /// Diagnose if an explicit lambda capture is unused. Returns true if a
9251 /// diagnostic is emitted.
9252 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9253 SourceRange FixItRange,
9254 const sema::Capture &From);
9255
9256 /// Build a FieldDecl suitable to hold the given capture.
9257 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
9258
9259 /// Initialize the given capture with a suitable expression.
9260 ExprResult BuildCaptureInit(const sema::Capture &Capture,
9261 SourceLocation ImplicitCaptureLoc,
9262 bool IsOpenMPMapping = false);
9263
9264 /// Complete a lambda-expression having processed and attached the
9265 /// lambda body.
9266 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc);
9267
9268 /// Get the return type to use for a lambda's conversion function(s) to
9269 /// function pointer type, given the type of the call operator.
9270 QualType
9271 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
9272 CallingConv CC);
9273
9274 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
9275 SourceLocation ConvLocation,
9276 CXXConversionDecl *Conv, Expr *Src);
9277
9278 class LambdaScopeForCallOperatorInstantiationRAII
9279 : private FunctionScopeRAII {
9280 public:
9281 LambdaScopeForCallOperatorInstantiationRAII(
9282 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9283 LocalInstantiationScope &Scope,
9284 bool ShouldAddDeclsFromParentScope = true);
9285 };
9286
9287 /// Compute the mangling number context for a lambda expression or
9288 /// block literal. Also return the extra mangling decl if any.
9289 ///
9290 /// \param DC - The DeclContext containing the lambda expression or
9291 /// block literal.
9292 std::tuple<MangleNumberingContext *, Decl *>
9293 getCurrentMangleNumberContext(const DeclContext *DC);
9294
9295 ///@}
9296
9297 //
9298 //
9299 // -------------------------------------------------------------------------
9300 //
9301 //
9302
9303 /// \name Name Lookup
9304 ///
9305 /// These routines provide name lookup that is used during semantic
9306 /// analysis to resolve the various kinds of names (identifiers,
9307 /// overloaded operator names, constructor names, etc.) into zero or
9308 /// more declarations within a particular scope. The major entry
9309 /// points are LookupName, which performs unqualified name lookup,
9310 /// and LookupQualifiedName, which performs qualified name lookup.
9311 ///
9312 /// All name lookup is performed based on some specific criteria,
9313 /// which specify what names will be visible to name lookup and how
9314 /// far name lookup should work. These criteria are important both
9315 /// for capturing language semantics (certain lookups will ignore
9316 /// certain names, for example) and for performance, since name
9317 /// lookup is often a bottleneck in the compilation of C++. Name
9318 /// lookup criteria is specified via the LookupCriteria enumeration.
9319 ///
9320 /// The results of name lookup can vary based on the kind of name
9321 /// lookup performed, the current language, and the translation
9322 /// unit. In C, for example, name lookup will either return nothing
9323 /// (no entity found) or a single declaration. In C++, name lookup
9324 /// can additionally refer to a set of overloaded functions or
9325 /// result in an ambiguity. All of the possible results of name
9326 /// lookup are captured by the LookupResult class, which provides
9327 /// the ability to distinguish among them.
9328 ///
9329 /// Implementations are in SemaLookup.cpp
9330 ///@{
9331
9332public:
9333 /// Tracks whether we are in a context where typo correction is
9334 /// disabled.
9335 bool DisableTypoCorrection;
9336
9337 /// The number of typos corrected by CorrectTypo.
9338 unsigned TyposCorrected;
9339
9340 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9341 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9342
9343 /// A cache containing identifiers for which typo correction failed and
9344 /// their locations, so that repeated attempts to correct an identifier in a
9345 /// given location are ignored if typo correction already failed for it.
9346 IdentifierSourceLocations TypoCorrectionFailures;
9347
9348 /// SpecialMemberOverloadResult - The overloading result for a special member
9349 /// function.
9350 ///
9351 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9352 /// integer are used to determine whether overload resolution succeeded.
9353 class SpecialMemberOverloadResult {
9354 public:
9355 enum Kind { NoMemberOrDeleted, Ambiguous, Success };
9356
9357 private:
9358 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9359
9360 public:
9361 SpecialMemberOverloadResult() {}
9362 SpecialMemberOverloadResult(CXXMethodDecl *MD)
9363 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9364
9365 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
9366 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9367
9368 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
9369 void setKind(Kind K) { Pair.setInt(K); }
9370 };
9371
9372 using SpecialMemberCacheKey = std::pair<const CXXRecordDecl *, unsigned>;
9373
9374 /// A cache of special member function overload resolution results
9375 /// for C++ records.
9376 llvm::DenseMap<SpecialMemberCacheKey, SpecialMemberOverloadResult>
9377 SpecialMemberCache;
9378
9379 enum class AcceptableKind { Visible, Reachable };
9380
9381 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9382 // TODO: make this is a typesafe union.
9383 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
9384 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
9385
9386 /// Describes the kind of name lookup to perform.
9387 enum LookupNameKind {
9388 /// Ordinary name lookup, which finds ordinary names (functions,
9389 /// variables, typedefs, etc.) in C and most kinds of names
9390 /// (functions, variables, members, types, etc.) in C++.
9391 LookupOrdinaryName = 0,
9392 /// Tag name lookup, which finds the names of enums, classes,
9393 /// structs, and unions.
9394 LookupTagName,
9395 /// Label name lookup.
9396 LookupLabel,
9397 /// Member name lookup, which finds the names of
9398 /// class/struct/union members.
9399 LookupMemberName,
9400 /// Look up of an operator name (e.g., operator+) for use with
9401 /// operator overloading. This lookup is similar to ordinary name
9402 /// lookup, but will ignore any declarations that are class members.
9403 LookupOperatorName,
9404 /// Look up a name following ~ in a destructor name. This is an ordinary
9405 /// lookup, but prefers tags to typedefs.
9406 LookupDestructorName,
9407 /// Look up of a name that precedes the '::' scope resolution
9408 /// operator in C++. This lookup completely ignores operator, object,
9409 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9410 LookupNestedNameSpecifierName,
9411 /// Look up a namespace name within a C++ using directive or
9412 /// namespace alias definition, ignoring non-namespace names (C++
9413 /// [basic.lookup.udir]p1).
9414 LookupNamespaceName,
9415 /// Look up all declarations in a scope with the given name,
9416 /// including resolved using declarations. This is appropriate
9417 /// for checking redeclarations for a using declaration.
9418 LookupUsingDeclName,
9419 /// Look up an ordinary name that is going to be redeclared as a
9420 /// name with linkage. This lookup ignores any declarations that
9421 /// are outside of the current scope unless they have linkage. See
9422 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9423 LookupRedeclarationWithLinkage,
9424 /// Look up a friend of a local class. This lookup does not look
9425 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9426 LookupLocalFriendName,
9427 /// Look up the name of an Objective-C protocol.
9428 LookupObjCProtocolName,
9429 /// Look up implicit 'self' parameter of an objective-c method.
9430 LookupObjCImplicitSelfParam,
9431 /// Look up the name of an OpenMP user-defined reduction operation.
9432 LookupOMPReductionName,
9433 /// Look up the name of an OpenMP user-defined mapper.
9434 LookupOMPMapperName,
9435 /// Look up any declaration with any name.
9436 LookupAnyName
9437 };
9438
9439 /// The possible outcomes of name lookup for a literal operator.
9440 enum LiteralOperatorLookupResult {
9441 /// The lookup resulted in an error.
9442 LOLR_Error,
9443 /// The lookup found no match but no diagnostic was issued.
9444 LOLR_ErrorNoDiagnostic,
9445 /// The lookup found a single 'cooked' literal operator, which
9446 /// expects a normal literal to be built and passed to it.
9447 LOLR_Cooked,
9448 /// The lookup found a single 'raw' literal operator, which expects
9449 /// a string literal containing the spelling of the literal token.
9450 LOLR_Raw,
9451 /// The lookup found an overload set of literal operator templates,
9452 /// which expect the characters of the spelling of the literal token to be
9453 /// passed as a non-type template argument pack.
9454 LOLR_Template,
9455 /// The lookup found an overload set of literal operator templates,
9456 /// which expect the character type and characters of the spelling of the
9457 /// string literal token to be passed as template arguments.
9458 LOLR_StringTemplatePack,
9459 };
9460
9461 SpecialMemberOverloadResult
9462 LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg,
9463 bool VolatileArg, bool RValueThis, bool ConstThis,
9464 bool VolatileThis);
9465
9466 RedeclarationKind forRedeclarationInCurContext() const;
9467
9468 /// Look up a name, looking for a single declaration. Return
9469 /// null if the results were absent, ambiguous, or overloaded.
9470 ///
9471 /// It is preferable to use the elaborated form and explicitly handle
9472 /// ambiguity and overloaded.
9473 NamedDecl *LookupSingleName(
9474 Scope *S, DeclarationName Name, SourceLocation Loc,
9475 LookupNameKind NameKind,
9476 RedeclarationKind Redecl = RedeclarationKind::NotForRedeclaration);
9477
9478 /// Lookup a builtin function, when name lookup would otherwise
9479 /// fail.
9480 bool LookupBuiltin(LookupResult &R);
9481 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9482
9483 /// Perform unqualified name lookup starting from a given
9484 /// scope.
9485 ///
9486 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9487 /// used to find names within the current scope. For example, 'x' in
9488 /// @code
9489 /// int x;
9490 /// int f() {
9491 /// return x; // unqualified name look finds 'x' in the global scope
9492 /// }
9493 /// @endcode
9494 ///
9495 /// Different lookup criteria can find different names. For example, a
9496 /// particular scope can have both a struct and a function of the same
9497 /// name, and each can be found by certain lookup criteria. For more
9498 /// information about lookup criteria, see the documentation for the
9499 /// class LookupCriteria.
9500 ///
9501 /// @param S The scope from which unqualified name lookup will
9502 /// begin. If the lookup criteria permits, name lookup may also search
9503 /// in the parent scopes.
9504 ///
9505 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9506 /// look up and the lookup kind), and is updated with the results of lookup
9507 /// including zero or more declarations and possibly additional information
9508 /// used to diagnose ambiguities.
9509 ///
9510 /// @returns \c true if lookup succeeded and false otherwise.
9511 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9512 bool ForceNoCPlusPlus = false);
9513
9514 /// Perform qualified name lookup into a given context.
9515 ///
9516 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9517 /// names when the context of those names is explicit specified, e.g.,
9518 /// "std::vector" or "x->member", or as part of unqualified name lookup.
9519 ///
9520 /// Different lookup criteria can find different names. For example, a
9521 /// particular scope can have both a struct and a function of the same
9522 /// name, and each can be found by certain lookup criteria. For more
9523 /// information about lookup criteria, see the documentation for the
9524 /// class LookupCriteria.
9525 ///
9526 /// \param R captures both the lookup criteria and any lookup results found.
9527 ///
9528 /// \param LookupCtx The context in which qualified name lookup will
9529 /// search. If the lookup criteria permits, name lookup may also search
9530 /// in the parent contexts or (for C++ classes) base classes.
9531 ///
9532 /// \param InUnqualifiedLookup true if this is qualified name lookup that
9533 /// occurs as part of unqualified name lookup.
9534 ///
9535 /// \returns true if lookup succeeded, false if it failed.
9536 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9537 bool InUnqualifiedLookup = false);
9538
9539 /// Performs qualified name lookup or special type of lookup for
9540 /// "__super::" scope specifier.
9541 ///
9542 /// This routine is a convenience overload meant to be called from contexts
9543 /// that need to perform a qualified name lookup with an optional C++ scope
9544 /// specifier that might require special kind of lookup.
9545 ///
9546 /// \param R captures both the lookup criteria and any lookup results found.
9547 ///
9548 /// \param LookupCtx The context in which qualified name lookup will
9549 /// search.
9550 ///
9551 /// \param SS An optional C++ scope-specifier.
9552 ///
9553 /// \returns true if lookup succeeded, false if it failed.
9554 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9555 CXXScopeSpec &SS);
9556
9557 /// Performs name lookup for a name that was parsed in the
9558 /// source code, and may contain a C++ scope specifier.
9559 ///
9560 /// This routine is a convenience routine meant to be called from
9561 /// contexts that receive a name and an optional C++ scope specifier
9562 /// (e.g., "N::M::x"). It will then perform either qualified or
9563 /// unqualified name lookup (with LookupQualifiedName or LookupName,
9564 /// respectively) on the given name and return those results. It will
9565 /// perform a special type of lookup for "__super::" scope specifier.
9566 ///
9567 /// @param S The scope from which unqualified name lookup will
9568 /// begin.
9569 ///
9570 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
9571 ///
9572 /// @param EnteringContext Indicates whether we are going to enter the
9573 /// context of the scope-specifier SS (if present).
9574 ///
9575 /// @returns True if any decls were found (but possibly ambiguous)
9576 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
9577 QualType ObjectType, bool AllowBuiltinCreation = false,
9578 bool EnteringContext = false);
9579
9580 /// Perform qualified name lookup into all base classes of the given
9581 /// class.
9582 ///
9583 /// \param R captures both the lookup criteria and any lookup results found.
9584 ///
9585 /// \param Class The context in which qualified name lookup will
9586 /// search. Name lookup will search in all base classes merging the results.
9587 ///
9588 /// @returns True if any decls were found (but possibly ambiguous)
9589 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
9590
9591 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
9592 UnresolvedSetImpl &Functions);
9593
9594 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9595 /// If GnuLabelLoc is a valid source location, then this is a definition
9596 /// of an __label__ label name, otherwise it is a normal label definition
9597 /// or use. If IsLabelStmt is true, then this is the label of a
9598 /// labeled-statement.
9599 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
9600 SourceLocation GnuLabelLoc = SourceLocation(),
9601 bool IsLabelStmt = false);
9602
9603 /// Perform a name lookup for a label with the specified name; this does not
9604 /// create a new label if the lookup fails.
9605 LabelDecl *LookupExistingLabel(IdentifierInfo *II, SourceLocation IdentLoc);
9606
9607 /// Look up the constructors for the given class.
9608 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
9609
9610 /// Look up the default constructor for the given class.
9611 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
9612
9613 /// Look up the copying constructor for the given class.
9614 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
9615 unsigned Quals);
9616
9617 /// Look up the copying assignment operator for the given class.
9618 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
9619 bool RValueThis, unsigned ThisQuals);
9620
9621 /// Look up the moving constructor for the given class.
9622 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
9623 unsigned Quals);
9624
9625 /// Look up the moving assignment operator for the given class.
9626 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
9627 bool RValueThis, unsigned ThisQuals);
9628
9629 /// Look for the destructor of the given class.
9630 ///
9631 /// During semantic analysis, this routine should be used in lieu of
9632 /// CXXRecordDecl::getDestructor().
9633 ///
9634 /// \returns The destructor for this class.
9635 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
9636
9637 /// Force the declaration of any implicitly-declared members of this
9638 /// class.
9639 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
9640
9641 /// Make a merged definition of an existing hidden definition \p ND
9642 /// visible at the specified location.
9643 void makeMergedDefinitionVisible(NamedDecl *ND);
9644
9645 /// Check ODR hashes for C/ObjC when merging types from modules.
9646 /// Differently from C++, actually parse the body and reject in case
9647 /// of a mismatch.
9648 template <typename T,
9649 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
9650 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
9651 if (Duplicate->getODRHash() != Previous->getODRHash())
9652 return false;
9653
9654 // Make the previous decl visible.
9655 makeMergedDefinitionVisible(ND: Previous);
9656 return true;
9657 }
9658
9659 /// Get the set of additional modules that should be checked during
9660 /// name lookup. A module and its imports become visible when instanting a
9661 /// template defined within it.
9662 llvm::DenseSet<Module *> &getLookupModules();
9663
9664 bool hasVisibleMergedDefinition(const NamedDecl *Def);
9665 bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
9666
9667 /// Determine if the template parameter \p D has a visible default argument.
9668 bool
9669 hasVisibleDefaultArgument(const NamedDecl *D,
9670 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9671 /// Determine if the template parameter \p D has a reachable default argument.
9672 bool hasReachableDefaultArgument(
9673 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9674 /// Determine if the template parameter \p D has a reachable default argument.
9675 bool hasAcceptableDefaultArgument(const NamedDecl *D,
9676 llvm::SmallVectorImpl<Module *> *Modules,
9677 Sema::AcceptableKind Kind);
9678
9679 /// Determine if there is a visible declaration of \p D that is an explicit
9680 /// specialization declaration for a specialization of a template. (For a
9681 /// member specialization, use hasVisibleMemberSpecialization.)
9682 bool hasVisibleExplicitSpecialization(
9683 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9684 /// Determine if there is a reachable declaration of \p D that is an explicit
9685 /// specialization declaration for a specialization of a template. (For a
9686 /// member specialization, use hasReachableMemberSpecialization.)
9687 bool hasReachableExplicitSpecialization(
9688 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9689
9690 /// Determine if there is a visible declaration of \p D that is a member
9691 /// specialization declaration (as opposed to an instantiated declaration).
9692 bool hasVisibleMemberSpecialization(
9693 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9694 /// Determine if there is a reachable declaration of \p D that is a member
9695 /// specialization declaration (as opposed to an instantiated declaration).
9696 bool hasReachableMemberSpecialization(
9697 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9698
9699 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9700
9701 /// Determine whether any declaration of an entity is visible.
9702 bool
9703 hasVisibleDeclaration(const NamedDecl *D,
9704 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9705 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9706 }
9707
9708 bool hasVisibleDeclarationSlow(const NamedDecl *D,
9709 llvm::SmallVectorImpl<Module *> *Modules);
9710 /// Determine whether any declaration of an entity is reachable.
9711 bool
9712 hasReachableDeclaration(const NamedDecl *D,
9713 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9714 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9715 }
9716 bool hasReachableDeclarationSlow(
9717 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9718
9719 void diagnoseTypo(const TypoCorrection &Correction,
9720 const PartialDiagnostic &TypoDiag,
9721 bool ErrorRecovery = true);
9722
9723 /// Diagnose a successfully-corrected typo. Separated from the correction
9724 /// itself to allow external validation of the result, etc.
9725 ///
9726 /// \param Correction The result of performing typo correction.
9727 /// \param TypoDiag The diagnostic to produce. This will have the corrected
9728 /// string added to it (and usually also a fixit).
9729 /// \param PrevNote A note to use when indicating the location of the entity
9730 /// to which we are correcting. Will have the correction string added
9731 /// to it.
9732 /// \param ErrorRecovery If \c true (the default), the caller is going to
9733 /// recover from the typo as if the corrected string had been typed.
9734 /// In this case, \c PDiag must be an error, and we will attach a fixit
9735 /// to it.
9736 void diagnoseTypo(const TypoCorrection &Correction,
9737 const PartialDiagnostic &TypoDiag,
9738 const PartialDiagnostic &PrevNote,
9739 bool ErrorRecovery = true);
9740
9741 /// Find the associated classes and namespaces for
9742 /// argument-dependent lookup for a call with the given set of
9743 /// arguments.
9744 ///
9745 /// This routine computes the sets of associated classes and associated
9746 /// namespaces searched by argument-dependent lookup
9747 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9748 void FindAssociatedClassesAndNamespaces(
9749 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9750 AssociatedNamespaceSet &AssociatedNamespaces,
9751 AssociatedClassSet &AssociatedClasses);
9752
9753 /// Produce a diagnostic describing the ambiguity that resulted
9754 /// from name lookup.
9755 ///
9756 /// \param Result The result of the ambiguous lookup to be diagnosed.
9757 void DiagnoseAmbiguousLookup(LookupResult &Result);
9758
9759 /// LookupLiteralOperator - Determine which literal operator should be used
9760 /// for a user-defined literal, per C++11 [lex.ext].
9761 ///
9762 /// Normal overload resolution is not used to select which literal operator to
9763 /// call for a user-defined literal. Look up the provided literal operator
9764 /// name, and filter the results to the appropriate set for the given argument
9765 /// types.
9766 LiteralOperatorLookupResult
9767 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
9768 bool AllowRaw, bool AllowTemplate,
9769 bool AllowStringTemplate, bool DiagnoseMissing,
9770 StringLiteral *StringLit = nullptr);
9771
9772 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
9773 ArrayRef<Expr *> Args, ADLResult &Functions);
9774
9775 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9776 VisibleDeclConsumer &Consumer,
9777 bool IncludeGlobalScope = true,
9778 bool LoadExternal = true);
9779 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9780 VisibleDeclConsumer &Consumer,
9781 bool IncludeGlobalScope = true,
9782 bool IncludeDependentBases = false,
9783 bool LoadExternal = true);
9784
9785 /// Try to "correct" a typo in the source code by finding
9786 /// visible declarations whose names are similar to the name that was
9787 /// present in the source code.
9788 ///
9789 /// \param TypoName the \c DeclarationNameInfo structure that contains
9790 /// the name that was present in the source code along with its location.
9791 ///
9792 /// \param LookupKind the name-lookup criteria used to search for the name.
9793 ///
9794 /// \param S the scope in which name lookup occurs.
9795 ///
9796 /// \param SS the nested-name-specifier that precedes the name we're
9797 /// looking for, if present.
9798 ///
9799 /// \param CCC A CorrectionCandidateCallback object that provides further
9800 /// validation of typo correction candidates. It also provides flags for
9801 /// determining the set of keywords permitted.
9802 ///
9803 /// \param MemberContext if non-NULL, the context in which to look for
9804 /// a member access expression.
9805 ///
9806 /// \param EnteringContext whether we're entering the context described by
9807 /// the nested-name-specifier SS.
9808 ///
9809 /// \param OPT when non-NULL, the search for visible declarations will
9810 /// also walk the protocols in the qualified interfaces of \p OPT.
9811 ///
9812 /// \returns a \c TypoCorrection containing the corrected name if the typo
9813 /// along with information such as the \c NamedDecl where the corrected name
9814 /// was declared, and any additional \c NestedNameSpecifier needed to access
9815 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9816 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
9817 Sema::LookupNameKind LookupKind, Scope *S,
9818 CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9819 CorrectTypoKind Mode,
9820 DeclContext *MemberContext = nullptr,
9821 bool EnteringContext = false,
9822 const ObjCObjectPointerType *OPT = nullptr,
9823 bool RecordFailure = true);
9824
9825 /// Kinds of missing import. Note, the values of these enumerators correspond
9826 /// to %select values in diagnostics.
9827 enum class MissingImportKind {
9828 Declaration,
9829 Definition,
9830 DefaultArgument,
9831 ExplicitSpecialization,
9832 PartialSpecialization
9833 };
9834
9835 /// Diagnose that the specified declaration needs to be visible but
9836 /// isn't, and suggest a module import that would resolve the problem.
9837 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9838 MissingImportKind MIK, bool Recover = true);
9839 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9840 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
9841 MissingImportKind MIK, bool Recover);
9842
9843 /// Called on #pragma clang __debug dump II
9844 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9845
9846 /// Called on #pragma clang __debug dump E
9847 void ActOnPragmaDump(Expr *E);
9848
9849private:
9850 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
9851 //
9852 // The boolean value will be true to indicate that the namespace was loaded
9853 // from an AST/PCH file, or false otherwise.
9854 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
9855
9856 /// Whether we have already loaded known namespaces from an extenal
9857 /// source.
9858 bool LoadedExternalKnownNamespaces;
9859
9860 bool CppLookupName(LookupResult &R, Scope *S);
9861
9862 /// Determine if we could use all the declarations in the module.
9863 bool isUsableModule(const Module *M);
9864
9865 /// Helper for CorrectTypo used to create and populate a new
9866 /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
9867 /// skipped entirely.
9868 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
9869 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
9870 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9871 DeclContext *MemberContext, bool EnteringContext,
9872 const ObjCObjectPointerType *OPT, bool ErrorRecovery);
9873
9874 /// Cache for module units which is usable for current module.
9875 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
9876
9877 /// Record the typo correction failure and return an empty correction.
9878 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
9879 bool RecordFailure = true) {
9880 if (RecordFailure)
9881 TypoCorrectionFailures[Typo].insert(V: TypoLoc);
9882 return TypoCorrection();
9883 }
9884
9885 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
9886
9887 /// Determine whether two declarations should be linked together, given that
9888 /// the old declaration might not be visible and the new declaration might
9889 /// not have external linkage.
9890 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
9891 const NamedDecl *New) {
9892 if (isVisible(D: Old))
9893 return true;
9894 // See comment in below overload for why it's safe to compute the linkage
9895 // of the new declaration here.
9896 if (New->isExternallyDeclarable()) {
9897 assert(Old->isExternallyDeclarable() &&
9898 "should not have found a non-externally-declarable previous decl");
9899 return true;
9900 }
9901 return false;
9902 }
9903 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
9904
9905 ///@}
9906
9907 //
9908 //
9909 // -------------------------------------------------------------------------
9910 //
9911 //
9912
9913 /// \name Modules
9914 /// Implementations are in SemaModule.cpp
9915 ///@{
9916
9917public:
9918 /// Get the module unit whose scope we are currently within.
9919 Module *getCurrentModule() const {
9920 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
9921 }
9922
9923 /// Is the module scope we are an implementation unit?
9924 bool currentModuleIsImplementation() const {
9925 if (ModuleScopes.empty())
9926 return false;
9927 const Module *M = ModuleScopes.back().Module;
9928 return M->isModuleImplementation() || M->isModulePartitionImplementation();
9929 }
9930
9931 // When loading a non-modular PCH files, this is used to restore module
9932 // visibility.
9933 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
9934 VisibleModules.setVisible(M: Mod, Loc: ImportLoc);
9935 }
9936
9937 enum class ModuleDeclKind {
9938 Interface, ///< 'export module X;'
9939 Implementation, ///< 'module X;'
9940 PartitionInterface, ///< 'export module X:Y;'
9941 PartitionImplementation, ///< 'module X:Y;'
9942 };
9943
9944 /// An enumeration to represent the transition of states in parsing module
9945 /// fragments and imports. If we are not parsing a C++20 TU, or we find
9946 /// an error in state transition, the state is set to NotACXX20Module.
9947 enum class ModuleImportState {
9948 FirstDecl, ///< Parsing the first decl in a TU.
9949 GlobalFragment, ///< after 'module;' but before 'module X;'
9950 ImportAllowed, ///< after 'module X;' but before any non-import decl.
9951 ImportFinished, ///< after any non-import decl.
9952 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
9953 ///< non-import decl.
9954 PrivateFragmentImportFinished, ///< after 'module :private;' but a
9955 ///< non-import decl has already been seen.
9956 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
9957 };
9958
9959 /// The parser has processed a module-declaration that begins the definition
9960 /// of a module interface or implementation.
9961 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
9962 SourceLocation ModuleLoc, ModuleDeclKind MDK,
9963 ModuleIdPath Path, ModuleIdPath Partition,
9964 ModuleImportState &ImportState,
9965 bool SeenNoTrivialPPDirective);
9966
9967 /// The parser has processed a global-module-fragment declaration that begins
9968 /// the definition of the global module fragment of the current module unit.
9969 /// \param ModuleLoc The location of the 'module' keyword.
9970 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
9971
9972 /// The parser has processed a private-module-fragment declaration that begins
9973 /// the definition of the private module fragment of the current module unit.
9974 /// \param ModuleLoc The location of the 'module' keyword.
9975 /// \param PrivateLoc The location of the 'private' keyword.
9976 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
9977 SourceLocation PrivateLoc);
9978
9979 /// The parser has processed a module import declaration.
9980 ///
9981 /// \param StartLoc The location of the first token in the declaration. This
9982 /// could be the location of an '@', 'export', or 'import'.
9983 /// \param ExportLoc The location of the 'export' keyword, if any.
9984 /// \param ImportLoc The location of the 'import' keyword.
9985 /// \param Path The module toplevel name as an access path.
9986 /// \param IsPartition If the name is for a partition.
9987 DeclResult ActOnModuleImport(SourceLocation StartLoc,
9988 SourceLocation ExportLoc,
9989 SourceLocation ImportLoc, ModuleIdPath Path,
9990 bool IsPartition = false);
9991 DeclResult ActOnModuleImport(SourceLocation StartLoc,
9992 SourceLocation ExportLoc,
9993 SourceLocation ImportLoc, Module *M,
9994 ModuleIdPath Path = {});
9995
9996 /// The parser has processed a module import translated from a
9997 /// #include or similar preprocessing directive.
9998 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
9999 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10000
10001 /// The parsed has entered a submodule.
10002 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
10003 /// The parser has left a submodule.
10004 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
10005
10006 /// Create an implicit import of the given module at the given
10007 /// source location, for error recovery, if possible.
10008 ///
10009 /// This routine is typically used when an entity found by name lookup
10010 /// is actually hidden within a module that we know about but the user
10011 /// has forgotten to import.
10012 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
10013 Module *Mod);
10014
10015 /// We have parsed the start of an export declaration, including the '{'
10016 /// (if present).
10017 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
10018 SourceLocation LBraceLoc);
10019
10020 /// Complete the definition of an export declaration.
10021 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
10022 SourceLocation RBraceLoc);
10023
10024private:
10025 /// The parser has begun a translation unit to be compiled as a C++20
10026 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
10027 void HandleStartOfHeaderUnit();
10028
10029 struct ModuleScope {
10030 SourceLocation BeginLoc;
10031 clang::Module *Module = nullptr;
10032 VisibleModuleSet OuterVisibleModules;
10033 };
10034 /// The modules we're currently parsing.
10035 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
10036
10037 /// For an interface unit, this is the implicitly imported interface unit.
10038 clang::Module *ThePrimaryInterface = nullptr;
10039
10040 /// The explicit global module fragment of the current translation unit.
10041 /// The explicit Global Module Fragment, as specified in C++
10042 /// [module.global.frag].
10043 clang::Module *TheGlobalModuleFragment = nullptr;
10044
10045 /// The implicit global module fragments of the current translation unit.
10046 ///
10047 /// The contents in the implicit global module fragment can't be discarded.
10048 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
10049
10050 /// Namespace definitions that we will export when they finish.
10051 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
10052
10053 /// In a C++ standard module, inline declarations require a definition to be
10054 /// present at the end of a definition domain. This set holds the decls to
10055 /// be checked at the end of the TU.
10056 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
10057
10058 /// Helper function to judge if we are in module purview.
10059 /// Return false if we are not in a module.
10060 bool isCurrentModulePurview() const;
10061
10062 /// Enter the scope of the explicit global module fragment.
10063 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
10064 /// Leave the scope of the explicit global module fragment.
10065 void PopGlobalModuleFragment();
10066
10067 /// Enter the scope of an implicit global module fragment.
10068 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
10069 /// Leave the scope of an implicit global module fragment.
10070 void PopImplicitGlobalModuleFragment();
10071
10072 VisibleModuleSet VisibleModules;
10073
10074 /// Whether we had imported any named modules.
10075 bool HadImportedNamedModules = false;
10076 /// The set of instantiations we need to check if they references TU-local
10077 /// entity from TUs. This only makes sense if we imported any named modules.
10078 llvm::SmallVector<std::pair<FunctionDecl *, SourceLocation>>
10079 PendingCheckReferenceForTULocal;
10080 /// Implement [basic.link]p18, which requires that we can't use TU-local
10081 /// entities from other TUs (ignoring header units).
10082 void checkReferenceToTULocalFromOtherTU(FunctionDecl *FD,
10083 SourceLocation PointOfInstantiation);
10084 /// Implement [basic.link]p17, which diagnose for non TU local exposure in
10085 /// module interface or module partition.
10086 void checkExposure(const TranslationUnitDecl *TU);
10087
10088 ///@}
10089
10090 //
10091 //
10092 // -------------------------------------------------------------------------
10093 //
10094 //
10095
10096 /// \name C++ Overloading
10097 /// Implementations are in SemaOverload.cpp
10098 ///@{
10099
10100public:
10101 /// Whether deferrable diagnostics should be deferred.
10102 bool DeferDiags = false;
10103
10104 /// RAII class to control scope of DeferDiags.
10105 class DeferDiagsRAII {
10106 Sema &S;
10107 bool SavedDeferDiags = false;
10108
10109 public:
10110 DeferDiagsRAII(Sema &S, bool DeferDiags)
10111 : S(S), SavedDeferDiags(S.DeferDiags) {
10112 S.DeferDiags = SavedDeferDiags || DeferDiags;
10113 }
10114 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
10115 DeferDiagsRAII(const DeferDiagsRAII &) = delete;
10116 DeferDiagsRAII &operator=(const DeferDiagsRAII &) = delete;
10117 };
10118
10119 /// Flag indicating if Sema is building a recovery call expression.
10120 ///
10121 /// This flag is used to avoid building recovery call expressions
10122 /// if Sema is already doing so, which would cause infinite recursions.
10123 bool IsBuildingRecoveryCallExpr;
10124
10125 /// Determine whether the given New declaration is an overload of the
10126 /// declarations in Old. This routine returns OverloadKind::Match or
10127 /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
10128 /// New has the same signature as some function in Old (C++ 1.3.10) or if the
10129 /// Old declarations aren't functions (or function templates) at all. When it
10130 /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
10131 /// will point to the decl that New cannot be overloaded with. This decl may
10132 /// be a UsingShadowDecl on top of the underlying declaration.
10133 ///
10134 /// Example: Given the following input:
10135 ///
10136 /// void f(int, float); // #1
10137 /// void f(int, int); // #2
10138 /// int f(int, int); // #3
10139 ///
10140 /// When we process #1, there is no previous declaration of "f", so IsOverload
10141 /// will not be used.
10142 ///
10143 /// When we process #2, Old contains only the FunctionDecl for #1. By
10144 /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10145 /// they have different signatures), so this routine returns
10146 /// OverloadKind::Overload; MatchedDecl is unchanged.
10147 ///
10148 /// When we process #3, Old is an overload set containing #1 and #2. We
10149 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10150 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10151 /// types of functions are not part of the signature), IsOverload returns
10152 /// OverloadKind::Match and MatchedDecl will be set to point to the
10153 /// FunctionDecl for #2.
10154 ///
10155 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10156 /// class by a using declaration. The rules for whether to hide shadow
10157 /// declarations ignore some properties which otherwise figure into a function
10158 /// template's signature.
10159 OverloadKind CheckOverload(Scope *S, FunctionDecl *New,
10160 const LookupResult &OldDecls, NamedDecl *&OldDecl,
10161 bool UseMemberUsingDeclRules);
10162 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
10163 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10164
10165 // Checks whether MD constitutes an override the base class method BaseMD.
10166 // When checking for overrides, the object object members are ignored.
10167 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10168 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10169
10170 enum class AllowedExplicit {
10171 /// Allow no explicit functions to be used.
10172 None,
10173 /// Allow explicit conversion functions but not explicit constructors.
10174 Conversions,
10175 /// Allow both explicit conversion functions and explicit constructors.
10176 All
10177 };
10178
10179 ImplicitConversionSequence TryImplicitConversion(
10180 Expr *From, QualType ToType, bool SuppressUserConversions,
10181 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10182 bool AllowObjCWritebackConversion);
10183
10184 /// PerformImplicitConversion - Perform an implicit conversion of the
10185 /// expression From to the type ToType. Returns the
10186 /// converted expression. Flavor is the kind of conversion we're
10187 /// performing, used in the error message. If @p AllowExplicit,
10188 /// explicit user-defined conversions are permitted.
10189 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10190 AssignmentAction Action,
10191 bool AllowExplicit = false);
10192
10193 /// IsIntegralPromotion - Determines whether the conversion from the
10194 /// expression From (whose potentially-adjusted type is FromType) to
10195 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10196 /// sets PromotedType to the promoted type.
10197 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10198
10199 /// IsFloatingPointPromotion - Determines whether the conversion from
10200 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10201 /// returns true and sets PromotedType to the promoted type.
10202 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10203
10204 /// Determine if a conversion is a complex promotion.
10205 ///
10206 /// A complex promotion is defined as a complex -> complex conversion
10207 /// where the conversion between the underlying real types is a
10208 /// floating-point or integral promotion.
10209 bool IsComplexPromotion(QualType FromType, QualType ToType);
10210
10211 /// IsOverflowBehaviorTypePromotion - Determines whether the conversion from
10212 /// FromType to ToType involves an OverflowBehaviorType FromType being
10213 /// promoted to an OverflowBehaviorType ToType which has a larger bitwidth.
10214 /// If so, returns true and sets FromType to ToType.
10215 bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType);
10216
10217 /// IsOverflowBehaviorTypeConversion - Determines whether the conversion from
10218 /// FromType to ToType necessarily involves both an OverflowBehaviorType and
10219 /// a non-OverflowBehaviorType. If so, returns true and sets FromType to
10220 /// ToType.
10221 bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType);
10222
10223 /// IsPointerConversion - Determines whether the conversion of the
10224 /// expression From, which has the (possibly adjusted) type FromType,
10225 /// can be converted to the type ToType via a pointer conversion (C++
10226 /// 4.10). If so, returns true and places the converted type (that
10227 /// might differ from ToType in its cv-qualifiers at some level) into
10228 /// ConvertedType.
10229 ///
10230 /// This routine also supports conversions to and from block pointers
10231 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10232 /// pointers to interfaces. FIXME: Once we've determined the
10233 /// appropriate overloading rules for Objective-C, we may want to
10234 /// split the Objective-C checks into a different routine; however,
10235 /// GCC seems to consider all of these conversions to be pointer
10236 /// conversions, so for now they live here. IncompatibleObjC will be
10237 /// set if the conversion is an allowed Objective-C conversion that
10238 /// should result in a warning.
10239 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10240 bool InOverloadResolution, QualType &ConvertedType,
10241 bool &IncompatibleObjC);
10242
10243 /// isObjCPointerConversion - Determines whether this is an
10244 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10245 /// with the same arguments and return values.
10246 bool isObjCPointerConversion(QualType FromType, QualType ToType,
10247 QualType &ConvertedType, bool &IncompatibleObjC);
10248 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10249 QualType &ConvertedType);
10250
10251 /// FunctionParamTypesAreEqual - This routine checks two function proto types
10252 /// for equality of their parameter types. Caller has already checked that
10253 /// they have same number of parameters. If the parameters are different,
10254 /// ArgPos will have the parameter index of the first different parameter.
10255 /// If `Reversed` is true, the parameters of `NewType` will be compared in
10256 /// reverse order. That's useful if one of the functions is being used as a
10257 /// C++20 synthesized operator overload with a reversed parameter order.
10258 bool FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
10259 ArrayRef<QualType> New,
10260 unsigned *ArgPos = nullptr,
10261 bool Reversed = false);
10262
10263 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
10264 const FunctionProtoType *NewType,
10265 unsigned *ArgPos = nullptr,
10266 bool Reversed = false);
10267
10268 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10269 const FunctionDecl *NewFunction,
10270 unsigned *ArgPos = nullptr,
10271 bool Reversed = false);
10272
10273 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10274 /// function types. Catches different number of parameter, mismatch in
10275 /// parameter types, and different return types.
10276 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType,
10277 QualType ToType);
10278
10279 /// CheckPointerConversion - Check the pointer conversion from the
10280 /// expression From to the type ToType. This routine checks for
10281 /// ambiguous or inaccessible derived-to-base pointer
10282 /// conversions for which IsPointerConversion has already returned
10283 /// true. It returns true and produces a diagnostic if there was an
10284 /// error, or returns false otherwise.
10285 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10286 CXXCastPath &BasePath, bool IgnoreBaseAccess,
10287 bool Diagnose = true);
10288
10289 /// IsMemberPointerConversion - Determines whether the conversion of the
10290 /// expression From, which has the (possibly adjusted) type FromType, can be
10291 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10292 /// If so, returns true and places the converted type (that might differ from
10293 /// ToType in its cv-qualifiers at some level) into ConvertedType.
10294 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10295 bool InOverloadResolution,
10296 QualType &ConvertedType);
10297
10298 enum class MemberPointerConversionResult {
10299 Success,
10300 DifferentPointee,
10301 NotDerived,
10302 Ambiguous,
10303 Virtual,
10304 Inaccessible
10305 };
10306 enum class MemberPointerConversionDirection : bool { Downcast, Upcast };
10307 /// CheckMemberPointerConversion - Check the member pointer conversion from
10308 /// the expression From to the type ToType. This routine checks for ambiguous
10309 /// or virtual or inaccessible base-to-derived member pointer conversions for
10310 /// which IsMemberPointerConversion has already returned true. It produces a
10311 // diagnostic if there was an error.
10312 MemberPointerConversionResult CheckMemberPointerConversion(
10313 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10314 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10315 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10316
10317 /// IsQualificationConversion - Determines whether the conversion from
10318 /// an rvalue of type FromType to ToType is a qualification conversion
10319 /// (C++ 4.4).
10320 ///
10321 /// \param ObjCLifetimeConversion Output parameter that will be set to
10322 /// indicate when the qualification conversion involves a change in the
10323 /// Objective-C object lifetime.
10324 bool IsQualificationConversion(QualType FromType, QualType ToType,
10325 bool CStyle, bool &ObjCLifetimeConversion);
10326
10327 /// Determine whether the conversion from FromType to ToType is a valid
10328 /// conversion of ExtInfo/ExtProtoInfo on the nested function type.
10329 /// More precisely, this method checks whether FromType can be transformed
10330 /// into an exact match for ToType, by transforming its extended function
10331 /// type information in legal manner (e.g. by strictly stripping "noreturn"
10332 /// or "noexcept", or by stripping "noescape" for arguments).
10333 bool IsFunctionConversion(QualType FromType, QualType ToType) const;
10334
10335 /// Same as `IsFunctionConversion`, but if this would return true, it sets
10336 /// `ResultTy` to `ToType`.
10337 bool TryFunctionConversion(QualType FromType, QualType ToType,
10338 QualType &ResultTy) const;
10339
10340 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
10341 void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
10342 DeclarationName Name,
10343 OverloadCandidateSet &CandidateSet,
10344 FunctionDecl *Fn, MultiExprArg Args,
10345 bool IsMember = false);
10346
10347 ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
10348 FunctionDecl *Fun);
10349 ExprResult PerformImplicitObjectArgumentInitialization(
10350 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
10351 CXXMethodDecl *Method);
10352
10353 /// PerformContextuallyConvertToBool - Perform a contextual conversion
10354 /// of the expression From to bool (C++0x [conv]p3).
10355 ExprResult PerformContextuallyConvertToBool(Expr *From);
10356
10357 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10358 /// conversion of the expression From to an Objective-C pointer type.
10359 /// Returns a valid but null ExprResult if no conversion sequence exists.
10360 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
10361
10362 ExprResult BuildConvertedConstantExpression(Expr *From, QualType T,
10363 CCEKind CCE,
10364 NamedDecl *Dest = nullptr);
10365
10366 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10367 llvm::APSInt &Value, CCEKind CCE);
10368 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10369 APValue &Value, CCEKind CCE,
10370 NamedDecl *Dest = nullptr);
10371
10372 /// EvaluateConvertedConstantExpression - Evaluate an Expression
10373 /// That is a converted constant expression
10374 /// (which was built with BuildConvertedConstantExpression)
10375 ExprResult
10376 EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
10377 CCEKind CCE, bool RequireInt,
10378 const APValue &PreNarrowingValue);
10379
10380 /// Abstract base class used to perform a contextual implicit
10381 /// conversion from an expression to any type passing a filter.
10382 class ContextualImplicitConverter {
10383 public:
10384 bool Suppress;
10385 bool SuppressConversion;
10386
10387 ContextualImplicitConverter(bool Suppress = false,
10388 bool SuppressConversion = false)
10389 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
10390
10391 /// Determine whether the specified type is a valid destination type
10392 /// for this conversion.
10393 virtual bool match(QualType T) = 0;
10394
10395 /// Emits a diagnostic complaining that the expression does not have
10396 /// integral or enumeration type.
10397 virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10398 QualType T) = 0;
10399
10400 /// Emits a diagnostic when the expression has incomplete class type.
10401 virtual SemaDiagnosticBuilder
10402 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
10403
10404 /// Emits a diagnostic when the only matching conversion function
10405 /// is explicit.
10406 virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S,
10407 SourceLocation Loc,
10408 QualType T,
10409 QualType ConvTy) = 0;
10410
10411 /// Emits a note for the explicit conversion function.
10412 virtual SemaDiagnosticBuilder
10413 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10414
10415 /// Emits a diagnostic when there are multiple possible conversion
10416 /// functions.
10417 virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10418 QualType T) = 0;
10419
10420 /// Emits a note for one of the candidate conversions.
10421 virtual SemaDiagnosticBuilder
10422 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10423
10424 /// Emits a diagnostic when we picked a conversion function
10425 /// (for cases when we are not allowed to pick a conversion function).
10426 virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S,
10427 SourceLocation Loc,
10428 QualType T,
10429 QualType ConvTy) = 0;
10430
10431 virtual ~ContextualImplicitConverter() {}
10432 };
10433
10434 class ICEConvertDiagnoser : public ContextualImplicitConverter {
10435 bool AllowScopedEnumerations;
10436
10437 public:
10438 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10439 bool SuppressConversion)
10440 : ContextualImplicitConverter(Suppress, SuppressConversion),
10441 AllowScopedEnumerations(AllowScopedEnumerations) {}
10442
10443 /// Match an integral or (possibly scoped) enumeration type.
10444 bool match(QualType T) override;
10445
10446 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10447 QualType T) override {
10448 return diagnoseNotInt(S, Loc, T);
10449 }
10450
10451 /// Emits a diagnostic complaining that the expression does not have
10452 /// integral or enumeration type.
10453 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10454 QualType T) = 0;
10455 };
10456
10457 /// Perform a contextual implicit conversion.
10458 ExprResult
10459 PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE,
10460 ContextualImplicitConverter &Converter);
10461
10462 /// ReferenceCompareResult - Expresses the result of comparing two
10463 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10464 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10465 enum ReferenceCompareResult {
10466 /// Ref_Incompatible - The two types are incompatible, so direct
10467 /// reference binding is not possible.
10468 Ref_Incompatible = 0,
10469 /// Ref_Related - The two types are reference-related, which means
10470 /// that their unqualified forms (T1 and T2) are either the same
10471 /// or T1 is a base class of T2.
10472 Ref_Related,
10473 /// Ref_Compatible - The two types are reference-compatible.
10474 Ref_Compatible
10475 };
10476
10477 // Fake up a scoped enumeration that still contextually converts to bool.
10478 struct ReferenceConversionsScope {
10479 /// The conversions that would be performed on an lvalue of type T2 when
10480 /// binding a reference of type T1 to it, as determined when evaluating
10481 /// whether T1 is reference-compatible with T2.
10482 enum ReferenceConversions {
10483 Qualification = 0x1,
10484 NestedQualification = 0x2,
10485 Function = 0x4,
10486 DerivedToBase = 0x8,
10487 ObjC = 0x10,
10488 ObjCLifetime = 0x20,
10489
10490 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
10491 };
10492 };
10493 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
10494
10495 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10496 /// determine whether they are reference-compatible,
10497 /// reference-related, or incompatible, for use in C++ initialization by
10498 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10499 /// type, and the first type (T1) is the pointee type of the reference
10500 /// type being initialized.
10501 ReferenceCompareResult
10502 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
10503 ReferenceConversions *Conv = nullptr);
10504
10505 /// AddOverloadCandidate - Adds the given function to the set of
10506 /// candidate functions, using the given function call arguments. If
10507 /// @p SuppressUserConversions, then don't allow user-defined
10508 /// conversions via constructors or conversion operators.
10509 ///
10510 /// \param PartialOverloading true if we are performing "partial" overloading
10511 /// based on an incomplete set of function arguments. This feature is used by
10512 /// code completion.
10513 void AddOverloadCandidate(
10514 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
10515 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10516 bool PartialOverloading = false, bool AllowExplicit = true,
10517 bool AllowExplicitConversion = false,
10518 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10519 ConversionSequenceList EarlyConversions = {},
10520 OverloadCandidateParamOrder PO = {},
10521 bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10522
10523 /// Add all of the function declarations in the given function set to
10524 /// the overload candidate set.
10525 void AddFunctionCandidates(
10526 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10527 OverloadCandidateSet &CandidateSet,
10528 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10529 bool SuppressUserConversions = false, bool PartialOverloading = false,
10530 bool FirstArgumentIsBase = false);
10531
10532 /// AddMethodCandidate - Adds a named decl (which is some kind of
10533 /// method) as a method candidate to the given overload set.
10534 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10535 Expr::Classification ObjectClassification,
10536 ArrayRef<Expr *> Args,
10537 OverloadCandidateSet &CandidateSet,
10538 bool SuppressUserConversion = false,
10539 OverloadCandidateParamOrder PO = {});
10540
10541 /// AddMethodCandidate - Adds the given C++ member function to the set
10542 /// of candidate functions, using the given function call arguments
10543 /// and the object argument (@c Object). For example, in a call
10544 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10545 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10546 /// allow user-defined conversions via constructors or conversion
10547 /// operators.
10548 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10549 CXXRecordDecl *ActingContext, QualType ObjectType,
10550 Expr::Classification ObjectClassification,
10551 ArrayRef<Expr *> Args,
10552 OverloadCandidateSet &CandidateSet,
10553 bool SuppressUserConversions = false,
10554 bool PartialOverloading = false,
10555 ConversionSequenceList EarlyConversions = {},
10556 OverloadCandidateParamOrder PO = {},
10557 bool StrictPackMatch = false);
10558
10559 /// Add a C++ member function template as a candidate to the candidate
10560 /// set, using template argument deduction to produce an appropriate member
10561 /// function template specialization.
10562 void AddMethodTemplateCandidate(
10563 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10564 CXXRecordDecl *ActingContext,
10565 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10566 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10567 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10568 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10569
10570 /// Add a C++ function template specialization as a candidate
10571 /// in the candidate set, using template argument deduction to produce
10572 /// an appropriate function template specialization.
10573 void AddTemplateOverloadCandidate(
10574 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10575 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10576 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10577 bool PartialOverloading = false, bool AllowExplicit = true,
10578 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10579 OverloadCandidateParamOrder PO = {},
10580 bool AggregateCandidateDeduction = false);
10581
10582 struct CheckNonDependentConversionsFlag {
10583 /// Do not consider any user-defined conversions when constructing the
10584 /// initializing sequence.
10585 bool SuppressUserConversions;
10586
10587 /// Before constructing the initializing sequence, we check whether the
10588 /// parameter type and argument type contain any user defined conversions.
10589 /// If so, do not initialize them. This effectively bypasses some undesired
10590 /// instantiation before checking constaints, which might otherwise result
10591 /// in non-SFINAE errors e.g. recursive constraints.
10592 bool OnlyInitializeNonUserDefinedConversions;
10593
10594 CheckNonDependentConversionsFlag(
10595 bool SuppressUserConversions,
10596 bool OnlyInitializeNonUserDefinedConversions)
10597 : SuppressUserConversions(SuppressUserConversions),
10598 OnlyInitializeNonUserDefinedConversions(
10599 OnlyInitializeNonUserDefinedConversions) {}
10600 };
10601
10602 /// Check that implicit conversion sequences can be formed for each argument
10603 /// whose corresponding parameter has a non-dependent type, per DR1391's
10604 /// [temp.deduct.call]p10.
10605 bool CheckNonDependentConversions(
10606 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
10607 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10608 ConversionSequenceList &Conversions,
10609 CheckNonDependentConversionsFlag UserConversionFlag,
10610 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10611 Expr::Classification ObjectClassification = {},
10612 OverloadCandidateParamOrder PO = {});
10613
10614 /// AddConversionCandidate - Add a C++ conversion function as a
10615 /// candidate in the candidate set (C++ [over.match.conv],
10616 /// C++ [over.match.copy]). From is the expression we're converting from,
10617 /// and ToType is the type that we're eventually trying to convert to
10618 /// (which may or may not be the same type as the type that the
10619 /// conversion function produces).
10620 void AddConversionCandidate(
10621 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10622 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10623 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10624 bool AllowExplicit, bool AllowResultConversion = true,
10625 bool StrictPackMatch = false);
10626
10627 /// Adds a conversion function template specialization
10628 /// candidate to the overload set, using template argument deduction
10629 /// to deduce the template arguments of the conversion function
10630 /// template from the type that we are converting to (C++
10631 /// [temp.deduct.conv]).
10632 void AddTemplateConversionCandidate(
10633 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10634 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10635 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10636 bool AllowExplicit, bool AllowResultConversion = true);
10637
10638 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10639 /// converts the given @c Object to a function pointer via the
10640 /// conversion function @c Conversion, and then attempts to call it
10641 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10642 /// the type of function that we'll eventually be calling.
10643 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10644 DeclAccessPair FoundDecl,
10645 CXXRecordDecl *ActingContext,
10646 const FunctionProtoType *Proto, Expr *Object,
10647 ArrayRef<Expr *> Args,
10648 OverloadCandidateSet &CandidateSet);
10649
10650 /// Add all of the non-member operator function declarations in the given
10651 /// function set to the overload candidate set.
10652 void AddNonMemberOperatorCandidates(
10653 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10654 OverloadCandidateSet &CandidateSet,
10655 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10656
10657 /// Add overload candidates for overloaded operators that are
10658 /// member functions.
10659 ///
10660 /// Add the overloaded operator candidates that are member functions
10661 /// for the operator Op that was used in an operator expression such
10662 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10663 /// CandidateSet will store the added overload candidates. (C++
10664 /// [over.match.oper]).
10665 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
10666 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10667 OverloadCandidateSet &CandidateSet,
10668 OverloadCandidateParamOrder PO = {});
10669
10670 /// AddBuiltinCandidate - Add a candidate for a built-in
10671 /// operator. ResultTy and ParamTys are the result and parameter types
10672 /// of the built-in candidate, respectively. Args and NumArgs are the
10673 /// arguments being passed to the candidate. IsAssignmentOperator
10674 /// should be true when this built-in candidate is an assignment
10675 /// operator. NumContextualBoolArguments is the number of arguments
10676 /// (at the beginning of the argument list) that will be contextually
10677 /// converted to bool.
10678 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10679 OverloadCandidateSet &CandidateSet,
10680 bool IsAssignmentOperator = false,
10681 unsigned NumContextualBoolArguments = 0);
10682
10683 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10684 /// operator overloads to the candidate set (C++ [over.built]), based
10685 /// on the operator @p Op and the arguments given. For example, if the
10686 /// operator is a binary '+', this routine might add "int
10687 /// operator+(int, int)" to cover integer addition.
10688 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10689 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10690 OverloadCandidateSet &CandidateSet);
10691
10692 /// Add function candidates found via argument-dependent lookup
10693 /// to the set of overloading candidates.
10694 ///
10695 /// This routine performs argument-dependent name lookup based on the
10696 /// given function name (which may also be an operator name) and adds
10697 /// all of the overload candidates found by ADL to the overload
10698 /// candidate set (C++ [basic.lookup.argdep]).
10699 void AddArgumentDependentLookupCandidates(
10700 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10701 TemplateArgumentListInfo *ExplicitTemplateArgs,
10702 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10703
10704 /// Check the enable_if expressions on the given function. Returns the first
10705 /// failing attribute, or NULL if they were all successful.
10706 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10707 ArrayRef<Expr *> Args,
10708 bool MissingImplicitThis = false);
10709
10710 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10711 /// non-ArgDependent DiagnoseIfAttrs.
10712 ///
10713 /// Argument-dependent diagnose_if attributes should be checked each time a
10714 /// function is used as a direct callee of a function call.
10715 ///
10716 /// Returns true if any errors were emitted.
10717 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10718 const Expr *ThisArg,
10719 ArrayRef<const Expr *> Args,
10720 SourceLocation Loc);
10721
10722 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10723 /// ArgDependent DiagnoseIfAttrs.
10724 ///
10725 /// Argument-independent diagnose_if attributes should be checked on every use
10726 /// of a function.
10727 ///
10728 /// Returns true if any errors were emitted.
10729 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10730 SourceLocation Loc);
10731
10732 /// Determine if \p A and \p B are equivalent internal linkage declarations
10733 /// from different modules, and thus an ambiguity error can be downgraded to
10734 /// an extension warning.
10735 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10736 const NamedDecl *B);
10737 void diagnoseEquivalentInternalLinkageDeclarations(
10738 SourceLocation Loc, const NamedDecl *D,
10739 ArrayRef<const NamedDecl *> Equiv);
10740
10741 // Emit as a 'note' the specific overload candidate
10742 void NoteOverloadCandidate(
10743 const NamedDecl *Found, const FunctionDecl *Fn,
10744 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
10745 QualType DestType = QualType(), bool TakingAddress = false);
10746
10747 // Emit as a series of 'note's all template and non-templates identified by
10748 // the expression Expr
10749 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10750 bool TakingAddress = false);
10751
10752 /// Returns whether the given function's address can be taken or not,
10753 /// optionally emitting a diagnostic if the address can't be taken.
10754 ///
10755 /// Returns false if taking the address of the function is illegal.
10756 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10757 bool Complain = false,
10758 SourceLocation Loc = SourceLocation());
10759
10760 // [PossiblyAFunctionType] --> [Return]
10761 // NonFunctionType --> NonFunctionType
10762 // R (A) --> R(A)
10763 // R (*)(A) --> R (A)
10764 // R (&)(A) --> R (A)
10765 // R (S::*)(A) --> R (A)
10766 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10767
10768 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10769 /// an overloaded function (C++ [over.over]), where @p From is an
10770 /// expression with overloaded function type and @p ToType is the type
10771 /// we're trying to resolve to. For example:
10772 ///
10773 /// @code
10774 /// int f(double);
10775 /// int f(int);
10776 ///
10777 /// int (*pfd)(double) = f; // selects f(double)
10778 /// @endcode
10779 ///
10780 /// This routine returns the resulting FunctionDecl if it could be
10781 /// resolved, and NULL otherwise. When @p Complain is true, this
10782 /// routine will emit diagnostics if there is an error.
10783 FunctionDecl *
10784 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10785 bool Complain, DeclAccessPair &Found,
10786 bool *pHadMultipleCandidates = nullptr);
10787
10788 /// Given an expression that refers to an overloaded function, try to
10789 /// resolve that function to a single function that can have its address
10790 /// taken. This will modify `Pair` iff it returns non-null.
10791 ///
10792 /// This routine can only succeed if from all of the candidates in the
10793 /// overload set for SrcExpr that can have their addresses taken, there is one
10794 /// candidate that is more constrained than the rest.
10795 FunctionDecl *
10796 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10797
10798 /// Given an overloaded function, tries to turn it into a non-overloaded
10799 /// function reference using resolveAddressOfSingleOverloadCandidate. This
10800 /// will perform access checks, diagnose the use of the resultant decl, and,
10801 /// if requested, potentially perform a function-to-pointer decay.
10802 ///
10803 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10804 /// Otherwise, returns true. This may emit diagnostics and return true.
10805 bool resolveAndFixAddressOfSingleOverloadCandidate(
10806 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10807
10808 /// Given an expression that refers to an overloaded function, try to
10809 /// resolve that overloaded function expression down to a single function.
10810 ///
10811 /// This routine can only resolve template-ids that refer to a single function
10812 /// template, where that template-id refers to a single template whose
10813 /// template arguments are either provided by the template-id or have
10814 /// defaults, as described in C++0x [temp.arg.explicit]p3.
10815 ///
10816 /// If no template-ids are found, no diagnostics are emitted and NULL is
10817 /// returned.
10818 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(
10819 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10820 TemplateSpecCandidateSet *FailedTSC = nullptr,
10821 bool ForTypeDeduction = false);
10822
10823 // Resolve and fix an overloaded expression that can be resolved
10824 // because it identifies a single function template specialization.
10825 //
10826 // Last three arguments should only be supplied if Complain = true
10827 //
10828 // Return true if it was logically possible to so resolve the
10829 // expression, regardless of whether or not it succeeded. Always
10830 // returns true if 'complain' is set.
10831 bool ResolveAndFixSingleFunctionTemplateSpecialization(
10832 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10833 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10834 QualType DestTypeForComplaining = QualType(),
10835 unsigned DiagIDForComplaining = 0);
10836
10837 /// Add the overload candidates named by callee and/or found by argument
10838 /// dependent lookup to the given overload set.
10839 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10840 ArrayRef<Expr *> Args,
10841 OverloadCandidateSet &CandidateSet,
10842 bool PartialOverloading = false);
10843
10844 /// Add the call candidates from the given set of lookup results to the given
10845 /// overload set. Non-function lookup results are ignored.
10846 void AddOverloadedCallCandidates(
10847 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
10848 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
10849
10850 // An enum used to represent the different possible results of building a
10851 // range-based for loop.
10852 enum ForRangeStatus {
10853 FRS_Success,
10854 FRS_NoViableFunction,
10855 FRS_DiagnosticIssued
10856 };
10857
10858 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
10859 /// given LookupResult is non-empty, it is assumed to describe a member which
10860 /// will be invoked. Otherwise, the function will be found via argument
10861 /// dependent lookup.
10862 /// CallExpr is set to a valid expression and FRS_Success returned on success,
10863 /// otherwise CallExpr is set to ExprError() and some non-success value
10864 /// is returned.
10865 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
10866 SourceLocation RangeLoc,
10867 const DeclarationNameInfo &NameInfo,
10868 LookupResult &MemberLookup,
10869 OverloadCandidateSet *CandidateSet,
10870 Expr *Range, ExprResult *CallExpr);
10871
10872 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10873 /// (which eventually refers to the declaration Func) and the call
10874 /// arguments Args/NumArgs, attempt to resolve the function call down
10875 /// to a specific function. If overload resolution succeeds, returns
10876 /// the call expression produced by overload resolution.
10877 /// Otherwise, emits diagnostics and returns ExprError.
10878 ExprResult BuildOverloadedCallExpr(
10879 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
10880 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
10881 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
10882
10883 /// Constructs and populates an OverloadedCandidateSet from
10884 /// the given function.
10885 /// \returns true when an the ExprResult output parameter has been set.
10886 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
10887 MultiExprArg Args, SourceLocation RParenLoc,
10888 OverloadCandidateSet *CandidateSet,
10889 ExprResult *Result);
10890
10891 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
10892 NestedNameSpecifierLoc NNSLoc,
10893 DeclarationNameInfo DNI,
10894 const UnresolvedSetImpl &Fns,
10895 bool PerformADL = true);
10896
10897 /// Perform lookup for an overloaded unary operator.
10898 void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet,
10899 OverloadedOperatorKind Op,
10900 const UnresolvedSetImpl &Fns,
10901 ArrayRef<Expr *> Args, bool RequiresADL = true);
10902
10903 /// Create a unary operation that may resolve to an overloaded
10904 /// operator.
10905 ///
10906 /// \param OpLoc The location of the operator itself (e.g., '*').
10907 ///
10908 /// \param Opc The UnaryOperatorKind that describes this operator.
10909 ///
10910 /// \param Fns The set of non-member functions that will be
10911 /// considered by overload resolution. The caller needs to build this
10912 /// set based on the context using, e.g.,
10913 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10914 /// set should not contain any member functions; those will be added
10915 /// by CreateOverloadedUnaryOp().
10916 ///
10917 /// \param Input The input argument.
10918 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
10919 UnaryOperatorKind Opc,
10920 const UnresolvedSetImpl &Fns, Expr *input,
10921 bool RequiresADL = true);
10922
10923 /// Perform lookup for an overloaded binary operator.
10924 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
10925 OverloadedOperatorKind Op,
10926 const UnresolvedSetImpl &Fns,
10927 ArrayRef<Expr *> Args, bool RequiresADL = true);
10928
10929 /// Create a binary operation that may resolve to an overloaded
10930 /// operator.
10931 ///
10932 /// \param OpLoc The location of the operator itself (e.g., '+').
10933 ///
10934 /// \param Opc The BinaryOperatorKind that describes this operator.
10935 ///
10936 /// \param Fns The set of non-member functions that will be
10937 /// considered by overload resolution. The caller needs to build this
10938 /// set based on the context using, e.g.,
10939 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10940 /// set should not contain any member functions; those will be added
10941 /// by CreateOverloadedBinOp().
10942 ///
10943 /// \param LHS Left-hand argument.
10944 /// \param RHS Right-hand argument.
10945 /// \param PerformADL Whether to consider operator candidates found by ADL.
10946 /// \param AllowRewrittenCandidates Whether to consider candidates found by
10947 /// C++20 operator rewrites.
10948 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
10949 /// the function in question. Such a function is never a candidate in
10950 /// our overload resolution. This also enables synthesizing a three-way
10951 /// comparison from < and == as described in C++20 [class.spaceship]p1.
10952 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
10953 const UnresolvedSetImpl &Fns, Expr *LHS,
10954 Expr *RHS, bool RequiresADL = true,
10955 bool AllowRewrittenCandidates = true,
10956 FunctionDecl *DefaultedFn = nullptr);
10957 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
10958 const UnresolvedSetImpl &Fns,
10959 Expr *LHS, Expr *RHS,
10960 FunctionDecl *DefaultedFn);
10961
10962 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10963 SourceLocation RLoc, Expr *Base,
10964 MultiExprArg Args);
10965
10966 /// BuildCallToMemberFunction - Build a call to a member
10967 /// function. MemExpr is the expression that refers to the member
10968 /// function (and includes the object parameter), Args/NumArgs are the
10969 /// arguments to the function call (not including the object
10970 /// parameter). The caller needs to validate that the member
10971 /// expression refers to a non-static member function or an overloaded
10972 /// member function.
10973 ExprResult BuildCallToMemberFunction(
10974 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
10975 SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
10976 bool IsExecConfig = false, bool AllowRecovery = false);
10977
10978 /// BuildCallToObjectOfClassType - Build a call to an object of class
10979 /// type (C++ [over.call.object]), which can end up invoking an
10980 /// overloaded function call operator (@c operator()) or performing a
10981 /// user-defined conversion on the object argument.
10982 ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object,
10983 SourceLocation LParenLoc,
10984 MultiExprArg Args,
10985 SourceLocation RParenLoc);
10986
10987 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
10988 /// (if one exists), where @c Base is an expression of class type and
10989 /// @c Member is the name of the member we're trying to find.
10990 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
10991 SourceLocation OpLoc,
10992 bool *NoArrowOperatorFound = nullptr);
10993
10994 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
10995 CXXConversionDecl *Method,
10996 bool HadMultipleCandidates);
10997
10998 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
10999 /// to a literal operator described by the provided lookup results.
11000 ExprResult BuildLiteralOperatorCall(
11001 LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args,
11002 SourceLocation LitEndLoc,
11003 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
11004
11005 /// FixOverloadedFunctionReference - E is an expression that refers to
11006 /// a C++ overloaded function (possibly with some parentheses and
11007 /// perhaps a '&' around it). We have resolved the overloaded function
11008 /// to the function declaration Fn, so patch up the expression E to
11009 /// refer (possibly indirectly) to Fn. Returns the new expr.
11010 ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl,
11011 FunctionDecl *Fn);
11012 ExprResult FixOverloadedFunctionReference(ExprResult,
11013 DeclAccessPair FoundDecl,
11014 FunctionDecl *Fn);
11015
11016 /// - Returns a selector which best matches given argument list or
11017 /// nullptr if none could be found
11018 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
11019 bool IsInstance,
11020 SmallVectorImpl<ObjCMethodDecl *> &Methods);
11021
11022 ///@}
11023
11024 //
11025 //
11026 // -------------------------------------------------------------------------
11027 //
11028 //
11029
11030 /// \name Statements
11031 /// Implementations are in SemaStmt.cpp
11032 ///@{
11033
11034public:
11035 /// Stack of active SEH __finally scopes. Can be empty.
11036 SmallVector<Scope *, 2> CurrentSEHFinally;
11037
11038 /// Stack of '_Defer' statements that are currently being parsed, as well
11039 /// as the locations of their '_Defer' keywords. Can be empty.
11040 SmallVector<std::pair<Scope *, SourceLocation>, 2> CurrentDefer;
11041
11042 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
11043 StmtResult ActOnExprStmtError();
11044
11045 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
11046 bool HasLeadingEmptyMacro = false);
11047
11048 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc,
11049 SourceLocation EndLoc);
11050 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
11051
11052 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
11053 /// whose result is unused, warn.
11054 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
11055
11056 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
11057 void ActOnAfterCompoundStatementLeadingPragmas();
11058 void ActOnFinishOfCompoundStmt();
11059 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
11060 ArrayRef<Stmt *> Elts, bool isStmtExpr);
11061
11062 sema::CompoundScopeInfo &getCurCompoundScope() const;
11063
11064 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
11065 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
11066 SourceLocation DotDotDotLoc, ExprResult RHS,
11067 SourceLocation ColonLoc);
11068
11069 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
11070 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
11071
11072 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
11073 SourceLocation ColonLoc, Stmt *SubStmt,
11074 Scope *CurScope);
11075 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
11076 SourceLocation ColonLoc, Stmt *SubStmt);
11077
11078 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
11079 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
11080 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
11081 Stmt *SubStmt);
11082
11083 /// Check whether the given statement can have musttail applied to it,
11084 /// issuing a diagnostic and returning false if not. In the success case,
11085 /// the statement is rewritten to remove implicit nodes from the return
11086 /// value.
11087 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11088
11089 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11090 SourceLocation LParenLoc, Stmt *InitStmt,
11091 ConditionResult Cond, SourceLocation RParenLoc,
11092 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11093 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11094 SourceLocation LParenLoc, Stmt *InitStmt,
11095 ConditionResult Cond, SourceLocation RParenLoc,
11096 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11097
11098 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11099
11100 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
11101 SourceLocation LParenLoc, Stmt *InitStmt,
11102 ConditionResult Cond,
11103 SourceLocation RParenLoc);
11104 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
11105 Stmt *Body);
11106
11107 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11108 /// integer not in the range of enum values.
11109 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11110 Expr *SrcExpr);
11111
11112 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
11113 ConditionResult Cond, SourceLocation RParenLoc,
11114 Stmt *Body);
11115 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
11116 SourceLocation WhileLoc, SourceLocation CondLParen,
11117 Expr *Cond, SourceLocation CondRParen);
11118
11119 StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
11120 Stmt *First, ConditionResult Second,
11121 FullExprArg Third, SourceLocation RParenLoc,
11122 Stmt *Body);
11123
11124 /// In an Objective C collection iteration statement:
11125 /// for (x in y)
11126 /// x can be an arbitrary l-value expression. Bind it up as a
11127 /// full-expression.
11128 StmtResult ActOnForEachLValueExpr(Expr *E);
11129
11130 enum BuildForRangeKind {
11131 /// Initial building of a for-range statement.
11132 BFRK_Build,
11133 /// Instantiation or recovery rebuild of a for-range statement. Don't
11134 /// attempt any typo-correction.
11135 BFRK_Rebuild,
11136 /// Determining whether a for-range statement could be built. Avoid any
11137 /// unnecessary or irreversible actions.
11138 BFRK_Check
11139 };
11140
11141 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
11142 ///
11143 /// C++11 [stmt.ranged]:
11144 /// A range-based for statement is equivalent to
11145 ///
11146 /// {
11147 /// auto && __range = range-init;
11148 /// for ( auto __begin = begin-expr,
11149 /// __end = end-expr;
11150 /// __begin != __end;
11151 /// ++__begin ) {
11152 /// for-range-declaration = *__begin;
11153 /// statement
11154 /// }
11155 /// }
11156 ///
11157 /// The body of the loop is not available yet, since it cannot be analysed
11158 /// until we have determined the type of the for-range-declaration.
11159 StmtResult ActOnCXXForRangeStmt(
11160 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11161 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11162 SourceLocation RParenLoc, BuildForRangeKind Kind,
11163 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11164
11165 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11166 StmtResult BuildCXXForRangeStmt(
11167 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11168 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11169 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11170 BuildForRangeKind Kind,
11171 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11172
11173 /// Set the type of a for-range declaration whose for-range or expansion
11174 /// initialiser is dependent.
11175 void ActOnDependentForRangeInitializer(VarDecl *LoopVar,
11176 BuildForRangeKind BFRK);
11177
11178 /// Holds the 'begin' and 'end' variables of a range-based for loop or
11179 /// expansion statement; begin-expr and end-expr are also provided; the
11180 /// latter are used in some diagnostics.
11181 struct ForRangeBeginEndInfo {
11182 VarDecl *BeginVar = nullptr;
11183 VarDecl *EndVar = nullptr;
11184 Expr *BeginExpr = nullptr;
11185 Expr *EndExpr = nullptr;
11186 bool isValid() const { return BeginVar != nullptr && EndVar != nullptr; }
11187 };
11188
11189 /// Determine begin-expr and end-expr and build variable declarations for
11190 /// them as per [stmt.ranged].
11191 ForRangeBeginEndInfo BuildCXXForRangeBeginEndVars(
11192 Scope *S, VarDecl *RangeVar, SourceLocation ColonLoc,
11193 SourceLocation CoawaitLoc,
11194 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps,
11195 BuildForRangeKind Kind, bool IsConstexpr,
11196 StmtResult *RebuildResult = nullptr,
11197 llvm::function_ref<StmtResult()> RebuildWithDereference = {},
11198 IdentifierInfo *BeginName = nullptr, IdentifierInfo *EndName = nullptr);
11199
11200 /// Helper used by the expansion statements and for-range code to build
11201 /// a variable declaration for e.g. 'begin' and 'end'.
11202 VarDecl *BuildForRangeVarDecl(SourceLocation Loc, QualType Type,
11203 IdentifierInfo *Name, bool IsConstexpr);
11204
11205 /// Build the range variable of a range-based for loop or iterating
11206 /// expansion statement and return its DeclStmt.
11207 StmtResult BuildCXXForRangeRangeVar(Scope *S, Expr *Range, QualType Type,
11208 bool IsConstexpr = false);
11209
11210 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11211 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11212 /// body cannot be performed until after the type of the range variable is
11213 /// determined.
11214 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11215
11216 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11217 LabelDecl *TheDecl);
11218 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11219 SourceLocation StarLoc, Expr *DestExp);
11220 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
11221 LabelDecl *Label, SourceLocation LabelLoc);
11222 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
11223 LabelDecl *Label, SourceLocation LabelLoc);
11224
11225 void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope);
11226 void ActOnDeferStmtError(Scope *CurScope);
11227 StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope);
11228
11229 struct NamedReturnInfo {
11230 const VarDecl *Candidate;
11231
11232 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
11233 Status S;
11234
11235 bool isMoveEligible() const { return S != None; };
11236 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
11237 };
11238 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
11239
11240 /// Determine whether the given expression might be move-eligible or
11241 /// copy-elidable in either a (co_)return statement or throw expression,
11242 /// without considering function return type, if applicable.
11243 ///
11244 /// \param E The expression being returned from the function or block,
11245 /// being thrown, or being co_returned from a coroutine. This expression
11246 /// might be modified by the implementation.
11247 ///
11248 /// \param Mode Overrides detection of current language mode
11249 /// and uses the rules for C++23.
11250 ///
11251 /// \returns An aggregate which contains the Candidate and isMoveEligible
11252 /// and isCopyElidable methods. If Candidate is non-null, it means
11253 /// isMoveEligible() would be true under the most permissive language
11254 /// standard.
11255 NamedReturnInfo getNamedReturnInfo(
11256 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
11257
11258 /// Determine whether the given NRVO candidate variable is move-eligible or
11259 /// copy-elidable, without considering function return type.
11260 ///
11261 /// \param VD The NRVO candidate variable.
11262 ///
11263 /// \returns An aggregate which contains the Candidate and isMoveEligible
11264 /// and isCopyElidable methods. If Candidate is non-null, it means
11265 /// isMoveEligible() would be true under the most permissive language
11266 /// standard.
11267 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11268
11269 /// Updates given NamedReturnInfo's move-eligible and
11270 /// copy-elidable statuses, considering the function
11271 /// return type criteria as applicable to return statements.
11272 ///
11273 /// \param Info The NamedReturnInfo object to update.
11274 ///
11275 /// \param ReturnType This is the return type of the function.
11276 /// \returns The copy elision candidate, in case the initial return expression
11277 /// was copy elidable, or nullptr otherwise.
11278 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11279 QualType ReturnType);
11280
11281 /// Perform the initialization of a potentially-movable value, which
11282 /// is the result of return value.
11283 ///
11284 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11285 /// treat returned lvalues as rvalues in certain cases (to prefer move
11286 /// construction), then falls back to treating them as lvalues if that failed.
11287 ExprResult
11288 PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
11289 const NamedReturnInfo &NRInfo, Expr *Value,
11290 bool SupressSimplerImplicitMoves = false);
11291
11292 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
11293
11294 /// Deduce the return type for a function from a returned expression, per
11295 /// C++1y [dcl.spec.auto]p6.
11296 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
11297 SourceLocation ReturnLoc, Expr *RetExpr,
11298 const AutoType *AT);
11299
11300 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11301 Scope *CurScope);
11302 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11303 bool AllowRecovery = false);
11304
11305 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11306 /// for capturing scopes.
11307 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11308 NamedReturnInfo &NRInfo,
11309 bool SupressSimplerImplicitMoves);
11310
11311 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11312 /// and creates a proper catch handler from them.
11313 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
11314 Stmt *HandlerBlock);
11315
11316 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11317 /// handlers and creates a try statement from them.
11318 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
11319 ArrayRef<Stmt *> Handlers);
11320
11321 void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11322
11323 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11324 SourceLocation TryLoc, Stmt *TryBlock,
11325 Stmt *Handler);
11326 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
11327 Stmt *Block);
11328 void ActOnStartSEHFinallyBlock();
11329 void ActOnAbortSEHFinallyBlock();
11330 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
11331 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
11332
11333 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
11334 bool IsIfExists,
11335 NestedNameSpecifierLoc QualifierLoc,
11336 DeclarationNameInfo NameInfo,
11337 Stmt *Nested);
11338 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
11339 bool IsIfExists, CXXScopeSpec &SS,
11340 UnqualifiedId &Name, Stmt *Nested);
11341
11342 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11343 CapturedRegionKind Kind, unsigned NumParams);
11344 typedef std::pair<StringRef, QualType> CapturedParamNameType;
11345 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11346 CapturedRegionKind Kind,
11347 ArrayRef<CapturedParamNameType> Params,
11348 unsigned OpenMPCaptureLevel = 0);
11349 StmtResult ActOnCapturedRegionEnd(Stmt *S);
11350 void ActOnCapturedRegionError();
11351 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
11352 SourceLocation Loc,
11353 unsigned NumParams);
11354
11355 void ApplyForRangeOrExpansionStatementLifetimeExtension(
11356 VarDecl *RangeVar, ArrayRef<MaterializeTemporaryExpr *> Temporaries);
11357
11358private:
11359 /// Check whether the given statement can have musttail applied to it,
11360 /// issuing a diagnostic and returning false if not.
11361 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11362
11363 ///@}
11364
11365 //
11366 //
11367 // -------------------------------------------------------------------------
11368 //
11369 //
11370
11371 /// \name `inline asm` Statement
11372 /// Implementations are in SemaStmtAsm.cpp
11373 ///@{
11374
11375public:
11376 ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel);
11377 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11378 bool IsVolatile, unsigned NumOutputs,
11379 unsigned NumInputs, IdentifierInfo **Names,
11380 MultiExprArg Constraints, MultiExprArg Exprs,
11381 Expr *AsmString, MultiExprArg Clobbers,
11382 unsigned NumLabels, SourceLocation RParenLoc);
11383
11384 void FillInlineAsmIdentifierInfo(Expr *Res,
11385 llvm::InlineAsmIdentifierInfo &Info);
11386 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
11387 SourceLocation TemplateKWLoc,
11388 UnqualifiedId &Id,
11389 bool IsUnevaluatedContext);
11390 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11391 SourceLocation AsmLoc);
11392 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
11393 SourceLocation AsmLoc);
11394 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
11395 ArrayRef<Token> AsmToks, StringRef AsmString,
11396 unsigned NumOutputs, unsigned NumInputs,
11397 ArrayRef<StringRef> Constraints,
11398 ArrayRef<StringRef> Clobbers,
11399 ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11400 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11401 SourceLocation Location, bool AlwaysCreate);
11402
11403 ///@}
11404
11405 //
11406 //
11407 // -------------------------------------------------------------------------
11408 //
11409 //
11410
11411 /// \name Statement Attribute Handling
11412 /// Implementations are in SemaStmtAttr.cpp
11413 ///@{
11414
11415public:
11416 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11417 const AttributeCommonInfo &A);
11418 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11419 const AttributeCommonInfo &A);
11420
11421 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11422 bool CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs);
11423
11424 /// Process the attributes before creating an attributed statement. Returns
11425 /// the semantic attributes that have been processed.
11426 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11427 SmallVectorImpl<const Attr *> &OutAttrs);
11428
11429 ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A,
11430 SourceRange Range);
11431 ExprResult BuildCXXAssumeExpr(Expr *Assumption,
11432 const IdentifierInfo *AttrName,
11433 SourceRange Range);
11434
11435 ///@}
11436
11437 //
11438 //
11439 // -------------------------------------------------------------------------
11440 //
11441 //
11442
11443 /// \name C++ Templates
11444 /// Implementations are in SemaTemplate.cpp
11445 ///@{
11446
11447public:
11448 // Saves the current floating-point pragma stack and clear it in this Sema.
11449 class FpPragmaStackSaveRAII {
11450 public:
11451 FpPragmaStackSaveRAII(Sema &S)
11452 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11453 S.FpPragmaStack.Stack.clear();
11454 }
11455 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11456 FpPragmaStackSaveRAII(const FpPragmaStackSaveRAII &) = delete;
11457 FpPragmaStackSaveRAII &operator=(const FpPragmaStackSaveRAII &) = delete;
11458
11459 private:
11460 Sema &S;
11461 PragmaStack<FPOptionsOverride> SavedStack;
11462 };
11463
11464 void resetFPOptions(FPOptions FPO) {
11465 CurFPFeatures = FPO;
11466 FpPragmaStack.CurrentValue = FPO.getChangesFrom(Base: FPOptions(LangOpts));
11467 }
11468
11469 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
11470 return llvm::ArrayRef(InventedParameterInfos.begin() +
11471 InventedParameterInfosStart,
11472 InventedParameterInfos.end());
11473 }
11474
11475 ArrayRef<sema::FunctionScopeInfo *> getFunctionScopes() const {
11476 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
11477 FunctionScopes.end());
11478 }
11479
11480 typedef llvm::MapVector<const FunctionDecl *,
11481 std::unique_ptr<LateParsedTemplate>>
11482 LateParsedTemplateMapT;
11483 LateParsedTemplateMapT LateParsedTemplateMap;
11484
11485 /// Determine the number of levels of enclosing template parameters. This is
11486 /// only usable while parsing. Note that this does not include dependent
11487 /// contexts in which no template parameters have yet been declared, such as
11488 /// in a terse function template or generic lambda before the first 'auto' is
11489 /// encountered.
11490 unsigned getTemplateDepth(Scope *S) const;
11491
11492 void FilterAcceptableTemplateNames(LookupResult &R,
11493 bool AllowFunctionTemplates = true,
11494 bool AllowDependent = true);
11495 bool hasAnyAcceptableTemplateNames(LookupResult &R,
11496 bool AllowFunctionTemplates = true,
11497 bool AllowDependent = true,
11498 bool AllowNonTemplateFunctions = false);
11499 /// Try to interpret the lookup result D as a template-name.
11500 ///
11501 /// \param D A declaration found by name lookup.
11502 /// \param AllowFunctionTemplates Whether function templates should be
11503 /// considered valid results.
11504 /// \param AllowDependent Whether unresolved using declarations (that might
11505 /// name templates) should be considered valid results.
11506 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
11507 bool AllowFunctionTemplates = true,
11508 bool AllowDependent = true);
11509
11510 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
11511 /// Whether and why a template name is required in this lookup.
11512 class RequiredTemplateKind {
11513 public:
11514 /// Template name is required if TemplateKWLoc is valid.
11515 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
11516 : TemplateKW(TemplateKWLoc) {}
11517 /// Template name is unconditionally required.
11518 RequiredTemplateKind(TemplateNameIsRequiredTag) {}
11519
11520 SourceLocation getTemplateKeywordLoc() const {
11521 return TemplateKW.value_or(u: SourceLocation());
11522 }
11523 bool hasTemplateKeyword() const {
11524 return getTemplateKeywordLoc().isValid();
11525 }
11526 bool isRequired() const { return TemplateKW != SourceLocation(); }
11527 explicit operator bool() const { return isRequired(); }
11528
11529 private:
11530 std::optional<SourceLocation> TemplateKW;
11531 };
11532
11533 enum class AssumedTemplateKind {
11534 /// This is not assumed to be a template name.
11535 None,
11536 /// This is assumed to be a template name because lookup found nothing.
11537 FoundNothing,
11538 /// This is assumed to be a template name because lookup found one or more
11539 /// functions (but no function templates).
11540 FoundFunctions,
11541 };
11542
11543 bool
11544 LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
11545 QualType ObjectType, bool EnteringContext,
11546 RequiredTemplateKind RequiredTemplate = SourceLocation(),
11547 AssumedTemplateKind *ATK = nullptr,
11548 bool AllowTypoCorrection = true);
11549
11550 TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS,
11551 bool hasTemplateKeyword,
11552 const UnqualifiedId &Name,
11553 ParsedType ObjectType, bool EnteringContext,
11554 TemplateTy &Template,
11555 bool &MemberOfUnknownSpecialization,
11556 bool AllowTypoCorrection = true);
11557
11558 /// Try to resolve an undeclared template name as a type template.
11559 ///
11560 /// Sets II to the identifier corresponding to the template name, and updates
11561 /// Name to a corresponding (typo-corrected) type template name and TNK to
11562 /// the corresponding kind, if possible.
11563 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
11564 TemplateNameKind &TNK,
11565 SourceLocation NameLoc,
11566 IdentifierInfo *&II);
11567
11568 /// Determine whether a particular identifier might be the name in a C++1z
11569 /// deduction-guide declaration.
11570 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11571 SourceLocation NameLoc, CXXScopeSpec &SS,
11572 ParsedTemplateTy *Template = nullptr);
11573
11574 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
11575 SourceLocation IILoc, Scope *S,
11576 const CXXScopeSpec *SS,
11577 TemplateTy &SuggestedTemplate,
11578 TemplateNameKind &SuggestedKind);
11579
11580 /// Determine whether we would be unable to instantiate this template (because
11581 /// it either has no definition, or is in the process of being instantiated).
11582 bool DiagnoseUninstantiableTemplate(
11583 SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11584 bool InstantiatedFromMember, const NamedDecl *Pattern,
11585 const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11586 bool Complain = true, bool *Unreachable = nullptr);
11587
11588 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11589 /// that the template parameter 'PrevDecl' is being shadowed by a new
11590 /// declaration at location Loc. Returns true to indicate that this is
11591 /// an error, and false otherwise.
11592 ///
11593 /// \param Loc The location of the declaration that shadows a template
11594 /// parameter.
11595 ///
11596 /// \param PrevDecl The template parameter that the declaration shadows.
11597 ///
11598 /// \param SupportedForCompatibility Whether to issue the diagnostic as
11599 /// a warning for compatibility with older versions of clang.
11600 /// Ignored when MSVC compatibility is enabled.
11601 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
11602 bool SupportedForCompatibility = false);
11603
11604 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11605 /// the parameter D to reference the templated declaration and return a
11606 /// pointer to the template declaration. Otherwise, do nothing to D and return
11607 /// null.
11608 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
11609
11610 /// ActOnTypeParameter - Called when a C++ template type parameter
11611 /// (e.g., "typename T") has been parsed. Typename specifies whether
11612 /// the keyword "typename" was used to declare the type parameter
11613 /// (otherwise, "class" was used), and KeyLoc is the location of the
11614 /// "class" or "typename" keyword. ParamName is the name of the
11615 /// parameter (NULL indicates an unnamed template parameter) and
11616 /// ParamNameLoc is the location of the parameter name (if any).
11617 /// If the type parameter has a default argument, it will be added
11618 /// later via ActOnTypeParameterDefault.
11619 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
11620 SourceLocation EllipsisLoc,
11621 SourceLocation KeyLoc,
11622 IdentifierInfo *ParamName,
11623 SourceLocation ParamNameLoc, unsigned Depth,
11624 unsigned Position, SourceLocation EqualLoc,
11625 ParsedType DefaultArg, bool HasTypeConstraint);
11626
11627 bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint);
11628
11629 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11630 TemplateIdAnnotation *TypeConstraint,
11631 TemplateTypeParmDecl *ConstrainedParameter,
11632 SourceLocation EllipsisLoc);
11633 bool BuildTypeConstraint(const CXXScopeSpec &SS,
11634 TemplateIdAnnotation *TypeConstraint,
11635 TemplateTypeParmDecl *ConstrainedParameter,
11636 SourceLocation EllipsisLoc,
11637 bool AllowUnexpandedPack);
11638
11639 /// Attach a type-constraint to a template parameter.
11640 /// \returns true if an error occurred. This can happen if the
11641 /// immediately-declared constraint could not be formed (e.g. incorrect number
11642 /// of arguments for the named concept).
11643 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
11644 DeclarationNameInfo NameInfo,
11645 TemplateName NamedConcept, NamedDecl *FoundDecl,
11646 const TemplateArgumentListInfo *TemplateArgs,
11647 TemplateTypeParmDecl *ConstrainedParameter,
11648 SourceLocation EllipsisLoc);
11649
11650 bool AttachTypeConstraint(AutoTypeLoc TL,
11651 NonTypeTemplateParmDecl *NewConstrainedParm,
11652 NonTypeTemplateParmDecl *OrigConstrainedParm,
11653 SourceLocation EllipsisLoc);
11654
11655 /// Require the given type to be a structural type, and diagnose if it is not.
11656 ///
11657 /// \return \c true if an error was produced.
11658 bool RequireStructuralType(QualType T, SourceLocation Loc);
11659
11660 /// Check that the type of a non-type template parameter is
11661 /// well-formed.
11662 ///
11663 /// \returns the (possibly-promoted) parameter type if valid;
11664 /// otherwise, produces a diagnostic and returns a NULL type.
11665 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
11666 SourceLocation Loc);
11667 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
11668
11669 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
11670 unsigned Depth, unsigned Position,
11671 SourceLocation EqualLoc,
11672 Expr *DefaultArg);
11673
11674 /// ActOnTemplateTemplateParameter - Called when a C++ template template
11675 /// parameter (e.g. T in template <template \<typename> class T> class array)
11676 /// has been parsed. S is the current scope.
11677 NamedDecl *ActOnTemplateTemplateParameter(
11678 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind,
11679 bool TypenameKeyword, TemplateParameterList *Params,
11680 SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11681 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11682 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11683
11684 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11685 /// constrained by RequiresClause, that contains the template parameters in
11686 /// Params.
11687 TemplateParameterList *ActOnTemplateParameterList(
11688 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11689 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11690 SourceLocation RAngleLoc, Expr *RequiresClause);
11691
11692 /// The context in which we are checking a template parameter list.
11693 enum TemplateParamListContext {
11694 // For this context, Class, Variable, TypeAlias, and non-pack Template
11695 // Template Parameters are treated uniformly.
11696 TPC_Other,
11697
11698 TPC_FunctionTemplate,
11699 TPC_ClassTemplateMember,
11700 TPC_FriendClassTemplate,
11701 TPC_FriendFunctionTemplate,
11702 TPC_FriendFunctionTemplateDefinition,
11703 TPC_TemplateTemplateParameterPack,
11704 };
11705
11706 /// Checks the validity of a template parameter list, possibly
11707 /// considering the template parameter list from a previous
11708 /// declaration.
11709 ///
11710 /// If an "old" template parameter list is provided, it must be
11711 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11712 /// template parameter list.
11713 ///
11714 /// \param NewParams Template parameter list for a new template
11715 /// declaration. This template parameter list will be updated with any
11716 /// default arguments that are carried through from the previous
11717 /// template parameter list.
11718 ///
11719 /// \param OldParams If provided, template parameter list from a
11720 /// previous declaration of the same template. Default template
11721 /// arguments will be merged from the old template parameter list to
11722 /// the new template parameter list.
11723 ///
11724 /// \param TPC Describes the context in which we are checking the given
11725 /// template parameter list.
11726 ///
11727 /// \param SkipBody If we might have already made a prior merged definition
11728 /// of this template visible, the corresponding body-skipping information.
11729 /// Default argument redefinition is not an error when skipping such a body,
11730 /// because (under the ODR) we can assume the default arguments are the same
11731 /// as the prior merged definition.
11732 ///
11733 /// \returns true if an error occurred, false otherwise.
11734 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
11735 TemplateParameterList *OldParams,
11736 TemplateParamListContext TPC,
11737 SkipBodyInfo *SkipBody = nullptr);
11738
11739 /// Match the given template parameter lists to the given scope
11740 /// specifier, returning the template parameter list that applies to the
11741 /// name.
11742 ///
11743 /// \param DeclStartLoc the start of the declaration that has a scope
11744 /// specifier or a template parameter list.
11745 ///
11746 /// \param DeclLoc The location of the declaration itself.
11747 ///
11748 /// \param SS the scope specifier that will be matched to the given template
11749 /// parameter lists. This scope specifier precedes a qualified name that is
11750 /// being declared.
11751 ///
11752 /// \param TemplateId The template-id following the scope specifier, if there
11753 /// is one. Used to check for a missing 'template<>'.
11754 ///
11755 /// \param ParamLists the template parameter lists, from the outermost to the
11756 /// innermost template parameter lists.
11757 ///
11758 /// \param IsFriend Whether to apply the slightly different rules for
11759 /// matching template parameters to scope specifiers in friend
11760 /// declarations.
11761 ///
11762 /// \param IsMemberSpecialization will be set true if the scope specifier
11763 /// denotes a fully-specialized type, and therefore this is a declaration of
11764 /// a member specialization.
11765 ///
11766 /// \returns the template parameter list, if any, that corresponds to the
11767 /// name that is preceded by the scope specifier @p SS. This template
11768 /// parameter list may have template parameters (if we're declaring a
11769 /// template) or may have no template parameters (if we're declaring a
11770 /// template specialization), or may be NULL (if what we're declaring isn't
11771 /// itself a template).
11772 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
11773 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11774 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11775 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11776 bool &IsMemberSpecialization, bool &Invalid,
11777 bool SuppressDiagnostic = false);
11778
11779 /// Returns the template parameter list with all default template argument
11780 /// information.
11781 TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD);
11782
11783 DeclResult CheckClassTemplate(
11784 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11785 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11786 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11787 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11788 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11789 TemplateParameterList **OuterTemplateParamLists,
11790 bool IsMemberSpecialization, SkipBodyInfo *SkipBody = nullptr);
11791
11792 /// Translates template arguments as provided by the parser
11793 /// into template arguments used by semantic analysis.
11794 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
11795 TemplateArgumentListInfo &Out);
11796
11797 /// Convert a parsed type into a parsed template argument. This is mostly
11798 /// trivial, except that we may have parsed a C++17 deduced class template
11799 /// specialization type, in which case we should form a template template
11800 /// argument instead of a type template argument.
11801 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
11802
11803 void NoteAllFoundTemplates(TemplateName Name);
11804
11805 QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
11806 TemplateName Template,
11807 SourceLocation TemplateLoc,
11808 TemplateArgumentListInfo &TemplateArgs,
11809 Scope *Scope, bool ForNestedNameSpecifier);
11810
11811 TypeResult
11812 ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
11813 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
11814 SourceLocation TemplateKWLoc, TemplateTy Template,
11815 const IdentifierInfo *TemplateII,
11816 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11817 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11818 bool IsCtorOrDtorName = false, bool IsClassName = false,
11819 ImplicitTypenameContext AllowImplicitTypename =
11820 ImplicitTypenameContext::No);
11821
11822 /// Parsed an elaborated-type-specifier that refers to a template-id,
11823 /// such as \c class T::template apply<U>.
11824 TypeResult ActOnTagTemplateIdType(
11825 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11826 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11827 SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11828 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11829
11830 DeclResult ActOnVarTemplateSpecialization(
11831 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
11832 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11833 StorageClass SC, bool IsPartialSpecialization);
11834
11835 /// Get the specialization of the given variable template corresponding to
11836 /// the specified argument list, or a null-but-valid result if the arguments
11837 /// are dependent.
11838 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
11839 SourceLocation TemplateLoc,
11840 SourceLocation TemplateNameLoc,
11841 const TemplateArgumentListInfo &TemplateArgs,
11842 bool SetWrittenArgs);
11843
11844 /// Form a reference to the specialization of the given variable template
11845 /// corresponding to the specified argument list, or a null-but-valid result
11846 /// if the arguments are dependent.
11847 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
11848 const DeclarationNameInfo &NameInfo,
11849 VarTemplateDecl *Template, NamedDecl *FoundD,
11850 SourceLocation TemplateLoc,
11851 const TemplateArgumentListInfo *TemplateArgs);
11852
11853 ExprResult CheckVarOrConceptTemplateTemplateId(
11854 const DeclarationNameInfo &NameInfo, TemplateName Template,
11855 const TemplateArgumentListInfo *TemplateArgs);
11856
11857 ExprResult
11858 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11859 const DeclarationNameInfo &ConceptNameInfo,
11860 NamedDecl *FoundDecl, TemplateDecl *NamedConcept,
11861 const TemplateArgumentListInfo *TemplateArgs,
11862 bool DoCheckConstraintSatisfaction = true);
11863
11864 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
11865 void diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
11866 bool TemplateKeyword, TemplateDecl *TD,
11867 SourceLocation Loc);
11868
11869 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
11870 SourceLocation TemplateKWLoc, LookupResult &R,
11871 bool RequiresADL,
11872 const TemplateArgumentListInfo *TemplateArgs);
11873
11874 // We actually only call this from template instantiation.
11875 ExprResult
11876 BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11877 const DeclarationNameInfo &NameInfo,
11878 const TemplateArgumentListInfo *TemplateArgs,
11879 bool IsAddressOfOperand);
11880
11881 UnsignedOrNone getPackIndex(TemplateArgument Pack) const {
11882 return Pack.pack_size() - 1 - *ArgPackSubstIndex;
11883 }
11884
11885 TemplateArgument
11886 getPackSubstitutedTemplateArgument(TemplateArgument Arg) const {
11887 Arg = Arg.pack_elements()[*ArgPackSubstIndex];
11888 if (Arg.isPackExpansion())
11889 Arg = Arg.getPackExpansionPattern();
11890 return Arg;
11891 }
11892
11893 ExprResult
11894 BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
11895 QualType ParamType, SourceLocation loc,
11896 TemplateArgument Replacement,
11897 UnsignedOrNone PackIndex, bool Final);
11898
11899 /// Form a template name from a name that is syntactically required to name a
11900 /// template, either due to use of the 'template' keyword or because a name in
11901 /// this syntactic context is assumed to name a template (C++
11902 /// [temp.names]p2-4).
11903 ///
11904 /// This action forms a template name given the name of the template and its
11905 /// optional scope specifier. This is used when the 'template' keyword is used
11906 /// or when the parsing context unambiguously treats a following '<' as
11907 /// introducing a template argument list. Note that this may produce a
11908 /// non-dependent template name if we can perform the lookup now and identify
11909 /// the named template.
11910 ///
11911 /// For example, given "x.MetaFun::template apply", the scope specifier
11912 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
11913 /// of the "template" keyword, and "apply" is the \p Name.
11914 TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS,
11915 SourceLocation TemplateKWLoc,
11916 const UnqualifiedId &Name,
11917 ParsedType ObjectType,
11918 bool EnteringContext, TemplateTy &Template,
11919 bool AllowInjectedClassName = false);
11920
11921 DeclResult ActOnClassTemplateSpecialization(
11922 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11923 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
11924 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
11925 MultiTemplateParamsArg TemplateParameterLists,
11926 SkipBodyInfo *SkipBody = nullptr);
11927
11928 /// Check the non-type template arguments of a class template
11929 /// partial specialization according to C++ [temp.class.spec]p9.
11930 ///
11931 /// \param TemplateNameLoc the location of the template name.
11932 /// \param PrimaryTemplate the template parameters of the primary class
11933 /// template.
11934 /// \param NumExplicit the number of explicitly-specified template arguments.
11935 /// \param TemplateArgs the template arguments of the class template
11936 /// partial specialization.
11937 ///
11938 /// \returns \c true if there was an error, \c false otherwise.
11939 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
11940 TemplateDecl *PrimaryTemplate,
11941 unsigned NumExplicitArgs,
11942 ArrayRef<TemplateArgument> Args);
11943 void CheckTemplatePartialSpecialization(
11944 ClassTemplatePartialSpecializationDecl *Partial);
11945 void CheckTemplatePartialSpecialization(
11946 VarTemplatePartialSpecializationDecl *Partial);
11947
11948 Decl *ActOnTemplateDeclarator(Scope *S,
11949 MultiTemplateParamsArg TemplateParameterLists,
11950 Declarator &D);
11951
11952 /// Diagnose cases where we have an explicit template specialization
11953 /// before/after an explicit template instantiation, producing diagnostics
11954 /// for those cases where they are required and determining whether the
11955 /// new specialization/instantiation will have any effect.
11956 ///
11957 /// \param NewLoc the location of the new explicit specialization or
11958 /// instantiation.
11959 ///
11960 /// \param NewTSK the kind of the new explicit specialization or
11961 /// instantiation.
11962 ///
11963 /// \param PrevDecl the previous declaration of the entity.
11964 ///
11965 /// \param PrevTSK the kind of the old explicit specialization or
11966 /// instantiatin.
11967 ///
11968 /// \param PrevPointOfInstantiation if valid, indicates where the previous
11969 /// declaration was instantiated (either implicitly or explicitly).
11970 ///
11971 /// \param HasNoEffect will be set to true to indicate that the new
11972 /// specialization or instantiation has no effect and should be ignored.
11973 ///
11974 /// \returns true if there was an error that should prevent the introduction
11975 /// of the new declaration into the AST, false otherwise.
11976 bool CheckSpecializationInstantiationRedecl(
11977 SourceLocation NewLoc,
11978 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
11979 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
11980 SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
11981
11982 /// Perform semantic analysis for the given dependent function
11983 /// template specialization.
11984 ///
11985 /// The only possible way to get a dependent function template specialization
11986 /// is with a friend declaration, like so:
11987 ///
11988 /// \code
11989 /// template \<class T> void foo(T);
11990 /// template \<class T> class A {
11991 /// friend void foo<>(T);
11992 /// };
11993 /// \endcode
11994 ///
11995 /// There really isn't any useful analysis we can do here, so we
11996 /// just store the information.
11997 bool CheckDependentFunctionTemplateSpecialization(
11998 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
11999 LookupResult &Previous);
12000
12001 /// Perform semantic analysis for the given function template
12002 /// specialization.
12003 ///
12004 /// This routine performs all of the semantic analysis required for an
12005 /// explicit function template specialization. On successful completion,
12006 /// the function declaration \p FD will become a function template
12007 /// specialization.
12008 ///
12009 /// \param FD the function declaration, which will be updated to become a
12010 /// function template specialization.
12011 ///
12012 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
12013 /// if any. Note that this may be valid info even when 0 arguments are
12014 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
12015 /// as it anyway contains info on the angle brackets locations.
12016 ///
12017 /// \param Previous the set of declarations that may be specialized by
12018 /// this function specialization.
12019 ///
12020 /// \param QualifiedFriend whether this is a lookup for a qualified friend
12021 /// declaration with no explicit template argument list that might be
12022 /// befriending a function template specialization.
12023 bool CheckFunctionTemplateSpecialization(
12024 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
12025 LookupResult &Previous, bool QualifiedFriend = false);
12026
12027 /// Perform semantic analysis for the given non-template member
12028 /// specialization.
12029 ///
12030 /// This routine performs all of the semantic analysis required for an
12031 /// explicit member function specialization. On successful completion,
12032 /// the function declaration \p FD will become a member function
12033 /// specialization.
12034 ///
12035 /// \param Member the member declaration, which will be updated to become a
12036 /// specialization.
12037 ///
12038 /// \param Previous the set of declarations, one of which may be specialized
12039 /// by this function specialization; the set will be modified to contain the
12040 /// redeclared member.
12041 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12042 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12043
12044 // Explicit instantiation of a class template specialization
12045 DeclResult ActOnExplicitInstantiation(
12046 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
12047 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
12048 TemplateTy Template, SourceLocation TemplateNameLoc,
12049 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
12050 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
12051
12052 // Explicit instantiation of a member class of a class template.
12053 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12054 SourceLocation TemplateLoc,
12055 unsigned TagSpec, SourceLocation KWLoc,
12056 CXXScopeSpec &SS, IdentifierInfo *Name,
12057 SourceLocation NameLoc,
12058 const ParsedAttributesView &Attr);
12059
12060 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12061 SourceLocation TemplateLoc,
12062 Declarator &D);
12063
12064 /// If the given template parameter has a default template
12065 /// argument, substitute into that default template argument and
12066 /// return the corresponding template argument.
12067 TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(
12068 TemplateDecl *Template, SourceLocation TemplateKWLoc,
12069 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
12070 ArrayRef<TemplateArgument> SugaredConverted,
12071 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
12072
12073 /// Returns the top most location responsible for the definition of \p N.
12074 /// If \p N is a a template specialization, this is the location
12075 /// of the top of the instantiation stack.
12076 /// Otherwise, the location of \p N is returned.
12077 SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const;
12078
12079 /// Specifies the context in which a particular template
12080 /// argument is being checked.
12081 enum CheckTemplateArgumentKind {
12082 /// The template argument was specified in the code or was
12083 /// instantiated with some deduced template arguments.
12084 CTAK_Specified,
12085
12086 /// The template argument was deduced via template argument
12087 /// deduction.
12088 CTAK_Deduced,
12089
12090 /// The template argument was deduced from an array bound
12091 /// via template argument deduction.
12092 CTAK_DeducedFromArrayBound
12093 };
12094
12095 struct CheckTemplateArgumentInfo {
12096 explicit CheckTemplateArgumentInfo(bool PartialOrdering = false,
12097 bool MatchingTTP = false)
12098 : PartialOrdering(PartialOrdering), MatchingTTP(MatchingTTP) {}
12099 CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &) = delete;
12100 CheckTemplateArgumentInfo &
12101 operator=(const CheckTemplateArgumentInfo &) = delete;
12102
12103 /// The checked, converted argument will be added to the
12104 /// end of these vectors.
12105 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
12106
12107 /// The check is being performed in the context of partial ordering.
12108 bool PartialOrdering;
12109
12110 /// If true, assume these template arguments are
12111 /// the injected template arguments for a template template parameter.
12112 /// This will relax the requirement that all its possible uses are valid:
12113 /// TTP checking is loose, and assumes that invalid uses will be diagnosed
12114 /// during instantiation.
12115 bool MatchingTTP;
12116
12117 /// Is set to true when, in the context of TTP matching, a pack parameter
12118 /// matches non-pack arguments.
12119 bool StrictPackMatch = false;
12120 };
12121
12122 /// Check that the given template argument corresponds to the given
12123 /// template parameter.
12124 ///
12125 /// \param Param The template parameter against which the argument will be
12126 /// checked.
12127 ///
12128 /// \param Arg The template argument, which may be updated due to conversions.
12129 ///
12130 /// \param Template The template in which the template argument resides.
12131 ///
12132 /// \param TemplateLoc The location of the template name for the template
12133 /// whose argument list we're matching.
12134 ///
12135 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
12136 /// the template argument list.
12137 ///
12138 /// \param ArgumentPackIndex The index into the argument pack where this
12139 /// argument will be placed. Only valid if the parameter is a parameter pack.
12140 ///
12141 /// \param CTAK Describes how we arrived at this particular template argument:
12142 /// explicitly written, deduced, etc.
12143 ///
12144 /// \returns true on error, false otherwise.
12145 bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
12146 NamedDecl *Template, SourceLocation TemplateLoc,
12147 SourceLocation RAngleLoc,
12148 unsigned ArgumentPackIndex,
12149 CheckTemplateArgumentInfo &CTAI,
12150 CheckTemplateArgumentKind CTAK);
12151
12152 /// Check that the given template arguments can be provided to
12153 /// the given template, converting the arguments along the way.
12154 ///
12155 /// \param Template The template to which the template arguments are being
12156 /// provided.
12157 ///
12158 /// \param TemplateLoc The location of the template name in the source.
12159 ///
12160 /// \param TemplateArgs The list of template arguments. If the template is
12161 /// a template template parameter, this function may extend the set of
12162 /// template arguments to also include substituted, defaulted template
12163 /// arguments.
12164 ///
12165 /// \param PartialTemplateArgs True if the list of template arguments is
12166 /// intentionally partial, e.g., because we're checking just the initial
12167 /// set of template arguments.
12168 ///
12169 /// \param Converted Will receive the converted, canonicalized template
12170 /// arguments.
12171 ///
12172 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
12173 /// contain the converted forms of the template arguments as written.
12174 /// Otherwise, \p TemplateArgs will not be modified.
12175 ///
12176 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
12177 /// receive true if the cause for the error is the associated constraints of
12178 /// the template not being satisfied by the template arguments.
12179 ///
12180 /// \param DefaultArgs any default arguments from template specialization
12181 /// deduction.
12182 ///
12183 /// \returns true if an error occurred, false otherwise.
12184 bool CheckTemplateArgumentList(TemplateDecl *Template,
12185 SourceLocation TemplateLoc,
12186 TemplateArgumentListInfo &TemplateArgs,
12187 const DefaultArguments &DefaultArgs,
12188 bool PartialTemplateArgs,
12189 CheckTemplateArgumentInfo &CTAI,
12190 bool UpdateArgsWithConversions = true,
12191 bool *ConstraintsNotSatisfied = nullptr);
12192
12193 bool CheckTemplateArgumentList(
12194 TemplateDecl *Template, TemplateParameterList *Params,
12195 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
12196 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
12197 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions = true,
12198 bool *ConstraintsNotSatisfied = nullptr);
12199
12200 bool CheckTemplateTypeArgument(
12201 TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
12202 SmallVectorImpl<TemplateArgument> &SugaredConverted,
12203 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
12204
12205 /// Check a template argument against its corresponding
12206 /// template type parameter.
12207 ///
12208 /// This routine implements the semantics of C++ [temp.arg.type]. It
12209 /// returns true if an error occurred, and false otherwise.
12210 bool CheckTemplateArgument(TypeSourceInfo *Arg);
12211
12212 /// Check a template argument against its corresponding
12213 /// non-type template parameter.
12214 ///
12215 /// This routine implements the semantics of C++ [temp.arg.nontype].
12216 /// If an error occurred, it returns ExprError(); otherwise, it
12217 /// returns the converted template argument. \p ParamType is the
12218 /// type of the non-type template parameter after it has been instantiated.
12219 ExprResult CheckTemplateArgument(NamedDecl *Param,
12220 QualType InstantiatedParamType, Expr *Arg,
12221 TemplateArgument &SugaredConverted,
12222 TemplateArgument &CanonicalConverted,
12223 bool StrictCheck,
12224 CheckTemplateArgumentKind CTAK);
12225
12226 /// Check a template argument against its corresponding
12227 /// template template parameter.
12228 ///
12229 /// This routine implements the semantics of C++ [temp.arg.template].
12230 /// It returns true if an error occurred, and false otherwise.
12231 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
12232 TemplateParameterList *Params,
12233 TemplateArgumentLoc &Arg,
12234 bool PartialOrdering,
12235 bool *StrictPackMatch);
12236
12237 bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template,
12238 TemplateTemplateParmDecl *Param,
12239 const TemplateArgumentLoc &Arg);
12240
12241 void NoteTemplateLocation(const NamedDecl &Decl,
12242 std::optional<SourceRange> ParamRange = {});
12243 void NoteTemplateParameterLocation(const NamedDecl &Decl);
12244
12245 /// Given a non-type template argument that refers to a
12246 /// declaration and the type of its corresponding non-type template
12247 /// parameter, produce an expression that properly refers to that
12248 /// declaration.
12249 /// FIXME: This is used in some contexts where the resulting expression
12250 /// doesn't need to live too long. It would be useful if this function
12251 /// could return a temporary expression.
12252 ExprResult BuildExpressionFromDeclTemplateArgument(
12253 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc);
12254 ExprResult
12255 BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
12256 SourceLocation Loc);
12257
12258 /// Enumeration describing how template parameter lists are compared
12259 /// for equality.
12260 enum TemplateParameterListEqualKind {
12261 /// We are matching the template parameter lists of two templates
12262 /// that might be redeclarations.
12263 ///
12264 /// \code
12265 /// template<typename T> struct X;
12266 /// template<typename T> struct X;
12267 /// \endcode
12268 TPL_TemplateMatch,
12269
12270 /// We are matching the template parameter lists of two template
12271 /// template parameters as part of matching the template parameter lists
12272 /// of two templates that might be redeclarations.
12273 ///
12274 /// \code
12275 /// template<template<int I> class TT> struct X;
12276 /// template<template<int Value> class Other> struct X;
12277 /// \endcode
12278 TPL_TemplateTemplateParmMatch,
12279
12280 /// We are determining whether the template-parameters are equivalent
12281 /// according to C++ [temp.over.link]/6. This comparison does not consider
12282 /// constraints.
12283 ///
12284 /// \code
12285 /// template<C1 T> void f(T);
12286 /// template<C2 T> void f(T);
12287 /// \endcode
12288 TPL_TemplateParamsEquivalent,
12289 };
12290
12291 // A struct to represent the 'new' declaration, which is either itself just
12292 // the named decl, or the important information we need about it in order to
12293 // do constraint comparisons.
12294 class TemplateCompareNewDeclInfo {
12295 const NamedDecl *ND = nullptr;
12296 const DeclContext *DC = nullptr;
12297 const DeclContext *LexicalDC = nullptr;
12298 SourceLocation Loc;
12299
12300 public:
12301 TemplateCompareNewDeclInfo(const NamedDecl *ND) : ND(ND) {}
12302 TemplateCompareNewDeclInfo(const DeclContext *DeclCtx,
12303 const DeclContext *LexicalDeclCtx,
12304 SourceLocation Loc)
12305
12306 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12307 assert(DC && LexicalDC &&
12308 "Constructor only for cases where we have the information to put "
12309 "in here");
12310 }
12311
12312 // If this was constructed with no information, we cannot do substitution
12313 // for constraint comparison, so make sure we can check that.
12314 bool isInvalid() const { return !ND && !DC; }
12315
12316 const NamedDecl *getDecl() const { return ND; }
12317
12318 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12319
12320 const DeclContext *getLexicalDeclContext() const {
12321 return ND ? ND->getLexicalDeclContext() : LexicalDC;
12322 }
12323
12324 const DeclContext *getDeclContext() const {
12325 return ND ? ND->getDeclContext() : DC;
12326 }
12327
12328 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12329 };
12330
12331 /// Determine whether the given template parameter lists are
12332 /// equivalent.
12333 ///
12334 /// \param New The new template parameter list, typically written in the
12335 /// source code as part of a new template declaration.
12336 ///
12337 /// \param Old The old template parameter list, typically found via
12338 /// name lookup of the template declared with this template parameter
12339 /// list.
12340 ///
12341 /// \param Complain If true, this routine will produce a diagnostic if
12342 /// the template parameter lists are not equivalent.
12343 ///
12344 /// \param Kind describes how we are to match the template parameter lists.
12345 ///
12346 /// \param TemplateArgLoc If this source location is valid, then we
12347 /// are actually checking the template parameter list of a template
12348 /// argument (New) against the template parameter list of its
12349 /// corresponding template template parameter (Old). We produce
12350 /// slightly different diagnostics in this scenario.
12351 ///
12352 /// \returns True if the template parameter lists are equal, false
12353 /// otherwise.
12354 bool TemplateParameterListsAreEqual(
12355 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12356 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12357 TemplateParameterListEqualKind Kind,
12358 SourceLocation TemplateArgLoc = SourceLocation());
12359
12360 bool TemplateParameterListsAreEqual(
12361 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12362 TemplateParameterListEqualKind Kind,
12363 SourceLocation TemplateArgLoc = SourceLocation()) {
12364 return TemplateParameterListsAreEqual(NewInstFrom: nullptr, New, OldInstFrom: nullptr, Old, Complain,
12365 Kind, TemplateArgLoc);
12366 }
12367
12368 /// Check whether a template can be declared within this scope.
12369 ///
12370 /// If the template declaration is valid in this scope, returns
12371 /// false. Otherwise, issues a diagnostic and returns true.
12372 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12373
12374 /// Called when the parser has parsed a C++ typename
12375 /// specifier, e.g., "typename T::type".
12376 ///
12377 /// \param S The scope in which this typename type occurs.
12378 /// \param TypenameLoc the location of the 'typename' keyword
12379 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12380 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12381 /// \param IdLoc the location of the identifier.
12382 /// \param IsImplicitTypename context where T::type refers to a type.
12383 TypeResult ActOnTypenameType(
12384 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12385 const IdentifierInfo &II, SourceLocation IdLoc,
12386 ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No);
12387
12388 /// Called when the parser has parsed a C++ typename
12389 /// specifier that ends in a template-id, e.g.,
12390 /// "typename MetaFun::template apply<T1, T2>".
12391 ///
12392 /// \param S The scope in which this typename type occurs.
12393 /// \param TypenameLoc the location of the 'typename' keyword
12394 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12395 /// \param TemplateLoc the location of the 'template' keyword, if any.
12396 /// \param TemplateName The template name.
12397 /// \param TemplateII The identifier used to name the template.
12398 /// \param TemplateIILoc The location of the template name.
12399 /// \param LAngleLoc The location of the opening angle bracket ('<').
12400 /// \param TemplateArgs The template arguments.
12401 /// \param RAngleLoc The location of the closing angle bracket ('>').
12402 TypeResult
12403 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12404 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12405 TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12406 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12407 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12408
12409 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12410 SourceLocation KeywordLoc,
12411 NestedNameSpecifierLoc QualifierLoc,
12412 const IdentifierInfo &II, SourceLocation IILoc,
12413 TypeSourceInfo **TSI, bool DeducedTSTContext);
12414
12415 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12416 SourceLocation KeywordLoc,
12417 NestedNameSpecifierLoc QualifierLoc,
12418 const IdentifierInfo &II, SourceLocation IILoc,
12419 bool DeducedTSTContext = true);
12420
12421 /// Rebuilds a type within the context of the current instantiation.
12422 ///
12423 /// The type \p T is part of the type of an out-of-line member definition of
12424 /// a class template (or class template partial specialization) that was
12425 /// parsed and constructed before we entered the scope of the class template
12426 /// (or partial specialization thereof). This routine will rebuild that type
12427 /// now that we have entered the declarator's scope, which may produce
12428 /// different canonical types, e.g.,
12429 ///
12430 /// \code
12431 /// template<typename T>
12432 /// struct X {
12433 /// typedef T* pointer;
12434 /// pointer data();
12435 /// };
12436 ///
12437 /// template<typename T>
12438 /// typename X<T>::pointer X<T>::data() { ... }
12439 /// \endcode
12440 ///
12441 /// Here, the type "typename X<T>::pointer" will be created as a
12442 /// DependentNameType, since we do not know that we can look into X<T> when we
12443 /// parsed the type. This function will rebuild the type, performing the
12444 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12445 /// canonical type is the same as the canonical type of T*, allowing the
12446 /// return types of the out-of-line definition and the declaration to match.
12447 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
12448 SourceLocation Loc,
12449 DeclarationName Name);
12450 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
12451
12452 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
12453
12454 /// Rebuild the template parameters now that we know we're in a current
12455 /// instantiation.
12456 bool
12457 RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params);
12458
12459 /// Produces a formatted string that describes the binding of
12460 /// template parameters to template arguments.
12461 std::string
12462 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12463 const TemplateArgumentList &Args);
12464
12465 std::string
12466 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12467 const TemplateArgument *Args,
12468 unsigned NumArgs);
12469
12470 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
12471 SourceLocation Less,
12472 SourceLocation Greater);
12473
12474 /// ActOnDependentIdExpression - Handle a dependent id-expression that
12475 /// was just parsed. This is only possible with an explicit scope
12476 /// specifier naming a dependent type.
12477 ExprResult ActOnDependentIdExpression(
12478 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12479 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12480 const TemplateArgumentListInfo *TemplateArgs);
12481
12482 ExprResult
12483 BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
12484 SourceLocation TemplateKWLoc,
12485 const DeclarationNameInfo &NameInfo,
12486 const TemplateArgumentListInfo *TemplateArgs);
12487
12488 // Calculates whether the expression Constraint depends on an enclosing
12489 // template, for the purposes of [temp.friend] p9.
12490 // TemplateDepth is the 'depth' of the friend function, which is used to
12491 // compare whether a declaration reference is referring to a containing
12492 // template, or just the current friend function. A 'lower' TemplateDepth in
12493 // the AST refers to a 'containing' template. As the constraint is
12494 // uninstantiated, this is relative to the 'top' of the TU.
12495 bool
12496 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
12497 unsigned TemplateDepth,
12498 const Expr *Constraint);
12499
12500 /// Find the failed Boolean condition within a given Boolean
12501 /// constant expression, and describe it with a string.
12502 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12503
12504 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
12505
12506 ConceptDecl *ActOnStartConceptDefinition(
12507 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12508 const IdentifierInfo *Name, SourceLocation NameLoc);
12509
12510 ConceptDecl *ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
12511 Expr *ConstraintExpr,
12512 const ParsedAttributesView &Attrs);
12513
12514 void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
12515 bool &AddToScope);
12516 bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc);
12517
12518 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12519 const CXXScopeSpec &SS,
12520 const IdentifierInfo *Name,
12521 SourceLocation TagLoc, SourceLocation NameLoc);
12522
12523 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
12524 CachedTokens &Toks);
12525 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
12526 bool IsInsideALocalClassWithinATemplateFunction();
12527
12528 /// We've found a use of a templated declaration that would trigger an
12529 /// implicit instantiation. Check that any relevant explicit specializations
12530 /// and partial specializations are visible/reachable, and diagnose if not.
12531 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
12532 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
12533
12534 ///@}
12535
12536 //
12537 //
12538 // -------------------------------------------------------------------------
12539 //
12540 //
12541
12542 /// \name C++ Template Argument Deduction
12543 /// Implementations are in SemaTemplateDeduction.cpp
12544 ///@{
12545
12546public:
12547 class SFINAETrap;
12548
12549 struct SFINAEContextBase {
12550 SFINAEContextBase(Sema &S, SFINAETrap *Cur)
12551 : S(S), Prev(std::exchange(obj&: S.CurrentSFINAEContext, new_val&: Cur)) {}
12552
12553 protected:
12554 Sema &S;
12555 ~SFINAEContextBase() { S.CurrentSFINAEContext = Prev; }
12556 SFINAEContextBase(const SFINAEContextBase &) = delete;
12557 SFINAEContextBase &operator=(const SFINAEContextBase &) = delete;
12558
12559 private:
12560 SFINAETrap *Prev;
12561 };
12562
12563 struct NonSFINAEContext : SFINAEContextBase {
12564 NonSFINAEContext(Sema &S) : SFINAEContextBase(S, nullptr) {}
12565 };
12566
12567 /// RAII class used to determine whether SFINAE has
12568 /// trapped any errors that occur during template argument
12569 /// deduction.
12570 class SFINAETrap : SFINAEContextBase {
12571 bool HasErrorOcurred = false;
12572 bool WithAccessChecking = false;
12573 bool PrevLastDiagnosticIgnored =
12574 S.getDiagnostics().isLastDiagnosticIgnored();
12575 sema::TemplateDeductionInfo *DeductionInfo = nullptr;
12576
12577 SFINAETrap(Sema &S, sema::TemplateDeductionInfo *Info,
12578 bool WithAccessChecking)
12579 : SFINAEContextBase(S, this), WithAccessChecking(WithAccessChecking),
12580 DeductionInfo(Info) {}
12581
12582 public:
12583 /// \param WithAccessChecking If true, discard all diagnostics (from the
12584 /// immediate context) instead of adding them to the currently active
12585 /// \ref TemplateDeductionInfo.
12586 explicit SFINAETrap(Sema &S, bool WithAccessChecking = false)
12587 : SFINAETrap(S, /*Info=*/nullptr, WithAccessChecking) {}
12588
12589 SFINAETrap(Sema &S, sema::TemplateDeductionInfo &Info)
12590 : SFINAETrap(S, &Info, /*WithAccessChecking=*/false) {}
12591
12592 ~SFINAETrap() {
12593 S.getDiagnostics().setLastDiagnosticIgnored(PrevLastDiagnosticIgnored);
12594 }
12595
12596 SFINAETrap(const SFINAETrap &) = delete;
12597 SFINAETrap &operator=(const SFINAETrap &) = delete;
12598
12599 sema::TemplateDeductionInfo *getDeductionInfo() const {
12600 return DeductionInfo;
12601 }
12602
12603 /// Determine whether any SFINAE errors have been trapped.
12604 bool hasErrorOccurred() const { return HasErrorOcurred; }
12605 void setErrorOccurred() { HasErrorOcurred = true; }
12606
12607 bool withAccessChecking() const { return WithAccessChecking; }
12608 };
12609
12610 /// RAII class used to indicate that we are performing provisional
12611 /// semantic analysis to determine the validity of a construct, so
12612 /// typo-correction and diagnostics in the immediate context (not within
12613 /// implicitly-instantiated templates) should be suppressed.
12614 class TentativeAnalysisScope {
12615 Sema &SemaRef;
12616 // FIXME: Using a SFINAETrap for this is a hack.
12617 SFINAETrap Trap;
12618 bool PrevDisableTypoCorrection;
12619
12620 public:
12621 explicit TentativeAnalysisScope(Sema &SemaRef)
12622 : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12623 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12624 SemaRef.DisableTypoCorrection = true;
12625 }
12626 ~TentativeAnalysisScope() {
12627 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12628 }
12629
12630 TentativeAnalysisScope(const TentativeAnalysisScope &) = delete;
12631 TentativeAnalysisScope &operator=(const TentativeAnalysisScope &) = delete;
12632 };
12633
12634 /// For each declaration that involved template argument deduction, the
12635 /// set of diagnostics that were suppressed during that template argument
12636 /// deduction.
12637 ///
12638 /// FIXME: Serialize this structure to the AST file.
12639 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12640 SuppressedDiagnosticsMap;
12641 SuppressedDiagnosticsMap SuppressedDiagnostics;
12642
12643 /// Compare types for equality with respect to possibly compatible
12644 /// function types (noreturn adjustment, implicit calling conventions). If any
12645 /// of parameter and argument is not a function, just perform type comparison.
12646 ///
12647 /// \param P the template parameter type.
12648 ///
12649 /// \param A the argument type.
12650 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
12651
12652 /// Allocate a TemplateArgumentLoc where all locations have
12653 /// been initialized to the given location.
12654 ///
12655 /// \param Arg The template argument we are producing template argument
12656 /// location information for.
12657 ///
12658 /// \param NTTPType For a declaration template argument, the type of
12659 /// the non-type template parameter that corresponds to this template
12660 /// argument. Can be null if no type sugar is available to add to the
12661 /// type from the template argument.
12662 ///
12663 /// \param Loc The source location to use for the resulting template
12664 /// argument.
12665 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
12666 QualType NTTPType,
12667 SourceLocation Loc);
12668
12669 /// Get a template argument mapping the given template parameter to itself,
12670 /// e.g. for X in \c template<int X>, this would return an expression template
12671 /// argument referencing X.
12672 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
12673 SourceLocation Location);
12674
12675 /// Adjust the type \p ArgFunctionType to match the calling convention,
12676 /// noreturn, and optionally the exception specification of \p FunctionType.
12677 /// Deduction often wants to ignore these properties when matching function
12678 /// types.
12679 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
12680 bool AdjustExceptionSpec = false);
12681
12682 TemplateDeductionResult
12683 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
12684 ArrayRef<TemplateArgument> TemplateArgs,
12685 sema::TemplateDeductionInfo &Info);
12686
12687 TemplateDeductionResult
12688 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
12689 ArrayRef<TemplateArgument> TemplateArgs,
12690 sema::TemplateDeductionInfo &Info);
12691
12692 /// Deduce the template arguments of the given template from \p FromType.
12693 /// Used to implement the IsDeducible constraint for alias CTAD per C++
12694 /// [over.match.class.deduct]p4.
12695 ///
12696 /// It only supports class or type alias templates.
12697 TemplateDeductionResult
12698 DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType,
12699 sema::TemplateDeductionInfo &Info);
12700
12701 TemplateDeductionResult DeduceTemplateArguments(
12702 TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps,
12703 ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info,
12704 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12705 bool NumberOfArgumentsMustMatch);
12706
12707 /// Substitute the explicitly-provided template arguments into the
12708 /// given function template according to C++ [temp.arg.explicit].
12709 ///
12710 /// \param FunctionTemplate the function template into which the explicit
12711 /// template arguments will be substituted.
12712 ///
12713 /// \param ExplicitTemplateArgs the explicitly-specified template
12714 /// arguments.
12715 ///
12716 /// \param Deduced the deduced template arguments, which will be populated
12717 /// with the converted and checked explicit template arguments.
12718 ///
12719 /// \param ParamTypes will be populated with the instantiated function
12720 /// parameters.
12721 ///
12722 /// \param FunctionType if non-NULL, the result type of the function template
12723 /// will also be instantiated and the pointed-to value will be updated with
12724 /// the instantiated function type.
12725 ///
12726 /// \param Info if substitution fails for any reason, this object will be
12727 /// populated with more information about the failure.
12728 ///
12729 /// \returns TemplateDeductionResult::Success if substitution was successful,
12730 /// or some failure condition.
12731 TemplateDeductionResult SubstituteExplicitTemplateArguments(
12732 FunctionTemplateDecl *FunctionTemplate,
12733 TemplateArgumentListInfo &ExplicitTemplateArgs,
12734 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12735 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
12736 sema::TemplateDeductionInfo &Info);
12737
12738 /// brief A function argument from which we performed template argument
12739 // deduction for a call.
12740 struct OriginalCallArg {
12741 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
12742 unsigned ArgIdx, QualType OriginalArgType)
12743 : OriginalParamType(OriginalParamType),
12744 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
12745 OriginalArgType(OriginalArgType) {}
12746
12747 QualType OriginalParamType;
12748 bool DecomposedParam;
12749 unsigned ArgIdx;
12750 QualType OriginalArgType;
12751 };
12752
12753 /// Finish template argument deduction for a function template,
12754 /// checking the deduced template arguments for completeness and forming
12755 /// the function template specialization.
12756 ///
12757 /// \param OriginalCallArgs If non-NULL, the original call arguments against
12758 /// which the deduced argument types should be compared.
12759 /// \param CheckNonDependent Callback before substituting into the declaration
12760 /// with the deduced template arguments.
12761 /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12762 /// some breakages introduced by CWG2369, where non-user-defined conversions
12763 /// are checked first before the constraints.
12764 TemplateDeductionResult FinishTemplateArgumentDeduction(
12765 FunctionTemplateDecl *FunctionTemplate,
12766 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12767 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12768 sema::TemplateDeductionInfo &Info,
12769 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12770 bool PartialOverloading, bool PartialOrdering,
12771 bool ForOverloadSetAddressResolution,
12772 llvm::function_ref<bool(bool)> CheckNonDependent =
12773 [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12774 return false;
12775 });
12776
12777 /// Perform [temp.friend] p5 template argument deduction for a dependent
12778 /// friend declaration and a candidate class template specialization.
12779 bool DeduceTemplateArguments(FriendTemplateDecl *FTD,
12780 ClassTemplateDecl *PatternCTD,
12781 ClassTemplateDecl *CandidateCTD,
12782 ArrayRef<TemplateParameterList *> TPLs,
12783 ArrayRef<TemplateArgument> PatternArgs,
12784 ArrayRef<TemplateArgument> CandidateArgs,
12785 SourceLocation Loc,
12786 TemplateSpecCandidateSet *FailedTSC,
12787 MultiLevelTemplateArgumentList &DeducedArgs);
12788
12789 /// Perform template argument deduction from a function call
12790 /// (C++ [temp.deduct.call]).
12791 ///
12792 /// \param FunctionTemplate the function template for which we are performing
12793 /// template argument deduction.
12794 ///
12795 /// \param ExplicitTemplateArgs the explicit template arguments provided
12796 /// for this call.
12797 ///
12798 /// \param Args the function call arguments
12799 ///
12800 /// \param Specialization if template argument deduction was successful,
12801 /// this will be set to the function template specialization produced by
12802 /// template argument deduction.
12803 ///
12804 /// \param Info the argument will be updated to provide additional information
12805 /// about template argument deduction.
12806 ///
12807 /// \param CheckNonDependent A callback to invoke to check conversions for
12808 /// non-dependent parameters, between deduction and substitution, per DR1391.
12809 /// If this returns true, substitution will be skipped and we return
12810 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12811 /// passed the parameter types (after substituting explicit template
12812 /// arguments).
12813 ///
12814 /// \returns the result of template argument deduction.
12815 TemplateDeductionResult DeduceTemplateArguments(
12816 FunctionTemplateDecl *FunctionTemplate,
12817 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12818 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12819 bool PartialOverloading, bool AggregateDeductionCandidate,
12820 bool PartialOrdering, QualType ObjectType,
12821 Expr::Classification ObjectClassification,
12822 bool ForOverloadSetAddressResolution,
12823 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12824
12825 /// Deduce template arguments when taking the address of a function
12826 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12827 /// a template.
12828 ///
12829 /// \param FunctionTemplate the function template for which we are performing
12830 /// template argument deduction.
12831 ///
12832 /// \param ExplicitTemplateArgs the explicitly-specified template
12833 /// arguments.
12834 ///
12835 /// \param ArgFunctionType the function type that will be used as the
12836 /// "argument" type (A) when performing template argument deduction from the
12837 /// function template's function type. This type may be NULL, if there is no
12838 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
12839 ///
12840 /// \param Specialization if template argument deduction was successful,
12841 /// this will be set to the function template specialization produced by
12842 /// template argument deduction.
12843 ///
12844 /// \param Info the argument will be updated to provide additional information
12845 /// about template argument deduction.
12846 ///
12847 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12848 /// the address of a function template per [temp.deduct.funcaddr] and
12849 /// [over.over]. If \c false, we are looking up a function template
12850 /// specialization based on its signature, per [temp.deduct.decl].
12851 ///
12852 /// \returns the result of template argument deduction.
12853 TemplateDeductionResult DeduceTemplateArguments(
12854 FunctionTemplateDecl *FunctionTemplate,
12855 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
12856 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12857 bool IsAddressOfFunction = false);
12858
12859 /// Deduce template arguments for a templated conversion
12860 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
12861 /// conversion function template specialization.
12862 TemplateDeductionResult DeduceTemplateArguments(
12863 FunctionTemplateDecl *FunctionTemplate, QualType ObjectType,
12864 Expr::Classification ObjectClassification, QualType ToType,
12865 CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info);
12866
12867 /// Deduce template arguments for a function template when there is
12868 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
12869 ///
12870 /// \param FunctionTemplate the function template for which we are performing
12871 /// template argument deduction.
12872 ///
12873 /// \param ExplicitTemplateArgs the explicitly-specified template
12874 /// arguments.
12875 ///
12876 /// \param Specialization if template argument deduction was successful,
12877 /// this will be set to the function template specialization produced by
12878 /// template argument deduction.
12879 ///
12880 /// \param Info the argument will be updated to provide additional information
12881 /// about template argument deduction.
12882 ///
12883 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12884 /// the address of a function template in a context where we do not have a
12885 /// target type, per [over.over]. If \c false, we are looking up a function
12886 /// template specialization based on its signature, which only happens when
12887 /// deducing a function parameter type from an argument that is a template-id
12888 /// naming a function template specialization.
12889 ///
12890 /// \returns the result of template argument deduction.
12891 TemplateDeductionResult
12892 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
12893 TemplateArgumentListInfo *ExplicitTemplateArgs,
12894 FunctionDecl *&Specialization,
12895 sema::TemplateDeductionInfo &Info,
12896 bool IsAddressOfFunction = false);
12897
12898 /// Substitute Replacement for \p auto in \p TypeWithAuto
12899 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
12900 /// Substitute Replacement for auto in TypeWithAuto
12901 TypeSourceInfo *SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12902 QualType Replacement);
12903
12904 // Substitute auto in TypeWithAuto for a Dependent auto type
12905 QualType SubstAutoTypeDependent(QualType TypeWithAuto);
12906
12907 // Substitute auto in TypeWithAuto for a Dependent auto type
12908 TypeSourceInfo *
12909 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
12910
12911 /// Completely replace the \c auto in \p TypeWithAuto by
12912 /// \p Replacement. This does not retain any \c auto type sugar.
12913 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
12914 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12915 QualType Replacement);
12916
12917 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
12918 ///
12919 /// Note that this is done even if the initializer is dependent. (This is
12920 /// necessary to support partial ordering of templates using 'auto'.)
12921 /// A dependent type will be produced when deducing from a dependent type.
12922 ///
12923 /// \param Type the type pattern using the auto type-specifier.
12924 /// \param Init the initializer for the variable whose type is to be deduced.
12925 /// \param Result if type deduction was successful, this will be set to the
12926 /// deduced type.
12927 /// \param Info the argument will be updated to provide additional information
12928 /// about template argument deduction.
12929 /// \param DependentDeduction Set if we should permit deduction in
12930 /// dependent cases. This is necessary for template partial ordering
12931 /// with 'auto' template parameters. The template parameter depth to be
12932 /// used should be specified in the 'Info' parameter.
12933 /// \param IgnoreConstraints Set if we should not fail if the deduced type
12934 /// does not satisfy the type-constraint in the auto
12935 /// type.
12936 TemplateDeductionResult
12937 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result,
12938 sema::TemplateDeductionInfo &Info,
12939 bool DependentDeduction = false,
12940 bool IgnoreConstraints = false,
12941 TemplateSpecCandidateSet *FailedTSC = nullptr);
12942 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
12943 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
12944 bool Diagnose = true);
12945
12946 bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD,
12947 SourceLocation Loc);
12948
12949 /// Returns the more specialized class template partial specialization
12950 /// according to the rules of partial ordering of class template partial
12951 /// specializations (C++ [temp.class.order]).
12952 ///
12953 /// \param PS1 the first class template partial specialization
12954 ///
12955 /// \param PS2 the second class template partial specialization
12956 ///
12957 /// \returns the more specialized class template partial specialization. If
12958 /// neither partial specialization is more specialized, returns NULL.
12959 ClassTemplatePartialSpecializationDecl *
12960 getMoreSpecializedPartialSpecialization(
12961 ClassTemplatePartialSpecializationDecl *PS1,
12962 ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
12963
12964 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
12965 sema::TemplateDeductionInfo &Info);
12966
12967 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
12968 VarTemplatePartialSpecializationDecl *PS1,
12969 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
12970
12971 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
12972 sema::TemplateDeductionInfo &Info);
12973
12974 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
12975 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
12976 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
12977 bool PartialOrdering, bool *StrictPackMatch);
12978
12979 /// Mark which template parameters are used in a given expression.
12980 ///
12981 /// \param E the expression from which template parameters will be deduced.
12982 ///
12983 /// \param Used a bit vector whose elements will be set to \c true
12984 /// to indicate when the corresponding template parameter will be
12985 /// deduced.
12986 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
12987 unsigned Depth, llvm::SmallBitVector &Used);
12988
12989 /// Mark which template parameters are named in a given expression.
12990 ///
12991 /// Unlike MarkUsedTemplateParameters, this excludes parameter that
12992 /// are used but not directly named by an expression - i.e. it excludes
12993 /// any template parameter that denotes the type of a referenced NTTP.
12994 ///
12995 /// \param Used a bit vector whose elements will be set to \c true
12996 /// to indicate when the corresponding template parameter will be
12997 /// deduced.
12998 void MarkUsedTemplateParametersForSubsumptionParameterMapping(
12999 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used);
13000
13001 /// Mark which template parameters can be deduced from a given
13002 /// template argument list.
13003 ///
13004 /// \param TemplateArgs the template argument list from which template
13005 /// parameters will be deduced.
13006 ///
13007 /// \param Used a bit vector whose elements will be set to \c true
13008 /// to indicate when the corresponding template parameter will be
13009 /// deduced.
13010 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
13011 bool OnlyDeduced, unsigned Depth,
13012 llvm::SmallBitVector &Used);
13013
13014 void MarkUsedTemplateParameters(ArrayRef<TemplateArgument> TemplateArgs,
13015 bool OnlyDeduced, unsigned Depth,
13016 llvm::SmallBitVector &Used);
13017
13018 void MarkUsedTemplateParameters(ArrayRef<TemplateArgumentLoc> TemplateArgs,
13019 unsigned Depth, llvm::SmallBitVector &Used);
13020
13021 void
13022 MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate,
13023 llvm::SmallBitVector &Deduced) {
13024 return MarkDeducedTemplateParameters(Ctx&: Context, FunctionTemplate, Deduced);
13025 }
13026
13027 /// Marks all of the template parameters that will be deduced by a
13028 /// call to the given function template.
13029 static void
13030 MarkDeducedTemplateParameters(ASTContext &Ctx,
13031 const FunctionTemplateDecl *FunctionTemplate,
13032 llvm::SmallBitVector &Deduced);
13033
13034 /// Returns the more specialized function template according
13035 /// to the rules of function template partial ordering (C++
13036 /// [temp.func.order]).
13037 ///
13038 /// \param FT1 the first function template
13039 ///
13040 /// \param FT2 the second function template
13041 ///
13042 /// \param TPOC the context in which we are performing partial ordering of
13043 /// function templates.
13044 ///
13045 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
13046 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
13047 /// when calling a member function.
13048 ///
13049 /// \param RawObj1Ty The type of the object parameter of FT1 if a member
13050 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
13051 /// template from a member function
13052 ///
13053 /// \param RawObj2Ty The type of the object parameter of FT2 if a member
13054 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
13055 /// template from a member function
13056 ///
13057 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
13058 /// candidate with a reversed parameter order. In this case, the corresponding
13059 /// P/A pairs between FT1 and FT2 are reversed.
13060 ///
13061 /// \returns the more specialized function template. If neither
13062 /// template is more specialized, returns NULL.
13063 FunctionTemplateDecl *getMoreSpecializedTemplate(
13064 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
13065 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
13066 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
13067 bool PartialOverloading = false);
13068
13069 /// Retrieve the most specialized of the given function template
13070 /// specializations.
13071 ///
13072 /// \param SpecBegin the start iterator of the function template
13073 /// specializations that we will be comparing.
13074 ///
13075 /// \param SpecEnd the end iterator of the function template
13076 /// specializations, paired with \p SpecBegin.
13077 ///
13078 /// \param Loc the location where the ambiguity or no-specializations
13079 /// diagnostic should occur.
13080 ///
13081 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
13082 /// no matching candidates.
13083 ///
13084 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
13085 /// occurs.
13086 ///
13087 /// \param CandidateDiag partial diagnostic used for each function template
13088 /// specialization that is a candidate in the ambiguous ordering. One
13089 /// parameter in this diagnostic should be unbound, which will correspond to
13090 /// the string describing the template arguments for the function template
13091 /// specialization.
13092 ///
13093 /// \returns the most specialized function template specialization, if
13094 /// found. Otherwise, returns SpecEnd.
13095 UnresolvedSetIterator
13096 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
13097 TemplateSpecCandidateSet &FailedCandidates,
13098 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
13099 const PartialDiagnostic &AmbigDiag,
13100 const PartialDiagnostic &CandidateDiag,
13101 bool Complain = true, QualType TargetType = QualType());
13102
13103 /// Returns the more constrained function according to the rules of
13104 /// partial ordering by constraints (C++ [temp.constr.order]).
13105 ///
13106 /// \param FD1 the first function
13107 ///
13108 /// \param FD2 the second function
13109 ///
13110 /// \returns the more constrained function. If neither function is
13111 /// more constrained, returns NULL.
13112 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
13113 FunctionDecl *FD2);
13114
13115 ///@}
13116
13117 //
13118 //
13119 // -------------------------------------------------------------------------
13120 //
13121 //
13122
13123 /// \name C++ Template Deduction Guide
13124 /// Implementations are in SemaTemplateDeductionGuide.cpp
13125 ///@{
13126
13127 /// Declare implicit deduction guides for a class template if we've
13128 /// not already done so.
13129 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
13130 SourceLocation Loc);
13131
13132 CXXDeductionGuideDecl *DeclareAggregateDeductionGuideFromInitList(
13133 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
13134 SourceLocation Loc);
13135
13136 ///@}
13137
13138 //
13139 //
13140 // -------------------------------------------------------------------------
13141 //
13142 //
13143
13144 /// \name C++ Template Instantiation
13145 /// Implementations are in SemaTemplateInstantiate.cpp
13146 ///@{
13147
13148public:
13149 /// A helper class for building up ExtParameterInfos.
13150 class ExtParameterInfoBuilder {
13151 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
13152 bool HasInteresting = false;
13153
13154 public:
13155 /// Set the ExtParameterInfo for the parameter at the given index,
13156 ///
13157 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
13158 assert(Infos.size() <= index);
13159 Infos.resize(N: index);
13160 Infos.push_back(Elt: info);
13161
13162 if (!HasInteresting)
13163 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
13164 }
13165
13166 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
13167 /// ExtParameterInfo array we've built up.
13168 const FunctionProtoType::ExtParameterInfo *
13169 getPointerOrNull(unsigned numParams) {
13170 if (!HasInteresting)
13171 return nullptr;
13172 Infos.resize(N: numParams);
13173 return Infos.data();
13174 }
13175 };
13176
13177 /// The current instantiation scope used to store local
13178 /// variables.
13179 LocalInstantiationScope *CurrentInstantiationScope;
13180
13181 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
13182 UnparsedDefaultArgInstantiationsMap;
13183
13184 /// A mapping from parameters with unparsed default arguments to the
13185 /// set of instantiations of each parameter.
13186 ///
13187 /// This mapping is a temporary data structure used when parsing
13188 /// nested class templates or nested classes of class templates,
13189 /// where we might end up instantiating an inner class before the
13190 /// default arguments of its methods have been parsed.
13191 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
13192
13193 using InstantiatingSpecializationsKey = llvm::PointerIntPair<Decl *, 2>;
13194
13195 struct RecursiveInstGuard {
13196 enum class Kind {
13197 Template,
13198 DefaultArgument,
13199 ExceptionSpec,
13200 };
13201
13202 RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
13203 : S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
13204 auto [_, Created] = S.InstantiatingSpecializations.insert(V: Key);
13205 if (!Created)
13206 Key = {};
13207 }
13208
13209 ~RecursiveInstGuard() {
13210 if (Key.getOpaqueValue()) {
13211 [[maybe_unused]] bool Erased =
13212 S.InstantiatingSpecializations.erase(V: Key);
13213 assert(Erased);
13214 }
13215 }
13216
13217 RecursiveInstGuard(const RecursiveInstGuard &) = delete;
13218 RecursiveInstGuard &operator=(const RecursiveInstGuard &) = delete;
13219
13220 operator bool() const { return Key.getOpaqueValue() == nullptr; }
13221
13222 private:
13223 Sema &S;
13224 Sema::InstantiatingSpecializationsKey Key;
13225 };
13226
13227 /// A context in which code is being synthesized (where a source location
13228 /// alone is not sufficient to identify the context). This covers template
13229 /// instantiation and various forms of implicitly-generated functions.
13230 struct CodeSynthesisContext {
13231 /// The kind of template instantiation we are performing
13232 enum SynthesisKind {
13233 /// We are instantiating a template declaration. The entity is
13234 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
13235 TemplateInstantiation,
13236
13237 /// We are instantiating a default argument for a template
13238 /// parameter. The Entity is the template parameter whose argument is
13239 /// being instantiated, the Template is the template, and the
13240 /// TemplateArgs/NumTemplateArguments provide the template arguments as
13241 /// specified.
13242 DefaultTemplateArgumentInstantiation,
13243
13244 /// We are instantiating a default argument for a function.
13245 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
13246 /// provides the template arguments as specified.
13247 DefaultFunctionArgumentInstantiation,
13248
13249 /// We are substituting explicit template arguments provided for
13250 /// a function template. The entity is a FunctionTemplateDecl.
13251 ExplicitTemplateArgumentSubstitution,
13252
13253 /// We are substituting template argument determined as part of
13254 /// template argument deduction for either a class template
13255 /// partial specialization or a function template. The
13256 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
13257 /// a TemplateDecl.
13258 DeducedTemplateArgumentSubstitution,
13259
13260 /// We are substituting into a lambda expression.
13261 LambdaExpressionSubstitution,
13262
13263 /// We are substituting prior template arguments into a new
13264 /// template parameter. The template parameter itself is either a
13265 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
13266 PriorTemplateArgumentSubstitution,
13267
13268 /// We are checking the validity of a default template argument that
13269 /// has been used when naming a template-id.
13270 DefaultTemplateArgumentChecking,
13271
13272 /// We are computing the exception specification for a defaulted special
13273 /// member function.
13274 ExceptionSpecEvaluation,
13275
13276 /// We are instantiating the exception specification for a function
13277 /// template which was deferred until it was needed.
13278 ExceptionSpecInstantiation,
13279
13280 /// We are instantiating a requirement of a requires expression.
13281 RequirementInstantiation,
13282
13283 /// We are checking the satisfaction of a nested requirement of a requires
13284 /// expression.
13285 NestedRequirementConstraintsCheck,
13286
13287 /// We are declaring an implicit special member function.
13288 DeclaringSpecialMember,
13289
13290 /// We are declaring an implicit 'operator==' for a defaulted
13291 /// 'operator<=>'.
13292 DeclaringImplicitEqualityComparison,
13293
13294 /// We are defining a synthesized function (such as a defaulted special
13295 /// member).
13296 DefiningSynthesizedFunction,
13297
13298 // We are checking the constraints associated with a constrained entity or
13299 // the constraint expression of a concept. This includes the checks that
13300 // atomic constraints have the type 'bool' and that they can be constant
13301 // evaluated.
13302 ConstraintsCheck,
13303
13304 // We are substituting template arguments into a constraint expression.
13305 ConstraintSubstitution,
13306
13307 // Instantiating a Requires Expression parameter clause.
13308 RequirementParameterInstantiation,
13309
13310 // We are substituting into the parameter mapping of an atomic constraint
13311 // during normalization.
13312 ParameterMappingSubstitution,
13313
13314 /// We are rewriting a comparison operator in terms of an operator<=>.
13315 RewritingOperatorAsSpaceship,
13316
13317 /// We are initializing a structured binding.
13318 InitializingStructuredBinding,
13319
13320 /// We are marking a class as __dllexport.
13321 MarkingClassDllexported,
13322
13323 /// We are building an implied call from __builtin_dump_struct. The
13324 /// arguments are in CallArgs.
13325 BuildingBuiltinDumpStructCall,
13326
13327 /// Added for Template instantiation observation.
13328 /// Memoization means we are _not_ instantiating a template because
13329 /// it is already instantiated (but we entered a context where we
13330 /// would have had to if it was not already instantiated).
13331 Memoization,
13332
13333 /// We are building deduction guides for a class.
13334 BuildingDeductionGuides,
13335
13336 /// We are instantiating a type alias template declaration.
13337 TypeAliasTemplateInstantiation,
13338
13339 /// We are performing partial ordering for template template parameters.
13340 PartialOrderingTTP,
13341
13342 /// We are performing name lookup for a function template or variable
13343 /// template named 'sycl_kernel_launch'.
13344 SYCLKernelLaunchLookup,
13345
13346 /// We are performing overload resolution for a call to a function
13347 /// template or variable template named 'sycl_kernel_launch'.
13348 SYCLKernelLaunchOverloadResolution,
13349
13350 /// We are instantiating an expansion statement.
13351 ExpansionStmtInstantiation,
13352 } Kind;
13353
13354 /// Whether we're substituting into constraints.
13355 bool InConstraintSubstitution;
13356
13357 /// Whether we're substituting into the parameter mapping of a constraint.
13358 bool InParameterMappingSubstitution;
13359
13360 /// The point of instantiation or synthesis within the source code.
13361 SourceLocation PointOfInstantiation;
13362
13363 /// The entity that is being synthesized.
13364 Decl *Entity;
13365
13366 /// The template (or partial specialization) in which we are
13367 /// performing the instantiation, for substitutions of prior template
13368 /// arguments.
13369 NamedDecl *Template;
13370
13371 union {
13372 /// The list of template arguments we are substituting, if they
13373 /// are not part of the entity.
13374 const TemplateArgument *TemplateArgs;
13375
13376 /// The list of argument expressions in a synthesized call.
13377 const Expr *const *CallArgs;
13378 };
13379
13380 // FIXME: Wrap this union around more members, or perhaps store the
13381 // kind-specific members in the RAII object owning the context.
13382 union {
13383 /// The number of template arguments in TemplateArgs.
13384 unsigned NumTemplateArgs;
13385
13386 /// The number of expressions in CallArgs.
13387 unsigned NumCallArgs;
13388
13389 /// The special member being declared or defined.
13390 CXXSpecialMemberKind SpecialMember;
13391 };
13392
13393 ArrayRef<TemplateArgument> template_arguments() const {
13394 assert(Kind != DeclaringSpecialMember);
13395 return {TemplateArgs, NumTemplateArgs};
13396 }
13397
13398 /// The source range that covers the construct that cause
13399 /// the instantiation, e.g., the template-id that causes a class
13400 /// template instantiation.
13401 SourceRange InstantiationRange;
13402
13403 CodeSynthesisContext()
13404 : Kind(TemplateInstantiation), InConstraintSubstitution(false),
13405 InParameterMappingSubstitution(false), Entity(nullptr),
13406 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0) {}
13407
13408 /// Determines whether this template is an actual instantiation
13409 /// that should be counted toward the maximum instantiation depth.
13410 bool isInstantiationRecord() const;
13411 };
13412
13413 /// A stack object to be created when performing template
13414 /// instantiation.
13415 ///
13416 /// Construction of an object of type \c InstantiatingTemplate
13417 /// pushes the current instantiation onto the stack of active
13418 /// instantiations. If the size of this stack exceeds the maximum
13419 /// number of recursive template instantiations, construction
13420 /// produces an error and evaluates true.
13421 ///
13422 /// Destruction of this object will pop the named instantiation off
13423 /// the stack.
13424 struct InstantiatingTemplate {
13425 /// Note that we are instantiating a class template,
13426 /// function template, variable template, alias template,
13427 /// or a member thereof.
13428 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13429 Decl *Entity,
13430 SourceRange InstantiationRange = SourceRange());
13431
13432 struct ExceptionSpecification {};
13433 /// Note that we are instantiating an exception specification
13434 /// of a function template.
13435 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13436 FunctionDecl *Entity, ExceptionSpecification,
13437 SourceRange InstantiationRange = SourceRange());
13438
13439 /// Note that we are instantiating a type alias template declaration.
13440 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13441 TypeAliasTemplateDecl *Entity,
13442 ArrayRef<TemplateArgument> TemplateArgs,
13443 SourceRange InstantiationRange = SourceRange());
13444
13445 /// Note that we are instantiating a default argument in a
13446 /// template-id.
13447 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13448 TemplateParameter Param, TemplateDecl *Template,
13449 ArrayRef<TemplateArgument> TemplateArgs,
13450 SourceRange InstantiationRange = SourceRange());
13451
13452 /// Note that we are substituting either explicitly-specified or
13453 /// deduced template arguments during function template argument deduction.
13454 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13455 FunctionTemplateDecl *FunctionTemplate,
13456 ArrayRef<TemplateArgument> TemplateArgs,
13457 CodeSynthesisContext::SynthesisKind Kind,
13458 SourceRange InstantiationRange = SourceRange());
13459
13460 /// Note that we are instantiating as part of template
13461 /// argument deduction for a class template declaration.
13462 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13463 TemplateDecl *Template,
13464 ArrayRef<TemplateArgument> TemplateArgs,
13465 SourceRange InstantiationRange = SourceRange());
13466
13467 /// Note that we are instantiating as part of template
13468 /// argument deduction for a class template partial
13469 /// specialization.
13470 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13471 ClassTemplatePartialSpecializationDecl *PartialSpec,
13472 ArrayRef<TemplateArgument> TemplateArgs,
13473 SourceRange InstantiationRange = SourceRange());
13474
13475 /// Note that we are instantiating as part of template
13476 /// argument deduction for a variable template partial
13477 /// specialization.
13478 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13479 VarTemplatePartialSpecializationDecl *PartialSpec,
13480 ArrayRef<TemplateArgument> TemplateArgs,
13481 SourceRange InstantiationRange = SourceRange());
13482
13483 /// Note that we are instantiating a default argument for a function
13484 /// parameter.
13485 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13486 ParmVarDecl *Param,
13487 ArrayRef<TemplateArgument> TemplateArgs,
13488 SourceRange InstantiationRange = SourceRange());
13489
13490 /// Note that we are substituting prior template arguments into a
13491 /// non-type parameter.
13492 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13493 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
13494 ArrayRef<TemplateArgument> TemplateArgs,
13495 SourceRange InstantiationRange);
13496
13497 /// Note that we are substituting prior template arguments into a
13498 /// template template parameter.
13499 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13500 NamedDecl *Template, TemplateTemplateParmDecl *Param,
13501 ArrayRef<TemplateArgument> TemplateArgs,
13502 SourceRange InstantiationRange);
13503
13504 /// Note that we are checking the default template argument
13505 /// against the template parameter for a given template-id.
13506 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13507 TemplateDecl *Template, NamedDecl *Param,
13508 ArrayRef<TemplateArgument> TemplateArgs,
13509 SourceRange InstantiationRange);
13510
13511 struct ConstraintsCheck {};
13512 /// \brief Note that we are checking the constraints associated with some
13513 /// constrained entity (a concept declaration or a template with associated
13514 /// constraints).
13515 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13516 ConstraintsCheck, NamedDecl *Template,
13517 ArrayRef<TemplateArgument> TemplateArgs,
13518 SourceRange InstantiationRange);
13519
13520 struct ConstraintSubstitution {};
13521 /// \brief Note that we are checking a constraint expression associated
13522 /// with a template declaration or as part of the satisfaction check of a
13523 /// concept.
13524 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13525 ConstraintSubstitution, NamedDecl *Template,
13526 SourceRange InstantiationRange);
13527
13528 struct ParameterMappingSubstitution {};
13529 /// \brief Note that we are subtituting into the parameter mapping of an
13530 /// atomic constraint during constraint normalization.
13531 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13532 ParameterMappingSubstitution, NamedDecl *Template,
13533 SourceRange InstantiationRange);
13534
13535 /// \brief Note that we are substituting template arguments into a part of
13536 /// a requirement of a requires expression.
13537 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13538 concepts::Requirement *Req,
13539 SourceRange InstantiationRange = SourceRange());
13540
13541 /// \brief Note that we are substituting the body of an expansion statement.
13542 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13543 CXXExpansionStmtPattern *ExpansionStmt,
13544 ArrayRef<TemplateArgument> TArgs,
13545 SourceRange InstantiationRange);
13546
13547 /// \brief Note that we are checking the satisfaction of the constraint
13548 /// expression inside of a nested requirement.
13549 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13550 concepts::NestedRequirement *Req, ConstraintsCheck,
13551 SourceRange InstantiationRange = SourceRange());
13552
13553 /// \brief Note that we are checking a requires clause.
13554 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13555 const RequiresExpr *E,
13556 SourceRange InstantiationRange);
13557
13558 struct BuildingDeductionGuidesTag {};
13559 /// \brief Note that we are building deduction guides.
13560 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13561 TemplateDecl *Entity, BuildingDeductionGuidesTag,
13562 SourceRange InstantiationRange = SourceRange());
13563
13564 struct PartialOrderingTTP {};
13565 /// \brief Note that we are partial ordering template template parameters.
13566 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13567 PartialOrderingTTP, TemplateDecl *PArg,
13568 SourceRange InstantiationRange = SourceRange());
13569
13570 /// Note that we have finished instantiating this template.
13571 void Clear();
13572
13573 ~InstantiatingTemplate() { Clear(); }
13574
13575 /// Determines whether we have exceeded the maximum
13576 /// recursive template instantiations.
13577 bool isInvalid() const { return Invalid; }
13578
13579 private:
13580 Sema &SemaRef;
13581 bool Invalid;
13582
13583 InstantiatingTemplate(Sema &SemaRef,
13584 CodeSynthesisContext::SynthesisKind Kind,
13585 SourceLocation PointOfInstantiation,
13586 SourceRange InstantiationRange, Decl *Entity,
13587 NamedDecl *Template = nullptr,
13588 ArrayRef<TemplateArgument> TemplateArgs = {});
13589
13590 InstantiatingTemplate(const InstantiatingTemplate &) = delete;
13591
13592 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13593 };
13594
13595 bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13596 const MultiLevelTemplateArgumentList &TemplateArgs,
13597 TemplateArgumentLoc &Output,
13598 SourceLocation Loc = {},
13599 const DeclarationName &Entity = {});
13600 bool
13601 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13602 const MultiLevelTemplateArgumentList &TemplateArgs,
13603 TemplateArgumentListInfo &Outputs);
13604
13605 /// Substitute concept template arguments in the constraint expression
13606 /// of a concept-id. This is used to implement [temp.constr.normal].
13607 ExprResult
13608 SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE,
13609 const Expr *ConstraintExpr,
13610 const MultiLevelTemplateArgumentList &MLTAL);
13611
13612 bool SubstTemplateArgumentsInParameterMapping(
13613 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
13614 const MultiLevelTemplateArgumentList &TemplateArgs,
13615 TemplateArgumentListInfo &Out);
13616
13617 /// Retrieve the template argument list(s) that should be used to
13618 /// instantiate the definition of the given declaration.
13619 ///
13620 /// \param ND the declaration for which we are computing template
13621 /// instantiation arguments.
13622 ///
13623 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13624 /// the decl context where it will be created. In this case, the `Innermost`
13625 /// should likely be provided. If ND is non-null, this is ignored.
13626 ///
13627 /// \param Innermost if non-NULL, specifies a template argument list for the
13628 /// template declaration passed as ND.
13629 ///
13630 /// \param RelativeToPrimary true if we should get the template
13631 /// arguments relative to the primary template, even when we're
13632 /// dealing with a specialization. This is only relevant for function
13633 /// template specializations.
13634 ///
13635 /// \param Pattern If non-NULL, indicates the pattern from which we will be
13636 /// instantiating the definition of the given declaration, \p ND. This is
13637 /// used to determine the proper set of template instantiation arguments for
13638 /// friend function template specializations.
13639 ///
13640 /// \param ForConstraintInstantiation when collecting arguments,
13641 /// ForConstraintInstantiation indicates we should continue looking when
13642 /// encountering a lambda generic call operator, and continue looking for
13643 /// arguments on an enclosing class template.
13644 ///
13645 /// \param SkipForSpecialization when specified, any template specializations
13646 /// in a traversal would be ignored.
13647 ///
13648 /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13649 /// when encountering a specialized member function template, rather than
13650 /// returning immediately.
13651 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13652 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13653 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13654 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13655 bool ForConstraintInstantiation = false,
13656 bool SkipForSpecialization = false,
13657 bool ForDefaultArgumentSubstitution = false);
13658
13659 /// RAII object to handle the state changes required to synthesize
13660 /// a function body.
13661 class SynthesizedFunctionScope {
13662 Sema &S;
13663 Sema::ContextRAII SavedContext;
13664 bool PushedCodeSynthesisContext = false;
13665
13666 public:
13667 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
13668 : S(S), SavedContext(S, DC) {
13669 auto *FD = dyn_cast<FunctionDecl>(Val: DC);
13670 S.PushFunctionScope();
13671 S.PushExpressionEvaluationContextForFunction(
13672 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, FD);
13673 if (FD)
13674 FD->setWillHaveBody(true);
13675 else
13676 assert(isa<ObjCMethodDecl>(DC));
13677 }
13678
13679 void addContextNote(SourceLocation UseLoc) {
13680 assert(!PushedCodeSynthesisContext);
13681
13682 Sema::CodeSynthesisContext Ctx;
13683 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
13684 Ctx.PointOfInstantiation = UseLoc;
13685 Ctx.Entity = cast<Decl>(Val: S.CurContext);
13686 S.pushCodeSynthesisContext(Ctx);
13687
13688 PushedCodeSynthesisContext = true;
13689 }
13690
13691 ~SynthesizedFunctionScope() {
13692 if (PushedCodeSynthesisContext)
13693 S.popCodeSynthesisContext();
13694 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
13695 FD->setWillHaveBody(false);
13696 S.CheckImmediateEscalatingFunctionDefinition(FD, FSI: S.getCurFunction());
13697 }
13698 S.PopExpressionEvaluationContext();
13699 S.PopFunctionScopeInfo();
13700 }
13701
13702 SynthesizedFunctionScope(const SynthesizedFunctionScope &) = delete;
13703 SynthesizedFunctionScope &
13704 operator=(const SynthesizedFunctionScope &) = delete;
13705 };
13706
13707 /// RAII object to ensure that a code synthesis context is popped on scope
13708 /// exit.
13709 class ScopedCodeSynthesisContext {
13710 Sema &S;
13711
13712 public:
13713 ScopedCodeSynthesisContext(Sema &S, const CodeSynthesisContext &Ctx)
13714 : S(S) {
13715 S.pushCodeSynthesisContext(Ctx);
13716 }
13717
13718 ~ScopedCodeSynthesisContext() { S.popCodeSynthesisContext(); }
13719 ScopedCodeSynthesisContext(const ScopedCodeSynthesisContext &) = delete;
13720 ScopedCodeSynthesisContext &
13721 operator=(const ScopedCodeSynthesisContext &) = delete;
13722 };
13723
13724 /// List of active code synthesis contexts.
13725 ///
13726 /// This vector is treated as a stack. As synthesis of one entity requires
13727 /// synthesis of another, additional contexts are pushed onto the stack.
13728 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
13729
13730 /// Specializations whose definitions are currently being instantiated.
13731 llvm::DenseSet<InstantiatingSpecializationsKey> InstantiatingSpecializations;
13732
13733 /// Non-dependent types used in templates that have already been instantiated
13734 /// by some template instantiation.
13735 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13736
13737 /// Extra modules inspected when performing a lookup during a template
13738 /// instantiation. Computed lazily.
13739 SmallVector<Module *, 16> CodeSynthesisContextLookupModules;
13740
13741 /// Cache of additional modules that should be used for name lookup
13742 /// within the current template instantiation. Computed lazily; use
13743 /// getLookupModules() to get a complete set.
13744 llvm::DenseSet<Module *> LookupModulesCache;
13745
13746 /// Map from the most recent declaration of a namespace to the most
13747 /// recent visible declaration of that namespace.
13748 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13749
13750 SFINAETrap *CurrentSFINAEContext = nullptr;
13751
13752 /// The number of \p CodeSynthesisContexts that are not template
13753 /// instantiations and, therefore, should not be counted as part of the
13754 /// instantiation depth.
13755 ///
13756 /// When the instantiation depth reaches the user-configurable limit
13757 /// \p LangOptions::InstantiationDepth we will abort instantiation.
13758 // FIXME: Should we have a similar limit for other forms of synthesis?
13759 unsigned NonInstantiationEntries;
13760
13761 /// The depth of the context stack at the point when the most recent
13762 /// error or warning was produced.
13763 ///
13764 /// This value is used to suppress printing of redundant context stacks
13765 /// when there are multiple errors or warnings in the same instantiation.
13766 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13767 unsigned LastEmittedCodeSynthesisContextDepth = 0;
13768
13769 /// The current index into pack expansion arguments that will be
13770 /// used for substitution of parameter packs.
13771 ///
13772 /// The pack expansion index will be none to indicate that parameter packs
13773 /// should be instantiated as themselves. Otherwise, the index specifies
13774 /// which argument within the parameter pack will be used for substitution.
13775 UnsignedOrNone ArgPackSubstIndex;
13776
13777 /// RAII object used to change the argument pack substitution index
13778 /// within a \c Sema object.
13779 ///
13780 /// See \c ArgPackSubstIndex for more information.
13781 class ArgPackSubstIndexRAII {
13782 Sema &Self;
13783 UnsignedOrNone OldSubstIndex;
13784
13785 public:
13786 ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
13787 : Self(Self),
13788 OldSubstIndex(std::exchange(obj&: Self.ArgPackSubstIndex, new_val&: NewSubstIndex)) {}
13789
13790 ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13791 ArgPackSubstIndexRAII(const ArgPackSubstIndexRAII &) = delete;
13792 ArgPackSubstIndexRAII &operator=(const ArgPackSubstIndexRAII &) = delete;
13793 };
13794
13795 bool pushCodeSynthesisContext(CodeSynthesisContext Ctx);
13796 void popCodeSynthesisContext();
13797
13798 void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc) {
13799 if (!CodeSynthesisContexts.empty() &&
13800 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
13801 PrintInstantiationStack(DiagFunc);
13802 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
13803 }
13804 if (PragmaAttributeCurrentTargetDecl)
13805 PrintPragmaAttributeInstantiationPoint(DiagFunc);
13806 }
13807 void PrintContextStack() { PrintContextStack(DiagFunc: getDefaultDiagFunc()); }
13808 /// Prints the current instantiation stack through a series of
13809 /// notes.
13810 void PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc);
13811 void PrintInstantiationStack() {
13812 PrintInstantiationStack(DiagFunc: getDefaultDiagFunc());
13813 }
13814
13815 /// Returns a pointer to the current SFINAE context, if any.
13816 [[nodiscard]] SFINAETrap *getSFINAEContext() const {
13817 return CurrentSFINAEContext;
13818 }
13819 [[nodiscard]] bool isSFINAEContext() const {
13820 return CurrentSFINAEContext != nullptr;
13821 }
13822
13823 /// Perform substitution on the type T with a given set of template
13824 /// arguments.
13825 ///
13826 /// This routine substitutes the given template arguments into the
13827 /// type T and produces the instantiated type.
13828 ///
13829 /// \param T the type into which the template arguments will be
13830 /// substituted. If this type is not dependent, it will be returned
13831 /// immediately.
13832 ///
13833 /// \param Args the template arguments that will be
13834 /// substituted for the top-level template parameters within T.
13835 ///
13836 /// \param Loc the location in the source code where this substitution
13837 /// is being performed. It will typically be the location of the
13838 /// declarator (if we're instantiating the type of some declaration)
13839 /// or the location of the type in the source code (if, e.g., we're
13840 /// instantiating the type of a cast expression).
13841 ///
13842 /// \param Entity the name of the entity associated with a declaration
13843 /// being instantiated (if any). May be empty to indicate that there
13844 /// is no such entity (if, e.g., this is a type that occurs as part of
13845 /// a cast expression) or that the entity has no name (e.g., an
13846 /// unnamed function parameter).
13847 ///
13848 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
13849 /// acceptable as the top level type of the result.
13850 ///
13851 /// \param IsIncompleteSubstitution If provided, the pointee will be set
13852 /// whenever substitution would perform a replacement with a null or
13853 /// non-existent template argument.
13854 ///
13855 /// \returns If the instantiation succeeds, the instantiated
13856 /// type. Otherwise, produces diagnostics and returns a NULL type.
13857 TypeSourceInfo *SubstType(TypeSourceInfo *T,
13858 const MultiLevelTemplateArgumentList &TemplateArgs,
13859 SourceLocation Loc, DeclarationName Entity,
13860 bool AllowDeducedTST = false);
13861
13862 QualType SubstType(QualType T,
13863 const MultiLevelTemplateArgumentList &TemplateArgs,
13864 SourceLocation Loc, DeclarationName Entity,
13865 bool *IsIncompleteSubstitution = nullptr);
13866
13867 TypeSourceInfo *SubstType(TypeLoc TL,
13868 const MultiLevelTemplateArgumentList &TemplateArgs,
13869 SourceLocation Loc, DeclarationName Entity);
13870
13871 TypeSourceInfo *
13872 SubstFriendType(TypeSourceInfo *TSI,
13873 const MultiLevelTemplateArgumentList &TemplateArgs,
13874 SourceLocation Loc, DeclarationName Entity);
13875
13876 /// A form of SubstType intended specifically for instantiating the
13877 /// type of a FunctionDecl. Its purpose is solely to force the
13878 /// instantiation of default-argument expressions and to avoid
13879 /// instantiating an exception-specification.
13880 TypeSourceInfo *SubstFunctionDeclType(
13881 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
13882 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
13883 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
13884 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
13885 const MultiLevelTemplateArgumentList &Args);
13886 bool SubstExceptionSpec(SourceLocation Loc,
13887 FunctionProtoType::ExceptionSpecInfo &ESI,
13888 SmallVectorImpl<QualType> &ExceptionStorage,
13889 const MultiLevelTemplateArgumentList &Args);
13890 ParmVarDecl *
13891 SubstParmVarDecl(ParmVarDecl *D,
13892 const MultiLevelTemplateArgumentList &TemplateArgs,
13893 int indexAdjustment, UnsignedOrNone NumExpansions,
13894 bool ExpectParameterPack, bool EvaluateConstraints = true);
13895
13896 /// Substitute the given template arguments into the given set of
13897 /// parameters, producing the set of parameter types that would be generated
13898 /// from such a substitution.
13899 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
13900 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
13901 const MultiLevelTemplateArgumentList &TemplateArgs,
13902 SmallVectorImpl<QualType> &ParamTypes,
13903 SmallVectorImpl<ParmVarDecl *> *OutParams,
13904 ExtParameterInfoBuilder &ParamInfos);
13905
13906 /// Substitute the given template arguments into the default argument.
13907 bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param,
13908 const MultiLevelTemplateArgumentList &TemplateArgs,
13909 bool ForCallExpr = false);
13910 ExprResult SubstExpr(Expr *E,
13911 const MultiLevelTemplateArgumentList &TemplateArgs);
13912 /// Substitute an expression as if it is a address-of-operand, which makes it
13913 /// act like a CXXIdExpression rather than an attempt to call.
13914 ExprResult SubstCXXIdExpr(Expr *E,
13915 const MultiLevelTemplateArgumentList &TemplateArgs);
13916
13917 // Must be used instead of SubstExpr at 'constraint checking' time.
13918 ExprResult
13919 SubstConstraintExpr(Expr *E,
13920 const MultiLevelTemplateArgumentList &TemplateArgs);
13921 // Unlike the above, this does not evaluate constraints.
13922 ExprResult SubstConstraintExprWithoutSatisfaction(
13923 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
13924
13925 /// Substitute the given template arguments into a list of
13926 /// expressions, expanding pack expansions if required.
13927 ///
13928 /// \param Exprs The list of expressions to substitute into.
13929 ///
13930 /// \param IsCall Whether this is some form of call, in which case
13931 /// default arguments will be dropped.
13932 ///
13933 /// \param TemplateArgs The set of template arguments to substitute.
13934 ///
13935 /// \param Outputs Will receive all of the substituted arguments.
13936 ///
13937 /// \returns true if an error occurred, false otherwise.
13938 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
13939 const MultiLevelTemplateArgumentList &TemplateArgs,
13940 SmallVectorImpl<Expr *> &Outputs);
13941
13942 StmtResult SubstStmt(Stmt *S,
13943 const MultiLevelTemplateArgumentList &TemplateArgs);
13944
13945 ExprResult
13946 SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs,
13947 bool CXXDirectInit);
13948
13949 /// Perform substitution on the base class specifiers of the
13950 /// given class template specialization.
13951 ///
13952 /// Produces a diagnostic and returns true on error, returns false and
13953 /// attaches the instantiated base classes to the class template
13954 /// specialization if successful.
13955 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13956 const MultiLevelTemplateArgumentList &TemplateArgs);
13957
13958 /// Instantiate the definition of a class from a given pattern.
13959 ///
13960 /// \param PointOfInstantiation The point of instantiation within the
13961 /// source code.
13962 ///
13963 /// \param Instantiation is the declaration whose definition is being
13964 /// instantiated. This will be either a class template specialization
13965 /// or a member class of a class template specialization.
13966 ///
13967 /// \param Pattern is the pattern from which the instantiation
13968 /// occurs. This will be either the declaration of a class template or
13969 /// the declaration of a member class of a class template.
13970 ///
13971 /// \param TemplateArgs The template arguments to be substituted into
13972 /// the pattern.
13973 ///
13974 /// \param TSK the kind of implicit or explicit instantiation to perform.
13975 ///
13976 /// \param Complain whether to complain if the class cannot be instantiated
13977 /// due to the lack of a definition.
13978 ///
13979 /// \returns true if an error occurred, false otherwise.
13980 bool InstantiateClass(SourceLocation PointOfInstantiation,
13981 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13982 const MultiLevelTemplateArgumentList &TemplateArgs,
13983 TemplateSpecializationKind TSK, bool Complain = true);
13984
13985private:
13986 bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
13987 CXXRecordDecl *Instantiation,
13988 CXXRecordDecl *Pattern,
13989 const MultiLevelTemplateArgumentList &TemplateArgs,
13990 TemplateSpecializationKind TSK, bool Complain);
13991
13992public:
13993 /// Instantiate the definition of an enum from a given pattern.
13994 ///
13995 /// \param PointOfInstantiation The point of instantiation within the
13996 /// source code.
13997 /// \param Instantiation is the declaration whose definition is being
13998 /// instantiated. This will be a member enumeration of a class
13999 /// temploid specialization, or a local enumeration within a
14000 /// function temploid specialization.
14001 /// \param Pattern The templated declaration from which the instantiation
14002 /// occurs.
14003 /// \param TemplateArgs The template arguments to be substituted into
14004 /// the pattern.
14005 /// \param TSK The kind of implicit or explicit instantiation to perform.
14006 ///
14007 /// \return \c true if an error occurred, \c false otherwise.
14008 bool InstantiateEnum(SourceLocation PointOfInstantiation,
14009 EnumDecl *Instantiation, EnumDecl *Pattern,
14010 const MultiLevelTemplateArgumentList &TemplateArgs,
14011 TemplateSpecializationKind TSK);
14012
14013 /// Instantiate the definition of a field from the given pattern.
14014 ///
14015 /// \param PointOfInstantiation The point of instantiation within the
14016 /// source code.
14017 /// \param Instantiation is the declaration whose definition is being
14018 /// instantiated. This will be a class of a class temploid
14019 /// specialization, or a local enumeration within a function temploid
14020 /// specialization.
14021 /// \param Pattern The templated declaration from which the instantiation
14022 /// occurs.
14023 /// \param TemplateArgs The template arguments to be substituted into
14024 /// the pattern.
14025 ///
14026 /// \return \c true if an error occurred, \c false otherwise.
14027 bool InstantiateInClassInitializer(
14028 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
14029 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
14030
14031 bool usesPartialOrExplicitSpecialization(
14032 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
14033
14034 bool InstantiateClassTemplateSpecialization(
14035 SourceLocation PointOfInstantiation,
14036 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14037 TemplateSpecializationKind TSK, bool Complain,
14038 bool PrimaryStrictPackMatch);
14039
14040 /// Instantiates the definitions of all of the member
14041 /// of the given class, which is an instantiation of a class template
14042 /// or a member class of a template.
14043 void
14044 InstantiateClassMembers(SourceLocation PointOfInstantiation,
14045 CXXRecordDecl *Instantiation,
14046 const MultiLevelTemplateArgumentList &TemplateArgs,
14047 TemplateSpecializationKind TSK);
14048
14049 /// Instantiate the definitions of all of the members of the
14050 /// given class template specialization, which was named as part of an
14051 /// explicit instantiation.
14052 void InstantiateClassTemplateSpecializationMembers(
14053 SourceLocation PointOfInstantiation,
14054 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14055 TemplateSpecializationKind TSK);
14056
14057 NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(
14058 NestedNameSpecifierLoc NNS,
14059 const MultiLevelTemplateArgumentList &TemplateArgs);
14060
14061 /// Do template substitution on declaration name info.
14062 DeclarationNameInfo
14063 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
14064 const MultiLevelTemplateArgumentList &TemplateArgs);
14065 TemplateName
14066 SubstTemplateName(SourceLocation TemplateKWLoc,
14067 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
14068 SourceLocation NameLoc,
14069 const MultiLevelTemplateArgumentList &TemplateArgs);
14070
14071 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
14072 const MultiLevelTemplateArgumentList &TemplateArgs,
14073 bool EvaluateConstraint);
14074
14075 /// Determine whether we are currently performing template instantiation.
14076 bool inTemplateInstantiation() const {
14077 return CodeSynthesisContexts.size() > NonInstantiationEntries;
14078 }
14079
14080 /// Determine whether we are currently performing constraint substitution.
14081 bool inConstraintSubstitution() const {
14082 return !CodeSynthesisContexts.empty() &&
14083 CodeSynthesisContexts.back().InConstraintSubstitution;
14084 }
14085
14086 bool inParameterMappingSubstitution() const {
14087 return !CodeSynthesisContexts.empty() &&
14088 CodeSynthesisContexts.back().InParameterMappingSubstitution &&
14089 !inConstraintSubstitution();
14090 }
14091
14092 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
14093
14094 /// \brief create a Requirement::SubstitutionDiagnostic with only a
14095 /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
14096 concepts::Requirement::SubstitutionDiagnostic *
14097 createSubstDiagAt(SourceLocation Location, EntityPrinter Printer);
14098
14099 ///@}
14100
14101 //
14102 //
14103 // -------------------------------------------------------------------------
14104 //
14105 //
14106
14107 /// \name C++ Template Declaration Instantiation
14108 /// Implementations are in SemaTemplateInstantiateDecl.cpp
14109 ///@{
14110
14111public:
14112 /// An entity for which implicit template instantiation is required.
14113 ///
14114 /// The source location associated with the declaration is the first place in
14115 /// the source code where the declaration was "used". It is not necessarily
14116 /// the point of instantiation (which will be either before or after the
14117 /// namespace-scope declaration that triggered this implicit instantiation),
14118 /// However, it is the location that diagnostics should generally refer to,
14119 /// because users will need to know what code triggered the instantiation.
14120 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
14121
14122 /// The queue of implicit template instantiations that are required
14123 /// but have not yet been performed.
14124 std::deque<PendingImplicitInstantiation> PendingInstantiations;
14125
14126 /// Queue of implicit template instantiations that cannot be performed
14127 /// eagerly.
14128 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
14129
14130 SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses;
14131 SmallVector<std::deque<PendingImplicitInstantiation>, 8>
14132 SavedPendingInstantiations;
14133
14134 /// The queue of implicit template instantiations that are required
14135 /// and must be performed within the current local scope.
14136 ///
14137 /// This queue is only used for member functions of local classes in
14138 /// templates, which must be instantiated in the same scope as their
14139 /// enclosing function, so that they can reference function-local
14140 /// types, static variables, enumerators, etc.
14141 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
14142
14143 class LocalEagerInstantiationScope {
14144 public:
14145 LocalEagerInstantiationScope(Sema &S, bool AtEndOfTU)
14146 : S(S), AtEndOfTU(AtEndOfTU) {
14147 SavedPendingLocalImplicitInstantiations.swap(
14148 x&: S.PendingLocalImplicitInstantiations);
14149 }
14150
14151 void perform() {
14152 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: true,
14153 /*AtEndOfTU=*/AtEndOfTU);
14154 }
14155
14156 ~LocalEagerInstantiationScope() {
14157 assert(S.PendingLocalImplicitInstantiations.empty() &&
14158 "there shouldn't be any pending local implicit instantiations");
14159 SavedPendingLocalImplicitInstantiations.swap(
14160 x&: S.PendingLocalImplicitInstantiations);
14161 }
14162
14163 LocalEagerInstantiationScope(const LocalEagerInstantiationScope &) = delete;
14164 LocalEagerInstantiationScope &
14165 operator=(const LocalEagerInstantiationScope &) = delete;
14166
14167 private:
14168 Sema &S;
14169 bool AtEndOfTU;
14170 std::deque<PendingImplicitInstantiation>
14171 SavedPendingLocalImplicitInstantiations;
14172 };
14173
14174 /// Records and restores the CurFPFeatures state on entry/exit of compound
14175 /// statements.
14176 class FPFeaturesStateRAII {
14177 public:
14178 FPFeaturesStateRAII(Sema &S);
14179 ~FPFeaturesStateRAII();
14180 FPFeaturesStateRAII(const FPFeaturesStateRAII &) = delete;
14181 FPFeaturesStateRAII &operator=(const FPFeaturesStateRAII &) = delete;
14182 FPOptionsOverride getOverrides() { return OldOverrides; }
14183
14184 private:
14185 Sema &S;
14186 FPOptions OldFPFeaturesState;
14187 FPOptionsOverride OldOverrides;
14188 LangOptions::FPEvalMethodKind OldEvalMethod;
14189 SourceLocation OldFPPragmaLocation;
14190 };
14191
14192 class GlobalEagerInstantiationScope {
14193 public:
14194 GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
14195 : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
14196 if (!Enabled)
14197 return;
14198
14199 S.SavedPendingInstantiations.emplace_back();
14200 S.SavedPendingInstantiations.back().swap(x&: S.PendingInstantiations);
14201
14202 S.SavedVTableUses.emplace_back();
14203 S.SavedVTableUses.back().swap(RHS&: S.VTableUses);
14204 }
14205
14206 void perform() {
14207 if (Enabled) {
14208 S.DefineUsedVTables();
14209 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: false,
14210 /*AtEndOfTU=*/AtEndOfTU);
14211 }
14212 }
14213
14214 ~GlobalEagerInstantiationScope() {
14215 if (!Enabled)
14216 return;
14217
14218 // Restore the set of pending vtables.
14219 assert(S.VTableUses.empty() &&
14220 "VTableUses should be empty before it is discarded.");
14221 S.VTableUses.swap(RHS&: S.SavedVTableUses.back());
14222 S.SavedVTableUses.pop_back();
14223
14224 // Restore the set of pending implicit instantiations.
14225 if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
14226 AtEndOfTU) {
14227 assert(S.PendingInstantiations.empty() &&
14228 "PendingInstantiations should be empty before it is discarded.");
14229 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14230 S.SavedPendingInstantiations.pop_back();
14231 } else {
14232 // Template instantiations in the PCH may be delayed until the TU.
14233 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14234 S.PendingInstantiations.insert(
14235 position: S.PendingInstantiations.end(),
14236 first: S.SavedPendingInstantiations.back().begin(),
14237 last: S.SavedPendingInstantiations.back().end());
14238 S.SavedPendingInstantiations.pop_back();
14239 }
14240 }
14241
14242 GlobalEagerInstantiationScope(const GlobalEagerInstantiationScope &) =
14243 delete;
14244 GlobalEagerInstantiationScope &
14245 operator=(const GlobalEagerInstantiationScope &) = delete;
14246
14247 private:
14248 Sema &S;
14249 bool Enabled;
14250 bool AtEndOfTU;
14251 };
14252
14253 ExplicitSpecifier instantiateExplicitSpecifier(
14254 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
14255
14256 struct LateInstantiatedAttribute {
14257 const Attr *TmplAttr;
14258 LocalInstantiationScope *Scope;
14259 Decl *NewDecl;
14260
14261 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
14262 Decl *D)
14263 : TmplAttr(A), Scope(S), NewDecl(D) {}
14264 };
14265 typedef SmallVector<LateInstantiatedAttribute, 1> LateInstantiatedAttrVec;
14266
14267 /// Recheck instantiated thread-safety attributes that could not be validated
14268 /// on the dependent pattern declaration.
14269 bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A);
14270
14271 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14272 const Decl *Pattern, Decl *Inst,
14273 LateInstantiatedAttrVec *LateAttrs = nullptr,
14274 LocalInstantiationScope *OuterMostScope = nullptr);
14275
14276 /// Update instantiation attributes after template was late parsed.
14277 ///
14278 /// Some attributes are evaluated based on the body of template. If it is
14279 /// late parsed, such attributes cannot be evaluated when declaration is
14280 /// instantiated. This function is used to update instantiation attributes
14281 /// when template definition is ready.
14282 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
14283
14284 void
14285 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
14286 const Decl *Pattern, Decl *Inst,
14287 LateInstantiatedAttrVec *LateAttrs = nullptr,
14288 LocalInstantiationScope *OuterMostScope = nullptr);
14289
14290 bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor,
14291 bool IsCopy = false);
14292
14293 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
14294 ParmVarDecl *Param);
14295 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
14296 FunctionDecl *Function);
14297
14298 /// Instantiate (or find existing instantiation of) a function template with a
14299 /// given set of template arguments.
14300 ///
14301 /// Usually this should not be used, and template argument deduction should be
14302 /// used in its place.
14303 FunctionDecl *InstantiateFunctionDeclaration(
14304 FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
14305 SourceLocation Loc,
14306 CodeSynthesisContext::SynthesisKind CSC =
14307 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution);
14308
14309 /// Instantiate the definition of the given function from its
14310 /// template.
14311 ///
14312 /// \param PointOfInstantiation the point at which the instantiation was
14313 /// required. Note that this is not precisely a "point of instantiation"
14314 /// for the function, but it's close.
14315 ///
14316 /// \param Function the already-instantiated declaration of a
14317 /// function template specialization or member function of a class template
14318 /// specialization.
14319 ///
14320 /// \param Recursive if true, recursively instantiates any functions that
14321 /// are required by this instantiation.
14322 ///
14323 /// \param DefinitionRequired if true, then we are performing an explicit
14324 /// instantiation where the body of the function is required. Complain if
14325 /// there is no such body.
14326 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
14327 FunctionDecl *Function,
14328 bool Recursive = false,
14329 bool DefinitionRequired = false,
14330 bool AtEndOfTU = false);
14331 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
14332 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
14333 const TemplateArgumentList *PartialSpecArgs,
14334 SmallVectorImpl<TemplateArgument> &Converted,
14335 SourceLocation PointOfInstantiation,
14336 LateInstantiatedAttrVec *LateAttrs = nullptr,
14337 LocalInstantiationScope *StartingScope = nullptr);
14338
14339 /// Instantiates a variable template specialization by completing it
14340 /// with appropriate type information and initializer.
14341 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
14342 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14343 const MultiLevelTemplateArgumentList &TemplateArgs);
14344
14345 /// BuildVariableInstantiation - Used after a new variable has been created.
14346 /// Sets basic variable data and decides whether to postpone the
14347 /// variable instantiation.
14348 void
14349 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
14350 const MultiLevelTemplateArgumentList &TemplateArgs,
14351 LateInstantiatedAttrVec *LateAttrs,
14352 DeclContext *Owner,
14353 LocalInstantiationScope *StartingScope,
14354 bool InstantiatingVarTemplate = false,
14355 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14356
14357 /// Instantiate the initializer of a variable.
14358 void InstantiateVariableInitializer(
14359 VarDecl *Var, VarDecl *OldVar,
14360 const MultiLevelTemplateArgumentList &TemplateArgs);
14361
14362 /// Instantiate the definition of the given variable from its
14363 /// template.
14364 ///
14365 /// \param PointOfInstantiation the point at which the instantiation was
14366 /// required. Note that this is not precisely a "point of instantiation"
14367 /// for the variable, but it's close.
14368 ///
14369 /// \param Var the already-instantiated declaration of a templated variable.
14370 ///
14371 /// \param Recursive if true, recursively instantiates any functions that
14372 /// are required by this instantiation.
14373 ///
14374 /// \param DefinitionRequired if true, then we are performing an explicit
14375 /// instantiation where a definition of the variable is required. Complain
14376 /// if there is no such definition.
14377 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14378 VarDecl *Var, bool Recursive = false,
14379 bool DefinitionRequired = false,
14380 bool AtEndOfTU = false);
14381
14382 void InstantiateMemInitializers(
14383 CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl,
14384 const MultiLevelTemplateArgumentList &TemplateArgs);
14385
14386 /// Find the instantiation of the given declaration within the
14387 /// current instantiation.
14388 ///
14389 /// This routine is intended to be used when \p D is a declaration
14390 /// referenced from within a template, that needs to mapped into the
14391 /// corresponding declaration within an instantiation. For example,
14392 /// given:
14393 ///
14394 /// \code
14395 /// template<typename T>
14396 /// struct X {
14397 /// enum Kind {
14398 /// KnownValue = sizeof(T)
14399 /// };
14400 ///
14401 /// bool getKind() const { return KnownValue; }
14402 /// };
14403 ///
14404 /// template struct X<int>;
14405 /// \endcode
14406 ///
14407 /// In the instantiation of X<int>::getKind(), we need to map the \p
14408 /// EnumConstantDecl for \p KnownValue (which refers to
14409 /// X<T>::<Kind>::KnownValue) to its instantiation
14410 /// (X<int>::<Kind>::KnownValue).
14411 /// \p FindInstantiatedDecl performs this mapping from within the
14412 /// instantiation of X<int>.
14413 NamedDecl *
14414 FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
14415 const MultiLevelTemplateArgumentList &TemplateArgs,
14416 bool FindingInstantiatedContext = false);
14417
14418 /// Finds the instantiation of the given declaration context
14419 /// within the current instantiation.
14420 ///
14421 /// \returns NULL if there was an error
14422 DeclContext *
14423 FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
14424 const MultiLevelTemplateArgumentList &TemplateArgs);
14425
14426 Decl *SubstDecl(Decl *D, DeclContext *Owner,
14427 const MultiLevelTemplateArgumentList &TemplateArgs);
14428
14429 /// Substitute the name and return type of a defaulted 'operator<=>' to form
14430 /// an implicit 'operator=='.
14431 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
14432 FunctionDecl *Spaceship);
14433
14434 /// Performs template instantiation for all implicit template
14435 /// instantiations we have seen until this point.
14436 void PerformPendingInstantiations(bool LocalOnly = false,
14437 bool AtEndOfTU = true);
14438
14439 TemplateParameterList *
14440 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
14441 const MultiLevelTemplateArgumentList &TemplateArgs,
14442 bool EvaluateConstraints = true);
14443
14444 void PerformDependentDiagnostics(
14445 const DeclContext *Pattern,
14446 const MultiLevelTemplateArgumentList &TemplateArgs);
14447
14448private:
14449 /// Introduce the instantiated local variables into the local
14450 /// instantiation scope.
14451 void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14452 const FunctionDecl *PatternDecl,
14453 LocalInstantiationScope &Scope);
14454 /// Introduce the instantiated function parameters into the local
14455 /// instantiation scope, and set the parameter names to those used
14456 /// in the template.
14457 bool addInstantiatedParametersToScope(
14458 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14459 LocalInstantiationScope &Scope,
14460 const MultiLevelTemplateArgumentList &TemplateArgs);
14461
14462 /// Introduce the instantiated captures of the lambda into the local
14463 /// instantiation scope.
14464 bool addInstantiatedCapturesToScope(
14465 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14466 LocalInstantiationScope &Scope,
14467 const MultiLevelTemplateArgumentList &TemplateArgs);
14468
14469 int ParsingClassDepth = 0;
14470
14471 class SavePendingParsedClassStateRAII {
14472 public:
14473 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14474
14475 ~SavePendingParsedClassStateRAII() {
14476 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14477 "there shouldn't be any pending delayed exception spec checks");
14478 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14479 "there shouldn't be any pending delayed exception spec checks");
14480 swapSavedState();
14481 }
14482
14483 SavePendingParsedClassStateRAII(const SavePendingParsedClassStateRAII &) =
14484 delete;
14485 SavePendingParsedClassStateRAII &
14486 operator=(const SavePendingParsedClassStateRAII &) = delete;
14487
14488 private:
14489 Sema &S;
14490 decltype(DelayedOverridingExceptionSpecChecks)
14491 SavedOverridingExceptionSpecChecks;
14492 decltype(DelayedEquivalentExceptionSpecChecks)
14493 SavedEquivalentExceptionSpecChecks;
14494
14495 void swapSavedState() {
14496 SavedOverridingExceptionSpecChecks.swap(
14497 RHS&: S.DelayedOverridingExceptionSpecChecks);
14498 SavedEquivalentExceptionSpecChecks.swap(
14499 RHS&: S.DelayedEquivalentExceptionSpecChecks);
14500 }
14501 };
14502
14503 ///@}
14504
14505 //
14506 //
14507 // -------------------------------------------------------------------------
14508 //
14509 //
14510
14511 /// \name C++ Variadic Templates
14512 /// Implementations are in SemaTemplateVariadic.cpp
14513 ///@{
14514
14515public:
14516 /// Determine whether an unexpanded parameter pack might be permitted in this
14517 /// location. Useful for error recovery.
14518 bool isUnexpandedParameterPackPermitted();
14519
14520 /// The context in which an unexpanded parameter pack is
14521 /// being diagnosed.
14522 ///
14523 /// Note that the values of this enumeration line up with the first
14524 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14525 enum UnexpandedParameterPackContext {
14526 /// An arbitrary expression.
14527 UPPC_Expression = 0,
14528
14529 /// The base type of a class type.
14530 UPPC_BaseType,
14531
14532 /// The type of an arbitrary declaration.
14533 UPPC_DeclarationType,
14534
14535 /// The type of a data member.
14536 UPPC_DataMemberType,
14537
14538 /// The size of a bit-field.
14539 UPPC_BitFieldWidth,
14540
14541 /// The expression in a static assertion.
14542 UPPC_StaticAssertExpression,
14543
14544 /// The fixed underlying type of an enumeration.
14545 UPPC_FixedUnderlyingType,
14546
14547 /// The enumerator value.
14548 UPPC_EnumeratorValue,
14549
14550 /// A using declaration.
14551 UPPC_UsingDeclaration,
14552
14553 /// A friend declaration.
14554 UPPC_FriendDeclaration,
14555
14556 /// A declaration qualifier.
14557 UPPC_DeclarationQualifier,
14558
14559 /// An initializer.
14560 UPPC_Initializer,
14561
14562 /// A default argument.
14563 UPPC_DefaultArgument,
14564
14565 /// The type of a non-type template parameter.
14566 UPPC_NonTypeTemplateParameterType,
14567
14568 /// The type of an exception.
14569 UPPC_ExceptionType,
14570
14571 /// Explicit specialization.
14572 UPPC_ExplicitSpecialization,
14573
14574 /// Partial specialization.
14575 UPPC_PartialSpecialization,
14576
14577 /// Microsoft __if_exists.
14578 UPPC_IfExists,
14579
14580 /// Microsoft __if_not_exists.
14581 UPPC_IfNotExists,
14582
14583 /// Lambda expression.
14584 UPPC_Lambda,
14585
14586 /// Block expression.
14587 UPPC_Block,
14588
14589 /// A type constraint.
14590 UPPC_TypeConstraint,
14591
14592 // A requirement in a requires-expression.
14593 UPPC_Requirement,
14594
14595 // A requires-clause.
14596 UPPC_RequiresClause,
14597 };
14598
14599 /// Diagnose unexpanded parameter packs.
14600 ///
14601 /// \param Loc The location at which we should emit the diagnostic.
14602 ///
14603 /// \param UPPC The context in which we are diagnosing unexpanded
14604 /// parameter packs.
14605 ///
14606 /// \param Unexpanded the set of unexpanded parameter packs.
14607 ///
14608 /// \returns true if an error occurred, false otherwise.
14609 bool DiagnoseUnexpandedParameterPacks(
14610 SourceLocation Loc, UnexpandedParameterPackContext UPPC,
14611 ArrayRef<UnexpandedParameterPack> Unexpanded);
14612
14613 /// If the given type contains an unexpanded parameter pack,
14614 /// diagnose the error.
14615 ///
14616 /// \param Loc The source location where a diagnostc should be emitted.
14617 ///
14618 /// \param T The type that is being checked for unexpanded parameter
14619 /// packs.
14620 ///
14621 /// \returns true if an error occurred, false otherwise.
14622 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
14623 UnexpandedParameterPackContext UPPC);
14624
14625 /// If the given expression contains an unexpanded parameter
14626 /// pack, diagnose the error.
14627 ///
14628 /// \param E The expression that is being checked for unexpanded
14629 /// parameter packs.
14630 ///
14631 /// \returns true if an error occurred, false otherwise.
14632 bool DiagnoseUnexpandedParameterPack(
14633 Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression);
14634
14635 /// If the given requirees-expression contains an unexpanded reference to one
14636 /// of its own parameter packs, diagnose the error.
14637 ///
14638 /// \param RE The requiress-expression that is being checked for unexpanded
14639 /// parameter packs.
14640 ///
14641 /// \returns true if an error occurred, false otherwise.
14642 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
14643
14644 /// If the given nested-name-specifier contains an unexpanded
14645 /// parameter pack, diagnose the error.
14646 ///
14647 /// \param SS The nested-name-specifier that is being checked for
14648 /// unexpanded parameter packs.
14649 ///
14650 /// \returns true if an error occurred, false otherwise.
14651 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
14652 UnexpandedParameterPackContext UPPC);
14653
14654 /// If the given name contains an unexpanded parameter pack,
14655 /// diagnose the error.
14656 ///
14657 /// \param NameInfo The name (with source location information) that
14658 /// is being checked for unexpanded parameter packs.
14659 ///
14660 /// \returns true if an error occurred, false otherwise.
14661 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
14662 UnexpandedParameterPackContext UPPC);
14663
14664 /// If the given template name contains an unexpanded parameter pack,
14665 /// diagnose the error.
14666 ///
14667 /// \param Loc The location of the template name.
14668 ///
14669 /// \param Template The template name that is being checked for unexpanded
14670 /// parameter packs.
14671 ///
14672 /// \returns true if an error occurred, false otherwise.
14673 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
14674 TemplateName Template,
14675 UnexpandedParameterPackContext UPPC);
14676
14677 /// If the given template argument contains an unexpanded parameter
14678 /// pack, diagnose the error.
14679 ///
14680 /// \param Arg The template argument that is being checked for unexpanded
14681 /// parameter packs.
14682 ///
14683 /// \returns true if an error occurred, false otherwise.
14684 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
14685 UnexpandedParameterPackContext UPPC);
14686
14687 /// Collect the set of unexpanded parameter packs within the given
14688 /// template argument.
14689 ///
14690 /// \param Arg The template argument that will be traversed to find
14691 /// unexpanded parameter packs.
14692 void collectUnexpandedParameterPacks(
14693 TemplateArgument Arg,
14694 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14695
14696 /// Collect the set of unexpanded parameter packs within the given
14697 /// template argument.
14698 ///
14699 /// \param Arg The template argument that will be traversed to find
14700 /// unexpanded parameter packs.
14701 void collectUnexpandedParameterPacks(
14702 TemplateArgumentLoc Arg,
14703 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14704
14705 /// Collect the set of unexpanded parameter packs within the given
14706 /// type.
14707 ///
14708 /// \param T The type that will be traversed to find
14709 /// unexpanded parameter packs.
14710 void collectUnexpandedParameterPacks(
14711 QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14712
14713 /// Collect the set of unexpanded parameter packs within the given
14714 /// template name.
14715 ///
14716 /// \param Template The template name that will be traversed to find
14717 /// unexpanded parameter packs.
14718 void collectUnexpandedParameterPacks(
14719 TemplateName Template,
14720 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14721
14722 /// Collect the set of unexpanded parameter packs within the given
14723 /// type.
14724 ///
14725 /// \param TL The type that will be traversed to find
14726 /// unexpanded parameter packs.
14727 void collectUnexpandedParameterPacks(
14728 TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14729
14730 /// Collect the set of unexpanded parameter packs within the given
14731 /// nested-name-specifier.
14732 ///
14733 /// \param NNS The nested-name-specifier that will be traversed to find
14734 /// unexpanded parameter packs.
14735 void collectUnexpandedParameterPacks(
14736 NestedNameSpecifierLoc NNS,
14737 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14738
14739 /// Collect the set of unexpanded parameter packs within the given
14740 /// name.
14741 ///
14742 /// \param NameInfo The name that will be traversed to find
14743 /// unexpanded parameter packs.
14744 void collectUnexpandedParameterPacks(
14745 const DeclarationNameInfo &NameInfo,
14746 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14747
14748 /// Collect the set of unexpanded parameter packs within the given
14749 /// expression.
14750 static void collectUnexpandedParameterPacks(
14751 Expr *E, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14752
14753 /// Invoked when parsing a template argument.
14754 ///
14755 /// \param Arg the template argument, which may already be invalid.
14756 ///
14757 /// If it is followed by ellipsis, this function is called before
14758 /// `ActOnPackExpansion`.
14759 ParsedTemplateArgument
14760 ActOnTemplateTemplateArgument(const ParsedTemplateArgument &Arg);
14761
14762 /// Invoked when parsing a template argument followed by an
14763 /// ellipsis, which creates a pack expansion.
14764 ///
14765 /// \param Arg The template argument preceding the ellipsis, which
14766 /// may already be invalid.
14767 ///
14768 /// \param EllipsisLoc The location of the ellipsis.
14769 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
14770 SourceLocation EllipsisLoc);
14771
14772 /// Invoked when parsing a type followed by an ellipsis, which
14773 /// creates a pack expansion.
14774 ///
14775 /// \param Type The type preceding the ellipsis, which will become
14776 /// the pattern of the pack expansion.
14777 ///
14778 /// \param EllipsisLoc The location of the ellipsis.
14779 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
14780
14781 /// Construct a pack expansion type from the pattern of the pack
14782 /// expansion.
14783 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
14784 SourceLocation EllipsisLoc,
14785 UnsignedOrNone NumExpansions);
14786
14787 /// Construct a pack expansion type from the pattern of the pack
14788 /// expansion.
14789 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14790 SourceLocation EllipsisLoc,
14791 UnsignedOrNone NumExpansions);
14792
14793 /// Invoked when parsing an expression followed by an ellipsis, which
14794 /// creates a pack expansion.
14795 ///
14796 /// \param Pattern The expression preceding the ellipsis, which will become
14797 /// the pattern of the pack expansion.
14798 ///
14799 /// \param EllipsisLoc The location of the ellipsis.
14800 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14801
14802 /// Invoked when parsing an expression followed by an ellipsis, which
14803 /// creates a pack expansion.
14804 ///
14805 /// \param Pattern The expression preceding the ellipsis, which will become
14806 /// the pattern of the pack expansion.
14807 ///
14808 /// \param EllipsisLoc The location of the ellipsis.
14809 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14810 UnsignedOrNone NumExpansions);
14811
14812 /// Determine whether we could expand a pack expansion with the
14813 /// given set of parameter packs into separate arguments by repeatedly
14814 /// transforming the pattern.
14815 ///
14816 /// \param EllipsisLoc The location of the ellipsis that identifies the
14817 /// pack expansion.
14818 ///
14819 /// \param PatternRange The source range that covers the entire pattern of
14820 /// the pack expansion.
14821 ///
14822 /// \param Unexpanded The set of unexpanded parameter packs within the
14823 /// pattern.
14824 ///
14825 /// \param ShouldExpand Will be set to \c true if the transformer should
14826 /// expand the corresponding pack expansions into separate arguments. When
14827 /// set, \c NumExpansions must also be set.
14828 ///
14829 /// \param RetainExpansion Whether the caller should add an unexpanded
14830 /// pack expansion after all of the expanded arguments. This is used
14831 /// when extending explicitly-specified template argument packs per
14832 /// C++0x [temp.arg.explicit]p9.
14833 ///
14834 /// \param NumExpansions The number of separate arguments that will be in
14835 /// the expanded form of the corresponding pack expansion. This is both an
14836 /// input and an output parameter, which can be set by the caller if the
14837 /// number of expansions is known a priori (e.g., due to a prior substitution)
14838 /// and will be set by the callee when the number of expansions is known.
14839 /// The callee must set this value when \c ShouldExpand is \c true; it may
14840 /// set this value in other cases.
14841 ///
14842 /// \returns true if an error occurred (e.g., because the parameter packs
14843 /// are to be instantiated with arguments of different lengths), false
14844 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
14845 /// must be set.
14846 bool CheckParameterPacksForExpansion(
14847 SourceLocation EllipsisLoc, SourceRange PatternRange,
14848 ArrayRef<UnexpandedParameterPack> Unexpanded,
14849 const MultiLevelTemplateArgumentList &TemplateArgs,
14850 bool FailOnPackProducingTemplates, bool &ShouldExpand,
14851 bool &RetainExpansion, UnsignedOrNone &NumExpansions,
14852 bool Diagnose = true);
14853
14854 /// Determine the number of arguments in the given pack expansion
14855 /// type.
14856 ///
14857 /// This routine assumes that the number of arguments in the expansion is
14858 /// consistent across all of the unexpanded parameter packs in its pattern.
14859 ///
14860 /// Returns an empty Optional if the type can't be expanded.
14861 UnsignedOrNone getNumArgumentsInExpansion(
14862 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
14863
14864 UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(
14865 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
14866 const MultiLevelTemplateArgumentList &TemplateArgs);
14867
14868 /// Determine whether the given declarator contains any unexpanded
14869 /// parameter packs.
14870 ///
14871 /// This routine is used by the parser to disambiguate function declarators
14872 /// with an ellipsis prior to the ')', e.g.,
14873 ///
14874 /// \code
14875 /// void f(T...);
14876 /// \endcode
14877 ///
14878 /// To determine whether we have an (unnamed) function parameter pack or
14879 /// a variadic function.
14880 ///
14881 /// \returns true if the declarator contains any unexpanded parameter packs,
14882 /// false otherwise.
14883 bool containsUnexpandedParameterPacks(Declarator &D);
14884
14885 /// Returns the pattern of the pack expansion for a template argument.
14886 ///
14887 /// \param OrigLoc The template argument to expand.
14888 ///
14889 /// \param Ellipsis Will be set to the location of the ellipsis.
14890 ///
14891 /// \param NumExpansions Will be set to the number of expansions that will
14892 /// be generated from this pack expansion, if known a priori.
14893 TemplateArgumentLoc
14894 getTemplateArgumentPackExpansionPattern(TemplateArgumentLoc OrigLoc,
14895 SourceLocation &Ellipsis,
14896 UnsignedOrNone &NumExpansions) const;
14897
14898 /// Given a template argument that contains an unexpanded parameter pack, but
14899 /// which has already been substituted, attempt to determine the number of
14900 /// elements that will be produced once this argument is fully-expanded.
14901 ///
14902 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
14903 /// avoid actually expanding the pack where possible.
14904 UnsignedOrNone getFullyPackExpandedSize(TemplateArgument Arg);
14905
14906 /// Called when an expression computing the size of a parameter pack
14907 /// is parsed.
14908 ///
14909 /// \code
14910 /// template<typename ...Types> struct count {
14911 /// static const unsigned value = sizeof...(Types);
14912 /// };
14913 /// \endcode
14914 ///
14915 //
14916 /// \param OpLoc The location of the "sizeof" keyword.
14917 /// \param Name The name of the parameter pack whose size will be determined.
14918 /// \param NameLoc The source location of the name of the parameter pack.
14919 /// \param RParenLoc The location of the closing parentheses.
14920 ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc,
14921 IdentifierInfo &Name,
14922 SourceLocation NameLoc,
14923 SourceLocation RParenLoc);
14924
14925 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
14926 SourceLocation EllipsisLoc,
14927 SourceLocation LSquareLoc, Expr *IndexExpr,
14928 SourceLocation RSquareLoc);
14929
14930 ExprResult BuildPackIndexingExpr(Expr *PackExpression,
14931 SourceLocation EllipsisLoc, Expr *IndexExpr,
14932 SourceLocation RSquareLoc,
14933 ArrayRef<Expr *> ExpandedExprs = {},
14934 bool FullySubstituted = false);
14935
14936 TemplateName ActOnPackIndexingTemplateName(TemplateName Pattern,
14937 SourceLocation NameLoc,
14938 Expr *IndexExpr);
14939
14940 TemplateName
14941 BuildPackIndexingTemplateName(TemplateName Pattern, Expr *IndexExpr,
14942 bool FullySubstituted = false,
14943 ArrayRef<TemplateName> Expansions = {});
14944
14945 TypeResult
14946 ActOnPackIndexingDeducedTemplateSpecializationType(TemplateName Name,
14947 SourceLocation NameLoc);
14948
14949 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
14950 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
14951 tok::TokenKind Operator,
14952 SourceLocation EllipsisLoc, Expr *RHS,
14953 SourceLocation RParenLoc);
14954 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
14955 SourceLocation LParenLoc, Expr *LHS,
14956 BinaryOperatorKind Operator,
14957 SourceLocation EllipsisLoc, Expr *RHS,
14958 SourceLocation RParenLoc,
14959 UnsignedOrNone NumExpansions);
14960 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
14961 BinaryOperatorKind Operator);
14962
14963 ///@}
14964
14965 //
14966 //
14967 // -------------------------------------------------------------------------
14968 //
14969 //
14970
14971 /// \name Constraints and Concepts
14972 /// Implementations are in SemaConcept.cpp
14973 ///@{
14974
14975public:
14976 ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI);
14977
14978 ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc,
14979 TypeSourceInfo *TSI);
14980
14981public:
14982 void PushSatisfactionStackEntry(const NamedDecl *D,
14983 const llvm::FoldingSetNodeID &ID) {
14984 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
14985 SatisfactionStack.emplace_back(Args&: Can, Args: ID);
14986 }
14987
14988 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
14989
14990 bool SatisfactionStackContains(const NamedDecl *D,
14991 const llvm::FoldingSetNodeID &ID) const {
14992 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
14993 return llvm::is_contained(Range: SatisfactionStack,
14994 Element: SatisfactionStackEntryTy{Can, ID});
14995 }
14996
14997 using SatisfactionStackEntryTy =
14998 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
14999
15000 // Resets the current SatisfactionStack for cases where we are instantiating
15001 // constraints as a 'side effect' of normal instantiation in a way that is not
15002 // indicative of recursive definition.
15003 class SatisfactionStackResetRAII {
15004 llvm::SmallVector<SatisfactionStackEntryTy, 10> BackupSatisfactionStack;
15005 Sema &SemaRef;
15006
15007 public:
15008 SatisfactionStackResetRAII(Sema &S) : SemaRef(S) {
15009 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
15010 }
15011
15012 ~SatisfactionStackResetRAII() {
15013 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
15014 }
15015
15016 SatisfactionStackResetRAII(const SatisfactionStackResetRAII &) = delete;
15017 SatisfactionStackResetRAII &
15018 operator=(const SatisfactionStackResetRAII &) = delete;
15019 };
15020
15021 void SwapSatisfactionStack(
15022 llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) {
15023 SatisfactionStack.swap(RHS&: NewSS);
15024 }
15025
15026 using ConstrainedDeclOrNestedRequirement =
15027 llvm::PointerUnion<const NamedDecl *,
15028 const concepts::NestedRequirement *>;
15029
15030 /// Check whether the given expression is a valid constraint expression.
15031 /// A diagnostic is emitted if it is not, false is returned, and
15032 /// PossibleNonPrimary will be set to true if the failure might be due to a
15033 /// non-primary expression being used as an atomic constraint.
15034 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
15035 bool *PossibleNonPrimary = nullptr,
15036 bool IsTrailingRequiresClause = false);
15037
15038 /// \brief Check whether the given list of constraint expressions are
15039 /// satisfied (as if in a 'conjunction') given template arguments.
15040 /// \param Template the template-like entity that triggered the constraints
15041 /// check (either a concept or a constrained entity).
15042 /// \param ConstraintExprs a list of constraint expressions, treated as if
15043 /// they were 'AND'ed together.
15044 /// \param TemplateArgLists the list of template arguments to substitute into
15045 /// the constraint expression.
15046 /// \param TemplateIDRange The source range of the template id that
15047 /// caused the constraints check.
15048 /// \param Satisfaction if true is returned, will contain details of the
15049 /// satisfaction, with enough information to diagnose an unsatisfied
15050 /// expression.
15051 /// \returns true if an error occurred and satisfaction could not be checked,
15052 /// false otherwise.
15053 bool CheckConstraintSatisfaction(
15054 ConstrainedDeclOrNestedRequirement Entity,
15055 ArrayRef<AssociatedConstraint> AssociatedConstraints,
15056 const MultiLevelTemplateArgumentList &TemplateArgLists,
15057 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
15058 const ConceptReference *TopLevelConceptId = nullptr,
15059 Expr **ConvertedExpr = nullptr);
15060
15061 /// Check whether the given function decl's trailing requires clause is
15062 /// satisfied, if any. Returns false and updates Satisfaction with the
15063 /// satisfaction verdict if successful, emits a diagnostic and returns true if
15064 /// an error occurred and satisfaction could not be determined.
15065 ///
15066 /// \returns true if an error occurred, false otherwise.
15067 bool CheckFunctionConstraints(const FunctionDecl *FD,
15068 ConstraintSatisfaction &Satisfaction,
15069 SourceLocation UsageLoc = SourceLocation(),
15070 bool ForOverloadResolution = false);
15071
15072 // Calculates whether two constraint expressions are equal irrespective of a
15073 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
15074 // 'New', which are the "source" of the constraint, since this is necessary
15075 // for figuring out the relative 'depth' of the constraint. The depth of the
15076 // 'primary template' and the 'instantiated from' templates aren't necessarily
15077 // the same, such as a case when one is a 'friend' defined in a class.
15078 bool AreConstraintExpressionsEqual(const NamedDecl *Old,
15079 const Expr *OldConstr,
15080 const TemplateCompareNewDeclInfo &New,
15081 const Expr *NewConstr);
15082
15083 // Calculates whether the friend function depends on an enclosing template for
15084 // the purposes of [temp.friend] p9.
15085 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
15086
15087 /// \brief Ensure that the given template arguments satisfy the constraints
15088 /// associated with the given template, emitting a diagnostic if they do not.
15089 ///
15090 /// \param Template The template to which the template arguments are being
15091 /// provided.
15092 ///
15093 /// \param TemplateArgs The converted, canonicalized template arguments.
15094 ///
15095 /// \param TemplateIDRange The source range of the template id that
15096 /// caused the constraints check.
15097 ///
15098 /// \returns true if the constrains are not satisfied or could not be checked
15099 /// for satisfaction, false if the constraints are satisfied.
15100 bool EnsureTemplateArgumentListConstraints(
15101 TemplateDecl *Template,
15102 const MultiLevelTemplateArgumentList &TemplateArgs,
15103 SourceRange TemplateIDRange);
15104
15105 bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
15106 FunctionDecl *Decl,
15107 ArrayRef<TemplateArgument> TemplateArgs,
15108 ConstraintSatisfaction &Satisfaction);
15109
15110 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15111 /// unsatisfied.
15112 /// \param First whether this is the first time an unsatisfied constraint is
15113 /// diagnosed for this error.
15114 void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
15115 SourceLocation Loc = {},
15116 bool First = true);
15117
15118 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15119 /// unsatisfied.
15120 void
15121 DiagnoseUnsatisfiedConstraint(const ConceptSpecializationExpr *ConstraintExpr,
15122 bool First = true);
15123
15124 void DiagnoseUnsatisfiedRequiresExpr(const RequiresExpr *RequiresExpr,
15125 bool First = true);
15126
15127 const NormalizedConstraint *getNormalizedAssociatedConstraints(
15128 ConstrainedDeclOrNestedRequirement Entity,
15129 ArrayRef<AssociatedConstraint> AssociatedConstraints);
15130
15131 /// \brief Check whether the given declaration's associated constraints are
15132 /// at least as constrained than another declaration's according to the
15133 /// partial ordering of constraints.
15134 ///
15135 /// \param Result If no error occurred, receives the result of true if D1 is
15136 /// at least constrained than D2, and false otherwise.
15137 ///
15138 /// \returns true if an error occurred, false otherwise.
15139 bool IsAtLeastAsConstrained(const NamedDecl *D1,
15140 MutableArrayRef<AssociatedConstraint> AC1,
15141 const NamedDecl *D2,
15142 MutableArrayRef<AssociatedConstraint> AC2,
15143 bool &Result);
15144
15145 /// If D1 was not at least as constrained as D2, but would've been if a pair
15146 /// of atomic constraints involved had been declared in a concept and not
15147 /// repeated in two separate places in code.
15148 /// \returns true if such a diagnostic was emitted, false otherwise.
15149 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(
15150 const NamedDecl *D1, ArrayRef<AssociatedConstraint> AC1,
15151 const NamedDecl *D2, ArrayRef<AssociatedConstraint> AC2);
15152
15153private:
15154 friend class ConstraintSatisfactionChecker;
15155 friend class SubstituteParameterMappings;
15156
15157 UnsignedOrNone EvaluateFoldExpandedConstraintSize(
15158 const Expr *Pattern, const MultiLevelTemplateArgumentList &MLTAL);
15159
15160 /// Cache the satisfaction of an atomic constraint.
15161 /// The key is based on the unsubstituted expression and the parameter
15162 /// mapping. This lets us not substituting the mapping more than once,
15163 /// which is (very!) expensive.
15164 llvm::DenseMap<llvm::FoldingSetNodeID,
15165 UnsubstitutedConstraintSatisfactionCacheResult>
15166 UnsubstitutedConstraintSatisfactionCache;
15167
15168 /// Cache the instantiation results of template parameter mappings within
15169 /// concepts. Substituting into normalized concepts can be extremely expensive
15170 /// due to the redundancy of template parameters. This cache is intended for
15171 /// use by TemplateInstantiator to avoid redundant semantic checking.
15172 llvm::DenseMap<llvm::FoldingSetNodeID, TemplateArgumentLoc>
15173 *CurrentCachedTemplateArgs = nullptr;
15174
15175 /// Caches pairs of template-like decls whose associated constraints were
15176 /// checked for subsumption and whether or not the first's constraints did in
15177 /// fact subsume the second's.
15178 llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
15179 SubsumptionCache;
15180 /// Caches the normalized associated constraints of declarations (concepts or
15181 /// constrained declarations). If an error occurred while normalizing the
15182 /// associated constraints of the template or concept, nullptr will be cached
15183 /// here.
15184 llvm::DenseMap<ConstrainedDeclOrNestedRequirement, NormalizedConstraint *>
15185 NormalizationCache;
15186
15187 /// Cache whether the associated constraint of a declaration
15188 /// is satisfied.
15189 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
15190 SatisfactionCache;
15191
15192 // The current stack of constraint satisfactions, so we can exit-early.
15193 llvm::SmallVector<SatisfactionStackEntryTy, 10> SatisfactionStack;
15194
15195 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
15196 /// LocalInstantiationScope of the current non-lambda function. For lambdas,
15197 /// use LambdaScopeForCallOperatorInstantiationRAII.
15198 bool
15199 SetupConstraintScope(FunctionDecl *FD,
15200 std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15201 const MultiLevelTemplateArgumentList &MLTAL,
15202 LocalInstantiationScope &Scope);
15203
15204 /// Used during constraint checking, sets up the constraint template argument
15205 /// lists, and calls SetupConstraintScope to set up the
15206 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
15207 std::optional<MultiLevelTemplateArgumentList>
15208 SetupConstraintCheckingTemplateArgumentsAndScope(
15209 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15210 LocalInstantiationScope &Scope);
15211
15212 ///@}
15213
15214 //
15215 //
15216 // -------------------------------------------------------------------------
15217 //
15218 //
15219
15220 /// \name Types
15221 /// Implementations are in SemaType.cpp
15222 ///@{
15223
15224public:
15225 /// A mapping that describes the nullability we've seen in each header file.
15226 FileNullabilityMap NullabilityMap;
15227
15228 static int getPrintable(int I) { return I; }
15229 static unsigned getPrintable(unsigned I) { return I; }
15230 static bool getPrintable(bool B) { return B; }
15231 static const char *getPrintable(const char *S) { return S; }
15232 static StringRef getPrintable(StringRef S) { return S; }
15233 static const std::string &getPrintable(const std::string &S) { return S; }
15234 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
15235 return II;
15236 }
15237 static DeclarationName getPrintable(DeclarationName N) { return N; }
15238 static QualType getPrintable(QualType T) { return T; }
15239 static SourceRange getPrintable(SourceRange R) { return R; }
15240 static SourceRange getPrintable(SourceLocation L) { return L; }
15241 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
15242 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange(); }
15243
15244 enum class CompleteTypeKind {
15245 /// Apply the normal rules for complete types. In particular,
15246 /// treat all sizeless types as incomplete.
15247 Normal,
15248
15249 /// Relax the normal rules for complete types so that they include
15250 /// sizeless built-in types.
15251 AcceptSizeless,
15252
15253 // FIXME: Eventually we should flip the default to Normal and opt in
15254 // to AcceptSizeless rather than opt out of it.
15255 Default = AcceptSizeless
15256 };
15257
15258 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
15259 const DeclSpec *DS = nullptr);
15260 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
15261 const DeclSpec *DS = nullptr);
15262
15263 /// Build a pointer type.
15264 ///
15265 /// \param T The type to which we'll be building a pointer.
15266 ///
15267 /// \param Loc The location of the entity whose type involves this
15268 /// pointer type or, if there is no such entity, the location of the
15269 /// type that will have pointer type.
15270 ///
15271 /// \param Entity The name of the entity that involves the pointer
15272 /// type, if known.
15273 ///
15274 /// \returns A suitable pointer type, if there are no
15275 /// errors. Otherwise, returns a NULL type.
15276 QualType BuildPointerType(QualType T, SourceLocation Loc,
15277 DeclarationName Entity);
15278
15279 /// Build a reference type.
15280 ///
15281 /// \param T The type to which we'll be building a reference.
15282 ///
15283 /// \param Loc The location of the entity whose type involves this
15284 /// reference type or, if there is no such entity, the location of the
15285 /// type that will have reference type.
15286 ///
15287 /// \param Entity The name of the entity that involves the reference
15288 /// type, if known.
15289 ///
15290 /// \returns A suitable reference type, if there are no
15291 /// errors. Otherwise, returns a NULL type.
15292 QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc,
15293 DeclarationName Entity);
15294
15295 /// Build an array type.
15296 ///
15297 /// \param T The type of each element in the array.
15298 ///
15299 /// \param ASM C99 array size modifier (e.g., '*', 'static').
15300 ///
15301 /// \param ArraySize Expression describing the size of the array.
15302 ///
15303 /// \param Brackets The range from the opening '[' to the closing ']'.
15304 ///
15305 /// \param Entity The name of the entity that involves the array
15306 /// type, if known.
15307 ///
15308 /// \returns A suitable array type, if there are no errors. Otherwise,
15309 /// returns a NULL type.
15310 QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize,
15311 unsigned Quals, SourceRange Brackets,
15312 DeclarationName Entity);
15313 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
15314
15315 /// Build an ext-vector type.
15316 ///
15317 /// Run the required checks for the extended vector type.
15318 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
15319 SourceLocation AttrLoc);
15320 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
15321 SourceLocation AttrLoc);
15322
15323 QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy,
15324 Expr *CountExpr,
15325 bool CountInBytes,
15326 bool OrNull);
15327
15328 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
15329 /// expression is uninstantiated. If instantiated it will apply the
15330 /// appropriate address space to the type. This function allows dependent
15331 /// template variables to be used in conjunction with the address_space
15332 /// attribute
15333 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
15334 SourceLocation AttrLoc);
15335
15336 /// Same as above, but constructs the AddressSpace index if not provided.
15337 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
15338 SourceLocation AttrLoc);
15339
15340 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
15341
15342 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
15343
15344 /// Build a function type.
15345 ///
15346 /// This routine checks the function type according to C++ rules and
15347 /// under the assumption that the result type and parameter types have
15348 /// just been instantiated from a template. It therefore duplicates
15349 /// some of the behavior of GetTypeForDeclarator, but in a much
15350 /// simpler form that is only suitable for this narrow use case.
15351 ///
15352 /// \param T The return type of the function.
15353 ///
15354 /// \param ParamTypes The parameter types of the function. This array
15355 /// will be modified to account for adjustments to the types of the
15356 /// function parameters.
15357 ///
15358 /// \param Loc The location of the entity whose type involves this
15359 /// function type or, if there is no such entity, the location of the
15360 /// type that will have function type.
15361 ///
15362 /// \param Entity The name of the entity that involves the function
15363 /// type, if known.
15364 ///
15365 /// \param EPI Extra information about the function type. Usually this will
15366 /// be taken from an existing function with the same prototype.
15367 ///
15368 /// \returns A suitable function type, if there are no errors. The
15369 /// unqualified type will always be a FunctionProtoType.
15370 /// Otherwise, returns a NULL type.
15371 QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes,
15372 SourceLocation Loc, DeclarationName Entity,
15373 const FunctionProtoType::ExtProtoInfo &EPI);
15374
15375 /// Build a member pointer type \c T Class::*.
15376 ///
15377 /// \param T the type to which the member pointer refers.
15378 /// \param Class the class type into which the member pointer points.
15379 /// \param Loc the location where this type begins
15380 /// \param Entity the name of the entity that will have this member pointer
15381 /// type
15382 ///
15383 /// \returns a member pointer type, if successful, or a NULL type if there was
15384 /// an error.
15385 QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS,
15386 CXXRecordDecl *Cls, SourceLocation Loc,
15387 DeclarationName Entity);
15388
15389 /// Build a block pointer type.
15390 ///
15391 /// \param T The type to which we'll be building a block pointer.
15392 ///
15393 /// \param Loc The source location, used for diagnostics.
15394 ///
15395 /// \param Entity The name of the entity that involves the block pointer
15396 /// type, if known.
15397 ///
15398 /// \returns A suitable block pointer type, if there are no
15399 /// errors. Otherwise, returns a NULL type.
15400 QualType BuildBlockPointerType(QualType T, SourceLocation Loc,
15401 DeclarationName Entity);
15402
15403 /// Build a paren type including \p T.
15404 QualType BuildParenType(QualType T);
15405 QualType BuildAtomicType(QualType T, SourceLocation Loc);
15406
15407 /// Build a Read-only Pipe type.
15408 ///
15409 /// \param T The type to which we'll be building a Pipe.
15410 ///
15411 /// \param Loc We do not use it for now.
15412 ///
15413 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15414 /// a NULL type.
15415 QualType BuildReadPipeType(QualType T, SourceLocation Loc);
15416
15417 /// Build a Write-only Pipe type.
15418 ///
15419 /// \param T The type to which we'll be building a Pipe.
15420 ///
15421 /// \param Loc We do not use it for now.
15422 ///
15423 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15424 /// a NULL type.
15425 QualType BuildWritePipeType(QualType T, SourceLocation Loc);
15426
15427 /// Build a bit-precise integer type.
15428 ///
15429 /// \param IsUnsigned Boolean representing the signedness of the type.
15430 ///
15431 /// \param BitWidth Size of this int type in bits, or an expression
15432 /// representing that.
15433 ///
15434 /// \param Loc Location of the keyword.
15435 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15436
15437 /// GetTypeForDeclarator - Convert the type for the specified
15438 /// declarator to Type instances.
15439 ///
15440 /// The result of this call will never be null, but the associated
15441 /// type may be a null type if there's an unrecoverable error.
15442 TypeSourceInfo *GetTypeForDeclarator(Declarator &D);
15443 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
15444
15445 /// Package the given type and TSI into a ParsedType.
15446 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
15447 static QualType GetTypeFromParser(ParsedType Ty,
15448 TypeSourceInfo **TInfo = nullptr);
15449
15450 TypeResult ActOnTypeName(Declarator &D);
15451
15452 // Check whether the size of array element of type \p EltTy is a multiple of
15453 // its alignment and return false if it isn't.
15454 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
15455
15456 void
15457 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15458 SourceLocation FallbackLoc,
15459 SourceLocation ConstQualLoc = SourceLocation(),
15460 SourceLocation VolatileQualLoc = SourceLocation(),
15461 SourceLocation RestrictQualLoc = SourceLocation(),
15462 SourceLocation AtomicQualLoc = SourceLocation(),
15463 SourceLocation UnalignedQualLoc = SourceLocation());
15464
15465 /// Retrieve the keyword associated
15466 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
15467
15468 /// Adjust the calling convention of a method to be the ABI default if it
15469 /// wasn't specified explicitly. This handles method types formed from
15470 /// function type typedefs and typename template arguments.
15471 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15472 bool IsCtorOrDtor, SourceLocation Loc);
15473
15474 // Check if there is an explicit attribute, but only look through parens.
15475 // The intent is to look for an attribute on the current declarator, but not
15476 // one that came from a typedef.
15477 bool hasExplicitCallingConv(QualType T);
15478
15479 /// Check whether a nullability type specifier can be added to the given
15480 /// type through some means not written in source (e.g. API notes).
15481 ///
15482 /// \param Type The type to which the nullability specifier will be
15483 /// added. On success, this type will be updated appropriately.
15484 ///
15485 /// \param Nullability The nullability specifier to add.
15486 ///
15487 /// \param DiagLoc The location to use for diagnostics.
15488 ///
15489 /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15490 /// array type (e.g., because it will decay to a pointer).
15491 ///
15492 /// \param OverrideExisting Whether to override an existing, locally-specified
15493 /// nullability specifier rather than complaining about the conflict.
15494 ///
15495 /// \returns true if nullability cannot be applied, false otherwise.
15496 bool CheckImplicitNullabilityTypeSpecifier(QualType &Type,
15497 NullabilityKind Nullability,
15498 SourceLocation DiagLoc,
15499 bool AllowArrayTypes,
15500 bool OverrideExisting);
15501
15502 /// Check whether the given variable declaration has a size that fits within
15503 /// the address space it is declared in. This issues a diagnostic if not.
15504 ///
15505 /// \param VD The variable declaration to check the size of.
15506 ///
15507 /// \param AS The address space to check the size of \p VD against.
15508 ///
15509 /// \returns true if the variable's size fits within the address space, false
15510 /// otherwise.
15511 bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS);
15512
15513 /// Get the type of expression E, triggering instantiation to complete the
15514 /// type if necessary -- that is, if the expression refers to a templated
15515 /// static data member of incomplete array type.
15516 ///
15517 /// May still return an incomplete type if instantiation was not possible or
15518 /// if the type is incomplete for a different reason. Use
15519 /// RequireCompleteExprType instead if a diagnostic is expected for an
15520 /// incomplete expression type.
15521 QualType getCompletedType(Expr *E);
15522
15523 void completeExprArrayBound(Expr *E);
15524
15525 /// Ensure that the type of the given expression is complete.
15526 ///
15527 /// This routine checks whether the expression \p E has a complete type. If
15528 /// the expression refers to an instantiable construct, that instantiation is
15529 /// performed as needed to complete its type. Furthermore
15530 /// Sema::RequireCompleteType is called for the expression's type (or in the
15531 /// case of a reference type, the referred-to type).
15532 ///
15533 /// \param E The expression whose type is required to be complete.
15534 /// \param Kind Selects which completeness rules should be applied.
15535 /// \param Diagnoser The object that will emit a diagnostic if the type is
15536 /// incomplete.
15537 ///
15538 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15539 /// otherwise.
15540 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
15541 TypeDiagnoser &Diagnoser);
15542 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15543
15544 template <typename... Ts>
15545 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15546 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15547 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
15548 }
15549
15550 // Returns the underlying type of a decltype with the given expression.
15551 QualType getDecltypeForExpr(Expr *E);
15552
15553 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
15554 /// If AsUnevaluated is false, E is treated as though it were an evaluated
15555 /// context, such as when building a type for decltype(auto).
15556 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15557
15558 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15559 SourceLocation Loc,
15560 SourceLocation EllipsisLoc);
15561 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15562 SourceLocation Loc, SourceLocation EllipsisLoc,
15563 bool FullySubstituted = false,
15564 ArrayRef<QualType> Expansions = {});
15565
15566 using UTTKind = UnaryTransformType::UTTKind;
15567 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
15568 SourceLocation Loc);
15569 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
15570 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
15571 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
15572 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
15573 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
15574 SourceLocation Loc);
15575 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
15576 SourceLocation Loc);
15577 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
15578 SourceLocation Loc);
15579
15580 QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc) {
15581 return BuiltinRemoveReference(BaseType, UKind: UTTKind::RemoveCVRef, Loc);
15582 }
15583
15584 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
15585 SourceLocation Loc);
15586 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
15587 SourceLocation Loc);
15588
15589 bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15590
15591 /// Ensure that the type T is a literal type.
15592 ///
15593 /// This routine checks whether the type @p T is a literal type. If @p T is an
15594 /// incomplete type, an attempt is made to complete it. If @p T is a literal
15595 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15596 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15597 /// it the type @p T), along with notes explaining why the type is not a
15598 /// literal type, and returns true.
15599 ///
15600 /// @param Loc The location in the source that the non-literal type
15601 /// diagnostic should refer to.
15602 ///
15603 /// @param T The type that this routine is examining for literalness.
15604 ///
15605 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15606 ///
15607 /// @returns @c true if @p T is not a literal type and a diagnostic was
15608 /// emitted, @c false otherwise.
15609 bool RequireLiteralType(SourceLocation Loc, QualType T,
15610 TypeDiagnoser &Diagnoser);
15611 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15612
15613 template <typename... Ts>
15614 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15615 const Ts &...Args) {
15616 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15617 return RequireLiteralType(Loc, T, Diagnoser);
15618 }
15619
15620 bool isCompleteType(SourceLocation Loc, QualType T,
15621 CompleteTypeKind Kind = CompleteTypeKind::Default) {
15622 return !RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser: nullptr);
15623 }
15624
15625 /// Ensure that the type T is a complete type.
15626 ///
15627 /// This routine checks whether the type @p T is complete in any
15628 /// context where a complete type is required. If @p T is a complete
15629 /// type, returns false. If @p T is a class template specialization,
15630 /// this routine then attempts to perform class template
15631 /// instantiation. If instantiation fails, or if @p T is incomplete
15632 /// and cannot be completed, issues the diagnostic @p diag (giving it
15633 /// the type @p T) and returns true.
15634 ///
15635 /// @param Loc The location in the source that the incomplete type
15636 /// diagnostic should refer to.
15637 ///
15638 /// @param T The type that this routine is examining for completeness.
15639 ///
15640 /// @param Kind Selects which completeness rules should be applied.
15641 ///
15642 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15643 /// @c false otherwise.
15644 bool RequireCompleteType(SourceLocation Loc, QualType T,
15645 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15646 bool RequireCompleteType(SourceLocation Loc, QualType T,
15647 CompleteTypeKind Kind, unsigned DiagID);
15648
15649 bool RequireCompleteType(SourceLocation Loc, QualType T,
15650 TypeDiagnoser &Diagnoser) {
15651 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, Diagnoser);
15652 }
15653 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15654 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, DiagID);
15655 }
15656
15657 template <typename... Ts>
15658 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15659 const Ts &...Args) {
15660 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15661 return RequireCompleteType(Loc, T, Diagnoser);
15662 }
15663
15664 /// Determine whether a declaration is visible to name lookup.
15665 bool isVisible(const NamedDecl *D) {
15666 return D->isUnconditionallyVisible() ||
15667 isAcceptableSlow(D, Kind: AcceptableKind::Visible);
15668 }
15669
15670 /// Determine whether a declaration is reachable.
15671 bool isReachable(const NamedDecl *D) {
15672 // All visible declarations are reachable.
15673 return D->isUnconditionallyVisible() ||
15674 isAcceptableSlow(D, Kind: AcceptableKind::Reachable);
15675 }
15676
15677 /// Determine whether a declaration is acceptable (visible/reachable).
15678 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
15679 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15680 }
15681
15682 /// Determine if \p D and \p Suggested have a structurally compatible
15683 /// layout as described in C11 6.2.7/1.
15684 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15685
15686 /// Determine if \p D has a visible definition. If not, suggest a declaration
15687 /// that should be made visible to expose the definition.
15688 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15689 bool OnlyNeedComplete = false);
15690 bool hasVisibleDefinition(const NamedDecl *D) {
15691 NamedDecl *Hidden;
15692 return hasVisibleDefinition(D: const_cast<NamedDecl *>(D), Suggested: &Hidden);
15693 }
15694 /// Determine if \p D has a definition which allows we redefine it in current
15695 /// TU. \p Suggested is the definition that should be made visible to expose
15696 /// the definition.
15697 bool isRedefinitionAllowedFor(NamedDecl *D, SourceLocation NewDefinitionLoc,
15698 NamedDecl **Suggested, bool &Visible);
15699 bool isRedefinitionAllowedFor(const NamedDecl *D, SourceLocation NewLoc,
15700 bool &Visible) {
15701 NamedDecl *Hidden;
15702 return isRedefinitionAllowedFor(D: const_cast<NamedDecl *>(D), NewDefinitionLoc: NewLoc, Suggested: &Hidden,
15703 Visible);
15704 }
15705
15706 /// Determine if \p D has a reachable definition. If not, suggest a
15707 /// declaration that should be made reachable to expose the definition.
15708 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15709 bool OnlyNeedComplete = false);
15710 bool hasReachableDefinition(NamedDecl *D) {
15711 NamedDecl *Hidden;
15712 return hasReachableDefinition(D, Suggested: &Hidden);
15713 }
15714
15715 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15716 AcceptableKind Kind,
15717 bool OnlyNeedComplete = false);
15718 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
15719 NamedDecl *Hidden;
15720 return hasAcceptableDefinition(D, Suggested: &Hidden, Kind);
15721 }
15722
15723 /// Determine if a definition at \p NewLoc coincides with \p PrevD.
15724 ///
15725 /// Including the same header as a non-modular and a modular allows to process
15726 /// its content twice despite guards against multiple inclusions. To handle
15727 /// such cases this method allows to detect if a currently-parsed decl is at
15728 /// the same location as an existing decl imported from a module.
15729 bool isFromSameSingleIncludeHeader(const Decl *PrevD, SourceLocation NewLoc);
15730
15731 /// Try to parse the conditional expression attached to an effect attribute
15732 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15733 /// optional on error.
15734 std::optional<FunctionEffectMode>
15735 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15736
15737 void ActOnCleanupAttr(Decl *D, const Attr *A);
15738 void ActOnInitPriorityAttr(Decl *D, const Attr *A);
15739
15740private:
15741 /// The implementation of RequireCompleteType
15742 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15743 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15744
15745 /// Nullability type specifiers.
15746 IdentifierInfo *Ident__Nonnull = nullptr;
15747 IdentifierInfo *Ident__Nullable = nullptr;
15748 IdentifierInfo *Ident__Nullable_result = nullptr;
15749 IdentifierInfo *Ident__Null_unspecified = nullptr;
15750
15751 ///@}
15752
15753 //
15754 //
15755 // -------------------------------------------------------------------------
15756 //
15757 //
15758
15759 /// \name FixIt Helpers
15760 /// Implementations are in SemaFixItUtils.cpp
15761 ///@{
15762
15763public:
15764 /// Get a string to suggest for zero-initialization of a type.
15765 std::string getFixItZeroInitializerForType(QualType T,
15766 SourceLocation Loc) const;
15767 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15768
15769 ///@}
15770
15771 //
15772 //
15773 // -------------------------------------------------------------------------
15774 //
15775 //
15776
15777 /// \name Function Effects
15778 /// Implementations are in SemaFunctionEffects.cpp
15779 ///@{
15780public:
15781 struct FunctionEffectDiff {
15782 enum class Kind { Added, Removed, ConditionMismatch };
15783
15784 FunctionEffect::Kind EffectKind;
15785 Kind DiffKind;
15786 std::optional<FunctionEffectWithCondition>
15787 Old; // Invalid when 'Kind' is 'Added'.
15788 std::optional<FunctionEffectWithCondition>
15789 New; // Invalid when 'Kind' is 'Removed'.
15790
15791 StringRef effectName() const {
15792 if (Old)
15793 return Old.value().Effect.name();
15794 return New.value().Effect.name();
15795 }
15796
15797 /// Describes the result of effects differing between a base class's virtual
15798 /// method and an overriding method in a subclass.
15799 enum class OverrideResult {
15800 NoAction,
15801 Warn,
15802 Merge // Merge missing effect from base to derived.
15803 };
15804
15805 /// Return true if adding or removing the effect as part of a type
15806 /// conversion should generate a diagnostic.
15807 bool shouldDiagnoseConversion(QualType SrcType,
15808 const FunctionEffectsRef &SrcFX,
15809 QualType DstType,
15810 const FunctionEffectsRef &DstFX) const;
15811
15812 /// Return true if adding or removing the effect in a redeclaration should
15813 /// generate a diagnostic.
15814 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
15815 const FunctionEffectsRef &OldFX,
15816 const FunctionDecl &NewFunction,
15817 const FunctionEffectsRef &NewFX) const;
15818
15819 /// Return true if adding or removing the effect in a C++ virtual method
15820 /// override should generate a diagnostic.
15821 OverrideResult shouldDiagnoseMethodOverride(
15822 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
15823 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
15824 };
15825
15826 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
15827 /// Caller should short-circuit by checking for equality first.
15828 FunctionEffectDiffVector(const FunctionEffectsRef &Old,
15829 const FunctionEffectsRef &New);
15830 };
15831
15832 /// All functions/lambdas/blocks which have bodies and which have a non-empty
15833 /// FunctionEffectsRef to be verified.
15834 SmallVector<const Decl *> DeclsWithEffectsToVerify;
15835
15836 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
15837 /// are all null.
15838 FunctionEffectKindSet AllEffectsToVerify;
15839
15840public:
15841 /// Warn and return true if adding a function effect to a set would create a
15842 /// conflict.
15843 bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX,
15844 const FunctionEffectWithCondition &EC,
15845 SourceLocation NewAttrLoc);
15846
15847 // Report a failure to merge function effects between declarations due to a
15848 // conflict.
15849 void
15850 diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs,
15851 SourceLocation NewLoc,
15852 SourceLocation OldLoc);
15853
15854 /// Inline checks from the start of maybeAddDeclWithEffects, to
15855 /// minimize performance impact on code not using effects.
15856 template <class FuncOrBlockDecl>
15857 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
15858 if (Context.hasAnyFunctionEffects())
15859 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
15860 maybeAddDeclWithEffects(D, FX);
15861 }
15862
15863 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
15864 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15865
15866 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
15867 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15868
15869 void performFunctionEffectAnalysis(TranslationUnitDecl *TU);
15870
15871 ///@}
15872
15873 //
15874 //
15875 // -------------------------------------------------------------------------
15876 //
15877 //
15878
15879 /// \name Expansion Statements
15880 /// Implementations are in SemaExpand.cpp
15881 ///@{
15882public:
15883 CXXExpansionStmtDecl *ActOnCXXExpansionStmtDecl(unsigned TemplateDepth,
15884 SourceLocation TemplateKWLoc);
15885
15886 CXXExpansionStmtDecl *
15887 BuildCXXExpansionStmtDecl(DeclContext *Ctx, SourceLocation TemplateKWLoc,
15888 NonTypeTemplateParmDecl *NTTP);
15889
15890 ExprResult ActOnCXXExpansionInitList(MultiExprArg SubExprs,
15891 SourceLocation LBraceLoc,
15892 SourceLocation RBraceLoc);
15893
15894 StmtResult ActOnCXXExpansionStmtPattern(
15895 CXXExpansionStmtDecl *ESD, Stmt *Init, Stmt *ExpansionVarStmt,
15896 Expr *ExpansionInitializer, SourceLocation LParenLoc,
15897 SourceLocation ColonLoc, SourceLocation RParenLoc,
15898 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps);
15899
15900 StmtResult FinishCXXExpansionStmt(Stmt *Expansion, Stmt *Body);
15901
15902 StmtResult BuildCXXEnumeratingExpansionStmtPattern(Decl *ESD, Stmt *Init,
15903 Stmt *ExpansionVar,
15904 SourceLocation LParenLoc,
15905 SourceLocation ColonLoc,
15906 SourceLocation RParenLoc);
15907
15908 StmtResult BuildNonEnumeratingCXXExpansionStmtPattern(
15909 CXXExpansionStmtDecl *ESD, Stmt *Init, DeclStmt *ExpansionVarStmt,
15910 Expr *ExpansionInitializer, SourceLocation LParenLoc,
15911 SourceLocation ColonLoc, SourceLocation RParenLoc,
15912 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
15913
15914 ExprResult BuildCXXExpansionSelectExpr(InitListExpr *Range, Expr *Idx);
15915
15916 std::optional<uint64_t>
15917 ComputeExpansionSize(CXXExpansionStmtPattern *Expansion);
15918 ///@}
15919};
15920
15921DeductionFailureInfo
15922MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK,
15923 sema::TemplateDeductionInfo &Info);
15924
15925/// Contains a late templated function.
15926/// Will be parsed at the end of the translation unit, used by Sema & Parser.
15927struct LateParsedTemplate {
15928 CachedTokens Toks;
15929 /// The template function declaration to be late parsed.
15930 Decl *D;
15931 /// Floating-point options in the point of definition.
15932 FPOptions FPO;
15933};
15934
15935template <>
15936void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
15937 PragmaMsStackAction Action,
15938 llvm::StringRef StackSlotLabel,
15939 AlignPackInfo Value);
15940
15941} // end namespace clang
15942
15943#endif
15944