1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/APINotes/APINotesManager.h"
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/ASTLambda.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/AttrIterator.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/DeclBase.h"
24#include "clang/AST/DeclCXX.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/DeclarationName.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprConcepts.h"
30#include "clang/AST/ExternalASTSource.h"
31#include "clang/AST/NestedNameSpecifier.h"
32#include "clang/AST/OperationKinds.h"
33#include "clang/AST/StmtCXX.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
36#include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h"
37#include "clang/Basic/AttrSubjectMatchRules.h"
38#include "clang/Basic/BuiltinTraits.h"
39#include "clang/Basic/Builtins.h"
40#include "clang/Basic/CapturedStmt.h"
41#include "clang/Basic/Cuda.h"
42#include "clang/Basic/DiagnosticSema.h"
43#include "clang/Basic/ExceptionSpecificationType.h"
44#include "clang/Basic/LLVM.h"
45#include "clang/Basic/Lambda.h"
46#include "clang/Basic/LangOptions.h"
47#include "clang/Basic/Module.h"
48#include "clang/Basic/OpenCLOptions.h"
49#include "clang/Basic/OperatorKinds.h"
50#include "clang/Basic/PartialDiagnostic.h"
51#include "clang/Basic/PragmaKinds.h"
52#include "clang/Basic/SourceLocation.h"
53#include "clang/Basic/Specifiers.h"
54#include "clang/Basic/StackExhaustionHandler.h"
55#include "clang/Basic/TemplateKinds.h"
56#include "clang/Basic/TokenKinds.h"
57#include "clang/Sema/AnalysisBasedWarnings.h"
58#include "clang/Sema/Attr.h"
59#include "clang/Sema/CleanupInfo.h"
60#include "clang/Sema/DeclSpec.h"
61#include "clang/Sema/ExternalSemaSource.h"
62#include "clang/Sema/IdentifierResolver.h"
63#include "clang/Sema/Ownership.h"
64#include "clang/Sema/ParsedAttr.h"
65#include "clang/Sema/Redeclaration.h"
66#include "clang/Sema/Scope.h"
67#include "clang/Sema/SemaBase.h"
68#include "clang/Sema/SemaConcept.h"
69#include "clang/Sema/TypoCorrection.h"
70#include "clang/Sema/Weak.h"
71#include "llvm/ADT/APInt.h"
72#include "llvm/ADT/ArrayRef.h"
73#include "llvm/ADT/BitmaskEnum.h"
74#include "llvm/ADT/DenseMap.h"
75#include "llvm/ADT/DenseSet.h"
76#include "llvm/ADT/FloatingPointMode.h"
77#include "llvm/ADT/FoldingSet.h"
78#include "llvm/ADT/MapVector.h"
79#include "llvm/ADT/PointerIntPair.h"
80#include "llvm/ADT/PointerUnion.h"
81#include "llvm/ADT/STLExtras.h"
82#include "llvm/ADT/STLForwardCompat.h"
83#include "llvm/ADT/STLFunctionalExtras.h"
84#include "llvm/ADT/SetVector.h"
85#include "llvm/ADT/SmallBitVector.h"
86#include "llvm/ADT/SmallPtrSet.h"
87#include "llvm/ADT/SmallSet.h"
88#include "llvm/ADT/SmallVector.h"
89#include "llvm/ADT/StringExtras.h"
90#include "llvm/ADT/StringMap.h"
91#include "llvm/ADT/TinyPtrVector.h"
92#include "llvm/Support/Allocator.h"
93#include "llvm/Support/Compiler.h"
94#include "llvm/Support/Error.h"
95#include "llvm/Support/ErrorHandling.h"
96#include <cassert>
97#include <climits>
98#include <cstddef>
99#include <cstdint>
100#include <deque>
101#include <functional>
102#include <iterator>
103#include <memory>
104#include <optional>
105#include <string>
106#include <tuple>
107#include <type_traits>
108#include <utility>
109#include <vector>
110
111namespace llvm {
112struct InlineAsmIdentifierInfo;
113} // namespace llvm
114
115namespace clang {
116class ADLResult;
117class APValue;
118struct ASTConstraintSatisfaction;
119class ASTConsumer;
120class ASTContext;
121class ASTDeclReader;
122class ASTMutationListener;
123class ASTReader;
124class ASTWriter;
125class CXXBasePath;
126class CXXBasePaths;
127class CXXFieldCollector;
128class CodeCompleteConsumer;
129enum class ComparisonCategoryType : unsigned char;
130class ConstraintSatisfaction;
131class DarwinSDKInfo;
132class DeclGroupRef;
133class DeducedTemplateArgument;
134struct DeductionFailureInfo;
135class DependentDiagnostic;
136class Designation;
137class IdentifierInfo;
138struct ImplicitAllocationArguments;
139class ImplicitConversionSequence;
140typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
141class InitializationKind;
142class InitializationSequence;
143class InitializedEntity;
144enum class LangAS : unsigned int;
145class LocalInstantiationScope;
146class LookupResult;
147class MangleNumberingContext;
148typedef ArrayRef<IdentifierLoc> ModuleIdPath;
149class ModuleLoader;
150class MultiLevelTemplateArgumentList;
151struct NormalizedConstraint;
152class ObjCInterfaceDecl;
153class ObjCMethodDecl;
154struct OverloadCandidate;
155enum class OverloadCandidateParamOrder : char;
156enum OverloadCandidateRewriteKind : unsigned;
157class OverloadCandidateSet;
158class Preprocessor;
159struct APINotesSelectorDiagnosticState;
160struct ResolvedAllocation;
161class SemaAMDGPU;
162class SemaARM;
163class SemaAVR;
164class SemaBPF;
165class SemaCodeCompletion;
166class SemaCUDA;
167class SemaDirectX;
168class SemaHLSL;
169class SemaHexagon;
170class SemaLoongArch;
171class SemaM68k;
172class SemaMIPS;
173class SemaMSP430;
174class SemaNVPTX;
175class SemaObjC;
176class SemaOpenACC;
177class SemaOpenCL;
178class SemaOpenMP;
179class SemaPPC;
180class SemaPseudoObject;
181class SemaRISCV;
182class SemaSPIRV;
183class SemaSYCL;
184class SemaSwift;
185class SemaSystemZ;
186class SemaWasm;
187class SemaX86;
188class StandardConversionSequence;
189class TemplateArgument;
190class TemplateArgumentLoc;
191class TemplateInstantiationCallback;
192class TemplatePartialOrderingContext;
193class TemplateSpecCandidateSet;
194class Token;
195class TypeConstraint;
196class TypoCorrectionConsumer;
197class UnresolvedSetImpl;
198class UnresolvedSetIterator;
199class VisibleDeclConsumer;
200
201namespace sema {
202class BlockScopeInfo;
203class Capture;
204class CapturedRegionScopeInfo;
205class CapturingScopeInfo;
206class CompoundScopeInfo;
207class DelayedDiagnostic;
208class DelayedDiagnosticPool;
209class FunctionScopeInfo;
210class LambdaScopeInfo;
211class SemaPPCallbacks;
212class TemplateDeductionInfo;
213} // namespace sema
214
215// AssignmentAction - This is used by all the assignment diagnostic functions
216// to represent what is actually causing the operation
217enum class AssignmentAction {
218 Assigning,
219 Passing,
220 Returning,
221 Converting,
222 Initializing,
223 Sending,
224 Casting,
225 Passing_CFAudited
226};
227
228// Inline capacity for type-aware, aligned, and unaligned allocation argument
229// list candidates.
230using AllocationArgumentSet = SmallVector<ImplicitAllocationArguments, 3>;
231
232namespace threadSafety {
233class BeforeSet;
234void threadSafetyCleanup(BeforeSet *Cache);
235} // namespace threadSafety
236
237// FIXME: No way to easily map from TemplateTypeParmTypes to
238// TemplateTypeParmDecls, so we have this horrible PointerUnion.
239typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *,
240 const TemplateSpecializationType *,
241 const SubstBuiltinTemplatePackType *>,
242 SourceLocation>
243 UnexpandedParameterPack;
244
245/// Describes whether we've seen any nullability information for the given
246/// file.
247struct FileNullability {
248 /// The first pointer declarator (of any pointer kind) in the file that does
249 /// not have a corresponding nullability annotation.
250 SourceLocation PointerLoc;
251
252 /// The end location for the first pointer declarator in the file. Used for
253 /// placing fix-its.
254 SourceLocation PointerEndLoc;
255
256 /// Which kind of pointer declarator we saw.
257 uint8_t PointerKind;
258
259 /// Whether we saw any type nullability annotations in the given file.
260 bool SawTypeNullability = false;
261};
262
263/// A mapping from file IDs to a record of whether we've seen nullability
264/// information in that file.
265class FileNullabilityMap {
266 /// A mapping from file IDs to the nullability information for each file ID.
267 llvm::DenseMap<FileID, FileNullability> Map;
268
269 /// A single-element cache based on the file ID.
270 struct {
271 FileID File;
272 FileNullability Nullability;
273 } Cache;
274
275public:
276 FileNullability &operator[](FileID file) {
277 // Check the single-element cache.
278 if (file == Cache.File)
279 return Cache.Nullability;
280
281 // It's not in the single-element cache; flush the cache if we have one.
282 if (!Cache.File.isInvalid()) {
283 Map[Cache.File] = Cache.Nullability;
284 }
285
286 // Pull this entry into the cache.
287 Cache.File = file;
288 Cache.Nullability = Map[file];
289 return Cache.Nullability;
290 }
291};
292
293/// Tracks expected type during expression parsing, for use in code completion.
294/// The type is tied to a particular token, all functions that update or consume
295/// the type take a start location of the token they are looking at as a
296/// parameter. This avoids updating the type on hot paths in the parser.
297class PreferredTypeBuilder {
298public:
299 PreferredTypeBuilder(ASTContext *Ctx, bool Enabled)
300 : Ctx(Ctx), Enabled(Enabled) {}
301
302 void enterCondition(Sema &S, SourceLocation Tok);
303 void enterReturn(Sema &S, SourceLocation Tok);
304 void enterVariableInit(SourceLocation Tok, Decl *D);
305 /// Handles e.g. BaseType{ .D = Tok...
306 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
307 const Designation &D);
308 /// Computing a type for the function argument may require running
309 /// overloading, so we postpone its computation until it is actually needed.
310 ///
311 /// Clients should be very careful when using this function, as it stores a
312 /// function_ref, clients should make sure all calls to get() with the same
313 /// location happen while function_ref is alive.
314 ///
315 /// The callback should also emit signature help as a side-effect, but only
316 /// if the completion point has been reached.
317 void enterFunctionArgument(SourceLocation Tok,
318 llvm::function_ref<QualType()> ComputeType);
319
320 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
321 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
322 SourceLocation OpLoc);
323 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
324 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
325 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
326 /// Handles all type casts, including C-style cast, C++ casts, etc.
327 void enterTypeCast(SourceLocation Tok, QualType CastType);
328
329 /// Get the expected type associated with this location, if any.
330 ///
331 /// If the location is a function argument, determining the expected type
332 /// involves considering all function overloads and the arguments so far.
333 /// In this case, signature help for these function overloads will be reported
334 /// as a side-effect (only if the completion point has been reached).
335 QualType get(SourceLocation Tok) const {
336 if (!Enabled || Tok != ExpectedLoc)
337 return QualType();
338 if (!Type.isNull())
339 return Type;
340 if (ComputeType)
341 return ComputeType();
342 return QualType();
343 }
344
345private:
346 ASTContext *Ctx;
347 bool Enabled;
348 /// Start position of a token for which we store expected type.
349 SourceLocation ExpectedLoc;
350 /// Expected type for a token starting at ExpectedLoc.
351 QualType Type;
352 /// A function to compute expected type at ExpectedLoc. It is only considered
353 /// if Type is null.
354 llvm::function_ref<QualType()> ComputeType;
355};
356
357struct SkipBodyInfo {
358 SkipBodyInfo() = default;
359 bool ShouldSkip = false;
360 bool CheckSameAsPrevious = false;
361 NamedDecl *Previous = nullptr;
362 NamedDecl *New = nullptr;
363};
364
365/// Describes the result of template argument deduction.
366///
367/// The TemplateDeductionResult enumeration describes the result of
368/// template argument deduction, as returned from
369/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
370/// structure provides additional information about the results of
371/// template argument deduction, e.g., the deduced template argument
372/// list (if successful) or the specific template parameters or
373/// deduced arguments that were involved in the failure.
374enum class TemplateDeductionResult {
375 /// Template argument deduction was successful.
376 Success = 0,
377 /// The declaration was invalid; do nothing.
378 Invalid,
379 /// Template argument deduction exceeded the maximum template
380 /// instantiation depth (which has already been diagnosed).
381 InstantiationDepth,
382 /// Template argument deduction did not deduce a value
383 /// for every template parameter.
384 Incomplete,
385 /// Template argument deduction did not deduce a value for every
386 /// expansion of an expanded template parameter pack.
387 IncompletePack,
388 /// Template argument deduction produced inconsistent
389 /// deduced values for the given template parameter.
390 Inconsistent,
391 /// Template argument deduction failed due to inconsistent
392 /// cv-qualifiers on a template parameter type that would
393 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
394 /// but were given a non-const "X".
395 Underqualified,
396 /// Substitution of the deduced template argument values
397 /// resulted in an error.
398 SubstitutionFailure,
399 /// After substituting deduced template arguments, a dependent
400 /// parameter type did not match the corresponding argument.
401 DeducedMismatch,
402 /// After substituting deduced template arguments, an element of
403 /// a dependent parameter type did not match the corresponding element
404 /// of the corresponding argument (when deducing from an initializer list).
405 DeducedMismatchNested,
406 /// A non-depnedent component of the parameter did not match the
407 /// corresponding component of the argument.
408 NonDeducedMismatch,
409 /// When performing template argument deduction for a function
410 /// template, there were too many call arguments.
411 TooManyArguments,
412 /// When performing template argument deduction for a function
413 /// template, there were too few call arguments.
414 TooFewArguments,
415 /// The explicitly-specified template arguments were not valid
416 /// template arguments for the given template.
417 InvalidExplicitArguments,
418 /// Checking non-dependent argument conversions failed.
419 NonDependentConversionFailure,
420 /// The deduced arguments did not satisfy the constraints associated
421 /// with the template.
422 ConstraintsNotSatisfied,
423 /// Deduction failed; that's all we know.
424 MiscellaneousDeductionFailure,
425 /// CUDA Target attributes do not match.
426 CUDATargetMismatch,
427 /// Some error which was already diagnosed.
428 AlreadyDiagnosed
429};
430
431/// The kind of conversion being performed.
432enum class CheckedConversionKind {
433 /// An implicit conversion.
434 Implicit,
435 /// A C-style cast.
436 CStyleCast,
437 /// A functional-style cast.
438 FunctionalCast,
439 /// A cast other than a C-style cast.
440 OtherCast,
441 /// A conversion for an operand of a builtin overloaded operator.
442 ForBuiltinOverloadedOp
443};
444
445enum class TagUseKind {
446 Reference, // Reference to a tag: 'struct foo *X;'
447 Declaration, // Fwd decl of a tag: 'struct foo;'
448 Definition, // Definition of a tag: 'struct foo { int X; } Y;'
449 Friend // Friend declaration: 'friend struct foo;'
450};
451
452/// Used with attributes/effects with a boolean condition, e.g. `nonblocking`.
453enum class FunctionEffectMode : uint8_t {
454 None, // effect is not present.
455 False, // effect(false).
456 True, // effect(true).
457 Dependent // effect(expr) where expr is dependent.
458};
459
460/// pragma clang section kind
461enum class PragmaClangSectionKind {
462 Invalid = 0,
463 BSS = 1,
464 Data = 2,
465 Rodata = 3,
466 Text = 4,
467 Relro = 5
468};
469
470enum class PragmaClangSectionAction { Set = 0, Clear = 1 };
471
472enum class PragmaOptionsAlignKind {
473 Native, // #pragma options align=native
474 Natural, // #pragma options align=natural
475 Packed, // #pragma options align=packed
476 Power, // #pragma options align=power
477 Mac68k, // #pragma options align=mac68k
478 Reset // #pragma options align=reset
479};
480
481enum class TUFragmentKind {
482 /// The global module fragment, between 'module;' and a module-declaration.
483 Global,
484 /// A normal translation unit fragment. For a non-module unit, this is the
485 /// entire translation unit. Otherwise, it runs from the module-declaration
486 /// to the private-module-fragment (if any) or the end of the TU (if not).
487 Normal,
488 /// The private module fragment, between 'module :private;' and the end of
489 /// the translation unit.
490 Private
491};
492
493enum class FormatStringType {
494 Scanf,
495 Printf,
496 NSString,
497 Strftime,
498 Strfmon,
499 Kprintf,
500 FreeBSDKPrintf,
501 OSTrace,
502 OSLog,
503 Unknown
504};
505
506// Used for emitting the right warning by DefaultVariadicArgumentPromotion
507enum class VariadicCallType {
508 Function,
509 Block,
510 Method,
511 Constructor,
512 DoesNotApply
513};
514
515enum class BuiltinCountedByRefKind {
516 Assignment,
517 Initializer,
518 FunctionArg,
519 ReturnArg,
520 ArraySubscript,
521 BinaryExpr,
522};
523
524// Contexts where using non-trivial C union types can be disallowed. This is
525// passed to err_non_trivial_c_union_in_invalid_context.
526enum class NonTrivialCUnionContext {
527 // Function parameter.
528 FunctionParam,
529 // Function return.
530 FunctionReturn,
531 // Default-initialized object.
532 DefaultInitializedObject,
533 // Variable with automatic storage duration.
534 AutoVar,
535 // Initializer expression that might copy from another object.
536 CopyInit,
537 // Assignment.
538 Assignment,
539 // Compound literal.
540 CompoundLiteral,
541 // Block capture.
542 BlockCapture,
543 // lvalue-to-rvalue conversion of volatile type.
544 LValueToRValueVolatile,
545};
546
547/// Describes the result of the name lookup and resolution performed
548/// by \c Sema::ClassifyName().
549enum class NameClassificationKind {
550 /// This name is not a type or template in this context, but might be
551 /// something else.
552 Unknown,
553 /// Classification failed; an error has been produced.
554 Error,
555 /// The name has been typo-corrected to a keyword.
556 Keyword,
557 /// The name was classified as a type.
558 Type,
559 /// The name was classified as a specific non-type, non-template
560 /// declaration. ActOnNameClassifiedAsNonType should be called to
561 /// convert the declaration to an expression.
562 NonType,
563 /// The name was classified as an ADL-only function name.
564 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
565 /// result to an expression.
566 UndeclaredNonType,
567 /// The name denotes a member of a dependent type that could not be
568 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
569 /// convert the result to an expression.
570 DependentNonType,
571 /// The name was classified as an overload set, and an expression
572 /// representing that overload set has been formed.
573 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
574 /// expression referencing the overload set.
575 OverloadSet,
576 /// The name was classified as a template whose specializations are types.
577 TypeTemplate,
578 /// The name was classified as a variable template name.
579 VarTemplate,
580 /// The name was classified as a function template name.
581 FunctionTemplate,
582 /// The name was classified as an ADL-only function template name.
583 UndeclaredTemplate,
584 /// The name was classified as a concept name.
585 Concept,
586};
587
588enum class PointerAuthDiscArgKind {
589 // Address discrimination argument of __ptrauth.
590 Addr,
591
592 // Extra discriminator argument of __ptrauth.
593 Extra,
594};
595
596/// Common ways to introduce type names without a tag for use in diagnostics.
597/// Keep in sync with err_tag_reference_non_tag.
598enum class NonTagKind {
599 NonStruct,
600 NonClass,
601 NonUnion,
602 NonEnum,
603 Typedef,
604 TypeAlias,
605 Template,
606 TypeAliasTemplate,
607 TemplateTemplateArgument,
608};
609
610enum class OffsetOfKind {
611 // Not parsing a type within __builtin_offsetof.
612 Outside,
613 // Parsing a type within __builtin_offsetof.
614 Builtin,
615 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
616 // To improve our diagnostic message.
617 Macro,
618};
619
620/// Describes the kind of merge to perform for availability
621/// attributes (including "deprecated", "unavailable", and "availability").
622enum class AvailabilityMergeKind {
623 /// Don't merge availability attributes at all.
624 None,
625 /// Merge availability attributes for a redeclaration, which requires
626 /// an exact match.
627 Redeclaration,
628 /// Merge availability attributes for an override, which requires
629 /// an exact match or a weakening of constraints.
630 Override,
631 /// Merge availability attributes for an implementation of
632 /// a protocol requirement.
633 ProtocolImplementation,
634 /// Merge availability attributes for an implementation of
635 /// an optional protocol requirement.
636 OptionalProtocolImplementation
637};
638
639enum class TrivialABIHandling {
640 /// The triviality of a method unaffected by "trivial_abi".
641 IgnoreTrivialABI,
642
643 /// The triviality of a method affected by "trivial_abi".
644 ConsiderTrivialABI
645};
646
647enum class TryCaptureKind { Implicit, ExplicitByVal, ExplicitByRef };
648
649enum class AllowFoldKind {
650 No,
651 Allow,
652};
653
654/// Context in which we're performing a usual arithmetic conversion.
655enum class ArithConvKind {
656 /// An arithmetic operation.
657 Arithmetic,
658 /// A bitwise operation.
659 BitwiseOp,
660 /// A comparison.
661 Comparison,
662 /// A conditional (?:) operator.
663 Conditional,
664 /// A compound assignment expression.
665 CompAssign,
666};
667
668// Used for determining in which context a type is allowed to be passed to a
669// vararg function.
670enum class VarArgKind {
671 Valid,
672 ValidInCXX11,
673 Undefined,
674 MSVCUndefined,
675 Invalid
676};
677
678/// AssignConvertType - All of the 'assignment' semantic checks return this
679/// enum to indicate whether the assignment was allowed. These checks are
680/// done for simple assignments, as well as initialization, return from
681/// function, argument passing, etc. The query is phrased in terms of a
682/// source and destination type.
683enum class AssignConvertType {
684 /// Compatible - the types are compatible according to the standard.
685 Compatible,
686
687 /// CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because
688 /// a void * can implicitly convert to another pointer type, which we
689 /// differentiate for better diagnostic behavior.
690 CompatibleVoidPtrToNonVoidPtr,
691
692 /// PointerToInt - The assignment converts a pointer to an int, which we
693 /// accept as an extension.
694 PointerToInt,
695
696 /// IntToPointer - The assignment converts an int to a pointer, which we
697 /// accept as an extension.
698 IntToPointer,
699
700 /// FunctionVoidPointer - The assignment is between a function pointer and
701 /// void*, which the standard doesn't allow, but we accept as an extension.
702 FunctionVoidPointer,
703
704 /// IncompatiblePointer - The assignment is between two pointers types that
705 /// are not compatible, but we accept them as an extension.
706 IncompatiblePointer,
707
708 /// IncompatibleFunctionPointer - The assignment is between two function
709 /// pointers types that are not compatible, but we accept them as an
710 /// extension.
711 IncompatibleFunctionPointer,
712
713 /// IncompatibleFunctionPointerStrict - The assignment is between two
714 /// function pointer types that are not identical, but are compatible,
715 /// unless compiled with -fsanitize=cfi, in which case the type mismatch
716 /// may trip an indirect call runtime check.
717 IncompatibleFunctionPointerStrict,
718
719 /// IncompatiblePointerSign - The assignment is between two pointers types
720 /// which point to integers which have a different sign, but are otherwise
721 /// identical. This is a subset of the above, but broken out because it's by
722 /// far the most common case of incompatible pointers.
723 IncompatiblePointerSign,
724
725 /// CompatiblePointerDiscardsQualifiers - The assignment discards
726 /// c/v/r qualifiers, which we accept as an extension.
727 CompatiblePointerDiscardsQualifiers,
728
729 /// IncompatiblePointerDiscardsQualifiers - The assignment
730 /// discards qualifiers that we don't permit to be discarded,
731 /// like address spaces.
732 IncompatiblePointerDiscardsQualifiers,
733
734 /// IncompatiblePointerDiscardsOverflowBehavior - The assignment
735 /// discards overflow behavior annotations between otherwise compatible
736 /// pointer types.
737 IncompatiblePointerDiscardsOverflowBehavior,
738
739 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
740 /// changes address spaces in nested pointer types which is not allowed.
741 /// For instance, converting __private int ** to __generic int ** is
742 /// illegal even though __private could be converted to __generic.
743 IncompatibleNestedPointerAddressSpaceMismatch,
744
745 /// IncompatibleNestedPointerQualifiers - The assignment is between two
746 /// nested pointer types, and the qualifiers other than the first two
747 /// levels differ e.g. char ** -> const char **, but we accept them as an
748 /// extension.
749 IncompatibleNestedPointerQualifiers,
750
751 /// IncompatibleVectors - The assignment is between two vector types that
752 /// have the same size, which we accept as an extension.
753 IncompatibleVectors,
754
755 /// IntToBlockPointer - The assignment converts an int to a block
756 /// pointer. We disallow this.
757 IntToBlockPointer,
758
759 /// IncompatibleBlockPointer - The assignment is between two block
760 /// pointers types that are not compatible.
761 IncompatibleBlockPointer,
762
763 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
764 /// id type and something else (that is incompatible with it). For example,
765 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
766 IncompatibleObjCQualifiedId,
767
768 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
769 /// object with __weak qualifier.
770 IncompatibleObjCWeakRef,
771
772 /// IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType
773 /// kinds, e.g., from __ob_trap to __ob_wrap or vice versa.
774 IncompatibleOBTKinds,
775
776 /// CompatibleOBTDiscards - Assignment discards overflow behavior
777 CompatibleOBTDiscards,
778
779 /// Incompatible - We reject this conversion outright, it is invalid to
780 /// represent it in the AST.
781 Incompatible
782};
783
784/// The scope in which to find allocation functions.
785enum class AllocationFunctionScope {
786 /// Only look for allocation functions in the global scope.
787 Global,
788 /// Only look for allocation functions in the scope of the
789 /// allocated class.
790 Class,
791 /// Look for allocation functions in both the global scope
792 /// and in the scope of the allocated class.
793 Both
794};
795
796/// Describes the result of an "if-exists" condition check.
797enum class IfExistsResult {
798 /// The symbol exists.
799 Exists,
800
801 /// The symbol does not exist.
802 DoesNotExist,
803
804 /// The name is a dependent name, so the results will differ
805 /// from one instantiation to the next.
806 Dependent,
807
808 /// An error occurred.
809 Error
810};
811
812enum class CorrectTypoKind {
813 NonError, // CorrectTypo used in a non error recovery situation.
814 ErrorRecovery // CorrectTypo used in normal error recovery.
815};
816
817enum class OverloadKind {
818 /// This is a legitimate overload: the existing declarations are
819 /// functions or function templates with different signatures.
820 Overload,
821
822 /// This is not an overload because the signature exactly matches
823 /// an existing declaration.
824 Match,
825
826 /// This is not an overload because the lookup results contain a
827 /// non-function.
828 NonFunction
829};
830
831/// Contexts in which a converted constant expression is required.
832enum class CCEKind {
833 CaseValue, ///< Expression in a case label.
834 Enumerator, ///< Enumerator value with fixed underlying type.
835 TemplateArg, ///< Value of a non-type template parameter.
836 TempArgStrict, ///< As above, but applies strict template checking
837 ///< rules.
838 ArrayBound, ///< Array bound in array declarator or new-expression.
839 ExplicitBool, ///< Condition in an explicit(bool) specifier.
840 Noexcept, ///< Condition in a noexcept(bool) specifier.
841 StaticAssertMessageSize, ///< Call to size() in a static assert
842 ///< message.
843 StaticAssertMessageData, ///< Call to data() in a static assert
844 ///< message.
845 PackIndex ///< Index of a pack indexing expression or specifier.
846};
847
848/// Enums for the diagnostics of target, target_version and target_clones.
849namespace DiagAttrParams {
850enum DiagType { Unsupported, Duplicate, Unknown };
851enum Specifier { None, CPU, Tune };
852enum AttrName { Target, TargetClones, TargetVersion };
853} // end namespace DiagAttrParams
854
855void inferNoReturnAttr(Sema &S, Decl *D);
856
857#ifdef __GNUC__
858#pragma GCC diagnostic push
859#pragma GCC diagnostic ignored "-Wattributes"
860#endif
861/// Sema - This implements semantic analysis and AST building for C.
862/// \nosubgrouping
863class Sema final : public SemaBase {
864#ifdef __GNUC__
865#pragma GCC diagnostic pop
866#endif
867 // Table of Contents
868 // -----------------
869 // 1. Semantic Analysis (Sema.cpp)
870 // 2. API Notes (SemaAPINotes.cpp)
871 // 3. C++ Access Control (SemaAccess.cpp)
872 // 4. Attributes (SemaAttr.cpp)
873 // 5. Availability Attribute Handling (SemaAvailability.cpp)
874 // 6. Bounds Safety (SemaBoundsSafety.cpp)
875 // 7. Casts (SemaCast.cpp)
876 // 8. Extra Semantic Checking (SemaChecking.cpp)
877 // 9. C++ Coroutines (SemaCoroutine.cpp)
878 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
879 // 11. Declarations (SemaDecl.cpp)
880 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
881 // 13. C++ Declarations (SemaDeclCXX.cpp)
882 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
883 // 15. Expressions (SemaExpr.cpp)
884 // 16. C++ Expressions (SemaExprCXX.cpp)
885 // 17. Member Access Expressions (SemaExprMember.cpp)
886 // 18. Initializers (SemaInit.cpp)
887 // 19. C++ Lambda Expressions (SemaLambda.cpp)
888 // 20. Name Lookup (SemaLookup.cpp)
889 // 21. Modules (SemaModule.cpp)
890 // 22. C++ Overloading (SemaOverload.cpp)
891 // 23. Statements (SemaStmt.cpp)
892 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
893 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
894 // 26. C++ Templates (SemaTemplate.cpp)
895 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
896 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
897 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
898 // 30. C++ Template Declaration Instantiation
899 // (SemaTemplateInstantiateDecl.cpp)
900 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
901 // 32. Constraints and Concepts (SemaConcept.cpp)
902 // 33. Types (SemaType.cpp)
903 // 34. FixIt Helpers (SemaFixItUtils.cpp)
904 // 35. Function Effects (SemaFunctionEffects.cpp)
905 // 36. C++ Expansion Statements (SemaExpand.cpp)
906
907 /// \name Semantic Analysis
908 /// Implementations are in Sema.cpp
909 ///@{
910
911public:
912 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
913 TranslationUnitKind TUKind = TU_Complete,
914 CodeCompleteConsumer *CompletionConsumer = nullptr);
915 ~Sema();
916
917 /// Perform initialization that occurs after the parser has been
918 /// initialized but before it parses anything.
919 void Initialize();
920
921 /// This virtual key function only exists to limit the emission of debug info
922 /// describing the Sema class. GCC and Clang only emit debug info for a class
923 /// with a vtable when the vtable is emitted. Sema is final and not
924 /// polymorphic, but the debug info size savings are so significant that it is
925 /// worth adding a vtable just to take advantage of this optimization.
926 LLVM_DECLARE_VIRTUAL_ANCHOR_FUNCTION();
927
928 const LangOptions &getLangOpts() const { return LangOpts; }
929 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
930 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
931
932 DiagnosticsEngine &getDiagnostics() const { return Diags; }
933 SourceManager &getSourceManager() const { return SourceMgr; }
934 Preprocessor &getPreprocessor() const { return PP; }
935 ASTContext &getASTContext() const { return Context; }
936 ASTConsumer &getASTConsumer() const { return Consumer; }
937 ASTMutationListener *getASTMutationListener() const;
938 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
939
940 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
941 StringRef Platform);
942 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
943
944 /// Registers an external source. If an external source already exists,
945 /// creates a multiplex external source and appends to it.
946 ///
947 ///\param[in] E - A non-null external sema source.
948 ///
949 void addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E);
950
951 /// Print out statistics about the semantic analysis.
952 void PrintStats() const;
953
954 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
955 /// guaranteed). Produces a warning if we're low on stack space and allocates
956 /// more in that case. Use this in code that may recurse deeply (for example,
957 /// in template instantiation) to avoid stack overflow.
958 void runWithSufficientStackSpace(SourceLocation Loc,
959 llvm::function_ref<void()> Fn);
960
961 /// Returns default addr space for method qualifiers.
962 LangAS getDefaultCXXMethodAddrSpace() const;
963
964 /// Load weak undeclared identifiers from the external source.
965 void LoadExternalWeakUndeclaredIdentifiers();
966
967 /// Load #pragma redefine_extname'd undeclared identifiers from the external
968 /// source.
969 void LoadExternalExtnameUndeclaredIdentifiers();
970
971 /// Determine if VD, which must be a variable or function, is an external
972 /// symbol that nonetheless can't be referenced from outside this translation
973 /// unit because its type has no linkage and it's not extern "C".
974 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
975
976 /// Determines whether the given source location is in the main file
977 /// and we're in a context where we should warn about unused entities.
978 bool isMainFileLoc(SourceLocation Loc) const;
979
980 /// Obtain a sorted list of functions that are undefined but ODR-used.
981 void getUndefinedButUsed(
982 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
983
984 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
985 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
986 /// Retrieves list of suspicious delete-expressions that will be checked at
987 /// the end of translation unit.
988 const llvm::MapVector<FieldDecl *, DeleteLocs> &
989 getMismatchingDeleteExpressions() const;
990
991 /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
992 /// This is closely coupled to the SemaDiagnosticBuilder class and
993 /// should not be used elsewhere.
994 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
995
996 void addImplicitTypedef(StringRef Name, QualType T);
997
998 /// Whether uncompilable error has occurred. This includes error happens
999 /// in deferred diagnostics.
1000 bool hasUncompilableErrorOccurred() const;
1001
1002 /// Looks through the macro-expansion chain for the given
1003 /// location, looking for a macro expansion with the given name.
1004 /// If one is found, returns true and sets the location to that
1005 /// expansion loc.
1006 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1007
1008 /// Calls \c Lexer::getLocForEndOfToken()
1009 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1010
1011 /// Calls \c Lexer::findNextToken() to find the next token, and if the
1012 /// locations of both ends of the token can be resolved it return that
1013 /// range; Otherwise it returns an invalid SourceRange.
1014 SourceRange getRangeForNextToken(
1015 SourceLocation Loc, bool IncludeMacros, bool IncludeComments,
1016 std::optional<tok::TokenKind> ExpectedToken = std::nullopt);
1017
1018 /// Retrieve the module loader associated with the preprocessor.
1019 ModuleLoader &getModuleLoader() const;
1020
1021 /// Invent a new identifier for parameters of abbreviated templates.
1022 IdentifierInfo *
1023 InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName,
1024 unsigned Index);
1025
1026 void emitAndClearUnusedLocalTypedefWarnings();
1027
1028 // Emit all deferred diagnostics.
1029 void emitDeferredDiags();
1030
1031 /// This is called before the very first declaration in the translation unit
1032 /// is parsed. Note that the ASTContext may have already injected some
1033 /// declarations.
1034 void ActOnStartOfTranslationUnit();
1035 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1036 /// translation unit when EOF is reached and all but the top-level scope is
1037 /// popped.
1038 void ActOnEndOfTranslationUnit();
1039 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1040
1041 /// Determines the active Scope associated with the given declaration
1042 /// context.
1043 ///
1044 /// This routine maps a declaration context to the active Scope object that
1045 /// represents that declaration context in the parser. It is typically used
1046 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1047 /// declarations) that injects a name for name-lookup purposes and, therefore,
1048 /// must update the Scope.
1049 ///
1050 /// \returns The scope corresponding to the given declaraion context, or NULL
1051 /// if no such scope is open.
1052 Scope *getScopeForContext(DeclContext *Ctx);
1053
1054 void PushFunctionScope();
1055 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1056 sema::LambdaScopeInfo *PushLambdaScope();
1057
1058 /// This is used to inform Sema what the current TemplateParameterDepth
1059 /// is during Parsing. Currently it is used to pass on the depth
1060 /// when parsing generic lambda 'auto' parameters.
1061 void RecordParsingTemplateParameterDepth(unsigned Depth);
1062
1063 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1064 RecordDecl *RD, CapturedRegionKind K,
1065 unsigned OpenMPCaptureLevel = 0);
1066
1067 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1068 /// time after they've been popped.
1069 class PoppedFunctionScopeDeleter {
1070 Sema *Self;
1071
1072 public:
1073 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1074 void operator()(sema::FunctionScopeInfo *Scope) const;
1075 };
1076
1077 using PoppedFunctionScopePtr =
1078 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1079
1080 /// Pop a function (or block or lambda or captured region) scope from the
1081 /// stack.
1082 ///
1083 /// \param WP The warning policy to use for CFG-based warnings, or null if
1084 /// such warnings should not be produced.
1085 /// \param D The declaration corresponding to this function scope, if
1086 /// producing CFG-based warnings.
1087 /// \param BlockType The type of the block expression, if D is a BlockDecl.
1088 PoppedFunctionScopePtr
1089 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1090 Decl *D = nullptr, QualType BlockType = QualType());
1091
1092 sema::FunctionScopeInfo *getEnclosingFunction() const;
1093
1094 void setFunctionHasBranchIntoScope();
1095 void setFunctionHasBranchProtectedScope();
1096 void setFunctionHasIndirectGoto();
1097 void setFunctionHasMustTail();
1098
1099 void PushCompoundScope(bool IsStmtExpr);
1100 void PopCompoundScope();
1101
1102 /// Determine whether any errors occurred within this function/method/
1103 /// block.
1104 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1105
1106 /// Retrieve the current block, if any.
1107 sema::BlockScopeInfo *getCurBlock();
1108
1109 /// Get the innermost lambda or block enclosing the current location, if any.
1110 /// This looks through intervening non-lambda, non-block scopes such as local
1111 /// functions.
1112 sema::CapturingScopeInfo *getEnclosingLambdaOrBlock() const;
1113
1114 /// Retrieve the current lambda scope info, if any.
1115 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1116 /// lambda scope info ignoring all inner capturing scopes that are not
1117 /// lambda scopes.
1118 sema::LambdaScopeInfo *
1119 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1120
1121 /// Retrieve the current generic lambda info, if any.
1122 sema::LambdaScopeInfo *getCurGenericLambda();
1123
1124 /// Retrieve the current captured region, if any.
1125 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1126
1127 void ActOnComment(SourceRange Comment);
1128
1129 /// Returns true if any of the documentation warnings is enabled at \p Loc.
1130 bool areDocumentationDiagsEnabled(SourceLocation Loc);
1131
1132 /// Discard the areDocumentationDiagsEnabled() cache, for when a
1133 /// `#pragma clang diagnostic` has changed diagnostic severities.
1134 void clearDocumentationDiagsCache();
1135
1136private:
1137 /// The uncached answer for both documentation groups at \p Loc.
1138 bool computeDocumentationDiagsAt(SourceLocation Loc) const;
1139
1140 /// Caches results for areDocumentationDiagsEnabled().
1141 /// Flushed whenever a diagnostic pragma changes severities.
1142 /// Level one is keyed on the diagnostic state alone.
1143 const void *DocDiagsStateKey = nullptr;
1144 bool DocDiagsEnabledIgnoringSystem = false;
1145
1146 /// Level two, for when the location does matter. Bit i of each mask is a
1147 /// DiagStateSystemClass value; bit 0 is unused.
1148 uint8_t DocDiagsExactComputed = 0;
1149 uint8_t DocDiagsExactEnabled = 0;
1150
1151public:
1152 /// Returns true if a comment at \p Loc should be retained in the AST
1153 /// (some consumer such as -Wdocumentation, -fparse-all-comments, code
1154 /// completion, or AST-file serialization may read it back).
1155 bool shouldRetainCommentsInAST(SourceLocation Loc);
1156
1157 /// Retrieve the parser's current scope.
1158 ///
1159 /// This routine must only be used when it is certain that semantic analysis
1160 /// and the parser are in precisely the same context, which is not the case
1161 /// when, e.g., we are performing any kind of template instantiation.
1162 /// Therefore, the only safe places to use this scope are in the parser
1163 /// itself and in routines directly invoked from the parser and *never* from
1164 /// template substitution or instantiation.
1165 Scope *getCurScope() const { return CurScope; }
1166
1167 IdentifierInfo *getSuperIdentifier() const;
1168
1169 DeclContext *getCurLexicalContext() const {
1170 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
1171 }
1172
1173 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1174 const FunctionDecl *FD = nullptr);
1175 SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
1176 const PartialDiagnostic &PD,
1177 const FunctionDecl *FD = nullptr) {
1178 return targetDiag(Loc, DiagID: PD.getDiagID(), FD) << PD;
1179 }
1180
1181 /// Check if the type is allowed to be used for the current target.
1182 void checkTypeSupport(QualType Ty, SourceLocation Loc,
1183 ValueDecl *D = nullptr);
1184
1185 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1186 /// cast. If there is already an implicit cast, merge into the existing one.
1187 /// If isLvalue, the result of the cast is an lvalue.
1188 ExprResult ImpCastExprToType(
1189 Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue,
1190 const CXXCastPath *BasePath = nullptr,
1191 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
1192
1193 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1194 /// to the conversion from scalar type ScalarTy to the Boolean type.
1195 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
1196
1197 /// If \p AllowLambda is true, treat lambda as function.
1198 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1199
1200 /// Returns a pointer to the innermost enclosing function, or nullptr if the
1201 /// current context is not inside a function. If \p AllowLambda is true,
1202 /// this can return the call operator of an enclosing lambda, otherwise
1203 /// lambdas are skipped when looking for an enclosing function.
1204 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1205
1206 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1207 /// the method decl for the method being parsed. If we're currently
1208 /// in a 'block', this returns the containing context.
1209 ObjCMethodDecl *getCurMethodDecl();
1210
1211 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1212 /// or C function we're in, otherwise return null. If we're currently
1213 /// in a 'block', this returns the containing context.
1214 NamedDecl *getCurFunctionOrMethodDecl() const;
1215
1216 /// Warn if we're implicitly casting from a _Nullable pointer type to a
1217 /// _Nonnull one.
1218 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
1219 SourceLocation Loc);
1220
1221 /// Warn when implicitly casting 0 to nullptr.
1222 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1223
1224 /// Warn when implicitly changing function effects.
1225 void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType,
1226 SourceLocation Loc);
1227
1228 /// makeUnavailableInSystemHeader - There is an error in the current
1229 /// context. If we're still in a system header, and we can plausibly
1230 /// make the relevant declaration unavailable instead of erroring, do
1231 /// so and return true.
1232 bool makeUnavailableInSystemHeader(SourceLocation loc,
1233 UnavailableAttr::ImplicitReason reason);
1234
1235 /// Retrieve a suitable printing policy for diagnostics.
1236 PrintingPolicy getPrintingPolicy() const {
1237 return getPrintingPolicy(Ctx: Context, PP);
1238 }
1239
1240 /// Retrieve a suitable printing policy for diagnostics.
1241 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1242 const Preprocessor &PP);
1243
1244 /// Scope actions.
1245 void ActOnTranslationUnitScope(Scope *S);
1246
1247 /// Determine whether \param D is function like (function or function
1248 /// template) for parsing.
1249 bool isDeclaratorFunctionLike(Declarator &D);
1250
1251 /// The maximum alignment, same as in llvm::Value. We duplicate them here
1252 /// because that allows us not to duplicate the constants in clang code,
1253 /// which we must to since we can't directly use the llvm constants.
1254 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1255 ///
1256 /// This is the greatest alignment value supported by load, store, and alloca
1257 /// instructions, and global values.
1258 static const unsigned MaxAlignmentExponent = 32;
1259 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1260
1261 /// Flag indicating whether or not to collect detailed statistics.
1262 bool CollectStats;
1263
1264 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1265
1266 /// Stack containing information about each of the nested
1267 /// function, block, and method scopes that are currently active.
1268 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
1269
1270 /// The index of the first FunctionScope that corresponds to the current
1271 /// context.
1272 unsigned FunctionScopesStart = 0;
1273
1274 /// Track the number of currently active capturing scopes.
1275 unsigned CapturingFunctionScopes = 0;
1276
1277 llvm::BumpPtrAllocator BumpAlloc;
1278
1279 /// The kind of translation unit we are processing.
1280 ///
1281 /// When we're processing a complete translation unit, Sema will perform
1282 /// end-of-translation-unit semantic tasks (such as creating
1283 /// initializers for tentative definitions in C) once parsing has
1284 /// completed. Modules and precompiled headers perform different kinds of
1285 /// checks.
1286 const TranslationUnitKind TUKind;
1287
1288 /// Translation Unit Scope - useful to Objective-C actions that need
1289 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1290 /// For example, user-defined classes, built-in "id" type, etc.
1291 Scope *TUScope;
1292
1293 void incrementMSManglingNumber() const {
1294 return CurScope->incrementMSManglingNumber();
1295 }
1296
1297 /// Try to recover by turning the given expression into a
1298 /// call. Returns true if recovery was attempted or an error was
1299 /// emitted; this may also leave the ExprResult invalid.
1300 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1301 bool ForceComplain = false,
1302 bool (*IsPlausibleResult)(QualType) = nullptr);
1303
1304 // Adds implicit lifetime bound attribute for implicit this to its
1305 // TypeSourceInfo.
1306 void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD);
1307
1308 /// Figure out if an expression could be turned into a call.
1309 ///
1310 /// Use this when trying to recover from an error where the programmer may
1311 /// have written just the name of a function instead of actually calling it.
1312 ///
1313 /// \param E - The expression to examine.
1314 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1315 /// with no arguments, this parameter is set to the type returned by such a
1316 /// call; otherwise, it is set to an empty QualType.
1317 /// \param OverloadSet - If the expression is an overloaded function
1318 /// name, this parameter is populated with the decls of the various
1319 /// overloads.
1320 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1321 UnresolvedSetImpl &NonTemplateOverloads);
1322
1323 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
1324 typedef OpaquePtr<TemplateName> TemplateTy;
1325 typedef OpaquePtr<QualType> TypeTy;
1326
1327 OpenCLOptions OpenCLFeatures;
1328 FPOptions CurFPFeatures;
1329
1330 const LangOptions &LangOpts;
1331 Preprocessor &PP;
1332 ASTContext &Context;
1333 ASTConsumer &Consumer;
1334 DiagnosticsEngine &Diags;
1335 SourceManager &SourceMgr;
1336 api_notes::APINotesManager APINotes;
1337
1338 std::unique_ptr<APINotesSelectorDiagnosticState> APINotesSelectorDiagnostics;
1339
1340 /// A RAII object to enter scope of a compound statement.
1341 class CompoundScopeRAII {
1342 public:
1343 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1344 S.ActOnStartOfCompoundStmt(IsStmtExpr);
1345 }
1346
1347 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1348 CompoundScopeRAII(const CompoundScopeRAII &) = delete;
1349 CompoundScopeRAII &operator=(const CompoundScopeRAII &) = delete;
1350
1351 private:
1352 Sema &S;
1353 };
1354
1355 /// An RAII helper that pops function a function scope on exit.
1356 struct FunctionScopeRAII {
1357 Sema &S;
1358 bool Active;
1359 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
1360 ~FunctionScopeRAII() {
1361 if (Active)
1362 S.PopFunctionScopeInfo();
1363 }
1364 void disable() { Active = false; }
1365 };
1366
1367 sema::FunctionScopeInfo *getCurFunction() const {
1368 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1369 }
1370
1371 /// Worker object for performing CFG-based warnings.
1372 sema::AnalysisBasedWarnings AnalysisWarnings;
1373 threadSafety::BeforeSet *ThreadSafetyDeclCache;
1374
1375 /// Callback to the parser to parse templated functions when needed.
1376 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1377 LateTemplateParserCB *LateTemplateParser;
1378 void *OpaqueParser;
1379
1380 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
1381 LateTemplateParser = LTP;
1382 OpaqueParser = P;
1383 }
1384
1385 /// Callback to the parser to parse a type expressed as a string.
1386 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1387 ParseTypeFromStringCallback;
1388
1389 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1390 /// This is used as part of a hack to omit that class from ADL results.
1391 DeclarationName VAListTagName;
1392
1393 /// Is the last error level diagnostic immediate. This is used to determined
1394 /// whether the next info diagnostic should be immediate.
1395 bool IsLastErrorImmediate = true;
1396
1397 /// Track if we're currently analyzing overflow behavior types in assignment
1398 /// context.
1399 bool InOverflowBehaviorAssignmentContext = false;
1400
1401 class DelayedDiagnostics;
1402
1403 class DelayedDiagnosticsState {
1404 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1405 friend class Sema::DelayedDiagnostics;
1406 };
1407 typedef DelayedDiagnosticsState ParsingDeclState;
1408 typedef DelayedDiagnosticsState ProcessingContextState;
1409
1410 /// A class which encapsulates the logic for delaying diagnostics
1411 /// during parsing and other processing.
1412 class DelayedDiagnostics {
1413 /// The current pool of diagnostics into which delayed
1414 /// diagnostics should go.
1415 sema::DelayedDiagnosticPool *CurPool = nullptr;
1416
1417 public:
1418 DelayedDiagnostics() = default;
1419
1420 /// Adds a delayed diagnostic.
1421 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1422
1423 /// Determines whether diagnostics should be delayed.
1424 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1425
1426 /// Returns the current delayed-diagnostics pool.
1427 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1428
1429 /// Enter a new scope. Access and deprecation diagnostics will be
1430 /// collected in this pool.
1431 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
1432 DelayedDiagnosticsState state;
1433 state.SavedPool = CurPool;
1434 CurPool = &pool;
1435 return state;
1436 }
1437
1438 /// Leave a delayed-diagnostic state that was previously pushed.
1439 /// Do not emit any of the diagnostics. This is performed as part
1440 /// of the bookkeeping of popping a pool "properly".
1441 void popWithoutEmitting(DelayedDiagnosticsState state) {
1442 CurPool = state.SavedPool;
1443 }
1444
1445 /// Enter a new scope where access and deprecation diagnostics are
1446 /// not delayed.
1447 DelayedDiagnosticsState pushUndelayed() {
1448 DelayedDiagnosticsState state;
1449 state.SavedPool = CurPool;
1450 CurPool = nullptr;
1451 return state;
1452 }
1453
1454 /// Undo a previous pushUndelayed().
1455 void popUndelayed(DelayedDiagnosticsState state) {
1456 assert(CurPool == nullptr);
1457 CurPool = state.SavedPool;
1458 }
1459 } DelayedDiagnostics;
1460
1461 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
1462 return DelayedDiagnostics.push(pool);
1463 }
1464
1465 /// Diagnostics that are emitted only if we discover that the given function
1466 /// must be codegen'ed. Because handling these correctly adds overhead to
1467 /// compilation, this is currently only used for offload languages like CUDA,
1468 /// OpenMP, and SYCL.
1469 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1470
1471 /// CurContext - This is the current declaration context of parsing.
1472 DeclContext *CurContext;
1473
1474 SemaAMDGPU &AMDGPU() {
1475 assert(AMDGPUPtr);
1476 return *AMDGPUPtr;
1477 }
1478
1479 SemaARM &ARM() {
1480 assert(ARMPtr);
1481 return *ARMPtr;
1482 }
1483
1484 SemaAVR &AVR() {
1485 assert(AVRPtr);
1486 return *AVRPtr;
1487 }
1488
1489 SemaBPF &BPF() {
1490 assert(BPFPtr);
1491 return *BPFPtr;
1492 }
1493
1494 SemaCodeCompletion &CodeCompletion() {
1495 assert(CodeCompletionPtr);
1496 return *CodeCompletionPtr;
1497 }
1498
1499 SemaCUDA &CUDA() {
1500 assert(CUDAPtr);
1501 return *CUDAPtr;
1502 }
1503
1504 SemaDirectX &DirectX() {
1505 assert(DirectXPtr);
1506 return *DirectXPtr;
1507 }
1508
1509 SemaHLSL &HLSL() {
1510 assert(HLSLPtr);
1511 return *HLSLPtr;
1512 }
1513
1514 SemaHexagon &Hexagon() {
1515 assert(HexagonPtr);
1516 return *HexagonPtr;
1517 }
1518
1519 SemaLoongArch &LoongArch() {
1520 assert(LoongArchPtr);
1521 return *LoongArchPtr;
1522 }
1523
1524 SemaM68k &M68k() {
1525 assert(M68kPtr);
1526 return *M68kPtr;
1527 }
1528
1529 SemaMIPS &MIPS() {
1530 assert(MIPSPtr);
1531 return *MIPSPtr;
1532 }
1533
1534 SemaMSP430 &MSP430() {
1535 assert(MSP430Ptr);
1536 return *MSP430Ptr;
1537 }
1538
1539 SemaNVPTX &NVPTX() {
1540 assert(NVPTXPtr);
1541 return *NVPTXPtr;
1542 }
1543
1544 SemaObjC &ObjC() {
1545 assert(ObjCPtr);
1546 return *ObjCPtr;
1547 }
1548
1549 SemaOpenACC &OpenACC() {
1550 assert(OpenACCPtr);
1551 return *OpenACCPtr;
1552 }
1553
1554 SemaOpenCL &OpenCL() {
1555 assert(OpenCLPtr);
1556 return *OpenCLPtr;
1557 }
1558
1559 SemaOpenMP &OpenMP() {
1560 assert(OpenMPPtr && "SemaOpenMP is dead");
1561 return *OpenMPPtr;
1562 }
1563
1564 SemaPPC &PPC() {
1565 assert(PPCPtr);
1566 return *PPCPtr;
1567 }
1568
1569 SemaPseudoObject &PseudoObject() {
1570 assert(PseudoObjectPtr);
1571 return *PseudoObjectPtr;
1572 }
1573
1574 SemaRISCV &RISCV() {
1575 assert(RISCVPtr);
1576 return *RISCVPtr;
1577 }
1578
1579 SemaSPIRV &SPIRV() {
1580 assert(SPIRVPtr);
1581 return *SPIRVPtr;
1582 }
1583
1584 SemaSYCL &SYCL() {
1585 assert(SYCLPtr);
1586 return *SYCLPtr;
1587 }
1588
1589 SemaSwift &Swift() {
1590 assert(SwiftPtr);
1591 return *SwiftPtr;
1592 }
1593
1594 SemaSystemZ &SystemZ() {
1595 assert(SystemZPtr);
1596 return *SystemZPtr;
1597 }
1598
1599 SemaWasm &Wasm() {
1600 assert(WasmPtr);
1601 return *WasmPtr;
1602 }
1603
1604 SemaX86 &X86() {
1605 assert(X86Ptr);
1606 return *X86Ptr;
1607 }
1608
1609 /// Source of additional semantic information.
1610 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
1611
1612protected:
1613 friend class Parser;
1614 friend class InitializationSequence;
1615 friend class ASTReader;
1616 friend class ASTDeclReader;
1617 friend class ASTWriter;
1618
1619private:
1620 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1621 bool WarnedDarwinSDKInfoMissing = false;
1622
1623 StackExhaustionHandler StackHandler;
1624
1625 Sema(const Sema &) = delete;
1626 void operator=(const Sema &) = delete;
1627
1628 /// The handler for the FileChanged preprocessor events.
1629 ///
1630 /// Used for diagnostics that implement custom semantic analysis for #include
1631 /// directives, like -Wpragma-pack.
1632 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1633
1634 /// The parser's current scope.
1635 ///
1636 /// The parser maintains this state here.
1637 Scope *CurScope;
1638
1639 mutable IdentifierInfo *Ident_super;
1640
1641 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1642 std::unique_ptr<SemaARM> ARMPtr;
1643 std::unique_ptr<SemaAVR> AVRPtr;
1644 std::unique_ptr<SemaBPF> BPFPtr;
1645 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1646 std::unique_ptr<SemaCUDA> CUDAPtr;
1647 std::unique_ptr<SemaDirectX> DirectXPtr;
1648 std::unique_ptr<SemaHLSL> HLSLPtr;
1649 std::unique_ptr<SemaHexagon> HexagonPtr;
1650 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1651 std::unique_ptr<SemaM68k> M68kPtr;
1652 std::unique_ptr<SemaMIPS> MIPSPtr;
1653 std::unique_ptr<SemaMSP430> MSP430Ptr;
1654 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1655 std::unique_ptr<SemaObjC> ObjCPtr;
1656 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1657 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1658 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1659 std::unique_ptr<SemaPPC> PPCPtr;
1660 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1661 std::unique_ptr<SemaRISCV> RISCVPtr;
1662 std::unique_ptr<SemaSPIRV> SPIRVPtr;
1663 std::unique_ptr<SemaSYCL> SYCLPtr;
1664 std::unique_ptr<SemaSwift> SwiftPtr;
1665 std::unique_ptr<SemaSystemZ> SystemZPtr;
1666 std::unique_ptr<SemaWasm> WasmPtr;
1667 std::unique_ptr<SemaX86> X86Ptr;
1668
1669 ///@}
1670
1671 //
1672 //
1673 // -------------------------------------------------------------------------
1674 //
1675 //
1676
1677 /// \name API Notes
1678 /// Implementations are in SemaAPINotes.cpp
1679 ///@{
1680
1681public:
1682 /// Map any API notes provided for this declaration to attributes on the
1683 /// declaration.
1684 ///
1685 /// Triggered by declaration-attribute processing.
1686 void ProcessAPINotes(Decl *D);
1687 /// Apply the 'Nullability:' annotation to the specified declaration
1688 void ApplyNullability(Decl *D, NullabilityKind Nullability);
1689 /// Apply the 'Type:' annotation to the specified declaration
1690 void ApplyAPINotesType(Decl *D, StringRef TypeString);
1691
1692 /// Diagnose exact API notes selectors that were not matched by any
1693 /// declaration processed in this translation unit.
1694 void DiagnoseUnusedAPINotesSelectors();
1695
1696 /// Whether APINotes should be gathered for all applicable Swift language
1697 /// versions, without being applied. Leaving clients of the current module
1698 /// to select and apply the correct version.
1699 bool captureSwiftVersionIndependentAPINotes() {
1700 return APINotes.captureVersionIndependentSwift();
1701 }
1702 ///@}
1703
1704 //
1705 //
1706 // -------------------------------------------------------------------------
1707 //
1708 //
1709
1710 /// \name C++ Access Control
1711 /// Implementations are in SemaAccess.cpp
1712 ///@{
1713
1714public:
1715 enum AccessResult {
1716 AR_accessible,
1717 AR_inaccessible,
1718 AR_dependent,
1719 AR_delayed
1720 };
1721
1722 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1723 /// Returns true on error (when the previous member decl access specifier
1724 /// is different from the new member decl access specifier).
1725 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1726 NamedDecl *PrevMemberDecl,
1727 AccessSpecifier LexicalAS);
1728
1729 /// Perform access-control checking on a previously-unresolved member
1730 /// access which has now been resolved to a member.
1731 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
1732 DeclAccessPair FoundDecl);
1733 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
1734 DeclAccessPair FoundDecl);
1735
1736 /// Checks access to an overloaded operator new or delete.
1737 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
1738 SourceRange PlacementRange,
1739 CXXRecordDecl *NamingClass,
1740 DeclAccessPair FoundDecl,
1741 bool Diagnose = true);
1742
1743 /// Checks access to a constructor.
1744 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1745 DeclAccessPair FoundDecl,
1746 const InitializedEntity &Entity,
1747 bool IsCopyBindingRefToTemp = false);
1748
1749 /// Checks access to a constructor.
1750 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1751 DeclAccessPair FoundDecl,
1752 const InitializedEntity &Entity,
1753 const PartialDiagnostic &PDiag);
1754 AccessResult CheckDestructorAccess(SourceLocation Loc,
1755 CXXDestructorDecl *Dtor,
1756 const PartialDiagnostic &PDiag,
1757 QualType objectType = QualType());
1758
1759 /// Checks access to the target of a friend declaration.
1760 AccessResult CheckFriendAccess(NamedDecl *D);
1761
1762 /// Checks access to a member.
1763 AccessResult CheckMemberAccess(SourceLocation UseLoc,
1764 CXXRecordDecl *NamingClass,
1765 DeclAccessPair Found);
1766
1767 /// Checks implicit access to a member in a structured binding.
1768 AccessResult
1769 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
1770 CXXRecordDecl *DecomposedClass,
1771 DeclAccessPair Field);
1772 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1773 const SourceRange &,
1774 DeclAccessPair FoundDecl);
1775
1776 /// Checks access to an overloaded member operator, including
1777 /// conversion operators.
1778 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1779 Expr *ArgExpr,
1780 DeclAccessPair FoundDecl);
1781 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1782 ArrayRef<Expr *> ArgExprs,
1783 DeclAccessPair FoundDecl);
1784 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
1785 DeclAccessPair FoundDecl);
1786
1787 /// Checks access for a hierarchy conversion.
1788 ///
1789 /// \param ForceCheck true if this check should be performed even if access
1790 /// control is disabled; some things rely on this for semantics
1791 /// \param ForceUnprivileged true if this check should proceed as if the
1792 /// context had no special privileges
1793 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base,
1794 QualType Derived, const CXXBasePath &Path,
1795 unsigned DiagID, bool ForceCheck = false,
1796 bool ForceUnprivileged = false);
1797
1798 AccessResult CheckBaseClassAccess(
1799 SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1800 const CXXBasePath &Path, unsigned DiagID,
1801 llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1802 bool ForceCheck = false, bool ForceUnprivileged = false);
1803
1804 /// Checks access to all the declarations in the given result set.
1805 void CheckLookupAccess(const LookupResult &R);
1806
1807 /// Checks access to Target from the given class. The check will take access
1808 /// specifiers into account, but no member access expressions and such.
1809 ///
1810 /// \param Target the declaration to check if it can be accessed
1811 /// \param NamingClass the class in which the lookup was started.
1812 /// \param BaseType type of the left side of member access expression.
1813 /// \p BaseType and \p NamingClass are used for C++ access control.
1814 /// Depending on the lookup case, they should be set to the following:
1815 /// - lhs.target (member access without a qualifier):
1816 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1817 /// - lhs.X::target (member access with a qualifier):
1818 /// BaseType is the type of 'lhs', NamingClass is 'X'
1819 /// - X::target (qualified lookup without member access):
1820 /// BaseType is null, NamingClass is 'X'.
1821 /// - target (unqualified lookup).
1822 /// BaseType is null, NamingClass is the parent class of 'target'.
1823 /// \return true if the Target is accessible from the Class, false otherwise.
1824 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1825 QualType BaseType);
1826
1827 /// Is the given member accessible for the purposes of deciding whether to
1828 /// define a special member function as deleted?
1829 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1830 DeclAccessPair Found, QualType ObjectType,
1831 SourceLocation Loc,
1832 const PartialDiagnostic &Diag);
1833 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1834 DeclAccessPair Found,
1835 QualType ObjectType) {
1836 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1837 Loc: SourceLocation(), Diag: PDiag());
1838 }
1839
1840 void HandleDependentAccessCheck(
1841 const DependentDiagnostic &DD,
1842 const MultiLevelTemplateArgumentList &TemplateArgs);
1843 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
1844
1845 ///@}
1846
1847 //
1848 //
1849 // -------------------------------------------------------------------------
1850 //
1851 //
1852
1853 /// \name Attributes
1854 /// Implementations are in SemaAttr.cpp
1855 ///@{
1856
1857public:
1858 /// Controls member pointer representation format under the MS ABI.
1859 LangOptions::PragmaMSPointersToMembersKind
1860 MSPointerToMemberRepresentationMethod;
1861
1862 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1863
1864 /// Source location for newly created implicit MSInheritanceAttrs
1865 SourceLocation ImplicitMSInheritanceAttrLoc;
1866
1867 struct PragmaClangSection {
1868 std::string SectionName;
1869 bool Valid = false;
1870 SourceLocation PragmaLocation;
1871 };
1872
1873 PragmaClangSection PragmaClangBSSSection;
1874 PragmaClangSection PragmaClangDataSection;
1875 PragmaClangSection PragmaClangRodataSection;
1876 PragmaClangSection PragmaClangRelroSection;
1877 PragmaClangSection PragmaClangTextSection;
1878
1879 enum PragmaMsStackAction {
1880 PSK_Reset = 0x0, // #pragma ()
1881 PSK_Set = 0x1, // #pragma (value)
1882 PSK_Push = 0x2, // #pragma (push[, id])
1883 PSK_Pop = 0x4, // #pragma (pop[, id])
1884 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1885 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1886 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1887 };
1888
1889 struct PragmaPackInfo {
1890 PragmaMsStackAction Action;
1891 StringRef SlotLabel;
1892 Token Alignment;
1893 };
1894
1895 // #pragma pack and align.
1896 class AlignPackInfo {
1897 public:
1898 // `Native` represents default align mode, which may vary based on the
1899 // platform.
1900 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1901
1902 // #pragma pack info constructor
1903 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1904 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1905 assert(Num == PackNumber && "The pack number has been truncated.");
1906 }
1907
1908 // #pragma align info constructor
1909 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
1910 : PackAttr(false), AlignMode(M),
1911 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1912
1913 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1914
1915 AlignPackInfo() : AlignPackInfo(Native, false) {}
1916
1917 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1918 // integer encoding for it. This should only be passed to
1919 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1920 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
1921 std::uint32_t Encoding{};
1922 if (Info.IsXLStack())
1923 Encoding |= IsXLMask;
1924
1925 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1926
1927 if (Info.IsPackAttr())
1928 Encoding |= PackAttrMask;
1929
1930 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1931
1932 return Encoding;
1933 }
1934
1935 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1936 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1937 AlignPackInfo::Mode M =
1938 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1939 int PackNumber = (Encoding & PackNumMask) >> 4;
1940
1941 if (Encoding & PackAttrMask)
1942 return AlignPackInfo(M, PackNumber, IsXL);
1943
1944 return AlignPackInfo(M, IsXL);
1945 }
1946
1947 bool IsPackAttr() const { return PackAttr; }
1948
1949 bool IsAlignAttr() const { return !PackAttr; }
1950
1951 Mode getAlignMode() const { return AlignMode; }
1952
1953 unsigned getPackNumber() const { return PackNumber; }
1954
1955 bool IsPackSet() const {
1956 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1957 // attriute on a decl.
1958 return PackNumber != UninitPackVal && PackNumber != 0;
1959 }
1960
1961 bool IsXLStack() const { return XLStack; }
1962
1963 bool operator==(const AlignPackInfo &Info) const {
1964 return std::tie(args: AlignMode, args: PackNumber, args: PackAttr, args: XLStack) ==
1965 std::tie(args: Info.AlignMode, args: Info.PackNumber, args: Info.PackAttr,
1966 args: Info.XLStack);
1967 }
1968
1969 bool operator!=(const AlignPackInfo &Info) const {
1970 return !(*this == Info);
1971 }
1972
1973 private:
1974 /// \brief True if this is a pragma pack attribute,
1975 /// not a pragma align attribute.
1976 bool PackAttr;
1977
1978 /// \brief The alignment mode that is in effect.
1979 Mode AlignMode;
1980
1981 /// \brief The pack number of the stack.
1982 unsigned char PackNumber;
1983
1984 /// \brief True if it is a XL #pragma align/pack stack.
1985 bool XLStack;
1986
1987 /// \brief Uninitialized pack value.
1988 static constexpr unsigned char UninitPackVal = -1;
1989
1990 // Masks to encode and decode an AlignPackInfo.
1991 static constexpr uint32_t IsXLMask{0x0000'0001};
1992 static constexpr uint32_t AlignModeMask{0x0000'0006};
1993 static constexpr uint32_t PackAttrMask{0x00000'0008};
1994 static constexpr uint32_t PackNumMask{0x0000'01F0};
1995 };
1996
1997 template <typename ValueType> struct PragmaStack {
1998 struct Slot {
1999 llvm::StringRef StackSlotLabel;
2000 ValueType Value;
2001 SourceLocation PragmaLocation;
2002 SourceLocation PragmaPushLocation;
2003 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
2004 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
2005 : StackSlotLabel(StackSlotLabel), Value(Value),
2006 PragmaLocation(PragmaLocation),
2007 PragmaPushLocation(PragmaPushLocation) {}
2008 };
2009
2010 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
2011 llvm::StringRef StackSlotLabel, ValueType Value) {
2012 if (Action == PSK_Reset) {
2013 CurrentValue = DefaultValue;
2014 CurrentPragmaLocation = PragmaLocation;
2015 return;
2016 }
2017 if (Action & PSK_Push)
2018 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
2019 PragmaLocation);
2020 else if (Action & PSK_Pop) {
2021 if (!StackSlotLabel.empty()) {
2022 // If we've got a label, try to find it and jump there.
2023 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
2024 return x.StackSlotLabel == StackSlotLabel;
2025 });
2026 // If we found the label so pop from there.
2027 if (I != Stack.rend()) {
2028 CurrentValue = I->Value;
2029 CurrentPragmaLocation = I->PragmaLocation;
2030 Stack.erase(std::prev(I.base()), Stack.end());
2031 }
2032 } else if (!Stack.empty()) {
2033 // We do not have a label, just pop the last entry.
2034 CurrentValue = Stack.back().Value;
2035 CurrentPragmaLocation = Stack.back().PragmaLocation;
2036 Stack.pop_back();
2037 }
2038 }
2039 if (Action & PSK_Set) {
2040 CurrentValue = Value;
2041 CurrentPragmaLocation = PragmaLocation;
2042 }
2043 }
2044
2045 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
2046 // method body to restore the stacks on exit, so it works like this:
2047 //
2048 // struct S {
2049 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
2050 // void Method {}
2051 // #pragma <name>(pop, InternalPragmaSlot)
2052 // };
2053 //
2054 // It works even with #pragma vtordisp, although MSVC doesn't support
2055 // #pragma vtordisp(push [, id], n)
2056 // syntax.
2057 //
2058 // Push / pop a named sentinel slot.
2059 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
2060 assert((Action == PSK_Push || Action == PSK_Pop) &&
2061 "Can only push / pop #pragma stack sentinels!");
2062 Act(PragmaLocation: CurrentPragmaLocation, Action, StackSlotLabel: Label, Value: CurrentValue);
2063 }
2064
2065 // Constructors.
2066 explicit PragmaStack(const ValueType &Default)
2067 : DefaultValue(Default), CurrentValue(Default) {}
2068
2069 bool hasValue() const { return CurrentValue != DefaultValue; }
2070
2071 SmallVector<Slot, 2> Stack;
2072 ValueType DefaultValue; // Value used for PSK_Reset action.
2073 ValueType CurrentValue;
2074 SourceLocation CurrentPragmaLocation;
2075 };
2076 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2077 // we shouldn't do so if they're in a module).
2078
2079 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2080 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
2081 ///
2082 /// 0: Suppress all vtordisps
2083 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2084 /// structors
2085 /// 2: Always insert vtordisps to support RTTI on partially constructed
2086 /// objects
2087 PragmaStack<MSVtorDispMode> VtorDispStack;
2088 PragmaStack<AlignPackInfo> AlignPackStack;
2089 // The current #pragma align/pack values and locations at each #include.
2090 struct AlignPackIncludeState {
2091 AlignPackInfo CurrentValue;
2092 SourceLocation CurrentPragmaLocation;
2093 bool HasNonDefaultValue, ShouldWarnOnInclude;
2094 };
2095 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
2096 // Segment #pragmas.
2097 PragmaStack<StringLiteral *> DataSegStack;
2098 PragmaStack<StringLiteral *> BSSSegStack;
2099 PragmaStack<StringLiteral *> ConstSegStack;
2100 PragmaStack<StringLiteral *> CodeSegStack;
2101
2102 // #pragma strict_gs_check.
2103 PragmaStack<bool> StrictGuardStackCheckStack;
2104
2105 // This stack tracks the current state of Sema.CurFPFeatures.
2106 PragmaStack<FPOptionsOverride> FpPragmaStack;
2107 FPOptionsOverride CurFPFeatureOverrides() {
2108 FPOptionsOverride result;
2109 if (!FpPragmaStack.hasValue()) {
2110 result = FPOptionsOverride();
2111 } else {
2112 result = FpPragmaStack.CurrentValue;
2113 }
2114 return result;
2115 }
2116
2117 enum PragmaSectionKind {
2118 PSK_DataSeg,
2119 PSK_BSSSeg,
2120 PSK_ConstSeg,
2121 PSK_CodeSeg,
2122 };
2123
2124 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2125 // Actions should be performed only if we enter / exit a C++ method body.
2126 class PragmaStackSentinelRAII {
2127 public:
2128 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2129 ~PragmaStackSentinelRAII();
2130 PragmaStackSentinelRAII(const PragmaStackSentinelRAII &) = delete;
2131 PragmaStackSentinelRAII &
2132 operator=(const PragmaStackSentinelRAII &) = delete;
2133
2134 private:
2135 Sema &S;
2136 StringRef SlotLabel;
2137 bool ShouldAct;
2138 };
2139
2140 /// Last section used with #pragma init_seg.
2141 StringLiteral *CurInitSeg;
2142 SourceLocation CurInitSegLoc;
2143
2144 /// Sections used with #pragma alloc_text.
2145 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2146
2147 /// VisContext - Manages the stack for \#pragma GCC visibility.
2148 void *VisContext; // Really a "PragmaVisStack*"
2149
2150 /// This an attribute introduced by \#pragma clang attribute.
2151 struct PragmaAttributeEntry {
2152 SourceLocation Loc;
2153 ParsedAttr *Attribute;
2154 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
2155 bool IsUsed;
2156 };
2157
2158 /// A push'd group of PragmaAttributeEntries.
2159 struct PragmaAttributeGroup {
2160 /// The location of the push attribute.
2161 SourceLocation Loc;
2162 /// The namespace of this push group.
2163 const IdentifierInfo *Namespace;
2164 SmallVector<PragmaAttributeEntry, 2> Entries;
2165 };
2166
2167 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
2168
2169 /// The declaration that is currently receiving an attribute from the
2170 /// #pragma attribute stack.
2171 const Decl *PragmaAttributeCurrentTargetDecl;
2172
2173 /// This represents the last location of a "#pragma clang optimize off"
2174 /// directive if such a directive has not been closed by an "on" yet. If
2175 /// optimizations are currently "on", this is set to an invalid location.
2176 SourceLocation OptimizeOffPragmaLocation;
2177
2178 /// Get the location for the currently active "\#pragma clang optimize
2179 /// off". If this location is invalid, then the state of the pragma is "on".
2180 SourceLocation getOptimizeOffPragmaLocation() const {
2181 return OptimizeOffPragmaLocation;
2182 }
2183
2184 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2185 /// whether the optimizations in the list passed to the pragma should be
2186 /// turned off or on. This boolean is true by default because command line
2187 /// options are honored when `#pragma optimize("", on)`.
2188 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2189 bool MSPragmaOptimizeIsOn = true;
2190
2191 /// Set of no-builtin functions listed by \#pragma function.
2192 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
2193
2194 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2195 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2196 void AddAlignmentAttributesForRecord(RecordDecl *RD);
2197
2198 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2199 void AddMsStructLayoutForRecord(RecordDecl *RD);
2200
2201 /// Add gsl::Pointer attribute to std::container::iterator
2202 /// \param ND The declaration that introduces the name
2203 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2204 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2205
2206 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2207 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
2208
2209 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2210 void inferLifetimeBoundAttribute(FunctionDecl *FD);
2211
2212 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2213 void inferLifetimeCaptureByAttribute(FunctionDecl *FD);
2214
2215 /// Add [[gsl::Pointer]] attributes for std:: types.
2216 void inferGslPointerAttribute(TypedefNameDecl *TD);
2217
2218 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2219 StringRef ParamName);
2220 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2221 // can be the name of a function parameter, we need to parse the function
2222 // declaration and rest of the parameters before processesing 'X'. Therefore
2223 // do this lazily instead of processing while parsing the annotation itself.
2224 void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD);
2225
2226 /// Add _Nullable attributes for std:: types.
2227 void inferNullableClassAttribute(CXXRecordDecl *CRD);
2228
2229 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2230 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
2231 PragmaClangSectionAction Action,
2232 PragmaClangSectionKind SecKind,
2233 StringRef SecName);
2234
2235 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2236 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
2237 SourceLocation PragmaLoc);
2238
2239 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2240 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2241 StringRef SlotLabel, Expr *Alignment);
2242
2243 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2244 /// (unless they are value dependent or type dependent). Returns false
2245 /// and emits a diagnostic if one or more of the arguments could not be
2246 /// folded into a constant.
2247 bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
2248 MutableArrayRef<Expr *> Args);
2249
2250 enum class PragmaAlignPackDiagnoseKind {
2251 NonDefaultStateAtInclude,
2252 ChangedStateAtExit
2253 };
2254
2255 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
2256 SourceLocation IncludeLoc);
2257 void DiagnoseUnterminatedPragmaAlignPack();
2258
2259 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2260 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
2261
2262 /// ActOnPragmaMSComment - Called on well formed
2263 /// \#pragma comment(kind, "arg").
2264 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
2265 StringRef Arg);
2266
2267 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2268 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2269 StringRef Value);
2270
2271 /// Are precise floating point semantics currently enabled?
2272 bool isPreciseFPEnabled() {
2273 return !CurFPFeatures.getAllowFPReassociate() &&
2274 !CurFPFeatures.getNoSignedZero() &&
2275 !CurFPFeatures.getAllowReciprocal() &&
2276 !CurFPFeatures.getAllowApproxFunc();
2277 }
2278
2279 void ActOnPragmaFPEvalMethod(SourceLocation Loc,
2280 LangOptions::FPEvalMethodKind Value);
2281
2282 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2283 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2284 PragmaFloatControlKind Value);
2285
2286 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2287 /// pointers_to_members(representation method[, general purpose
2288 /// representation]).
2289 void ActOnPragmaMSPointersToMembers(
2290 LangOptions::PragmaMSPointersToMembersKind Kind,
2291 SourceLocation PragmaLoc);
2292
2293 /// Called on well formed \#pragma vtordisp().
2294 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2295 SourceLocation PragmaLoc, MSVtorDispMode Value);
2296
2297 bool UnifySection(StringRef SectionName, int SectionFlags,
2298 NamedDecl *TheDecl);
2299 bool UnifySection(StringRef SectionName, int SectionFlags,
2300 SourceLocation PragmaSectionLocation);
2301
2302 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2303 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2304 PragmaMsStackAction Action,
2305 llvm::StringRef StackSlotLabel,
2306 StringLiteral *SegmentName, llvm::StringRef PragmaName);
2307
2308 /// Called on well formed \#pragma section().
2309 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2310 StringLiteral *SegmentName);
2311
2312 /// Called on well-formed \#pragma init_seg().
2313 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2314 StringLiteral *SegmentName);
2315
2316 /// Called on well-formed \#pragma alloc_text().
2317 void ActOnPragmaMSAllocText(
2318 SourceLocation PragmaLocation, StringRef Section,
2319 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2320 &Functions);
2321
2322 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2323 /// strict_gs_check.
2324 void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
2325 PragmaMsStackAction Action,
2326 bool Value);
2327
2328 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2329 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2330 SourceLocation PragmaLoc);
2331
2332 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
2333 SourceLocation PragmaLoc,
2334 attr::ParsedSubjectMatchRuleSet Rules);
2335 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
2336 const IdentifierInfo *Namespace);
2337
2338 /// Called on well-formed '\#pragma clang attribute pop'.
2339 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
2340 const IdentifierInfo *Namespace);
2341
2342 /// Adds the attributes that have been specified using the
2343 /// '\#pragma clang attribute push' directives to the given declaration.
2344 void AddPragmaAttributes(Scope *S, Decl *D);
2345
2346 using InstantiationContextDiagFuncRef =
2347 llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
2348 auto getDefaultDiagFunc() {
2349 return [this](SourceLocation Loc, PartialDiagnostic PD) {
2350 // This bypasses a lot of the filters in the diag engine, as it's
2351 // to be used to attach notes to diagnostics which have already
2352 // been filtered through.
2353 DiagnosticBuilder Builder(Diags.Report(Loc, DiagID: PD.getDiagID()));
2354 PD.Emit(DB: Builder);
2355 };
2356 }
2357
2358 void PrintPragmaAttributeInstantiationPoint(
2359 InstantiationContextDiagFuncRef DiagFunc);
2360 void PrintPragmaAttributeInstantiationPoint() {
2361 PrintPragmaAttributeInstantiationPoint(DiagFunc: getDefaultDiagFunc());
2362 }
2363
2364 void DiagnoseUnterminatedPragmaAttribute();
2365
2366 /// Called on well formed \#pragma clang optimize.
2367 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2368
2369 /// #pragma optimize("[optimization-list]", on | off).
2370 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2371
2372 /// Call on well formed \#pragma function.
2373 void
2374 ActOnPragmaMSFunction(SourceLocation Loc,
2375 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2376
2377 NamedDecl *lookupExternCFunctionOrVariable(IdentifierInfo *IdentId,
2378 SourceLocation NameLoc,
2379 Scope *curScope);
2380
2381 /// Information from a C++ #pragma export, for a symbol that we
2382 /// haven't seen the declaration for yet.
2383 struct PendingPragmaInfo {
2384 SourceLocation NameLoc;
2385 bool Used;
2386 };
2387
2388 llvm::DenseMap<IdentifierInfo *, PendingPragmaInfo> PendingExportedNames;
2389
2390 /// ActonPragmaExport - called on well-formed '\#pragma export'.
2391 void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc,
2392 Scope *curScope);
2393
2394 /// Only called on function definitions; if there is a pragma in scope
2395 /// with the effect of a range-based optnone, consider marking the function
2396 /// with attribute optnone.
2397 void AddRangeBasedOptnone(FunctionDecl *FD);
2398
2399 /// Only called on function definitions; if there is a `#pragma alloc_text`
2400 /// that decides which code section the function should be in, add
2401 /// attribute section to the function.
2402 void AddSectionMSAllocText(FunctionDecl *FD);
2403
2404 /// Adds the 'optnone' attribute to the function declaration if there
2405 /// are no conflicts; Loc represents the location causing the 'optnone'
2406 /// attribute to be added (usually because of a pragma).
2407 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
2408
2409 /// Only called on function definitions; if there is a MSVC #pragma optimize
2410 /// in scope, consider changing the function's attributes based on the
2411 /// optimization list passed to the pragma.
2412 void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
2413
2414 /// Only called on function definitions; if there is a pragma in scope
2415 /// with the effect of a range-based no_builtin, consider marking the function
2416 /// with attribute no_builtin.
2417 void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
2418
2419 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2420 /// add an appropriate visibility attribute.
2421 void AddPushedVisibilityAttribute(Decl *RD);
2422
2423 /// FreeVisContext - Deallocate and null out VisContext.
2424 void FreeVisContext();
2425
2426 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2427 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2428 SourceLocation PragmaLoc);
2429
2430 /// ActOnPragmaFPContract - Called on well formed
2431 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2432 /// \#pragma clang fp contract
2433 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
2434
2435 /// Called on well formed
2436 /// \#pragma clang fp reassociate
2437 /// or
2438 /// \#pragma clang fp reciprocal
2439 void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind,
2440 bool IsEnabled);
2441
2442 /// ActOnPragmaFenvAccess - Called on well formed
2443 /// \#pragma STDC FENV_ACCESS
2444 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2445
2446 /// ActOnPragmaCXLimitedRange - Called on well formed
2447 /// \#pragma STDC CX_LIMITED_RANGE
2448 void ActOnPragmaCXLimitedRange(SourceLocation Loc,
2449 LangOptions::ComplexRangeKind Range);
2450
2451 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2452 void ActOnPragmaFPExceptions(SourceLocation Loc,
2453 LangOptions::FPExceptionModeKind);
2454
2455 /// Called to set constant rounding mode for floating point operations.
2456 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2457
2458 /// Called to set exception behavior for floating point operations.
2459 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
2460
2461 /// PushNamespaceVisibilityAttr - Note that we've entered a
2462 /// namespace with a visibility attribute.
2463 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2464 SourceLocation Loc);
2465
2466 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2467 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2468 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2469
2470 /// Handles semantic checking for features that are common to all attributes,
2471 /// such as checking whether a parameter was properly specified, or the
2472 /// correct number of arguments were passed, etc. Returns true if the
2473 /// attribute has been diagnosed.
2474 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2475 bool SkipArgCountCheck = false);
2476 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2477 bool SkipArgCountCheck = false);
2478
2479 ///@}
2480
2481 //
2482 //
2483 // -------------------------------------------------------------------------
2484 //
2485 //
2486
2487 /// \name Availability Attribute Handling
2488 /// Implementations are in SemaAvailability.cpp
2489 ///@{
2490
2491public:
2492 /// Issue any -Wunguarded-availability warnings in \c FD
2493 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
2494
2495 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2496
2497 /// Retrieve the current function, if any, that should be analyzed for
2498 /// potential availability violations.
2499 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2500
2501 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
2502 const ObjCInterfaceDecl *UnknownObjCClass,
2503 bool ObjCPropertyAccess,
2504 bool AvoidPartialAvailabilityChecks,
2505 ObjCInterfaceDecl *ClassReceiver);
2506
2507 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs);
2508
2509 std::pair<AvailabilityResult, const NamedDecl *>
2510 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2511 ObjCInterfaceDecl *ClassReceiver);
2512 ///@}
2513
2514 //
2515 //
2516 // -------------------------------------------------------------------------
2517 //
2518 //
2519
2520 /// \name Bounds Safety
2521 /// Implementations are in SemaBoundsSafety.cpp
2522 ///@{
2523public:
2524 /// Check if applying the specified attribute variant from the "counted by"
2525 /// family of attributes to FieldDecl \p FD is semantically valid. If
2526 /// semantically invalid diagnostics will be emitted explaining the problems.
2527 ///
2528 /// \param FD The FieldDecl to apply the attribute to
2529 /// \param E The count expression on the attribute
2530 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2531 /// attributes. If the false the attribute is from
2532 /// "counted_by" family of attributes.
2533 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2534 /// of attributes. If false the attribute does not have the
2535 /// suffix.
2536 ///
2537 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2538 /// \p CountInBytes and \p OrNull both being true indicates the
2539 /// `counted_by_or_null` attribute.
2540 ///
2541 /// \returns false iff semantically valid.
2542 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2543 bool OrNull);
2544
2545 /// Late-parsed bounds types dropped while their declarator was built. The
2546 /// attribute has already been diagnosed and its node is no longer part of
2547 /// any type, so the completion pass must skip it rather than parse its
2548 /// argument and complete it.
2549 llvm::SmallPtrSet<const BoundsAttributedType *, 1>
2550 RejectedLateParsedBoundsTypes;
2551
2552 void markLateParsedBoundsTypeRejected(const BoundsAttributedType *BATy) {
2553 RejectedLateParsedBoundsTypes.insert(Ptr: BATy);
2554 }
2555
2556 bool isLateParsedBoundsTypeRejected(const BoundsAttributedType *BATy) const {
2557 return RejectedLateParsedBoundsTypes.contains(Ptr: BATy);
2558 }
2559
2560 /// Supply the parsed argument of a late-parsed bounds attribute to the type
2561 /// built for it by ActOnLateParsedTypeAttr, and run the checks that need the
2562 /// owning declaration. \p FD is the field the type belongs to. Returns false
2563 /// if the attribute was rejected.
2564 bool ActOnLateParsedTypeAttrArgument(BoundsAttributedType *BATy,
2565 FieldDecl *FD, Expr *Arg);
2566
2567 /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2568 /// `__counted_by_or_null` pointer type \param LHSTy.
2569 ///
2570 /// \param LHSTy The type being assigned to. Checks will only be performed if
2571 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2572 /// \param RHSExpr The expression being assigned from.
2573 /// \param Action The type assignment being performed
2574 /// \param Loc The SourceLocation to use for error diagnostics
2575 /// \param Assignee The ValueDecl being assigned. This is used to compute
2576 /// the name of the assignee. If the assignee isn't known this can
2577 /// be set to nullptr.
2578 /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2579 /// Assignee to compute the name of the assignee use the fully
2580 /// qualified name, otherwise use the unqualified name.
2581 ///
2582 /// \returns True iff no diagnostic where emitted, false otherwise.
2583 bool BoundsSafetyCheckAssignmentToCountAttrPtr(
2584 QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2585 SourceLocation Loc, const ValueDecl *Assignee,
2586 bool ShowFullyQualifiedAssigneeName);
2587
2588 /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2589 /// pointer.
2590 ///
2591 /// \param Entity The entity being initialized
2592 /// \param Kind The kind of initialization being performed
2593 /// \param Action The type assignment being performed
2594 /// \param LHSTy The type being assigned to. Checks will only be performed if
2595 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2596 /// \param RHSExpr The expression being used for initialization.
2597 ///
2598 /// \returns True iff no diagnostic where emitted, false otherwise.
2599 bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity,
2600 const InitializationKind &Kind,
2601 AssignmentAction Action,
2602 QualType LHSType, Expr *RHSExpr);
2603
2604 /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2605 /// or counted_by_or_null pointers in \param E.
2606 ///
2607 /// \param E the expression to check
2608 ///
2609 /// \returns True iff no diagnostic where emitted, false otherwise.
2610 bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E);
2611 ///@}
2612
2613 //
2614 //
2615 // -------------------------------------------------------------------------
2616 //
2617 //
2618
2619 /// \name Casts
2620 /// Implementations are in SemaCast.cpp
2621 ///@{
2622
2623public:
2624 static bool isCast(CheckedConversionKind CCK) {
2625 return CCK == CheckedConversionKind::CStyleCast ||
2626 CCK == CheckedConversionKind::FunctionalCast ||
2627 CCK == CheckedConversionKind::OtherCast;
2628 }
2629
2630 /// ActOnCXXNamedCast - Parse
2631 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2632 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2633 SourceLocation LAngleBracketLoc, Declarator &D,
2634 SourceLocation RAngleBracketLoc,
2635 SourceLocation LParenLoc, Expr *E,
2636 SourceLocation RParenLoc);
2637
2638 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2639 TypeSourceInfo *Ty, Expr *E,
2640 SourceRange AngleBrackets, SourceRange Parens);
2641
2642 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
2643 ExprResult Operand,
2644 SourceLocation RParenLoc);
2645
2646 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
2647 Expr *Operand, SourceLocation RParenLoc);
2648
2649 // Checks that reinterpret casts don't have undefined behavior.
2650 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2651 bool IsDereference, SourceRange Range);
2652
2653 // Checks that the vector type should be initialized from a scalar
2654 // by splatting the value rather than populating a single element.
2655 // This is the case for AltiVecVector types as well as with
2656 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2657 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2658
2659 // Checks if the -faltivec-src-compat=gcc option is specified.
2660 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2661 // treated the same way as they are when trying to initialize
2662 // these vectors on gcc (an error is emitted).
2663 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
2664 QualType SrcTy);
2665
2666 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
2667 SourceLocation RParenLoc, Expr *Op);
2668
2669 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
2670 SourceLocation LParenLoc,
2671 Expr *CastExpr,
2672 SourceLocation RParenLoc);
2673
2674 ///@}
2675
2676 //
2677 //
2678 // -------------------------------------------------------------------------
2679 //
2680 //
2681
2682 /// \name Extra Semantic Checking
2683 /// Implementations are in SemaChecking.cpp
2684 ///@{
2685
2686public:
2687 /// Used to change context to isConstantEvaluated without pushing a heavy
2688 /// ExpressionEvaluationContextRecord object.
2689 bool isConstantEvaluatedOverride = false;
2690
2691 bool isConstantEvaluatedContext() const {
2692 return currentEvaluationContext().isConstantEvaluated() ||
2693 isConstantEvaluatedOverride;
2694 }
2695
2696 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
2697 unsigned ByteNo) const;
2698
2699 enum FormatArgumentPassingKind {
2700 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2701 FAPK_Variadic, // values to format are passed as variadic arguments
2702 FAPK_VAList, // values to format are passed in a va_list
2703 FAPK_Elsewhere, // values to format are not passed to this function
2704 };
2705
2706 // Used to grab the relevant information from a FormatAttr and a
2707 // FunctionDeclaration.
2708 struct FormatStringInfo {
2709 unsigned FormatIdx;
2710 unsigned FirstDataArg;
2711 FormatArgumentPassingKind ArgPassingKind;
2712 };
2713
2714 /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2715 /// populate the FormatStringInfo parameter with the attribute's correct
2716 /// format_idx and firstDataArg. Returns true when the format fits the
2717 /// function and the FormatStringInfo has been populated.
2718 static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2719 unsigned FirstArg, FormatStringInfo *FSI);
2720 static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2721 bool HasImplicitThisParam, bool IsVariadic,
2722 FormatStringInfo *FSI);
2723
2724 // Used by C++ template instantiation.
2725 ExprResult BuiltinShuffleVector(CallExpr *TheCall);
2726
2727 /// ConvertVectorExpr - Handle __builtin_convertvector
2728 ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2729 SourceLocation BuiltinLoc,
2730 SourceLocation RParenLoc);
2731
2732 static StringRef GetFormatStringTypeName(FormatStringType FST);
2733 static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2734 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2735 static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2736
2737 bool FormatStringHasSArg(const StringLiteral *FExpr);
2738
2739 /// Check for comparisons of floating-point values using == and !=. Issue a
2740 /// warning if the comparison is not likely to do what the programmer
2741 /// intended.
2742 void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2743 const Expr *RHS, BinaryOperatorKind Opcode);
2744
2745 /// Register a magic integral constant to be used as a type tag.
2746 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2747 uint64_t MagicValue, QualType Type,
2748 bool LayoutCompatible, bool MustBeNull);
2749
2750 struct TypeTagData {
2751 TypeTagData() {}
2752
2753 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
2754 : Type(Type), LayoutCompatible(LayoutCompatible),
2755 MustBeNull(MustBeNull) {}
2756
2757 QualType Type;
2758
2759 /// If true, \c Type should be compared with other expression's types for
2760 /// layout-compatibility.
2761 LLVM_PREFERRED_TYPE(bool)
2762 unsigned LayoutCompatible : 1;
2763 LLVM_PREFERRED_TYPE(bool)
2764 unsigned MustBeNull : 1;
2765 };
2766
2767 /// A pair of ArgumentKind identifier and magic value. This uniquely
2768 /// identifies the magic value.
2769 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2770
2771 /// Diagnoses the current set of gathered accesses. This happens at the end of
2772 /// each expression evaluation context. Diagnostics are emitted only for
2773 /// accesses gathered in the current evaluation context.
2774 void DiagnoseMisalignedMembers();
2775
2776 /// This function checks if the expression is in the sef of potentially
2777 /// misaligned members and it is converted to some pointer type T with lower
2778 /// or equal alignment requirements. If so it removes it. This is used when
2779 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2780 /// void*).
2781 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2782
2783 /// Returns true if `From` is a function or pointer to a function with the
2784 /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2785 /// function without this attribute.
2786 bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2787
2788 /// This function calls Action when it determines that E designates a
2789 /// misaligned member due to the packed attribute. This is used to emit
2790 /// local diagnostics like in reference binding.
2791 void RefersToMemberWithReducedAlignment(
2792 Expr *E,
2793 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2794 Action);
2795
2796 enum class AtomicArgumentOrder { API, AST };
2797 ExprResult
2798 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2799 SourceLocation RParenLoc, MultiExprArg Args,
2800 AtomicExpr::AtomicOp Op,
2801 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
2802
2803 /// Check to see if a given expression could have '.c_str()' called on it.
2804 bool hasCStrMethod(const Expr *E);
2805
2806 /// Diagnose pointers that are always non-null.
2807 /// \param E the expression containing the pointer
2808 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2809 /// compared to a null pointer
2810 /// \param IsEqual True when the comparison is equal to a null pointer
2811 /// \param Range Extra SourceRange to highlight in the diagnostic
2812 void DiagnoseAlwaysNonNullPointer(Expr *E,
2813 Expr::NullPointerConstantKind NullType,
2814 bool IsEqual, SourceRange Range);
2815
2816 /// CheckParmsForFunctionDef - Check that the parameters of the given
2817 /// function are appropriate for the definition of a function. This
2818 /// takes care of any checks that cannot be performed on the
2819 /// declaration itself, e.g., that the types of each of the function
2820 /// parameters are complete.
2821 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2822 bool CheckParameterNames);
2823
2824 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2825 /// pointer cast increases the alignment requirements.
2826 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2827
2828 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2829 /// to weak/__unsafe_unretained type.
2830 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2831
2832 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2833 /// to weak/__unsafe_unretained expression.
2834 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2835
2836 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2837 /// statement as a \p Body, and it is located on the same line.
2838 ///
2839 /// This helps prevent bugs due to typos, such as:
2840 /// if (condition);
2841 /// do_stuff();
2842 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2843 unsigned DiagID);
2844
2845 /// Warn if a for/while loop statement \p S, which is followed by
2846 /// \p PossibleBody, has a suspicious null statement as a body.
2847 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2848
2849 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2850 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2851 SourceLocation OpLoc);
2852
2853 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2854 bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
2855 const TypeSourceInfo *Derived);
2856
2857 /// CheckFunctionCall - Check a direct function call for various correctness
2858 /// and safety properties not strictly enforced by the C type system.
2859 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2860 const FunctionProtoType *Proto);
2861
2862 enum class EltwiseBuiltinArgTyRestriction {
2863 None,
2864 FloatTy,
2865 IntegerTy,
2866 SignedIntOrFloatTy,
2867 };
2868
2869 /// \param FPOnly restricts the arguments to floating-point types.
2870 std::optional<QualType>
2871 BuiltinVectorMath(CallExpr *TheCall,
2872 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2873 EltwiseBuiltinArgTyRestriction::None);
2874 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2875
2876 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2877 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2878
2879 /// Handles the checks for format strings, non-POD arguments to vararg
2880 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2881 /// attributes and AArch64 SME attributes.
2882 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2883 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2884 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2885 VariadicCallType CallType);
2886
2887 /// Verify that two format strings (as understood by attribute(format) and
2888 /// attribute(format_matches) are compatible. If they are incompatible,
2889 /// diagnostics are emitted with the assumption that \c
2890 /// AuthoritativeFormatString is correct and
2891 /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2892 /// diagnostics will point to it and a note will refer to \c
2893 /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2894 bool
2895 CheckFormatStringsCompatible(FormatStringType FST,
2896 const StringLiteral *AuthoritativeFormatString,
2897 const StringLiteral *TestedFormatString,
2898 const Expr *FunctionCallArg = nullptr);
2899
2900 /// Verify that one format string (as understood by attribute(format)) is
2901 /// self-consistent; for instance, that it doesn't have multiple positional
2902 /// arguments referring to the same argument in incompatible ways. Diagnose
2903 /// if it isn't.
2904 bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str);
2905
2906 /// \brief Enforce the bounds of a TCB
2907 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2908 /// directly calls other functions in the same TCB as marked by the
2909 /// enforce_tcb and enforce_tcb_leaf attributes.
2910 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2911 const NamedDecl *Callee);
2912
2913 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2914
2915 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2916 /// TheCall is a constant expression.
2917 bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
2918 llvm::APSInt &Result);
2919
2920 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2921 /// TheCall is a constant expression in the range [Low, High].
2922 bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
2923 int High, bool RangeIsError = true);
2924
2925 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2926 /// TheCall is a constant expression is a multiple of Num..
2927 bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
2928 unsigned Multiple);
2929
2930 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2931 /// constant expression representing a power of 2.
2932 bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum);
2933
2934 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2935 /// a constant expression representing an arbitrary byte value shifted left by
2936 /// a multiple of 8 bits.
2937 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
2938 unsigned ArgBits);
2939
2940 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2941 /// TheCall is a constant expression representing either a shifted byte value,
2942 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2943 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2944 /// Arm MVE intrinsics.
2945 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum,
2946 unsigned ArgBits);
2947
2948 /// Checks that a call expression's argument count is at least the desired
2949 /// number. This is useful when doing custom type-checking on a variadic
2950 /// function. Returns true on error.
2951 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2952
2953 /// Checks that a call expression's argument count is at most the desired
2954 /// number. This is useful when doing custom type-checking on a variadic
2955 /// function. Returns true on error.
2956 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
2957
2958 /// Checks that a call expression's argument count is in the desired range.
2959 /// This is useful when doing custom type-checking on a variadic function.
2960 /// Returns true on error.
2961 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
2962 unsigned MaxArgCount);
2963
2964 /// Checks that a call expression's argument count is the desired number.
2965 /// This is useful when doing custom type-checking. Returns true on error.
2966 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
2967
2968 bool convertArgumentToType(Expr *&Value, QualType Ty);
2969
2970 /// Returns true if the argument consists of one contiguous run of 1s with any
2971 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
2972 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
2973 /// since all 1s are not contiguous.
2974 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2975
2976 void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
2977 bool *ICContext = nullptr,
2978 bool IsListInit = false);
2979
2980 /// Check for overflow behavior type related implicit conversion diagnostics.
2981 /// Returns true if OBT-related diagnostic was issued, false otherwise.
2982 bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
2983 SourceLocation CC);
2984
2985 bool
2986 BuiltinElementwiseTernaryMath(CallExpr *TheCall,
2987 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2988 EltwiseBuiltinArgTyRestriction::FloatTy);
2989 bool PrepareBuiltinElementwiseMathOneArgCall(
2990 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
2991 EltwiseBuiltinArgTyRestriction::None);
2992
2993private:
2994 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2995 const ArraySubscriptExpr *ASE = nullptr,
2996 bool AllowOnePastEnd = true, bool IndexNegated = false);
2997 void CheckArrayAccess(const Expr *E);
2998
2999 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3000 const FunctionProtoType *Proto);
3001
3002 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3003 /// such as function pointers returned from functions.
3004 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
3005
3006 /// CheckConstructorCall - Check a constructor call for correctness and safety
3007 /// properties not enforced by the C type system.
3008 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
3009 ArrayRef<const Expr *> Args,
3010 const FunctionProtoType *Proto, SourceLocation Loc);
3011
3012 /// Warn if a pointer or reference argument passed to a function points to an
3013 /// object that is less aligned than the parameter. This can happen when
3014 /// creating a typedef with a lower alignment than the original type and then
3015 /// calling functions defined in terms of the original type.
3016 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3017 StringRef ParamName, QualType ArgTy, QualType ParamTy);
3018
3019 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
3020
3021 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3022 CallExpr *TheCall);
3023
3024 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3025 CallExpr *TheCall);
3026
3027 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
3028
3029 /// Argument-value fortify checks for libc functions that are not builtins,
3030 /// dispatched by name (e.g. umask). Diagnostics belong to -Wfortify-source.
3031 void checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall);
3032
3033 /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
3034 /// or '__builtin_c23_va_start' for validity. Emit an error and return true
3035 /// on failure; return false on success.
3036 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
3037 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
3038
3039 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3040 /// friends. This is declared to take (...), so we have to check everything.
3041 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
3042
3043 /// BuiltinSemaBuiltinFPClassification - Handle functions like
3044 /// __builtin_isnan and friends. This is declared to take (...), so we have
3045 /// to check everything.
3046 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
3047 unsigned BuiltinID);
3048
3049 /// Perform semantic analysis for a call to __builtin_complex.
3050 bool BuiltinComplex(CallExpr *TheCall);
3051 bool BuiltinOSLogFormat(CallExpr *TheCall);
3052
3053 /// BuiltinPrefetch - Handle __builtin_prefetch.
3054 /// This is declared to take (const void*, ...) and can take two
3055 /// optional constant int args.
3056 bool BuiltinPrefetch(CallExpr *TheCall);
3057
3058 /// Handle __builtin_alloca_with_align. This is declared
3059 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3060 /// than 8.
3061 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
3062
3063 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
3064 bool BuiltinArithmeticFence(CallExpr *TheCall);
3065
3066 /// BuiltinAssume - Handle __assume (MS Extension).
3067 /// __assume does not evaluate its arguments, and should warn if its argument
3068 /// has side effects.
3069 bool BuiltinAssume(CallExpr *TheCall);
3070
3071 /// Handle __builtin_assume_aligned. This is declared
3072 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3073 bool BuiltinAssumeAligned(CallExpr *TheCall);
3074
3075 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3076 /// This checks that the target supports __builtin_longjmp and
3077 /// that val is a constant 1.
3078 bool BuiltinLongjmp(CallExpr *TheCall);
3079
3080 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3081 /// This checks that the target supports __builtin_setjmp.
3082 bool BuiltinSetjmp(CallExpr *TheCall);
3083
3084 /// We have a call to a function like __sync_fetch_and_add, which is an
3085 /// overloaded function based on the pointer type of its first argument.
3086 /// The main BuildCallExpr routines have already promoted the types of
3087 /// arguments because all of these calls are prototyped as void(...).
3088 ///
3089 /// This function goes through and does final semantic checking for these
3090 /// builtins, as well as generating any warnings.
3091 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
3092
3093 /// BuiltinNontemporalOverloaded - We have a call to
3094 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3095 /// overloaded function based on the pointer type of its last argument.
3096 ///
3097 /// This function goes through and does final semantic checking for these
3098 /// builtins.
3099 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
3100 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
3101 AtomicExpr::AtomicOp Op);
3102
3103 /// \param FPOnly restricts the arguments to floating-point types.
3104 bool BuiltinElementwiseMath(CallExpr *TheCall,
3105 EltwiseBuiltinArgTyRestriction ArgTyRestr =
3106 EltwiseBuiltinArgTyRestriction::None);
3107 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
3108
3109 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
3110
3111 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
3112 BuiltinCountedByRefKind K);
3113 bool BuiltinCountedByRef(CallExpr *TheCall);
3114
3115 // Matrix builtin handling.
3116 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
3117 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
3118 ExprResult CallResult);
3119 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
3120 ExprResult CallResult);
3121
3122 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3123 /// functions) for correct use of format strings.
3124 /// Returns true if a format string has been fully checked.
3125 bool CheckFormatArguments(const FormatAttr *Format,
3126 ArrayRef<const Expr *> Args, bool IsCXXMember,
3127 VariadicCallType CallType, SourceLocation Loc,
3128 SourceRange Range,
3129 llvm::SmallBitVector &CheckedVarArgs);
3130 bool CheckFormatString(const FormatMatchesAttr *Format,
3131 ArrayRef<const Expr *> Args, bool IsCXXMember,
3132 VariadicCallType CallType, SourceLocation Loc,
3133 SourceRange Range,
3134 llvm::SmallBitVector &CheckedVarArgs);
3135 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3136 FormatArgumentPassingKind FAPK,
3137 StringLiteral *ReferenceFormatString,
3138 unsigned format_idx, unsigned firstDataArg,
3139 FormatStringType Type, VariadicCallType CallType,
3140 SourceLocation Loc, SourceRange range,
3141 llvm::SmallBitVector &CheckedVarArgs);
3142
3143 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3144
3145 /// Warn when using the wrong abs() function.
3146 void CheckAbsoluteValueFunction(const CallExpr *Call,
3147 const FunctionDecl *FDecl);
3148
3149 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3150
3151 /// Check for dangerous or invalid arguments to memset().
3152 ///
3153 /// This issues warnings on known problematic, dangerous or unspecified
3154 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3155 /// function calls.
3156 ///
3157 /// \param Call The call expression to diagnose.
3158 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3159 IdentifierInfo *FnName);
3160
3161 bool CheckSizeofMemaccessArgument(const Expr *SizeOfArg, const Expr *Dest,
3162 IdentifierInfo *FnName);
3163 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3164 // be the size of the source, instead of the destination.
3165 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3166
3167 // Warn on anti-patterns as the 'size' argument to strncat.
3168 // The correct size argument should look like following:
3169 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3170 void CheckStrncatArguments(const CallExpr *Call,
3171 const IdentifierInfo *FnName);
3172
3173 /// Alerts the user that they are attempting to free a non-malloc'd object.
3174 void CheckFreeArguments(const CallExpr *E);
3175
3176 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3177 SourceLocation ReturnLoc, bool isObjCMethod = false,
3178 const AttrVec *Attrs = nullptr,
3179 const FunctionDecl *FD = nullptr);
3180
3181 /// Diagnoses "dangerous" implicit conversions within the given
3182 /// expression (which is a full expression). Implements -Wconversion
3183 /// and -Wsign-compare.
3184 ///
3185 /// \param CC the "context" location of the implicit conversion, i.e.
3186 /// the most location of the syntactic entity requiring the implicit
3187 /// conversion
3188 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3189
3190 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3191 /// Input argument E is a logical expression.
3192 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
3193
3194 /// Diagnose when expression is an integer constant expression and its
3195 /// evaluation results in integer overflow
3196 void CheckForIntOverflow(const Expr *E);
3197 void CheckUnsequencedOperations(const Expr *E);
3198
3199 /// Perform semantic checks on a completed expression. This will either
3200 /// be a full-expression or a default argument expression.
3201 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3202 bool IsConstexpr = false);
3203
3204 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3205 Expr *Init);
3206
3207 /// A map from magic value to type information.
3208 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3209 TypeTagForDatatypeMagicValues;
3210
3211 /// Peform checks on a call of a function with argument_with_type_tag
3212 /// or pointer_with_type_tag attributes.
3213 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3214 const ArrayRef<const Expr *> ExprArgs,
3215 SourceLocation CallSiteLoc);
3216
3217 /// Check if we are taking the address of a packed field
3218 /// as this may be a problem if the pointer value is dereferenced.
3219 void CheckAddressOfPackedMember(Expr *rhs);
3220
3221 /// Helper class that collects misaligned member designations and
3222 /// their location info for delayed diagnostics.
3223 struct MisalignedMember {
3224 Expr *E;
3225 RecordDecl *RD;
3226 ValueDecl *MD;
3227 CharUnits Alignment;
3228
3229 MisalignedMember() : E(), RD(), MD() {}
3230 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3231 CharUnits Alignment)
3232 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
3233 explicit MisalignedMember(Expr *E)
3234 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3235
3236 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3237 };
3238
3239 /// Adds an expression to the set of gathered misaligned members.
3240 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3241 CharUnits Alignment);
3242 ///@}
3243
3244 //
3245 //
3246 // -------------------------------------------------------------------------
3247 //
3248 //
3249
3250 /// \name C++ Coroutines
3251 /// Implementations are in SemaCoroutine.cpp
3252 ///@{
3253
3254public:
3255 /// The C++ "std::coroutine_traits" template, which is defined in
3256 /// \<coroutine_traits>
3257 ClassTemplateDecl *StdCoroutineTraitsCache;
3258
3259 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
3260 StringRef Keyword);
3261 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3262 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3263 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
3264
3265 ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
3266 ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
3267 UnresolvedLookupExpr *Lookup);
3268 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3269 Expr *Awaiter, bool IsImplicit = false);
3270 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3271 UnresolvedLookupExpr *Lookup);
3272 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
3273 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
3274 bool IsImplicit = false);
3275 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
3276 bool buildCoroutineParameterMoves(SourceLocation Loc);
3277 VarDecl *buildCoroutinePromise(SourceLocation Loc);
3278 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
3279
3280 // As a clang extension, enforces that a non-coroutine function must be marked
3281 // with [[clang::coro_wrapper]] if it returns a type marked with
3282 // [[clang::coro_return_type]].
3283 // Expects that FD is not a coroutine.
3284 void CheckCoroutineWrapper(FunctionDecl *FD);
3285 /// Lookup 'coroutine_traits' in std namespace and std::experimental
3286 /// namespace. The namespace found is recorded in Namespace.
3287 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
3288 SourceLocation FuncLoc);
3289 /// Check that the expression co_await promise.final_suspend() shall not be
3290 /// potentially-throwing.
3291 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3292
3293 ///@}
3294
3295 //
3296 //
3297 // -------------------------------------------------------------------------
3298 //
3299 //
3300
3301 /// \name C++ Scope Specifiers
3302 /// Implementations are in SemaCXXScopeSpec.cpp
3303 ///@{
3304
3305public:
3306 // Marks SS invalid if it represents an incomplete type.
3307 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
3308 // Complete an enum decl, maybe without a scope spec.
3309 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
3310 CXXScopeSpec *SS = nullptr);
3311
3312 /// Compute the DeclContext that is associated with the given type.
3313 ///
3314 /// \param T the type for which we are attempting to find a DeclContext.
3315 ///
3316 /// \returns the declaration context represented by the type T,
3317 /// or NULL if the declaration context cannot be computed (e.g., because it is
3318 /// dependent and not the current instantiation).
3319 DeclContext *computeDeclContext(QualType T);
3320
3321 /// Compute the DeclContext that is associated with the given
3322 /// scope specifier.
3323 ///
3324 /// \param SS the C++ scope specifier as it appears in the source
3325 ///
3326 /// \param EnteringContext when true, we will be entering the context of
3327 /// this scope specifier, so we can retrieve the declaration context of a
3328 /// class template or class template partial specialization even if it is
3329 /// not the current instantiation.
3330 ///
3331 /// \returns the declaration context represented by the scope specifier @p SS,
3332 /// or NULL if the declaration context cannot be computed (e.g., because it is
3333 /// dependent and not the current instantiation).
3334 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
3335 bool EnteringContext = false);
3336 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
3337
3338 /// If the given nested name specifier refers to the current
3339 /// instantiation, return the declaration that corresponds to that
3340 /// current instantiation (C++0x [temp.dep.type]p1).
3341 ///
3342 /// \param NNS a dependent nested name specifier.
3343 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier NNS);
3344
3345 /// The parser has parsed a global nested-name-specifier '::'.
3346 ///
3347 /// \param CCLoc The location of the '::'.
3348 ///
3349 /// \param SS The nested-name-specifier, which will be updated in-place
3350 /// to reflect the parsed nested-name-specifier.
3351 ///
3352 /// \returns true if an error occurred, false otherwise.
3353 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
3354
3355 /// The parser has parsed a '__super' nested-name-specifier.
3356 ///
3357 /// \param SuperLoc The location of the '__super' keyword.
3358 ///
3359 /// \param ColonColonLoc The location of the '::'.
3360 ///
3361 /// \param SS The nested-name-specifier, which will be updated in-place
3362 /// to reflect the parsed nested-name-specifier.
3363 ///
3364 /// \returns true if an error occurred, false otherwise.
3365 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
3366 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3367
3368 /// Determines whether the given declaration is an valid acceptable
3369 /// result for name lookup of a nested-name-specifier.
3370 /// \param SD Declaration checked for nested-name-specifier.
3371 /// \param IsExtension If not null and the declaration is accepted as an
3372 /// extension, the pointed variable is assigned true.
3373 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
3374 bool *CanCorrect = nullptr);
3375
3376 /// If the given nested-name-specifier begins with a bare identifier
3377 /// (e.g., Base::), perform name lookup for that identifier as a
3378 /// nested-name-specifier within the given scope, and return the result of
3379 /// that name lookup.
3380 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier NNS);
3381
3382 /// Keeps information about an identifier in a nested-name-spec.
3383 ///
3384 struct NestedNameSpecInfo {
3385 /// The type of the object, if we're parsing nested-name-specifier in
3386 /// a member access expression.
3387 ParsedType ObjectType;
3388
3389 /// The identifier preceding the '::'.
3390 IdentifierInfo *Identifier;
3391
3392 /// The location of the identifier.
3393 SourceLocation IdentifierLoc;
3394
3395 /// The location of the '::'.
3396 SourceLocation CCLoc;
3397
3398 /// Creates info object for the most typical case.
3399 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3400 SourceLocation ColonColonLoc,
3401 ParsedType ObjectType = ParsedType())
3402 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
3403 CCLoc(ColonColonLoc) {}
3404
3405 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3406 SourceLocation ColonColonLoc, QualType ObjectType)
3407 : ObjectType(ParsedType::make(P: ObjectType)), Identifier(II),
3408 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3409 };
3410
3411 /// Build a new nested-name-specifier for "identifier::", as described
3412 /// by ActOnCXXNestedNameSpecifier.
3413 ///
3414 /// \param S Scope in which the nested-name-specifier occurs.
3415 /// \param IdInfo Parser information about an identifier in the
3416 /// nested-name-spec.
3417 /// \param EnteringContext If true, enter the context specified by the
3418 /// nested-name-specifier.
3419 /// \param SS Optional nested name specifier preceding the identifier.
3420 /// \param ScopeLookupResult Provides the result of name lookup within the
3421 /// scope of the nested-name-specifier that was computed at template
3422 /// definition time.
3423 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3424 /// error recovery and what kind of recovery is performed.
3425 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3426 /// are allowed. The bool value pointed by this parameter is set to
3427 /// 'true' if the identifier is treated as if it was followed by ':',
3428 /// not '::'.
3429 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3430 ///
3431 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3432 /// that it contains an extra parameter \p ScopeLookupResult, which provides
3433 /// the result of name lookup within the scope of the nested-name-specifier
3434 /// that was computed at template definition time.
3435 ///
3436 /// If ErrorRecoveryLookup is true, then this call is used to improve error
3437 /// recovery. This means that it should not emit diagnostics, it should
3438 /// just return true on failure. It also means it should only return a valid
3439 /// scope if it *knows* that the result is correct. It should not return in a
3440 /// dependent context, for example. Nor will it extend \p SS with the scope
3441 /// specifier.
3442 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3443 bool EnteringContext, CXXScopeSpec &SS,
3444 NamedDecl *ScopeLookupResult,
3445 bool ErrorRecoveryLookup,
3446 bool *IsCorrectedToColon = nullptr,
3447 bool OnlyNamespace = false);
3448
3449 /// The parser has parsed a nested-name-specifier 'identifier::'.
3450 ///
3451 /// \param S The scope in which this nested-name-specifier occurs.
3452 ///
3453 /// \param IdInfo Parser information about an identifier in the
3454 /// nested-name-spec.
3455 ///
3456 /// \param EnteringContext Whether we're entering the context nominated by
3457 /// this nested-name-specifier.
3458 ///
3459 /// \param SS The nested-name-specifier, which is both an input
3460 /// parameter (the nested-name-specifier before this type) and an
3461 /// output parameter (containing the full nested-name-specifier,
3462 /// including this new type).
3463 ///
3464 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3465 /// are allowed. The bool value pointed by this parameter is set to 'true'
3466 /// if the identifier is treated as if it was followed by ':', not '::'.
3467 ///
3468 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3469 ///
3470 /// \returns true if an error occurred, false otherwise.
3471 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3472 bool EnteringContext, CXXScopeSpec &SS,
3473 bool *IsCorrectedToColon = nullptr,
3474 bool OnlyNamespace = false);
3475
3476 /// The parser has parsed a nested-name-specifier
3477 /// 'template[opt] template-name < template-args >::'.
3478 ///
3479 /// \param S The scope in which this nested-name-specifier occurs.
3480 ///
3481 /// \param SS The nested-name-specifier, which is both an input
3482 /// parameter (the nested-name-specifier before this type) and an
3483 /// output parameter (containing the full nested-name-specifier,
3484 /// including this new type).
3485 ///
3486 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3487 /// \param TemplateName the template name.
3488 /// \param TemplateNameLoc The location of the template name.
3489 /// \param LAngleLoc The location of the opening angle bracket ('<').
3490 /// \param TemplateArgs The template arguments.
3491 /// \param RAngleLoc The location of the closing angle bracket ('>').
3492 /// \param CCLoc The location of the '::'.
3493 ///
3494 /// \param EnteringContext Whether we're entering the context of the
3495 /// nested-name-specifier.
3496 ///
3497 ///
3498 /// \returns true if an error occurred, false otherwise.
3499 bool ActOnCXXNestedNameSpecifier(
3500 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3501 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3502 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3503 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3504
3505 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS,
3506 SourceLocation ColonColonLoc);
3507
3508 bool ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS,
3509 const DeclSpec &DS,
3510 SourceLocation ColonColonLoc,
3511 QualType Type);
3512
3513 /// IsInvalidUnlessNestedName - This method is used for error recovery
3514 /// purposes to determine whether the specified identifier is only valid as
3515 /// a nested name specifier, for example a namespace name. It is
3516 /// conservatively correct to always return false from this method.
3517 ///
3518 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3519 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3520 NestedNameSpecInfo &IdInfo,
3521 bool EnteringContext);
3522
3523 /// Given a C++ nested-name-specifier, produce an annotation value
3524 /// that the parser can use later to reconstruct the given
3525 /// nested-name-specifier.
3526 ///
3527 /// \param SS A nested-name-specifier.
3528 ///
3529 /// \returns A pointer containing all of the information in the
3530 /// nested-name-specifier \p SS.
3531 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3532
3533 /// Given an annotation pointer for a nested-name-specifier, restore
3534 /// the nested-name-specifier structure.
3535 ///
3536 /// \param Annotation The annotation pointer, produced by
3537 /// \c SaveNestedNameSpecifierAnnotation().
3538 ///
3539 /// \param AnnotationRange The source range corresponding to the annotation.
3540 ///
3541 /// \param SS The nested-name-specifier that will be updated with the contents
3542 /// of the annotation pointer.
3543 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3544 SourceRange AnnotationRange,
3545 CXXScopeSpec &SS);
3546
3547 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3548
3549 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3550 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3551 /// After this method is called, according to [C++ 3.4.3p3], names should be
3552 /// looked up in the declarator-id's scope, until the declarator is parsed and
3553 /// ActOnCXXExitDeclaratorScope is called.
3554 /// The 'SS' should be a non-empty valid CXXScopeSpec.
3555 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
3556
3557 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3558 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3559 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3560 /// Used to indicate that names should revert to being looked up in the
3561 /// defining scope.
3562 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3563
3564 ///@}
3565
3566 //
3567 //
3568 // -------------------------------------------------------------------------
3569 //
3570 //
3571
3572 /// \name Declarations
3573 /// Implementations are in SemaDecl.cpp
3574 ///@{
3575
3576public:
3577 IdentifierResolver IdResolver;
3578
3579 /// The index of the first InventedParameterInfo that refers to the current
3580 /// context.
3581 unsigned InventedParameterInfosStart = 0;
3582
3583 /// A RAII object to temporarily push a declaration context.
3584 class ContextRAII {
3585 private:
3586 Sema &S;
3587 DeclContext *SavedContext;
3588 ProcessingContextState SavedContextState;
3589 QualType SavedCXXThisTypeOverride;
3590 unsigned SavedFunctionScopesStart;
3591 unsigned SavedInventedParameterInfosStart;
3592
3593 public:
3594 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3595 : S(S), SavedContext(S.CurContext),
3596 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3597 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3598 SavedFunctionScopesStart(S.FunctionScopesStart),
3599 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3600 assert(ContextToPush && "pushing null context");
3601 S.CurContext = ContextToPush;
3602 if (NewThisContext)
3603 S.CXXThisTypeOverride = QualType();
3604 // Any saved FunctionScopes do not refer to this context.
3605 S.FunctionScopesStart = S.FunctionScopes.size();
3606 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3607 }
3608
3609 void pop() {
3610 if (!SavedContext)
3611 return;
3612 S.CurContext = SavedContext;
3613 S.DelayedDiagnostics.popUndelayed(state: SavedContextState);
3614 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3615 S.FunctionScopesStart = SavedFunctionScopesStart;
3616 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3617 SavedContext = nullptr;
3618 }
3619
3620 ~ContextRAII() { pop(); }
3621 ContextRAII(const ContextRAII &) = delete;
3622 ContextRAII &operator=(const ContextRAII &) = delete;
3623 };
3624
3625 void DiagnoseInvalidJumps(Stmt *Body);
3626
3627 /// The function definitions which were renamed as part of typo-correction
3628 /// to match their respective declarations. We want to keep track of them
3629 /// to ensure that we don't emit a "redefinition" error if we encounter a
3630 /// correctly named definition after the renamed definition.
3631 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
3632
3633 /// A cache of the flags available in enumerations with the flag_enum
3634 /// attribute.
3635 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3636
3637 /// A cache of enumerator values for enums checked by -Wassign-enum.
3638 llvm::DenseMap<const EnumDecl *, llvm::SmallVector<llvm::APSInt>>
3639 AssignEnumCache;
3640
3641 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3642 /// declared. Rare. May alias another identifier, declared or undeclared.
3643 ///
3644 /// For aliases, the target identifier is used as a key for eventual
3645 /// processing when the target is declared. For the single-identifier form,
3646 /// the sole identifier is used as the key. Each entry is a `SetVector`
3647 /// (ordered by parse order) of aliases (identified by the alias name) in case
3648 /// of multiple aliases to the same undeclared identifier.
3649 llvm::MapVector<
3650 IdentifierInfo *,
3651 llvm::SetVector<
3652 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
3653 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3654 WeakUndeclaredIdentifiers;
3655
3656 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3657 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3658 /// to define functions that occur in multiple standards to call the version
3659 /// in the currently selected standard.
3660 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>
3661 ExtnameUndeclaredIdentifiers;
3662
3663 /// Set containing all typedefs that are likely unused.
3664 llvm::SmallPtrSet<const TypedefNameDecl *, 4>
3665 UnusedLocalTypedefNameCandidates;
3666
3667 /// Store UnusedLocalTypedefNameCandidates in \p Sorted in a deterministic
3668 /// order.
3669 void getSortedUnusedLocalTypedefNameCandidates(
3670 SmallVectorImpl<const TypedefNameDecl *> &Sorted) const;
3671
3672 typedef LazyVector<const DeclaratorDecl *,
3673 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
3674 UnusedFileScopedDeclsType;
3675
3676 /// The set of file scoped decls seen so far that have not been used
3677 /// and must warn if not used. Only contains the first declaration.
3678 UnusedFileScopedDeclsType UnusedFileScopedDecls;
3679
3680 typedef LazyVector<VarDecl *, &ExternalSemaSource::ReadTentativeDefinitions,
3681 2, 2>
3682 TentativeDefinitionsType;
3683
3684 /// All the tentative definitions encountered in the TU.
3685 TentativeDefinitionsType TentativeDefinitions;
3686
3687 /// All the external declarations encoutered and used in the TU.
3688 SmallVector<DeclaratorDecl *, 4> ExternalDeclarations;
3689
3690 /// Generally null except when we temporarily switch decl contexts,
3691 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3692 DeclContext *OriginalLexicalContext;
3693
3694 /// Is the module scope we are in a C++ Header Unit?
3695 bool currentModuleIsHeaderUnit() const {
3696 return ModuleScopes.empty() ? false
3697 : ModuleScopes.back().Module->isHeaderUnit();
3698 }
3699
3700 /// Get the module owning an entity.
3701 Module *getOwningModule(const Decl *Entity) {
3702 return Entity->getOwningModule();
3703 }
3704
3705 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3706
3707 enum class DiagCtorKind { None, Implicit, Typename };
3708 /// Returns the TypeDeclType for the given type declaration,
3709 /// as ASTContext::getTypeDeclType would, but
3710 /// performs the required semantic checks for name lookup of said entity.
3711 void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD,
3712 SourceLocation NameLoc);
3713
3714 /// If the identifier refers to a type name within this scope,
3715 /// return the declaration of that type.
3716 ///
3717 /// This routine performs ordinary name lookup of the identifier II
3718 /// within the given scope, with optional C++ scope specifier SS, to
3719 /// determine whether the name refers to a type. If so, returns an
3720 /// opaque pointer (actually a QualType) corresponding to that
3721 /// type. Otherwise, returns NULL.
3722 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
3723 Scope *S, CXXScopeSpec *SS = nullptr,
3724 bool isClassName = false, bool HasTrailingDot = false,
3725 ParsedType ObjectType = nullptr,
3726 bool IsCtorOrDtorName = false,
3727 bool WantNontrivialTypeSourceInfo = false,
3728 bool IsClassTemplateDeductionContext = true,
3729 ImplicitTypenameContext AllowImplicitTypename =
3730 ImplicitTypenameContext::No,
3731 IdentifierInfo **CorrectedII = nullptr);
3732
3733 /// isTagName() - This method is called *for error recovery purposes only*
3734 /// to determine if the specified name is a valid tag name ("struct foo"). If
3735 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3736 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3737 /// diagnose cases in C where the user forgot to specify the tag.
3738 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
3739
3740 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3741 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3742 /// then downgrade the missing typename error to a warning.
3743 /// This is needed for MSVC compatibility; Example:
3744 /// @code
3745 /// template<class T> class A {
3746 /// public:
3747 /// typedef int TYPE;
3748 /// };
3749 /// template<class T> class B : public A<T> {
3750 /// public:
3751 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3752 /// };
3753 /// @endcode
3754 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3755 void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc,
3756 Scope *S, CXXScopeSpec *SS,
3757 ParsedType &SuggestedType,
3758 bool IsTemplateName = false);
3759
3760 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3761 /// type name has failed in a dependent context. In these situations, we
3762 /// automatically form a DependentTypeName that will retry lookup in a related
3763 /// scope during instantiation.
3764 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
3765 SourceLocation NameLoc,
3766 bool IsTemplateTypeArg);
3767
3768 class NameClassification {
3769 NameClassificationKind Kind;
3770 union {
3771 ExprResult Expr;
3772 NamedDecl *NonTypeDecl;
3773 TemplateName Template;
3774 ParsedType Type;
3775 };
3776
3777 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3778
3779 public:
3780 NameClassification(ParsedType Type)
3781 : Kind(NameClassificationKind::Type), Type(Type) {}
3782
3783 NameClassification(const IdentifierInfo *Keyword)
3784 : Kind(NameClassificationKind::Keyword) {}
3785
3786 static NameClassification Error() {
3787 return NameClassification(NameClassificationKind::Error);
3788 }
3789
3790 static NameClassification Unknown() {
3791 return NameClassification(NameClassificationKind::Unknown);
3792 }
3793
3794 static NameClassification OverloadSet(ExprResult E) {
3795 NameClassification Result(NameClassificationKind::OverloadSet);
3796 Result.Expr = E;
3797 return Result;
3798 }
3799
3800 static NameClassification NonType(NamedDecl *D) {
3801 NameClassification Result(NameClassificationKind::NonType);
3802 Result.NonTypeDecl = D;
3803 return Result;
3804 }
3805
3806 static NameClassification UndeclaredNonType() {
3807 return NameClassification(NameClassificationKind::UndeclaredNonType);
3808 }
3809
3810 static NameClassification DependentNonType() {
3811 return NameClassification(NameClassificationKind::DependentNonType);
3812 }
3813
3814 static NameClassification TypeTemplate(TemplateName Name) {
3815 NameClassification Result(NameClassificationKind::TypeTemplate);
3816 Result.Template = Name;
3817 return Result;
3818 }
3819
3820 static NameClassification VarTemplate(TemplateName Name) {
3821 NameClassification Result(NameClassificationKind::VarTemplate);
3822 Result.Template = Name;
3823 return Result;
3824 }
3825
3826 static NameClassification FunctionTemplate(TemplateName Name) {
3827 NameClassification Result(NameClassificationKind::FunctionTemplate);
3828 Result.Template = Name;
3829 return Result;
3830 }
3831
3832 static NameClassification Concept(TemplateName Name) {
3833 NameClassification Result(NameClassificationKind::Concept);
3834 Result.Template = Name;
3835 return Result;
3836 }
3837
3838 static NameClassification UndeclaredTemplate(TemplateName Name) {
3839 NameClassification Result(NameClassificationKind::UndeclaredTemplate);
3840 Result.Template = Name;
3841 return Result;
3842 }
3843
3844 NameClassificationKind getKind() const { return Kind; }
3845
3846 ExprResult getExpression() const {
3847 assert(Kind == NameClassificationKind::OverloadSet);
3848 return Expr;
3849 }
3850
3851 ParsedType getType() const {
3852 assert(Kind == NameClassificationKind::Type);
3853 return Type;
3854 }
3855
3856 NamedDecl *getNonTypeDecl() const {
3857 assert(Kind == NameClassificationKind::NonType);
3858 return NonTypeDecl;
3859 }
3860
3861 TemplateName getTemplateName() const {
3862 assert(Kind == NameClassificationKind::TypeTemplate ||
3863 Kind == NameClassificationKind::FunctionTemplate ||
3864 Kind == NameClassificationKind::VarTemplate ||
3865 Kind == NameClassificationKind::Concept ||
3866 Kind == NameClassificationKind::UndeclaredTemplate);
3867 return Template;
3868 }
3869
3870 TemplateNameKind getTemplateNameKind() const {
3871 switch (Kind) {
3872 case NameClassificationKind::TypeTemplate:
3873 return TNK_Type_template;
3874 case NameClassificationKind::FunctionTemplate:
3875 return TNK_Function_template;
3876 case NameClassificationKind::VarTemplate:
3877 return TNK_Var_template;
3878 case NameClassificationKind::Concept:
3879 return TNK_Concept_template;
3880 case NameClassificationKind::UndeclaredTemplate:
3881 return TNK_Undeclared_template;
3882 default:
3883 llvm_unreachable("unsupported name classification.");
3884 }
3885 }
3886 };
3887
3888 /// Perform name lookup on the given name, classifying it based on
3889 /// the results of name lookup and the following token.
3890 ///
3891 /// This routine is used by the parser to resolve identifiers and help direct
3892 /// parsing. When the identifier cannot be found, this routine will attempt
3893 /// to correct the typo and classify based on the resulting name.
3894 ///
3895 /// \param S The scope in which we're performing name lookup.
3896 ///
3897 /// \param SS The nested-name-specifier that precedes the name.
3898 ///
3899 /// \param Name The identifier. If typo correction finds an alternative name,
3900 /// this pointer parameter will be updated accordingly.
3901 ///
3902 /// \param NameLoc The location of the identifier.
3903 ///
3904 /// \param NextToken The token following the identifier. Used to help
3905 /// disambiguate the name.
3906 ///
3907 /// \param CCC The correction callback, if typo correction is desired.
3908 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3909 IdentifierInfo *&Name, SourceLocation NameLoc,
3910 const Token &NextToken,
3911 CorrectionCandidateCallback *CCC = nullptr);
3912
3913 /// Act on the result of classifying a name as an undeclared (ADL-only)
3914 /// non-type declaration.
3915 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
3916 SourceLocation NameLoc);
3917 /// Act on the result of classifying a name as an undeclared member of a
3918 /// dependent base class.
3919 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
3920 IdentifierInfo *Name,
3921 SourceLocation NameLoc,
3922 bool IsAddressOfOperand);
3923 /// Act on the result of classifying a name as a specific non-type
3924 /// declaration.
3925 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
3926 NamedDecl *Found,
3927 SourceLocation NameLoc,
3928 const Token &NextToken);
3929 /// Act on the result of classifying a name as an overload set.
3930 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
3931
3932 /// Describes the detailed kind of a template name. Used in diagnostics.
3933 enum class TemplateNameKindForDiagnostics {
3934 ClassTemplate,
3935 FunctionTemplate,
3936 VarTemplate,
3937 AliasTemplate,
3938 TemplateTemplateParam,
3939 Concept,
3940 DependentTemplate
3941 };
3942 TemplateNameKindForDiagnostics
3943 getTemplateNameKindForDiagnostics(TemplateName Name);
3944
3945 /// Determine whether it's plausible that E was intended to be a
3946 /// template-name.
3947 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
3948 if (!getLangOpts().CPlusPlus || E.isInvalid())
3949 return false;
3950 Dependent = false;
3951 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E.get()))
3952 return !DRE->hasExplicitTemplateArgs();
3953 if (auto *ME = dyn_cast<MemberExpr>(Val: E.get()))
3954 return !ME->hasExplicitTemplateArgs();
3955 Dependent = true;
3956 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(Val: E.get()))
3957 return !DSDRE->hasExplicitTemplateArgs();
3958 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(Val: E.get()))
3959 return !DSME->hasExplicitTemplateArgs();
3960 // Any additional cases recognized here should also be handled by
3961 // diagnoseExprIntendedAsTemplateName.
3962 return false;
3963 }
3964
3965 void warnOnReservedIdentifier(const NamedDecl *D);
3966 void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D);
3967
3968 void ProcessPragmaExport(DeclaratorDecl *newDecl);
3969
3970 Decl *ActOnDeclarator(Scope *S, Declarator &D);
3971
3972 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
3973 MultiTemplateParamsArg TemplateParameterLists);
3974
3975 /// Attempt to fold a variable-sized type to a constant-sized type, returning
3976 /// true if we were successful.
3977 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T,
3978 SourceLocation Loc,
3979 unsigned FailedFoldDiagID);
3980
3981 /// Register the given locally-scoped extern "C" declaration so
3982 /// that it can be found later for redeclarations. We include any extern "C"
3983 /// declaration that is not visible in the translation unit here, not just
3984 /// function-scope declarations.
3985 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
3986
3987 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3988 /// If T is the name of a class, then each of the following shall have a
3989 /// name different from T:
3990 /// - every static data member of class T;
3991 /// - every member function of class T
3992 /// - every member of class T that is itself a type;
3993 /// \returns true if the declaration name violates these rules.
3994 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
3995
3996 /// Diagnose a declaration whose declarator-id has the given
3997 /// nested-name-specifier.
3998 ///
3999 /// \param SS The nested-name-specifier of the declarator-id.
4000 ///
4001 /// \param DC The declaration context to which the nested-name-specifier
4002 /// resolves.
4003 ///
4004 /// \param Name The name of the entity being declared.
4005 ///
4006 /// \param Loc The location of the name of the entity being declared.
4007 ///
4008 /// \param IsMemberSpecialization Whether we are declaring a member
4009 /// specialization.
4010 ///
4011 /// \param TemplateId The template-id, if any.
4012 ///
4013 /// \returns true if we cannot safely recover from this error, false
4014 /// otherwise.
4015 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4016 DeclarationName Name, SourceLocation Loc,
4017 TemplateIdAnnotation *TemplateId,
4018 bool IsMemberSpecialization);
4019
4020 bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range);
4021
4022 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
4023
4024 bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind,
4025 unsigned &IntVal);
4026
4027 /// Diagnose function specifiers on a declaration of an identifier that
4028 /// does not identify a function.
4029 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
4030
4031 /// Return the declaration shadowed by the given typedef \p D, or null
4032 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
4033 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
4034 const LookupResult &R);
4035
4036 /// Return the declaration shadowed by the given variable \p D, or null
4037 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
4038 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
4039
4040 /// Return the declaration shadowed by the given variable \p D, or null
4041 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
4042 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
4043 const LookupResult &R);
4044 /// Diagnose variable or built-in function shadowing. Implements
4045 /// -Wshadow.
4046 ///
4047 /// This method is called whenever a VarDecl is added to a "useful"
4048 /// scope.
4049 ///
4050 /// \param ShadowedDecl the declaration that is shadowed by the given variable
4051 /// \param R the lookup of the name
4052 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
4053 const LookupResult &R);
4054
4055 /// Check -Wshadow without the advantage of a previous lookup.
4056 void CheckShadow(Scope *S, VarDecl *D);
4057
4058 /// Warn if 'E', which is an expression that is about to be modified, refers
4059 /// to a shadowing declaration.
4060 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
4061
4062 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
4063 /// when these variables are captured by the lambda.
4064 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
4065
4066 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
4067 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4068 TypedefNameDecl *NewTD);
4069 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
4070 NamedDecl *ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4071 TypeSourceInfo *TInfo,
4072 LookupResult &Previous);
4073
4074 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4075 /// declares a typedef-name, either using the 'typedef' type specifier or via
4076 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4077 NamedDecl *ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D,
4078 LookupResult &Previous, bool &Redeclaration);
4079 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4080 TypeSourceInfo *TInfo,
4081 LookupResult &Previous,
4082 MultiTemplateParamsArg TemplateParamLists,
4083 bool &AddToScope,
4084 ArrayRef<BindingDecl *> Bindings = {});
4085
4086private:
4087 // Perform a check on an AsmLabel to verify its consistency and emit
4088 // diagnostics in case of an error.
4089 void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
4090 TypeSourceInfo *TInfo, VarDecl *);
4091
4092public:
4093 /// Perform semantic checking on a newly-created variable
4094 /// declaration.
4095 ///
4096 /// This routine performs all of the type-checking required for a
4097 /// variable declaration once it has been built. It is used both to
4098 /// check variables after they have been parsed and their declarators
4099 /// have been translated into a declaration, and to check variables
4100 /// that have been instantiated from a template.
4101 ///
4102 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4103 ///
4104 /// Returns true if the variable declaration is a redeclaration.
4105 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
4106 void CheckVariableDeclarationType(VarDecl *NewVD);
4107 void CheckCompleteVariableDeclaration(VarDecl *VD);
4108
4109 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4110 TypeSourceInfo *TInfo,
4111 LookupResult &Previous,
4112 MultiTemplateParamsArg TemplateParamLists,
4113 bool &AddToScope);
4114
4115 /// Attach the ABI tag a standard calling convention variant requires, as an
4116 /// implicit abi_tag attribute. Call this once the function type is final.
4117 void addImplicitCallingConvAbiTag(FunctionDecl *FD);
4118
4119 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4120 /// and if so, check that it's a valid override and remember it.
4121 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
4122
4123 /// Perform semantic checking of a new function declaration.
4124 ///
4125 /// Performs semantic analysis of the new function declaration
4126 /// NewFD. This routine performs all semantic checking that does not
4127 /// require the actual declarator involved in the declaration, and is
4128 /// used both for the declaration of functions as they are parsed
4129 /// (called via ActOnDeclarator) and for the declaration of functions
4130 /// that have been instantiated via C++ template instantiation (called
4131 /// via InstantiateDecl).
4132 ///
4133 /// \param IsMemberSpecialization whether this new function declaration is
4134 /// a member specialization (that replaces any definition provided by the
4135 /// previous declaration).
4136 ///
4137 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4138 ///
4139 /// \returns true if the function declaration is a redeclaration.
4140 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4141 LookupResult &Previous,
4142 bool IsMemberSpecialization, bool DeclIsDefn);
4143
4144 /// Checks if the new declaration declared in dependent context must be
4145 /// put in the same redeclaration chain as the specified declaration.
4146 ///
4147 /// \param D Declaration that is checked.
4148 /// \param PrevDecl Previous declaration found with proper lookup method for
4149 /// the same declaration name.
4150 /// \returns True if D must be added to the redeclaration chain which PrevDecl
4151 /// belongs to.
4152 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4153
4154 /// Determines if we can perform a correct type check for \p D as a
4155 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4156 /// best-effort check.
4157 ///
4158 /// \param NewD The new declaration.
4159 /// \param OldD The old declaration.
4160 /// \param NewT The portion of the type of the new declaration to check.
4161 /// \param OldT The portion of the type of the old declaration to check.
4162 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4163 QualType NewT, QualType OldT);
4164 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4165 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4166
4167 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4168 /// containing class. Otherwise it will return implicit SectionAttr if the
4169 /// function is a definition and there is an active value on CodeSegStack
4170 /// (from the current #pragma code-seg value).
4171 ///
4172 /// \param FD Function being declared.
4173 /// \param IsDefinition Whether it is a definition or just a declaration.
4174 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4175 /// nullptr if no attribute should be added.
4176 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4177 bool IsDefinition);
4178
4179 /// Common checks for a parameter-declaration that should apply to both
4180 /// function parameters and non-type template parameters.
4181 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4182
4183 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4184 /// to introduce parameters into function prototype scope.
4185 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4186 SourceLocation ExplicitThisLoc = {});
4187
4188 /// Synthesizes a variable for a parameter arising from a
4189 /// typedef.
4190 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4191 QualType T);
4192 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4193 SourceLocation NameLoc,
4194 const IdentifierInfo *Name, QualType T,
4195 TypeSourceInfo *TSInfo, StorageClass SC);
4196
4197 /// Emit diagnostics if the initializer or any of its explicit or
4198 /// implicitly-generated subexpressions require copying or
4199 /// default-initializing a type that is or contains a C union type that is
4200 /// non-trivial to copy or default-initialize.
4201 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4202
4203 // These flags are passed to checkNonTrivialCUnion.
4204 enum NonTrivialCUnionKind {
4205 NTCUK_Init = 0x1,
4206 NTCUK_Destruct = 0x2,
4207 NTCUK_Copy = 0x4,
4208 };
4209
4210 /// Emit diagnostics if a non-trivial C union type or a struct that contains
4211 /// a non-trivial C union is used in an invalid context.
4212 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
4213 NonTrivialCUnionContext UseContext,
4214 unsigned NonTrivialKind);
4215
4216 /// Certain globally-unique variables might be accidentally duplicated if
4217 /// built into multiple shared libraries with hidden visibility. This can
4218 /// cause problems if the variable is mutable, its initialization is
4219 /// effectful, or its address is taken.
4220 bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl);
4221 void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl);
4222
4223 /// AddInitializerToDecl - Adds the initializer Init to the
4224 /// declaration dcl. If DirectInit is true, this is C++ direct
4225 /// initialization rather than copy initialization.
4226 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4227 void ActOnUninitializedDecl(Decl *dcl);
4228
4229 /// ActOnInitializerError - Given that there was an error parsing an
4230 /// initializer for the given declaration, try to at least re-establish
4231 /// invariants such as whether a variable's type is either dependent or
4232 /// complete.
4233 void ActOnInitializerError(Decl *Dcl);
4234
4235 void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt);
4236 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
4237 IdentifierInfo *Ident,
4238 ParsedAttributes &Attrs);
4239
4240 /// Check if VD needs to be dllexport/dllimport due to being in a
4241 /// dllexport/import function.
4242 void CheckStaticLocalForDllExport(VarDecl *VD);
4243 void CheckThreadLocalForLargeAlignment(VarDecl *VD);
4244
4245 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4246 /// any semantic actions necessary after any initializer has been attached.
4247 void FinalizeDeclaration(Decl *D);
4248 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4249 ArrayRef<Decl *> Group);
4250
4251 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4252 /// group, performing any necessary semantic checking.
4253 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
4254
4255 /// Should be called on all declarations that might have attached
4256 /// documentation comments.
4257 void ActOnDocumentableDecl(Decl *D);
4258 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
4259
4260 enum class FnBodyKind {
4261 /// C++26 [dcl.fct.def.general]p1
4262 /// function-body:
4263 /// ctor-initializer[opt] compound-statement
4264 /// function-try-block
4265 Other,
4266 /// = default ;
4267 Default,
4268 /// deleted-function-body
4269 ///
4270 /// deleted-function-body:
4271 /// = delete ;
4272 /// = delete ( unevaluated-string ) ;
4273 Delete
4274 };
4275
4276 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4277 SourceLocation LocAfterDecls);
4278 void CheckForFunctionRedefinition(
4279 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4280 SkipBodyInfo *SkipBody = nullptr);
4281 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
4282 MultiTemplateParamsArg TemplateParamLists,
4283 SkipBodyInfo *SkipBody = nullptr,
4284 FnBodyKind BodyKind = FnBodyKind::Other);
4285 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
4286 SkipBodyInfo *SkipBody = nullptr,
4287 FnBodyKind BodyKind = FnBodyKind::Other);
4288 void applyFunctionAttributesBeforeParsingBody(Decl *FD);
4289
4290 /// Determine whether we can delay parsing the body of a function or
4291 /// function template until it is used, assuming we don't care about emitting
4292 /// code for that function.
4293 ///
4294 /// This will be \c false if we may need the body of the function in the
4295 /// middle of parsing an expression (where it's impractical to switch to
4296 /// parsing a different function), for instance, if it's constexpr in C++11
4297 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4298 bool canDelayFunctionBody(const Declarator &D);
4299
4300 /// Determine whether we can skip parsing the body of a function
4301 /// definition, assuming we don't care about analyzing its body or emitting
4302 /// code for that function.
4303 ///
4304 /// This will be \c false only if we may need the body of the function in
4305 /// order to parse the rest of the program (for instance, if it is
4306 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4307 bool canSkipFunctionBody(Decl *D);
4308
4309 /// Given the set of return statements within a function body,
4310 /// compute the variables that are subject to the named return value
4311 /// optimization.
4312 ///
4313 /// Each of the variables that is subject to the named return value
4314 /// optimization will be marked as NRVO variables in the AST, and any
4315 /// return statement that has a marked NRVO variable as its NRVO candidate can
4316 /// use the named return value optimization.
4317 ///
4318 /// This function applies a very simplistic algorithm for NRVO: if every
4319 /// return statement in the scope of a variable has the same NRVO candidate,
4320 /// that candidate is an NRVO variable.
4321 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
4322
4323 /// Performs semantic analysis at the end of a function body.
4324 ///
4325 /// \param RetainFunctionScopeInfo If \c true, the client is responsible for
4326 /// releasing the associated \p FunctionScopeInfo. This is useful when
4327 /// building e.g. LambdaExprs.
4328 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body,
4329 bool IsInstantiation = false,
4330 bool RetainFunctionScopeInfo = false);
4331 Decl *ActOnSkippedFunctionBody(Decl *Decl);
4332 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
4333
4334 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4335 /// attribute for which parsing is delayed.
4336 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
4337
4338 /// Diagnose any unused parameters in the given sequence of
4339 /// ParmVarDecl pointers.
4340 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
4341
4342 /// Diagnose whether the size of parameters or return value of a
4343 /// function or obj-c method definition is pass-by-value and larger than a
4344 /// specified threshold.
4345 void
4346 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
4347 QualType ReturnTy, NamedDecl *D);
4348
4349 Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc,
4350 SourceLocation RParenLoc);
4351
4352 TopLevelStmtDecl *ActOnStartTopLevelStmtDecl(Scope *S);
4353 void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement);
4354
4355 void ActOnPopScope(SourceLocation Loc, Scope *S);
4356
4357 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4358 /// no declarator (e.g. "struct foo;") is parsed.
4359 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4360 const ParsedAttributesView &DeclAttrs,
4361 RecordDecl *&AnonRecord);
4362
4363 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4364 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4365 /// parameters to cope with template friend declarations.
4366 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4367 const ParsedAttributesView &DeclAttrs,
4368 MultiTemplateParamsArg TemplateParams,
4369 bool IsExplicitInstantiation,
4370 RecordDecl *&AnonRecord,
4371 SourceLocation EllipsisLoc = {});
4372
4373 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4374 /// anonymous structure or union. Anonymous unions are a C++ feature
4375 /// (C++ [class.union]) and a C11 feature; anonymous structures
4376 /// are a C11 feature and GNU C++ extension.
4377 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4378 RecordDecl *Record,
4379 const PrintingPolicy &Policy);
4380
4381 /// Called once it is known whether
4382 /// a tag declaration is an anonymous union or struct.
4383 void ActOnDefinedDeclarationSpecifier(Decl *D);
4384
4385 /// Emit diagnostic warnings for placeholder members.
4386 /// We can only do that after the class is fully constructed,
4387 /// as anonymous union/structs can insert placeholders
4388 /// in their parent scope (which might be a Record).
4389 void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record);
4390
4391 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4392 /// Microsoft C anonymous structure.
4393 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4394 /// Example:
4395 ///
4396 /// struct A { int a; };
4397 /// struct B { struct A; int b; };
4398 ///
4399 /// void foo() {
4400 /// B var;
4401 /// var.a = 3;
4402 /// }
4403 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4404 RecordDecl *Record);
4405
4406 /// Given a non-tag type declaration, returns an enum useful for indicating
4407 /// what kind of non-tag type this is.
4408 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4409
4410 /// Determine whether a tag with a given kind is acceptable
4411 /// as a redeclaration of the given tag declaration.
4412 ///
4413 /// \returns true if the new tag kind is acceptable, false otherwise.
4414 bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag,
4415 bool isDefinition, SourceLocation NewTagLoc,
4416 const IdentifierInfo *Name);
4417
4418 /// This is invoked when we see 'struct foo' or 'struct {'. In the
4419 /// former case, Name will be non-null. In the later case, Name will be null.
4420 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4421 /// a reference/declaration/definition of a tag.
4422 ///
4423 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4424 /// trailing-type-specifier) other than one in an alias-declaration.
4425 ///
4426 /// \param SkipBody If non-null, will be set to indicate if the caller should
4427 /// skip the definition of this tag and treat it as if it were a declaration.
4428 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4429 SourceLocation KWLoc, CXXScopeSpec &SS,
4430 IdentifierInfo *Name, SourceLocation NameLoc,
4431 const ParsedAttributesView &Attr, AccessSpecifier AS,
4432 SourceLocation ModulePrivateLoc,
4433 MultiTemplateParamsArg TemplateParameterLists,
4434 bool &OwnedDecl, bool &IsDependent,
4435 SourceLocation ScopedEnumKWLoc,
4436 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4437 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4438 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4439
4440 /// ActOnField - Each field of a C struct/union is passed into this in order
4441 /// to create a FieldDecl object for it.
4442 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4443 Declarator &D, Expr *BitfieldWidth);
4444
4445 /// HandleField - Analyze a field of a C struct or a C++ data member.
4446 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4447 Declarator &D, Expr *BitfieldWidth,
4448 InClassInitStyle InitStyle, AccessSpecifier AS);
4449
4450 /// Build a new FieldDecl and check its well-formedness.
4451 ///
4452 /// This routine builds a new FieldDecl given the fields name, type,
4453 /// record, etc. \p PrevDecl should refer to any previous declaration
4454 /// with the same name and in the same scope as the field to be
4455 /// created.
4456 ///
4457 /// \returns a new FieldDecl.
4458 ///
4459 /// \todo The Declarator argument is a hack. It will be removed once
4460 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4461 TypeSourceInfo *TInfo, RecordDecl *Record,
4462 SourceLocation Loc, bool Mutable,
4463 Expr *BitfieldWidth, InClassInitStyle InitStyle,
4464 SourceLocation TSSL, AccessSpecifier AS,
4465 NamedDecl *PrevDecl, Declarator *D = nullptr);
4466
4467 bool CheckNontrivialField(FieldDecl *FD);
4468
4469 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4470 /// class and class extensions. For every class \@interface and class
4471 /// extension \@interface, if the last ivar is a bitfield of any type,
4472 /// then add an implicit `char :0` ivar to the end of that interface.
4473 void ActOnLastBitfield(SourceLocation DeclStart,
4474 SmallVectorImpl<Decl *> &AllIvarDecls);
4475
4476 // This is used for both record definitions and ObjC interface declarations.
4477 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4478 ArrayRef<Decl *> Fields, SourceLocation LBrac,
4479 SourceLocation RBrac, const ParsedAttributesView &AttrList);
4480
4481 /// ActOnTagStartDefinition - Invoked when we have entered the
4482 /// scope of a tag's definition (e.g., for an enumeration, class,
4483 /// struct, or union).
4484 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4485
4486 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4487 /// Differently from C++, actually parse the body and reject / error out
4488 /// in case of a structural mismatch.
4489 bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4490
4491 typedef void *SkippedDefinitionContext;
4492
4493 /// Invoked when we enter a tag definition that we're skipping.
4494 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
4495
4496 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4497 /// C++ record definition's base-specifiers clause and are starting its
4498 /// member declarations.
4499 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
4500 SourceLocation FinalLoc,
4501 bool IsFinalSpelledSealed,
4502 bool IsAbstract,
4503 SourceLocation LBraceLoc);
4504
4505 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4506 /// the definition of a tag (enumeration, class, struct, or union).
4507 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
4508 SourceRange BraceRange);
4509
4510 ASTContext::CXXRecordDeclRelocationInfo
4511 CheckCXX2CRelocatable(const clang::CXXRecordDecl *D);
4512
4513 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
4514
4515 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4516 /// error parsing the definition of a tag.
4517 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
4518
4519 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
4520 EnumConstantDecl *LastEnumConst,
4521 SourceLocation IdLoc, IdentifierInfo *Id,
4522 Expr *val);
4523
4524 /// Check that this is a valid underlying type for an enum declaration.
4525 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
4526
4527 /// Check whether this is a valid redeclaration of a previous enumeration.
4528 /// \return true if the redeclaration was invalid.
4529 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4530 QualType EnumUnderlyingTy, bool IsFixed,
4531 const EnumDecl *Prev);
4532
4533 /// Determine whether the body of an anonymous enumeration should be skipped.
4534 /// \param II The name of the first enumerator.
4535 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
4536 SourceLocation IILoc);
4537
4538 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4539 SourceLocation IdLoc, IdentifierInfo *Id,
4540 const ParsedAttributesView &Attrs,
4541 SourceLocation EqualLoc, Expr *Val,
4542 SkipBodyInfo *SkipBody = nullptr);
4543 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4544 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4545 const ParsedAttributesView &Attr);
4546
4547 /// Set the current declaration context until it gets popped.
4548 void PushDeclContext(Scope *S, DeclContext *DC);
4549 void PopDeclContext();
4550
4551 /// EnterDeclaratorContext - Used when we must lookup names in the context
4552 /// of a declarator's nested name specifier.
4553 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
4554 void ExitDeclaratorContext(Scope *S);
4555
4556 /// Enter a template parameter scope, after it's been associated with a
4557 /// particular DeclContext. Causes lookup within the scope to chain through
4558 /// enclosing contexts in the correct order.
4559 void EnterTemplatedContext(Scope *S, DeclContext *DC);
4560
4561 /// Push the parameters of D, which must be a function, into scope.
4562 void ActOnReenterFunctionContext(Scope *S, Decl *D);
4563 void ActOnExitFunctionContext();
4564
4565 /// Add this decl to the scope shadowed decl chains.
4566 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4567
4568 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4569 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4570 /// true if 'D' belongs to the given declaration context.
4571 ///
4572 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4573 /// enclosing namespace set of the context, rather than contained
4574 /// directly within it.
4575 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4576 bool AllowInlineNamespace = false) const;
4577
4578 /// Determine whether a tag-like declaration found by lookup can be
4579 /// redeclared in the given scope. If lookup found a using-shadow, also
4580 /// consider the scope of the declaration named by the using-shadow.
4581 bool isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx,
4582 Scope *S = nullptr,
4583 bool AllowInlineNamespace = false) const;
4584
4585 /// Finds the scope corresponding to the given decl context, if it
4586 /// happens to be an enclosing scope. Otherwise return NULL.
4587 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
4588
4589 /// Subroutines of ActOnDeclarator().
4590 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4591 TypeSourceInfo *TInfo);
4592 bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New);
4593
4594 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4595 void mergeDeclAttributes(
4596 NamedDecl *New, Decl *Old,
4597 AvailabilityMergeKind AMK = AvailabilityMergeKind::Redeclaration);
4598
4599 /// CheckAttributesOnDeducedType - Calls Sema functions for attributes that
4600 /// requires the type to be deduced.
4601 void CheckAttributesOnDeducedType(Decl *D);
4602
4603 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4604 /// same name and scope as a previous declaration 'Old'. Figure out
4605 /// how to resolve this situation, merging decls or emitting
4606 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4607 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
4608 LookupResult &OldDecls);
4609
4610 /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4611 /// definition visible.
4612 /// This method performs any necessary cleanup on the parser state to discard
4613 /// child nodes from newly parsed decl we are retiring.
4614 void CleanupMergedEnum(Scope *S, Decl *New);
4615
4616 /// MergeFunctionDecl - We just parsed a function 'New' from
4617 /// declarator D which has the same name and scope as a previous
4618 /// declaration 'Old'. Figure out how to resolve this situation,
4619 /// merging decls or emitting diagnostics as appropriate.
4620 ///
4621 /// In C++, New and Old must be declarations that are not
4622 /// overloaded. Use IsOverload to determine whether New and Old are
4623 /// overloaded, and to select the Old declaration that New should be
4624 /// merged with.
4625 ///
4626 /// Returns true if there was an error, false otherwise.
4627 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
4628 bool MergeTypeWithOld, bool NewDeclIsDefn);
4629
4630 /// Completes the merge of two function declarations that are
4631 /// known to be compatible.
4632 ///
4633 /// This routine handles the merging of attributes and other
4634 /// properties of function declarations from the old declaration to
4635 /// the new declaration, once we know that New is in fact a
4636 /// redeclaration of Old.
4637 ///
4638 /// \returns false
4639 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4640 Scope *S, bool MergeTypeWithOld);
4641 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
4642
4643 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4644 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4645 /// situation, merging decls or emitting diagnostics as appropriate.
4646 ///
4647 /// Tentative definition rules (C99 6.9.2p2) are checked by
4648 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4649 /// definitions here, since the initializer hasn't been attached.
4650 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
4651
4652 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4653 /// scope as a previous declaration 'Old'. Figure out how to merge their
4654 /// types, emitting diagnostics as appropriate.
4655 ///
4656 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4657 /// back to here in AddInitializerToDecl. We can't check them before the
4658 /// initializer is attached.
4659 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4660
4661 /// We've just determined that \p Old and \p New both appear to be definitions
4662 /// of the same variable. Either diagnose or fix the problem.
4663 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4664 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
4665
4666 /// Filters out lookup results that don't fall within the given scope
4667 /// as determined by isDeclInScope.
4668 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4669 bool ConsiderLinkage, bool AllowInlineNamespace);
4670
4671 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4672 /// have compatible owning modules.
4673 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4674
4675 /// [module.interface]p6:
4676 /// A redeclaration of an entity X is implicitly exported if X was introduced
4677 /// by an exported declaration; otherwise it shall not be exported.
4678 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4679
4680 /// A wrapper function for checking the semantic restrictions of
4681 /// a redeclaration within a module.
4682 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4683
4684 /// Check the redefinition in C++20 Modules.
4685 ///
4686 /// [basic.def.odr]p14:
4687 /// For any definable item D with definitions in multiple translation units,
4688 /// - if D is a non-inline non-templated function or variable, or
4689 /// - if the definitions in different translation units do not satisfy the
4690 /// following requirements,
4691 /// the program is ill-formed; a diagnostic is required only if the
4692 /// definable item is attached to a named module and a prior definition is
4693 /// reachable at the point where a later definition occurs.
4694 /// - Each such definition shall not be attached to a named module
4695 /// ([module.unit]).
4696 /// - Each such definition shall consist of the same sequence of tokens, ...
4697 /// ...
4698 ///
4699 /// Return true if the redefinition is not allowed. Return false otherwise.
4700 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4701
4702 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4703
4704 /// If it's a file scoped decl that must warn if not used, keep track
4705 /// of it.
4706 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4707
4708 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4709 DiagReceiverTy;
4710
4711 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4712 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
4713 DiagReceiverTy DiagReceiver);
4714 void DiagnoseUnusedDecl(const NamedDecl *ND);
4715
4716 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4717 /// unless they are marked attr(unused).
4718 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4719
4720 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4721 /// variable.
4722 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4723
4724 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4725 /// from S, where a non-field would be declared. This routine copes
4726 /// with the difference between C and C++ scoping rules in structs and
4727 /// unions. For example, the following code is well-formed in C but
4728 /// ill-formed in C++:
4729 /// @code
4730 /// struct S6 {
4731 /// enum { BAR } e;
4732 /// };
4733 ///
4734 /// void test_S6() {
4735 /// struct S6 a;
4736 /// a.e = BAR;
4737 /// }
4738 /// @endcode
4739 /// For the declaration of BAR, this routine will return a different
4740 /// scope. The scope S will be the scope of the unnamed enumeration
4741 /// within S6. In C++, this routine will return the scope associated
4742 /// with S6, because the enumeration's scope is a transparent
4743 /// context but structures can contain non-field names. In C, this
4744 /// routine will return the translation unit scope, since the
4745 /// enumeration's scope is a transparent context and structures cannot
4746 /// contain non-field names.
4747 Scope *getNonFieldDeclScope(Scope *S);
4748
4749 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4750 SourceLocation Loc);
4751
4752 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4753 /// file scope. lazily create a decl for it. ForRedeclaration is true
4754 /// if we're creating this built-in in anticipation of redeclaring the
4755 /// built-in.
4756 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4757 bool ForRedeclaration, SourceLocation Loc);
4758
4759 /// Get the outermost AttributedType node that sets a calling convention.
4760 /// Valid types should not have multiple attributes with different CCs.
4761 const AttributedType *getCallingConvAttributedType(QualType T) const;
4762
4763 /// GetNameForDeclarator - Determine the full declaration name for the
4764 /// given Declarator.
4765 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
4766
4767 /// Retrieves the declaration name from a parsed unqualified-id.
4768 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
4769
4770 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4771 /// we are currently parsing the initializer.
4772 llvm::SmallPtrSet<const Decl *, 4> ParsingInitForAutoVars;
4773
4774 /// Look for a locally scoped extern "C" declaration by the given name.
4775 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
4776
4777 void deduceOpenCLAddressSpace(VarDecl *decl);
4778 void deduceHLSLAddressSpace(VarDecl *decl);
4779
4780 /// Adjust the \c DeclContext for a function or variable that might be a
4781 /// function-local external declaration.
4782 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
4783
4784 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4785
4786 /// Checks if the variant/multiversion functions are compatible.
4787 bool areMultiversionVariantFunctionsCompatible(
4788 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4789 const PartialDiagnostic &NoProtoDiagID,
4790 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4791 const PartialDiagnosticAt &NoSupportDiagIDAt,
4792 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4793 bool ConstexprSupported, bool CLinkageMayDiffer);
4794
4795 /// type checking declaration initializers (C99 6.7.8)
4796 bool CheckForConstantInitializer(
4797 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4798
4799 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
4800 QualType Type, TypeSourceInfo *TSI,
4801 SourceRange Range, bool DirectInit,
4802 Expr *Init);
4803
4804 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
4805 Expr *Init);
4806
4807 sema::LambdaScopeInfo *RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator);
4808
4809 // Heuristically tells if the function is `get_return_object` member of a
4810 // coroutine promise_type by matching the function name.
4811 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4812 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4813
4814 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4815 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4816 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4817 Scope *S);
4818
4819 /// If this function is a C++ replaceable global allocation function
4820 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4821 /// adds any function attributes that we know a priori based on the standard.
4822 ///
4823 /// We need to check for duplicate attributes both here and where user-written
4824 /// attributes are applied to declarations.
4825 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4826 FunctionDecl *FD);
4827
4828 /// Adds any function attributes that we know a priori based on
4829 /// the declaration of this function.
4830 ///
4831 /// These attributes can apply both to implicitly-declared builtins
4832 /// (like __builtin___printf_chk) or to library-declared functions
4833 /// like NSLog or printf.
4834 ///
4835 /// We need to check for duplicate attributes both here and where user-written
4836 /// attributes are applied to declarations.
4837 void AddKnownFunctionAttributes(FunctionDecl *FD);
4838
4839 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4840 /// the correct width, and that the field type is valid.
4841 /// Returns false on success.
4842 ExprResult VerifyBitField(SourceLocation FieldLoc,
4843 const IdentifierInfo *FieldName, QualType FieldTy,
4844 bool IsMsStruct, Expr *BitWidth);
4845
4846 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4847 /// enum. If AllowMask is true, then we also allow the complement of a valid
4848 /// value, to be used as a mask.
4849 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4850 bool AllowMask) const;
4851
4852 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4853 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4854 SourceLocation WeakNameLoc);
4855
4856 /// ActOnPragmaRedefineExtname - Called on well formed
4857 /// \#pragma redefine_extname oldname newname.
4858 void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName,
4859 IdentifierInfo *AliasName,
4860 SourceLocation PragmaLoc,
4861 SourceLocation WeakNameLoc,
4862 SourceLocation AliasNameLoc);
4863
4864 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4865 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4866 SourceLocation PragmaLoc,
4867 SourceLocation WeakNameLoc,
4868 SourceLocation AliasNameLoc);
4869
4870 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4871 enum class FunctionEmissionStatus {
4872 Emitted,
4873 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4874 OMPDiscarded, // Discarded due to OpenMP hostness
4875 TemplateDiscarded, // Discarded due to uninstantiated templates
4876 Unknown,
4877 };
4878 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4879 bool Final = false);
4880
4881 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4882 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4883
4884 /// Function or variable declarations to be checked for whether the deferred
4885 /// diagnostics should be emitted.
4886 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
4887
4888private:
4889 /// Map of current shadowing declarations to shadowed declarations. Warn if
4890 /// it looks like the user is trying to modify the shadowing declaration.
4891 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4892
4893 // We need this to handle
4894 //
4895 // typedef struct {
4896 // void *foo() { return 0; }
4897 // } A;
4898 //
4899 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4900 // for example. If 'A', foo will have external linkage. If we have '*A',
4901 // foo will have no linkage. Since we can't know until we get to the end
4902 // of the typedef, this function finds out if D might have non-external
4903 // linkage. Callers should verify at the end of the TU if it D has external
4904 // linkage or not.
4905 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4906
4907#include "clang/Sema/AttrIsTypeDependent.inc"
4908
4909 ///@}
4910
4911 //
4912 //
4913 // -------------------------------------------------------------------------
4914 //
4915 //
4916
4917 /// \name Declaration Attribute Handling
4918 /// Implementations are in SemaDeclAttr.cpp
4919 ///@{
4920
4921public:
4922 /// Describes the kind of priority given to an availability attribute.
4923 ///
4924 /// The sum of priorities deteremines the final priority of the attribute.
4925 /// The final priority determines how the attribute will be merged.
4926 /// An attribute with a lower priority will always remove higher priority
4927 /// attributes for the specified platform when it is being applied. An
4928 /// attribute with a higher priority will not be applied if the declaration
4929 /// already has an availability attribute with a lower priority for the
4930 /// specified platform. The final prirority values are not expected to match
4931 /// the values in this enumeration, but instead should be treated as a plain
4932 /// integer value. This enumeration just names the priority weights that are
4933 /// used to calculate that final vaue.
4934 enum AvailabilityPriority : int {
4935 /// The availability attribute was specified explicitly next to the
4936 /// declaration.
4937 AP_Explicit = 0,
4938
4939 /// The availability attribute was applied using '#pragma clang attribute'.
4940 AP_PragmaClangAttribute = 1,
4941
4942 /// The availability attribute for a specific platform was inferred from
4943 /// an availability attribute for another platform.
4944 AP_InferredFromOtherPlatform = 2,
4945
4946 /// The availability attribute was inferred from an 'anyAppleOS'
4947 /// availability attribute.
4948 AP_InferredFromAnyAppleOS = 3,
4949
4950 /// The availability attribute was inferred from an 'anyAppleOS'
4951 /// availability attribute that was applied using '#pragma clang attribute'.
4952 /// This has the lowest priority.
4953 AP_PragmaClangAttribute_InferredFromAnyAppleOS = 4
4954 };
4955
4956 /// Describes the reason a calling convention specification was ignored, used
4957 /// for diagnostics.
4958 enum class CallingConventionIgnoredReason {
4959 ForThisTarget = 0,
4960 VariadicFunction,
4961 ConstructorDestructor,
4962 BuiltinFunction
4963 };
4964
4965 /// A helper function to provide Attribute Location for the Attr types
4966 /// AND the ParsedAttr.
4967 template <typename AttrInfo>
4968 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
4969 getAttrLoc(const AttrInfo &AL) {
4970 return AL.getLocation();
4971 }
4972 SourceLocation getAttrLoc(const AttributeCommonInfo &CI);
4973
4974 /// If Expr is a valid integer constant, get the value of the integer
4975 /// expression and return success or failure. May output an error.
4976 ///
4977 /// Negative argument is implicitly converted to unsigned, unless
4978 /// \p StrictlyUnsigned is true.
4979 template <typename AttrInfo>
4980 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
4981 unsigned Idx = UINT_MAX,
4982 bool StrictlyUnsigned = false) {
4983 std::optional<llvm::APSInt> I = llvm::APSInt(32);
4984 if (Expr->isTypeDependent() ||
4985 !(I = Expr->getIntegerConstantExpr(Ctx: Context))) {
4986 if (Idx != UINT_MAX)
4987 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
4988 << &AI << Idx << AANT_ArgumentIntegerConstant
4989 << Expr->getSourceRange();
4990 else
4991 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
4992 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
4993 return false;
4994 }
4995
4996 if (!I->isIntN(N: 32)) {
4997 Diag(Loc: Expr->getExprLoc(), DiagID: diag::err_ice_too_large)
4998 << toString(I: *I, Radix: 10, Signed: false) << 32 << /* Unsigned */ 1;
4999 return false;
5000 }
5001
5002 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
5003 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
5004 << &AI << /*non-negative*/ 1;
5005 return false;
5006 }
5007
5008 Val = (uint32_t)I->getZExtValue();
5009 return true;
5010 }
5011
5012 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
5013 /// \#pragma weak during processing of other Decls.
5014 /// I couldn't figure out a clean way to generate these in-line, so
5015 /// we store them here and handle separately -- which is a hack.
5016 /// It would be best to refactor this.
5017 SmallVector<Decl *, 2> WeakTopLevelDecl;
5018
5019 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
5020 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
5021
5022 typedef LazyVector<TypedefNameDecl *, &ExternalSemaSource::ReadExtVectorDecls,
5023 2, 2>
5024 ExtVectorDeclsType;
5025
5026 /// ExtVectorDecls - This is a list all the extended vector types. This allows
5027 /// us to associate a raw vector type with one of the ext_vector type names.
5028 /// This is only necessary for issuing pretty diagnostics.
5029 ExtVectorDeclsType ExtVectorDecls;
5030
5031 /// Check if the argument \p E is a ASCII string literal. If not emit an error
5032 /// and return false, otherwise set \p Str to the value of the string literal
5033 /// and return true.
5034 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
5035 const Expr *E, StringRef &Str,
5036 SourceLocation *ArgLocation = nullptr);
5037
5038 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
5039 /// If not emit an error and return false. If the argument is an identifier it
5040 /// will emit an error with a fixit hint and treat it as if it was a string
5041 /// literal.
5042 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
5043 StringRef &Str,
5044 SourceLocation *ArgLocation = nullptr);
5045
5046 /// Determine if type T is a valid subject for a nonnull and similar
5047 /// attributes. Dependent types are considered valid so they can be checked
5048 /// during instantiation time. By default, we look through references (the
5049 /// behavior used by nonnull), but if the second parameter is true, then we
5050 /// treat a reference type as valid.
5051 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
5052
5053 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
5054 /// declaration.
5055 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5056 Expr *OE);
5057
5058 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
5059 /// declaration.
5060 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
5061 Expr *ParamExpr);
5062
5063 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
5064 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
5065
5066 AvailabilityAttr *
5067 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
5068 const IdentifierInfo *Platform, bool Implicit,
5069 VersionTuple Introduced, VersionTuple Deprecated,
5070 VersionTuple Obsoleted, bool IsUnavailable,
5071 StringRef Message, bool IsStrict, StringRef Replacement,
5072 AvailabilityMergeKind AMK, int Priority,
5073 const IdentifierInfo *IIEnvironment,
5074 const IdentifierInfo *InferredPlatformII = nullptr);
5075
5076 AvailabilityAttr *mergeAndInferAvailabilityAttr(
5077 NamedDecl *D, const AttributeCommonInfo &CI,
5078 const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced,
5079 VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable,
5080 StringRef Message, bool IsStrict, StringRef Replacement,
5081 AvailabilityMergeKind AMK, int Priority,
5082 const IdentifierInfo *IIEnvironment,
5083 const IdentifierInfo *InferredPlatformII);
5084
5085 TypeVisibilityAttr *
5086 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5087 TypeVisibilityAttr::VisibilityType Vis);
5088 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5089 VisibilityAttr::VisibilityType Vis);
5090 void mergeVisibilityType(Decl *D, SourceLocation Loc,
5091 VisibilityAttr::VisibilityType Type);
5092 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
5093 StringRef Name);
5094
5095 /// Used to implement to perform semantic checking on
5096 /// attribute((section("foo"))) specifiers.
5097 ///
5098 /// In this case, "foo" is passed in to be checked. If the section
5099 /// specifier is invalid, return an Error that indicates the problem.
5100 ///
5101 /// This is a simple quality of implementation feature to catch errors
5102 /// and give good diagnostics in cases when the assembler or code generator
5103 /// would otherwise reject the section specifier.
5104 llvm::Error isValidSectionSpecifier(StringRef Str);
5105 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
5106 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
5107 StringRef Name);
5108
5109 // Check for things we'd like to warn about. Multiversioning issues are
5110 // handled later in the process, once we know how many exist.
5111 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
5112
5113 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
5114 StringRef NewUserDiagnostic);
5115 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
5116 const IdentifierInfo *Format, int FormatIdx,
5117 int FirstArg);
5118 FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
5119 const AttributeCommonInfo &CI,
5120 const IdentifierInfo *Format,
5121 int FormatIdx,
5122 StringLiteral *FormatStr);
5123 ModularFormatAttr *mergeModularFormatAttr(Decl *D,
5124 const AttributeCommonInfo &CI,
5125 const IdentifierInfo *ModularImplFn,
5126 StringRef ImplName,
5127 MutableArrayRef<StringRef> Aspects);
5128
5129 PersonalityAttr *mergePersonalityAttr(Decl *D, FunctionDecl *Routine,
5130 const AttributeCommonInfo &CI);
5131
5132 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5133 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5134 bool IsPackExpansion);
5135 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
5136 bool IsPackExpansion);
5137
5138 /// AddAlignValueAttr - Adds an align_value attribute to a particular
5139 /// declaration.
5140 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
5141
5142 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
5143 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
5144 MutableArrayRef<Expr *> Args);
5145 Attr *CreateAnnotationAttr(const ParsedAttr &AL);
5146
5147 bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range,
5148 bool BestCase,
5149 MSInheritanceModel SemanticSpelling);
5150
5151 void CheckAlignasUnderalignment(Decl *D);
5152
5153 /// AddModeAttr - Adds a mode attribute to a particular declaration.
5154 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
5155 const IdentifierInfo *Name, bool InInstantiation = false);
5156 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
5157 const AttributeCommonInfo &CI,
5158 const IdentifierInfo *Ident);
5159 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
5160 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
5161 const AttributeCommonInfo &CI);
5162 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
5163 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
5164 const InternalLinkageAttr &AL);
5165
5166 /// Check validaty of calling convention attribute \p attr. If \p FD
5167 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
5168 /// target. Otherwise, it is specified by \p CFT.
5169 bool CheckCallingConvAttr(
5170 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
5171 CUDAFunctionTarget CFT = CUDAFunctionTarget::InvalidTarget);
5172
5173 /// Checks a regparm attribute, returning true if it is ill-formed and
5174 /// otherwise setting numParams to the appropriate value.
5175 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
5176
5177 /// Create a CUDALaunchBoundsAttr attribute. By default, the function only
5178 /// supports nvptx target architectures and skips MaxBlocks if it is previous
5179 /// to sm_90. Use \p IgnoreArch to skip the architecture check.
5180 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
5181 Expr *MaxThreads,
5182 Expr *MinBlocks, Expr *MaxBlocks,
5183 bool IgnoreArch = false);
5184
5185 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
5186 /// declaration.
5187 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5188 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
5189
5190 /// Add a cluster_dims attribute to a particular declaration.
5191 CUDAClusterDimsAttr *createClusterDimsAttr(const AttributeCommonInfo &CI,
5192 Expr *X, Expr *Y, Expr *Z);
5193 void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
5194 Expr *Y, Expr *Z);
5195 /// Add a no_cluster attribute to a particular declaration.
5196 void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI);
5197
5198 enum class RetainOwnershipKind { NS, CF, OS };
5199
5200 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5201 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5202
5203 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5204
5205 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5206 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5207 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5208 const AttributeCommonInfo &CI,
5209 bool BestCase,
5210 MSInheritanceModel Model);
5211
5212 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5213 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5214 const EnforceTCBLeafAttr &AL);
5215
5216 /// Helper for delayed processing TransparentUnion or
5217 /// BPFPreserveAccessIndexAttr attribute.
5218 void ProcessDeclAttributeDelayed(Decl *D,
5219 const ParsedAttributesView &AttrList);
5220
5221 // Options for ProcessDeclAttributeList().
5222 struct ProcessDeclAttributeOptions {
5223 ProcessDeclAttributeOptions()
5224 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
5225
5226 ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
5227 ProcessDeclAttributeOptions Result = *this;
5228 Result.IncludeCXX11Attributes = Val;
5229 return Result;
5230 }
5231
5232 ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
5233 ProcessDeclAttributeOptions Result = *this;
5234 Result.IgnoreTypeAttributes = Val;
5235 return Result;
5236 }
5237
5238 // Should C++11 attributes be processed?
5239 bool IncludeCXX11Attributes;
5240
5241 // Should any type attributes encountered be ignored?
5242 // If this option is false, a diagnostic will be emitted for any type
5243 // attributes of a kind that does not "slide" from the declaration to
5244 // the decl-specifier-seq.
5245 bool IgnoreTypeAttributes;
5246 };
5247
5248 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5249 /// attribute list to the specified decl, ignoring any type attributes.
5250 void ProcessDeclAttributeList(Scope *S, Decl *D,
5251 const ParsedAttributesView &AttrList,
5252 const ProcessDeclAttributeOptions &Options =
5253 ProcessDeclAttributeOptions());
5254
5255 /// Annotation attributes are the only attributes allowed after an access
5256 /// specifier.
5257 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5258 const ParsedAttributesView &AttrList);
5259
5260 /// checkUnusedDeclAttributes - Given a declarator which is not being
5261 /// used to build a declaration, complain about any decl attributes
5262 /// which might be lying around on it.
5263 void checkUnusedDeclAttributes(Declarator &D);
5264
5265 void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5266
5267 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5268 /// \#pragma weak needs a non-definition decl and source may not have one.
5269 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
5270 SourceLocation Loc);
5271
5272 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5273 /// applied to it, possibly with an alias.
5274 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5275
5276 void ProcessPragmaWeak(Scope *S, Decl *D);
5277 // Decl attributes - this routine is the top level dispatcher.
5278 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5279
5280 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5281
5282 /// Given a set of delayed diagnostics, re-emit them as if they had
5283 /// been delayed in the current context instead of in the given pool.
5284 /// Essentially, this just moves them to the current pool.
5285 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5286
5287 /// Check that the type is a plain record with one field being a pointer
5288 /// type and the other field being an integer. This matches the common
5289 /// implementation of std::span or sized_allocation_t in P0901R11.
5290 bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty);
5291
5292 /// Check if IdxExpr is a valid parameter index for a function or
5293 /// instance method D. May output an error.
5294 ///
5295 /// \returns true if IdxExpr is a valid index.
5296 template <typename AttrInfo>
5297 bool checkFunctionOrMethodParameterIndex(
5298 const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5299 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5300 bool CanIndexVariadicArguments = false) {
5301 assert(isFunctionOrMethodOrBlockForAttrSubject(D));
5302
5303 // In C++ the implicit 'this' function parameter also counts.
5304 // Parameters are counted from one.
5305 bool HP = hasFunctionProto(D);
5306 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
5307 bool IV = HP && isFunctionOrMethodVariadic(D);
5308 unsigned NumParams =
5309 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
5310
5311 std::optional<llvm::APSInt> IdxInt;
5312 if (IdxExpr->isTypeDependent() ||
5313 !(IdxInt = IdxExpr->getIntegerConstantExpr(Ctx: Context))) {
5314 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5315 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5316 << IdxExpr->getSourceRange();
5317 return false;
5318 }
5319
5320 constexpr unsigned Limit = 1 << ParamIdx::IdxBitWidth;
5321 unsigned IdxSource = IdxInt->getLimitedValue(Limit);
5322 if (IdxSource < 1 || IdxSource == Limit ||
5323 ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5324 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5325 << &AI << AttrArgNum << IdxExpr->getSourceRange();
5326 return false;
5327 }
5328 if (HasImplicitThisParam && !CanIndexImplicitThis) {
5329 if (IdxSource == 1) {
5330 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5331 << &AI << IdxExpr->getSourceRange();
5332 return false;
5333 }
5334 }
5335
5336 Idx = ParamIdx(IdxSource, D);
5337 return true;
5338 }
5339
5340 ///@}
5341
5342 //
5343 //
5344 // -------------------------------------------------------------------------
5345 //
5346 //
5347
5348 /// \name C++ Declarations
5349 /// Implementations are in SemaDeclCXX.cpp
5350 ///@{
5351
5352public:
5353 void CheckDelegatingCtorCycles();
5354
5355 /// Called before parsing a function declarator belonging to a function
5356 /// declaration.
5357 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
5358 unsigned TemplateParameterDepth);
5359
5360 /// Called after parsing a function declarator belonging to a function
5361 /// declaration.
5362 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
5363
5364 // Act on C++ namespaces
5365 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5366 SourceLocation NamespaceLoc,
5367 SourceLocation IdentLoc, IdentifierInfo *Ident,
5368 SourceLocation LBrace,
5369 const ParsedAttributesView &AttrList,
5370 UsingDirectiveDecl *&UsingDecl, bool IsNested);
5371
5372 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5373 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5374 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5375
5376 NamespaceDecl *getStdNamespace() const;
5377
5378 /// Retrieve the special "std" namespace, which may require us to
5379 /// implicitly define the namespace.
5380 NamespaceDecl *getOrCreateStdNamespace();
5381
5382 CXXRecordDecl *getStdBadAlloc() const;
5383 EnumDecl *getStdAlignValT() const;
5384
5385 TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const;
5386 FunctionDecl *BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl,
5387 QualType AllocType, SourceLocation);
5388
5389 ValueDecl *tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
5390 const IdentifierInfo *MemberOrBase);
5391
5392 enum class ComparisonCategoryUsage {
5393 /// The '<=>' operator was used in an expression and a builtin operator
5394 /// was selected.
5395 OperatorInExpression,
5396 /// A defaulted 'operator<=>' needed the comparison category. This
5397 /// typically only applies to 'std::strong_ordering', due to the implicit
5398 /// fallback return value.
5399 DefaultedOperator,
5400 /// A builtin needed 'std::strong_ordering' (eg. '__builtin_type_order').
5401 Builtin,
5402 };
5403
5404 /// Lookup the specified comparison category types in the standard
5405 /// library, an check the VarDecls possibly returned by the operator<=>
5406 /// builtins for that type.
5407 ///
5408 /// \return The type of the comparison category type corresponding to the
5409 /// specified Kind, or a null type if an error occurs
5410 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5411 SourceLocation Loc,
5412 ComparisonCategoryUsage Usage);
5413
5414 /// Tests whether Ty is an instance of std::initializer_list and, if
5415 /// it is and Element is not NULL, assigns the element type to Element.
5416 bool isStdInitializerList(QualType Ty, QualType *Element);
5417
5418 /// Tests whether Ty is an instance of std::type_identity and, if
5419 /// it is and TypeArgument is not NULL, assigns the element type to Element.
5420 /// If MalformedDecl is not null, and type_identity was ruled out due to being
5421 /// incorrectly structured despite having the correct name, the faulty Decl
5422 /// will be assigned to MalformedDecl.
5423 bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5424 const Decl **MalformedDecl = nullptr);
5425
5426 /// Looks for the std::initializer_list template and instantiates it
5427 /// with Element, or emits an error if it's not found.
5428 ///
5429 /// \returns The instantiated template, or null on error.
5430 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5431
5432 /// Looks for the std::type_identity template and instantiates it
5433 /// with Type, or returns a null type if type_identity has not been declared
5434 ///
5435 /// \returns The instantiated template, or null if std::type_identity is not
5436 /// declared
5437 QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc);
5438
5439 /// Determine whether Ctor is an initializer-list constructor, as
5440 /// defined in [dcl.init.list]p2.
5441 bool isInitListConstructor(const FunctionDecl *Ctor);
5442
5443 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5444 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5445 SourceLocation IdentLoc,
5446 IdentifierInfo *NamespcName,
5447 const ParsedAttributesView &AttrList);
5448
5449 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5450
5451 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5452 SourceLocation AliasLoc, IdentifierInfo *Alias,
5453 CXXScopeSpec &SS, SourceLocation IdentLoc,
5454 IdentifierInfo *Ident);
5455
5456 /// Remove decls we can't actually see from a lookup being used to declare
5457 /// shadow using decls.
5458 ///
5459 /// \param S - The scope of the potential shadow decl
5460 /// \param Previous - The lookup of a potential shadow decl's name.
5461 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5462
5463 /// Hides a using shadow declaration. This is required by the current
5464 /// using-decl implementation when a resolvable using declaration in a
5465 /// class is followed by a declaration which would hide or override
5466 /// one or more of the using decl's targets; for example:
5467 ///
5468 /// struct Base { void foo(int); };
5469 /// struct Derived : Base {
5470 /// using Base::foo;
5471 /// void foo(int);
5472 /// };
5473 ///
5474 /// The governing language is C++03 [namespace.udecl]p12:
5475 ///
5476 /// When a using-declaration brings names from a base class into a
5477 /// derived class scope, member functions in the derived class
5478 /// override and/or hide member functions with the same name and
5479 /// parameter types in a base class (rather than conflicting).
5480 ///
5481 /// There are two ways to implement this:
5482 /// (1) optimistically create shadow decls when they're not hidden
5483 /// by existing declarations, or
5484 /// (2) don't create any shadow decls (or at least don't make them
5485 /// visible) until we've fully parsed/instantiated the class.
5486 /// The problem with (1) is that we might have to retroactively remove
5487 /// a shadow decl, which requires several O(n) operations because the
5488 /// decl structures are (very reasonably) not designed for removal.
5489 /// (2) avoids this but is very fiddly and phase-dependent.
5490 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5491
5492 /// Determines whether to create a using shadow decl for a particular
5493 /// decl, given the set of decls existing prior to this using lookup.
5494 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5495 const LookupResult &PreviousDecls,
5496 UsingShadowDecl *&PrevShadow);
5497
5498 /// Builds a shadow declaration corresponding to a 'using' declaration.
5499 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5500 NamedDecl *Target,
5501 UsingShadowDecl *PrevDecl);
5502
5503 /// Checks that the given using declaration is not an invalid
5504 /// redeclaration. Note that this is checking only for the using decl
5505 /// itself, not for any ill-formedness among the UsingShadowDecls.
5506 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5507 bool HasTypenameKeyword,
5508 const CXXScopeSpec &SS,
5509 SourceLocation NameLoc,
5510 const LookupResult &Previous);
5511
5512 /// Checks that the given nested-name qualifier used in a using decl
5513 /// in the current context is appropriately related to the current
5514 /// scope. If an error is found, diagnoses it and returns true.
5515 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5516 /// the result of that lookup. UD is likewise nullptr, except when we have an
5517 /// already-populated UsingDecl whose shadow decls contain the same
5518 /// information (i.e. we're instantiating a UsingDecl with non-dependent
5519 /// scope).
5520 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5521 const CXXScopeSpec &SS,
5522 const DeclarationNameInfo &NameInfo,
5523 SourceLocation NameLoc,
5524 const LookupResult *R = nullptr,
5525 const UsingDecl *UD = nullptr);
5526
5527 /// Builds a using declaration.
5528 ///
5529 /// \param IsInstantiation - Whether this call arises from an
5530 /// instantiation of an unresolved using declaration. We treat
5531 /// the lookup differently for these declarations.
5532 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5533 SourceLocation UsingLoc,
5534 bool HasTypenameKeyword,
5535 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5536 DeclarationNameInfo NameInfo,
5537 SourceLocation EllipsisLoc,
5538 const ParsedAttributesView &AttrList,
5539 bool IsInstantiation, bool IsUsingIfExists);
5540 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
5541 SourceLocation UsingLoc,
5542 SourceLocation EnumLoc,
5543 SourceLocation NameLoc,
5544 TypeSourceInfo *EnumType, EnumDecl *ED);
5545 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5546 ArrayRef<NamedDecl *> Expansions);
5547
5548 /// Additional checks for a using declaration referring to a constructor name.
5549 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5550
5551 /// Given a derived-class using shadow declaration for a constructor and the
5552 /// correspnding base class constructor, find or create the implicit
5553 /// synthesized derived class constructor to use for this initialization.
5554 CXXConstructorDecl *
5555 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5556 ConstructorUsingShadowDecl *DerivedShadow);
5557
5558 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5559 SourceLocation UsingLoc,
5560 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5561 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5562 const ParsedAttributesView &AttrList);
5563 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
5564 SourceLocation UsingLoc,
5565 SourceLocation EnumLoc, SourceRange TyLoc,
5566 const IdentifierInfo &II, ParsedType Ty,
5567 const CXXScopeSpec &SS);
5568 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5569 MultiTemplateParamsArg TemplateParams,
5570 SourceLocation UsingLoc, UnqualifiedId &Name,
5571 const ParsedAttributesView &AttrList,
5572 TypeResult Type, Decl *DeclFromDeclSpec);
5573
5574 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5575 /// including handling of its default argument expressions.
5576 ///
5577 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5578 ExprResult BuildCXXConstructExpr(
5579 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5580 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5581 bool HadMultipleCandidates, bool IsListInitialization,
5582 bool IsStdInitListInitialization, bool RequiresZeroInit,
5583 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5584
5585 /// Build a CXXConstructExpr whose constructor has already been resolved if
5586 /// it denotes an inherited constructor.
5587 ExprResult BuildCXXConstructExpr(
5588 SourceLocation ConstructLoc, QualType DeclInitType,
5589 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5590 bool HadMultipleCandidates, bool IsListInitialization,
5591 bool IsStdInitListInitialization, bool RequiresZeroInit,
5592 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5593
5594 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5595 // the constructor can be elidable?
5596 ExprResult BuildCXXConstructExpr(
5597 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5598 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5599 bool HadMultipleCandidates, bool IsListInitialization,
5600 bool IsStdInitListInitialization, bool RequiresZeroInit,
5601 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5602
5603 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr,
5604 SourceLocation InitLoc);
5605 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD,
5606 const InitializedEntity &Entity,
5607 Expr *InitExpr,
5608 SourceLocation InitLoc);
5609
5610 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5611 /// constructed variable.
5612 void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit);
5613
5614 /// Helper class that collects exception specifications for
5615 /// implicitly-declared special member functions.
5616 class ImplicitExceptionSpecification {
5617 // Pointer to allow copying
5618 Sema *Self;
5619 // We order exception specifications thus:
5620 // noexcept is the most restrictive, but is only used in C++11.
5621 // throw() comes next.
5622 // Then a throw(collected exceptions)
5623 // Finally no specification, which is expressed as noexcept(false).
5624 // throw(...) is used instead if any called function uses it.
5625 ExceptionSpecificationType ComputedEST;
5626 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5627 SmallVector<QualType, 4> Exceptions;
5628
5629 void ClearExceptions() {
5630 ExceptionsSeen.clear();
5631 Exceptions.clear();
5632 }
5633
5634 public:
5635 explicit ImplicitExceptionSpecification(Sema &Self)
5636 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5637 if (!Self.getLangOpts().CPlusPlus11)
5638 ComputedEST = EST_DynamicNone;
5639 }
5640
5641 /// Get the computed exception specification type.
5642 ExceptionSpecificationType getExceptionSpecType() const {
5643 assert(!isComputedNoexcept(ComputedEST) &&
5644 "noexcept(expr) should not be a possible result");
5645 return ComputedEST;
5646 }
5647
5648 /// The number of exceptions in the exception specification.
5649 unsigned size() const { return Exceptions.size(); }
5650
5651 /// The set of exceptions in the exception specification.
5652 const QualType *data() const { return Exceptions.data(); }
5653
5654 /// Integrate another called method into the collected data.
5655 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5656
5657 /// Integrate an invoked expression into the collected data.
5658 void CalledExpr(Expr *E) { CalledStmt(S: E); }
5659
5660 /// Integrate an invoked statement into the collected data.
5661 void CalledStmt(Stmt *S);
5662
5663 /// Overwrite an EPI's exception specification with this
5664 /// computed exception specification.
5665 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5666 FunctionProtoType::ExceptionSpecInfo ESI;
5667 ESI.Type = getExceptionSpecType();
5668 if (ESI.Type == EST_Dynamic) {
5669 ESI.Exceptions = Exceptions;
5670 } else if (ESI.Type == EST_None) {
5671 /// C++11 [except.spec]p14:
5672 /// The exception-specification is noexcept(false) if the set of
5673 /// potential exceptions of the special member function contains "any"
5674 ESI.Type = EST_NoexceptFalse;
5675 ESI.NoexceptExpr =
5676 Self->ActOnCXXBoolLiteral(OpLoc: SourceLocation(), Kind: tok::kw_false).get();
5677 }
5678 return ESI;
5679 }
5680 };
5681
5682 /// Evaluate the implicit exception specification for a defaulted
5683 /// special member function.
5684 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5685
5686 /// Check the given exception-specification and update the
5687 /// exception specification information with the results.
5688 void checkExceptionSpecification(bool IsTopLevel,
5689 ExceptionSpecificationType EST,
5690 ArrayRef<ParsedType> DynamicExceptions,
5691 ArrayRef<SourceRange> DynamicExceptionRanges,
5692 Expr *NoexceptExpr,
5693 SmallVectorImpl<QualType> &Exceptions,
5694 FunctionProtoType::ExceptionSpecInfo &ESI);
5695
5696 /// Add an exception-specification to the given member or friend function
5697 /// (or function template). The exception-specification was parsed
5698 /// after the function itself was declared.
5699 void actOnDelayedExceptionSpecification(
5700 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5701 ArrayRef<ParsedType> DynamicExceptions,
5702 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5703
5704 class InheritedConstructorInfo;
5705
5706 /// Determine if a special member function should have a deleted
5707 /// definition when it is defaulted.
5708 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
5709 InheritedConstructorInfo *ICI = nullptr,
5710 bool Diagnose = false);
5711
5712 /// Produce notes explaining why a defaulted function was defined as deleted.
5713 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5714
5715 /// Declare the implicit default constructor for the given class.
5716 ///
5717 /// \param ClassDecl The class declaration into which the implicit
5718 /// default constructor will be added.
5719 ///
5720 /// \returns The implicitly-declared default constructor.
5721 CXXConstructorDecl *
5722 DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl);
5723
5724 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5725 /// defining this constructor as the default constructor.
5726 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5727 CXXConstructorDecl *Constructor);
5728
5729 /// Declare the implicit destructor for the given class.
5730 ///
5731 /// \param ClassDecl The class declaration into which the implicit
5732 /// destructor will be added.
5733 ///
5734 /// \returns The implicitly-declared destructor.
5735 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5736
5737 /// DefineImplicitDestructor - Checks for feasibility of
5738 /// defining this destructor as the default destructor.
5739 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5740 CXXDestructorDecl *Destructor);
5741
5742 /// Build an exception spec for destructors that don't have one.
5743 ///
5744 /// C++11 says that user-defined destructors with no exception spec get one
5745 /// that looks as if the destructor was implicitly declared.
5746 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5747
5748 /// Define the specified inheriting constructor.
5749 void DefineInheritingConstructor(SourceLocation UseLoc,
5750 CXXConstructorDecl *Constructor);
5751
5752 /// Declare the implicit copy constructor for the given class.
5753 ///
5754 /// \param ClassDecl The class declaration into which the implicit
5755 /// copy constructor will be added.
5756 ///
5757 /// \returns The implicitly-declared copy constructor.
5758 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5759
5760 /// DefineImplicitCopyConstructor - Checks for feasibility of
5761 /// defining this constructor as the copy constructor.
5762 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5763 CXXConstructorDecl *Constructor);
5764
5765 /// Declare the implicit move constructor for the given class.
5766 ///
5767 /// \param ClassDecl The Class declaration into which the implicit
5768 /// move constructor will be added.
5769 ///
5770 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5771 /// declared.
5772 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5773
5774 /// DefineImplicitMoveConstructor - Checks for feasibility of
5775 /// defining this constructor as the move constructor.
5776 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5777 CXXConstructorDecl *Constructor);
5778
5779 /// Declare the implicit copy assignment operator for the given class.
5780 ///
5781 /// \param ClassDecl The class declaration into which the implicit
5782 /// copy assignment operator will be added.
5783 ///
5784 /// \returns The implicitly-declared copy assignment operator.
5785 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5786
5787 /// Defines an implicitly-declared copy assignment operator.
5788 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5789 CXXMethodDecl *MethodDecl);
5790
5791 /// Declare the implicit move assignment operator for the given class.
5792 ///
5793 /// \param ClassDecl The Class declaration into which the implicit
5794 /// move assignment operator will be added.
5795 ///
5796 /// \returns The implicitly-declared move assignment operator, or NULL if it
5797 /// wasn't declared.
5798 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5799
5800 /// Defines an implicitly-declared move assignment operator.
5801 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5802 CXXMethodDecl *MethodDecl);
5803
5804 /// Check a completed declaration of an implicit special member.
5805 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5806
5807 /// Determine whether the given function is an implicitly-deleted
5808 /// special member function.
5809 bool isImplicitlyDeleted(FunctionDecl *FD);
5810
5811 /// Check whether 'this' shows up in the type of a static member
5812 /// function after the (naturally empty) cv-qualifier-seq would be.
5813 ///
5814 /// \returns true if an error occurred.
5815 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5816
5817 /// Whether this' shows up in the exception specification of a static
5818 /// member function.
5819 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5820
5821 /// Check whether 'this' shows up in the attributes of the given
5822 /// static member function.
5823 ///
5824 /// \returns true if an error occurred.
5825 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5826
5827 bool CheckImmediateEscalatingFunctionDefinition(
5828 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5829
5830 void DiagnoseImmediateEscalatingReason(FunctionDecl *FD);
5831
5832 /// Given a constructor and the set of arguments provided for the
5833 /// constructor, convert the arguments and add any required default arguments
5834 /// to form a proper call to this constructor.
5835 ///
5836 /// \returns true if an error occurred, false otherwise.
5837 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5838 QualType DeclInitType, MultiExprArg ArgsPtr,
5839 SourceLocation Loc,
5840 SmallVectorImpl<Expr *> &ConvertedArgs,
5841 bool AllowExplicit = false,
5842 bool IsListInitialization = false);
5843
5844 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5845 /// initializer for the declaration 'Dcl'.
5846 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5847 /// static data member of class X, names should be looked up in the scope of
5848 /// class X.
5849 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5850
5851 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5852 /// initializer for the declaration 'Dcl'.
5853 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5854
5855 /// Define the "body" of the conversion from a lambda object to a
5856 /// function pointer.
5857 ///
5858 /// This routine doesn't actually define a sensible body; rather, it fills
5859 /// in the initialization expression needed to copy the lambda object into
5860 /// the block, and IR generation actually generates the real body of the
5861 /// block pointer conversion.
5862 void
5863 DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc,
5864 CXXConversionDecl *Conv);
5865
5866 /// Define the "body" of the conversion from a lambda object to a
5867 /// block pointer.
5868 ///
5869 /// This routine doesn't actually define a sensible body; rather, it fills
5870 /// in the initialization expression needed to copy the lambda object into
5871 /// the block, and IR generation actually generates the real body of the
5872 /// block pointer conversion.
5873 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5874 CXXConversionDecl *Conv);
5875
5876 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5877 /// linkage specification, including the language and (if present)
5878 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5879 /// language string literal. LBraceLoc, if valid, provides the location of
5880 /// the '{' brace. Otherwise, this linkage specification does not
5881 /// have any braces.
5882 Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5883 Expr *LangStr, SourceLocation LBraceLoc);
5884
5885 /// ActOnFinishLinkageSpecification - Complete the definition of
5886 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5887 /// valid, it's the position of the closing '}' brace in a linkage
5888 /// specification that uses braces.
5889 Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec,
5890 SourceLocation RBraceLoc);
5891
5892 //===--------------------------------------------------------------------===//
5893 // C++ Classes
5894 //
5895
5896 /// Get the class that is directly named by the current context. This is the
5897 /// class for which an unqualified-id in this scope could name a constructor
5898 /// or destructor.
5899 ///
5900 /// If the scope specifier denotes a class, this will be that class.
5901 /// If the scope specifier is empty, this will be the class whose
5902 /// member-specification we are currently within. Otherwise, there
5903 /// is no such class.
5904 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
5905
5906 /// isCurrentClassName - Determine whether the identifier II is the
5907 /// name of the class type currently being defined. In the case of
5908 /// nested classes, this will only return true if II is the name of
5909 /// the innermost class.
5910 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5911 const CXXScopeSpec *SS = nullptr);
5912
5913 /// Determine whether the identifier II is a typo for the name of
5914 /// the class type currently being defined. If so, update it to the identifier
5915 /// that should have been used.
5916 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5917
5918 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5919 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
5920 SourceLocation ColonLoc,
5921 const ParsedAttributesView &Attrs);
5922
5923 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5924 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5925 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
5926 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
5927 /// present (but parsing it has been deferred).
5928 NamedDecl *
5929 ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
5930 MultiTemplateParamsArg TemplateParameterLists,
5931 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5932 InClassInitStyle InitStyle);
5933
5934 /// Enter a new C++ default initializer scope. After calling this, the
5935 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
5936 /// parsing or instantiating the initializer failed.
5937 void ActOnStartCXXInClassMemberInitializer();
5938
5939 /// This is invoked after parsing an in-class initializer for a
5940 /// non-static C++ class member, and after instantiating an in-class
5941 /// initializer in a class template. Such actions are deferred until the class
5942 /// is complete.
5943 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5944 SourceLocation EqualLoc,
5945 ExprResult Init);
5946
5947 /// Handle a C++ member initializer using parentheses syntax.
5948 MemInitResult
5949 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
5950 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
5951 const DeclSpec &DS, SourceLocation IdLoc,
5952 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
5953 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
5954
5955 /// Handle a C++ member initializer using braced-init-list syntax.
5956 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
5957 CXXScopeSpec &SS,
5958 IdentifierInfo *MemberOrBase,
5959 ParsedType TemplateTypeTy,
5960 const DeclSpec &DS, SourceLocation IdLoc,
5961 Expr *InitList, SourceLocation EllipsisLoc);
5962
5963 /// Handle a C++ member initializer.
5964 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
5965 CXXScopeSpec &SS,
5966 IdentifierInfo *MemberOrBase,
5967 ParsedType TemplateTypeTy,
5968 const DeclSpec &DS, SourceLocation IdLoc,
5969 Expr *Init, SourceLocation EllipsisLoc);
5970
5971 MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init,
5972 SourceLocation IdLoc);
5973
5974 MemInitResult BuildBaseInitializer(QualType BaseType,
5975 TypeSourceInfo *BaseTInfo, Expr *Init,
5976 CXXRecordDecl *ClassDecl,
5977 SourceLocation EllipsisLoc);
5978
5979 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
5980 CXXRecordDecl *ClassDecl);
5981
5982 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5983 CXXCtorInitializer *Initializer);
5984
5985 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5986 ArrayRef<CXXCtorInitializer *> Initializers = {});
5987
5988 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5989 /// mark all the non-trivial destructors of its members and bases as
5990 /// referenced.
5991 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5992 CXXRecordDecl *Record);
5993
5994 /// Mark destructors of virtual bases of this class referenced. In the Itanium
5995 /// C++ ABI, this is done when emitting a destructor for any non-abstract
5996 /// class. In the Microsoft C++ ABI, this is done any time a class's
5997 /// destructor is referenced.
5998 void MarkVirtualBaseDestructorsReferenced(
5999 SourceLocation Location, CXXRecordDecl *ClassDecl,
6000 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
6001 nullptr);
6002
6003 /// Do semantic checks to allow the complete destructor variant to be emitted
6004 /// when the destructor is defined in another translation unit. In the Itanium
6005 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
6006 /// can be emitted in separate TUs. To emit the complete variant, run a subset
6007 /// of the checks performed when emitting a regular destructor.
6008 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
6009 CXXDestructorDecl *Dtor);
6010
6011 /// The list of classes whose vtables have been used within
6012 /// this translation unit, and the source locations at which the
6013 /// first use occurred.
6014 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
6015
6016 /// The list of vtables that are required but have not yet been
6017 /// materialized.
6018 SmallVector<VTableUse, 16> VTableUses;
6019
6020 /// The set of classes whose vtables have been used within
6021 /// this translation unit, and a bit that will be true if the vtable is
6022 /// required to be emitted (otherwise, it should be emitted only if needed
6023 /// by code generation).
6024 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
6025
6026 /// Load any externally-stored vtable uses.
6027 void LoadExternalVTableUses();
6028
6029 /// Note that the vtable for the given class was used at the
6030 /// given location.
6031 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6032 bool DefinitionRequired = false);
6033
6034 /// Mark the exception specifications of all virtual member functions
6035 /// in the given class as needed.
6036 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
6037 const CXXRecordDecl *RD);
6038
6039 /// MarkVirtualMembersReferenced - Will mark all members of the given
6040 /// CXXRecordDecl referenced.
6041 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
6042 bool ConstexprOnly = false);
6043
6044 /// Define all of the vtables that have been used in this
6045 /// translation unit and reference any virtual members used by those
6046 /// vtables.
6047 ///
6048 /// \returns true if any work was done, false otherwise.
6049 bool DefineUsedVTables();
6050
6051 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6052 /// special functions, such as the default constructor, copy
6053 /// constructor, or destructor, to the given C++ class (C++
6054 /// [special]p1). This routine can only be executed just before the
6055 /// definition of the class is complete.
6056 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
6057
6058 /// ActOnMemInitializers - Handle the member initializers for a constructor.
6059 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
6060 ArrayRef<CXXCtorInitializer *> MemInits,
6061 bool AnyErrors);
6062
6063 /// Check class-level dllimport/dllexport attribute. The caller must
6064 /// ensure that referenceDLLExportedClassMethods is called some point later
6065 /// when all outer classes of Class are complete.
6066 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
6067 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
6068
6069 void referenceDLLExportedClassMethods();
6070
6071 /// Perform propagation of DLL attributes from a derived class to a
6072 /// templated base class for MS compatibility.
6073 void propagateDLLAttrToBaseClassTemplate(
6074 CXXRecordDecl *Class, Attr *ClassAttr,
6075 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6076 SourceLocation BaseLoc);
6077
6078 /// Perform semantic checks on a class definition that has been
6079 /// completing, introducing implicitly-declared members, checking for
6080 /// abstract types, etc.
6081 ///
6082 /// \param S The scope in which the class was parsed. Null if we didn't just
6083 /// parse a class definition.
6084 /// \param Record The completed class.
6085 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
6086
6087 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6088 /// conditions that are needed for the attribute to have an effect.
6089 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6090
6091 /// Check that VTable Pointer authentication is only being set on the first
6092 /// first instantiation of the vtable
6093 void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD);
6094
6095 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6096 Decl *TagDecl, SourceLocation LBrac,
6097 SourceLocation RBrac,
6098 const ParsedAttributesView &AttrList);
6099
6100 /// Perform any semantic analysis which needs to be delayed until all
6101 /// pending class member declarations have been parsed.
6102 void ActOnFinishCXXMemberDecls();
6103 void ActOnFinishCXXNonNestedClass();
6104
6105 /// This is used to implement the constant expression evaluation part of the
6106 /// attribute enable_if extension. There is nothing in standard C++ which
6107 /// would require reentering parameters.
6108 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6109 unsigned ActOnReenterTemplateScope(Decl *Template,
6110 llvm::function_ref<Scope *()> EnterScope);
6111 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6112
6113 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6114 /// parsing a top-level (non-nested) C++ class, and we are now
6115 /// parsing those parts of the given Method declaration that could
6116 /// not be parsed earlier (C++ [class.mem]p2), such as default
6117 /// arguments. This action should enter the scope of the given
6118 /// Method declaration as if we had just parsed the qualified method
6119 /// name. However, it should not bring the parameters into scope;
6120 /// that will be performed by ActOnDelayedCXXMethodParameter.
6121 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6122 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6123 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6124
6125 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6126 /// processing the delayed method declaration for Method. The method
6127 /// declaration is now considered finished. There may be a separate
6128 /// ActOnStartOfFunctionDef action later (not necessarily
6129 /// immediately!) for this method, if it was also defined inside the
6130 /// class body.
6131 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6132 void ActOnFinishDelayedMemberInitializers(Decl *Record);
6133
6134 enum class StringEvaluationContext { StaticAssert = 0, Asm = 1 };
6135
6136 bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
6137 StringEvaluationContext EvalContext,
6138 bool ErrorOnInvalidMessage);
6139 bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
6140 StringEvaluationContext EvalContext,
6141 bool ErrorOnInvalidMessage);
6142
6143 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6144 Expr *AssertExpr, Expr *AssertMessageExpr,
6145 SourceLocation RParenLoc);
6146 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6147 Expr *AssertExpr, Expr *AssertMessageExpr,
6148 SourceLocation RParenLoc, bool Failed);
6149
6150 /// Try to print more useful information about a failed static_assert
6151 /// with expression \E
6152 void DiagnoseStaticAssertDetails(const Expr *E);
6153
6154 /// If E represents a built-in type trait, or a known standard type trait,
6155 /// try to print more information about why the type type-trait failed.
6156 /// This assumes we already evaluated the expression to a false boolean value.
6157 void DiagnoseTypeTraitDetails(const Expr *E);
6158
6159 /// Handle a friend type declaration. This works in tandem with
6160 /// ActOnTag.
6161 ///
6162 /// Notes on friend class templates:
6163 ///
6164 /// We generally treat friend class declarations as if they were
6165 /// declaring a class. So, for example, the elaborated type specifier
6166 /// in a friend declaration is required to obey the restrictions of a
6167 /// class-head (i.e. no typedefs in the scope chain), template
6168 /// parameters are required to match up with simple template-ids, &c.
6169 /// However, unlike when declaring a template specialization, it's
6170 /// okay to refer to a template specialization without an empty
6171 /// template parameter declaration, e.g.
6172 /// friend class A<T>::B<unsigned>;
6173 /// We permit this as a special case; if there are any template
6174 /// parameters present at all, require proper matching, i.e.
6175 /// template <> template \<class T> friend class A<int>::B;
6176 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6177 MultiTemplateParamsArg TemplateParams,
6178 SourceLocation EllipsisLoc);
6179 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6180 MultiTemplateParamsArg TemplateParams);
6181
6182 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6183 /// the well-formedness of the constructor declarator @p D with type @p
6184 /// R. If there are any errors in the declarator, this routine will
6185 /// emit diagnostics and set the invalid bit to true. In any case, the type
6186 /// will be updated to reflect a well-formed type for the constructor and
6187 /// returned.
6188 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6189 StorageClass &SC);
6190
6191 /// CheckConstructor - Checks a fully-formed constructor for
6192 /// well-formedness, issuing any diagnostics required. Returns true if
6193 /// the constructor declarator is invalid.
6194 void CheckConstructor(CXXConstructorDecl *Constructor);
6195
6196 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6197 /// the well-formednes of the destructor declarator @p D with type @p
6198 /// R. If there are any errors in the declarator, this routine will
6199 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6200 /// will be updated to reflect a well-formed type for the destructor and
6201 /// returned.
6202 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6203 StorageClass &SC);
6204
6205 /// CheckDestructor - Checks a fully-formed destructor definition for
6206 /// well-formedness, issuing any diagnostics required. Returns true
6207 /// on error.
6208 bool CheckDestructor(CXXDestructorDecl *Destructor);
6209
6210 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6211 /// well-formednes of the conversion function declarator @p D with
6212 /// type @p R. If there are any errors in the declarator, this routine
6213 /// will emit diagnostics and return true. Otherwise, it will return
6214 /// false. Either way, the type @p R will be updated to reflect a
6215 /// well-formed type for the conversion operator.
6216 void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC);
6217
6218 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6219 /// the declaration of the given C++ conversion function. This routine
6220 /// is responsible for recording the conversion function in the C++
6221 /// class, if possible.
6222 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6223
6224 /// Check the validity of a declarator that we parsed for a deduction-guide.
6225 /// These aren't actually declarators in the grammar, so we need to check that
6226 /// the user didn't specify any pieces that are not part of the
6227 /// deduction-guide grammar. Return true on invalid deduction-guide.
6228 bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6229 StorageClass &SC);
6230
6231 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6232
6233 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6234 CXXSpecialMemberKind CSM,
6235 SourceLocation DefaultLoc);
6236 void CheckDelayedMemberExceptionSpecs();
6237
6238 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6239 DefaultedComparisonKind DCK);
6240 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6241 FunctionDecl *Spaceship);
6242 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6243 DefaultedComparisonKind DCK);
6244
6245 void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name,
6246 QualType R, bool IsLambda,
6247 DeclContext *DC = nullptr);
6248 void CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
6249 DeclarationName Name, QualType R);
6250 void CheckExplicitObjectLambda(Declarator &D);
6251
6252 //===--------------------------------------------------------------------===//
6253 // C++ Derived Classes
6254 //
6255
6256 /// Check the validity of a C++ base class specifier.
6257 ///
6258 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6259 /// and returns NULL otherwise.
6260 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6261 SourceRange SpecifierRange, bool Virtual,
6262 AccessSpecifier Access,
6263 TypeSourceInfo *TInfo,
6264 SourceLocation EllipsisLoc);
6265
6266 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6267 /// one entry in the base class list of a class specifier, for
6268 /// example:
6269 /// class foo : public bar, virtual private baz {
6270 /// 'public bar' and 'virtual private baz' are each base-specifiers.
6271 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6272 const ParsedAttributesView &Attrs, bool Virtual,
6273 AccessSpecifier Access, ParsedType basetype,
6274 SourceLocation BaseLoc,
6275 SourceLocation EllipsisLoc);
6276
6277 /// Performs the actual work of attaching the given base class
6278 /// specifiers to a C++ class.
6279 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6280 MutableArrayRef<CXXBaseSpecifier *> Bases);
6281
6282 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6283 /// class, after checking whether there are any duplicate base
6284 /// classes.
6285 void ActOnBaseSpecifiers(Decl *ClassDecl,
6286 MutableArrayRef<CXXBaseSpecifier *> Bases);
6287
6288 /// Determine whether the type \p Derived is a C++ class that is
6289 /// derived from the type \p Base.
6290 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6291 CXXRecordDecl *Base, CXXBasePaths &Paths);
6292 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6293 CXXRecordDecl *Base);
6294 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6295 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6296 CXXBasePaths &Paths);
6297
6298 // FIXME: I don't like this name.
6299 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6300
6301 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6302 SourceLocation Loc, SourceRange Range,
6303 CXXCastPath *BasePath = nullptr,
6304 bool IgnoreAccess = false);
6305
6306 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6307 /// conversion (where Derived and Base are class types) is
6308 /// well-formed, meaning that the conversion is unambiguous (and
6309 /// that all of the base classes are accessible). Returns true
6310 /// and emits a diagnostic if the code is ill-formed, returns false
6311 /// otherwise. Loc is the location where this routine should point to
6312 /// if there is an error, and Range is the source range to highlight
6313 /// if there is an error.
6314 ///
6315 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6316 /// diagnostic for the respective type of error will be suppressed, but the
6317 /// check for ill-formed code will still be performed.
6318 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6319 unsigned InaccessibleBaseID,
6320 unsigned AmbiguousBaseConvID,
6321 SourceLocation Loc, SourceRange Range,
6322 DeclarationName Name, CXXCastPath *BasePath,
6323 bool IgnoreAccess = false);
6324
6325 /// Builds a string representing ambiguous paths from a
6326 /// specific derived class to different subobjects of the same base
6327 /// class.
6328 ///
6329 /// This function builds a string that can be used in error messages
6330 /// to show the different paths that one can take through the
6331 /// inheritance hierarchy to go from the derived class to different
6332 /// subobjects of a base class. The result looks something like this:
6333 /// @code
6334 /// struct D -> struct B -> struct A
6335 /// struct D -> struct C -> struct A
6336 /// @endcode
6337 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6338
6339 bool CheckOverridingFunctionAttributes(CXXMethodDecl *New,
6340 const CXXMethodDecl *Old);
6341
6342 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6343 /// covariant, according to C++ [class.virtual]p5.
6344 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6345 const CXXMethodDecl *Old);
6346
6347 // Check that the overriding method has no explicit object parameter.
6348 bool CheckExplicitObjectOverride(CXXMethodDecl *New,
6349 const CXXMethodDecl *Old);
6350
6351 /// Mark the given method pure.
6352 ///
6353 /// \param Method the method to be marked pure.
6354 ///
6355 /// \param InitRange the source range that covers the "0" initializer.
6356 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6357
6358 /// CheckOverrideControl - Check C++11 override control semantics.
6359 void CheckOverrideControl(NamedDecl *D);
6360
6361 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6362 /// not used in the declaration of an overriding method.
6363 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
6364
6365 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6366 /// function overrides a virtual member function marked 'final', according to
6367 /// C++11 [class.virtual]p4.
6368 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6369 const CXXMethodDecl *Old);
6370
6371 enum AbstractDiagSelID {
6372 AbstractNone = -1,
6373 AbstractReturnType,
6374 AbstractParamType,
6375 AbstractVariableType,
6376 AbstractFieldType,
6377 AbstractIvarType,
6378 AbstractSynthesizedIvarType,
6379 AbstractArrayType
6380 };
6381
6382 struct TypeDiagnoser;
6383
6384 bool isAbstractType(SourceLocation Loc, QualType T);
6385 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6386 TypeDiagnoser &Diagnoser);
6387 template <typename... Ts>
6388 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6389 const Ts &...Args) {
6390 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6391 return RequireNonAbstractType(Loc, T, Diagnoser);
6392 }
6393
6394 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6395
6396 //===--------------------------------------------------------------------===//
6397 // C++ Overloaded Operators [C++ 13.5]
6398 //
6399
6400 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6401 /// of this overloaded operator is well-formed. If so, returns false;
6402 /// otherwise, emits appropriate diagnostics and returns true.
6403 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6404
6405 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6406 /// of this literal operator function is well-formed. If so, returns
6407 /// false; otherwise, emits appropriate diagnostics and returns true.
6408 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6409
6410 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6411 /// found in an explicit(bool) specifier.
6412 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
6413
6414 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6415 /// Returns true if the explicit specifier is now resolved.
6416 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
6417
6418 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6419 /// C++ if/switch/while/for statement.
6420 /// e.g: "if (int x = f()) {...}"
6421 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
6422
6423 // Emitting members of dllexported classes is delayed until the class
6424 // (including field initializers) is fully parsed.
6425 SmallVector<CXXRecordDecl *, 4> DelayedDllExportClasses;
6426 SmallVector<CXXMethodDecl *, 4> DelayedDllExportMemberFunctions;
6427
6428 /// Merge the exception specifications of two variable declarations.
6429 ///
6430 /// This is called when there's a redeclaration of a VarDecl. The function
6431 /// checks if the redeclaration might have an exception specification and
6432 /// validates compatibility and merges the specs if necessary.
6433 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
6434
6435 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6436 /// function, once we already know that they have the same
6437 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6438 /// error, false otherwise.
6439 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
6440
6441 /// Helpers for dealing with blocks and functions.
6442 void CheckCXXDefaultArguments(FunctionDecl *FD);
6443
6444 /// CheckExtraCXXDefaultArguments - Check for any extra default
6445 /// arguments in the declarator, which is not a function declaration
6446 /// or definition and therefore is not permitted to have default
6447 /// arguments. This routine should be invoked for every declarator
6448 /// that is not a function declaration or definition.
6449 void CheckExtraCXXDefaultArguments(Declarator &D);
6450
6451 /// Perform semantic analysis for the variable declaration that
6452 /// occurs within a C++ catch clause, returning the newly-created
6453 /// variable.
6454 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
6455 SourceLocation StartLoc,
6456 SourceLocation IdLoc,
6457 const IdentifierInfo *Id);
6458
6459 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6460 /// handler.
6461 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
6462
6463 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
6464
6465 /// Handle a friend tag declaration where the scope specifier was
6466 /// templated.
6467 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6468 unsigned TagSpec, SourceLocation TagLoc,
6469 CXXScopeSpec &SS, IdentifierInfo *Name,
6470 SourceLocation NameLoc,
6471 SourceLocation EllipsisLoc,
6472 const ParsedAttributesView &Attr,
6473 MultiTemplateParamsArg TempParamLists,
6474 TemplateIdAnnotation *TemplateId);
6475
6476 bool CheckDependentFriend(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc,
6477 ArrayRef<TemplateParameterList *> TPLs,
6478 bool IsInstantiation);
6479
6480 bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc,
6481 NestedNameSpecifierLoc NNSLoc);
6482
6483 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
6484 SourceLocation DeclStart, Declarator &D,
6485 Expr *BitfieldWidth,
6486 InClassInitStyle InitStyle,
6487 AccessSpecifier AS,
6488 const ParsedAttr &MSPropertyAttr);
6489
6490 /// Diagnose why the specified class does not have a trivial special member of
6491 /// the given kind.
6492 void DiagnoseNontrivial(const CXXRecordDecl *Record,
6493 CXXSpecialMemberKind CSM);
6494
6495 /// Determine whether a defaulted or deleted special member function is
6496 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6497 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6498 bool SpecialMemberIsTrivial(
6499 CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
6500 TrivialABIHandling TAH = TrivialABIHandling::IgnoreTrivialABI,
6501 bool Diagnose = false);
6502
6503 /// Handle a C++11 empty-declaration and attribute-declaration.
6504 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
6505 SourceLocation SemiLoc);
6506
6507 enum class CheckConstexprKind {
6508 /// Diagnose issues that are non-constant or that are extensions.
6509 Diagnose,
6510 /// Identify whether this function satisfies the formal rules for constexpr
6511 /// functions in the current lanugage mode (with no extensions).
6512 CheckValid
6513 };
6514
6515 // Check whether a function declaration satisfies the requirements of a
6516 // constexpr function definition or a constexpr constructor definition. If so,
6517 // return true. If not, produce appropriate diagnostics (unless asked not to
6518 // by Kind) and return false.
6519 //
6520 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6521 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
6522 CheckConstexprKind Kind);
6523
6524 /// Diagnose methods which overload virtual methods in a base class
6525 /// without overriding any.
6526 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
6527
6528 /// Check if a method overloads virtual methods in a base class without
6529 /// overriding any.
6530 void
6531 FindHiddenVirtualMethods(CXXMethodDecl *MD,
6532 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6533 void
6534 NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6535 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6536
6537 /// ActOnParamDefaultArgument - Check whether the default argument
6538 /// provided for a function parameter is well-formed. If so, attach it
6539 /// to the parameter declaration.
6540 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6541 Expr *defarg);
6542
6543 /// ActOnParamUnparsedDefaultArgument - We've seen a default
6544 /// argument for a function parameter, but we can't parse it yet
6545 /// because we're inside a class definition. Note that this default
6546 /// argument will be parsed later.
6547 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
6548 SourceLocation ArgLoc);
6549
6550 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6551 /// the default argument for the parameter param failed.
6552 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
6553 Expr *DefaultArg);
6554 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6555 SourceLocation EqualLoc);
6556 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6557 SourceLocation EqualLoc);
6558
6559 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6560 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6561 StringLiteral *Message = nullptr);
6562 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
6563
6564 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6565 StringLiteral *DeletedMessage = nullptr);
6566 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
6567 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
6568 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
6569
6570 NamedDecl *
6571 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
6572 MultiTemplateParamsArg TemplateParamLists);
6573 void DiagPlaceholderVariableDefinition(SourceLocation Loc);
6574 bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
6575 RecordDecl *ClassDecl,
6576 const IdentifierInfo *Name);
6577
6578 UnsignedOrNone GetDecompositionElementCount(QualType DecompType,
6579 SourceLocation Loc);
6580 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
6581
6582 /// Stack containing information needed when in C++2a an 'auto' is encountered
6583 /// in a function declaration parameter type specifier in order to invent a
6584 /// corresponding template parameter in the enclosing abbreviated function
6585 /// template. This information is also present in LambdaScopeInfo, stored in
6586 /// the FunctionScopes stack.
6587 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
6588
6589 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6590 std::unique_ptr<CXXFieldCollector> FieldCollector;
6591
6592 typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType;
6593 /// Set containing all declared private fields that are not used.
6594 NamedDeclSetType UnusedPrivateFields;
6595
6596 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 8> RecordDeclSetTy;
6597
6598 /// PureVirtualClassDiagSet - a set of class declarations which we have
6599 /// emitted a list of pure virtual functions. Used to prevent emitting the
6600 /// same list more than once.
6601 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6602
6603 typedef LazyVector<CXXConstructorDecl *,
6604 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
6605 DelegatingCtorDeclsType;
6606
6607 /// All the delegating constructors seen so far in the file, used for
6608 /// cycle detection at the end of the TU.
6609 DelegatingCtorDeclsType DelegatingCtorDecls;
6610
6611 /// The C++ "std" namespace, where the standard library resides.
6612 LazyDeclPtr StdNamespace;
6613
6614 /// The C++ "std::initializer_list" template, which is defined in
6615 /// \<initializer_list>.
6616 ClassTemplateDecl *StdInitializerList;
6617
6618 /// The C++ "std::type_identity" template, which is defined in
6619 /// \<type_traits>.
6620 ClassTemplateDecl *StdTypeIdentity;
6621
6622 // Contains the locations of the beginning of unparsed default
6623 // argument locations.
6624 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6625
6626 /// UndefinedInternals - all the used, undefined objects which require a
6627 /// definition in this translation unit.
6628 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6629
6630 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6631 SpecialMemberDecl;
6632
6633 /// The C++ special members which we are currently in the process of
6634 /// declaring. If this process recursively triggers the declaration of the
6635 /// same special member, we should act as if it is not yet declared.
6636 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
6637
6638 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
6639
6640 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6641
6642 typedef ProcessingContextState ParsingClassState;
6643 ParsingClassState PushParsingClass() {
6644 ParsingClassDepth++;
6645 return DelayedDiagnostics.pushUndelayed();
6646 }
6647 void PopParsingClass(ParsingClassState state) {
6648 ParsingClassDepth--;
6649 DelayedDiagnostics.popUndelayed(state);
6650 }
6651
6652 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
6653 CXXScopeSpec &SS,
6654 ParsedType TemplateTypeTy,
6655 IdentifierInfo *MemberOrBase);
6656
6657private:
6658 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6659 QualType ResultTy,
6660 ArrayRef<QualType> Args);
6661 // Helper for ActOnFields to check for all function pointer members.
6662 bool EntirelyFunctionPointers(const RecordDecl *Record);
6663
6664 // A cache representing if we've fully checked the various comparison category
6665 // types stored in ASTContext. The bit-index corresponds to the integer value
6666 // of a ComparisonCategoryType enumerator.
6667 llvm::SmallBitVector FullyCheckedComparisonCategories;
6668
6669 /// Check if there is a field shadowing.
6670 void CheckShadowInheritedFields(const SourceLocation &Loc,
6671 DeclarationName FieldName,
6672 const CXXRecordDecl *RD,
6673 bool DeclIsField = true);
6674
6675 ///@}
6676
6677 //
6678 //
6679 // -------------------------------------------------------------------------
6680 //
6681 //
6682
6683 /// \name C++ Exception Specifications
6684 /// Implementations are in SemaExceptionSpec.cpp
6685 ///@{
6686
6687public:
6688 /// All the overriding functions seen during a class definition
6689 /// that had their exception spec checks delayed, plus the overridden
6690 /// function.
6691 SmallVector<std::pair<const CXXMethodDecl *, const CXXMethodDecl *>, 2>
6692 DelayedOverridingExceptionSpecChecks;
6693
6694 /// All the function redeclarations seen during a class definition that had
6695 /// their exception spec checks delayed, plus the prior declaration they
6696 /// should be checked against. Except during error recovery, the new decl
6697 /// should always be a friend declaration, as that's the only valid way to
6698 /// redeclare a special member before its class is complete.
6699 SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 2>
6700 DelayedEquivalentExceptionSpecChecks;
6701
6702 /// Determine if we're in a case where we need to (incorrectly) eagerly
6703 /// parse an exception specification to work around a libstdc++ bug.
6704 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6705
6706 /// Check the given noexcept-specifier, convert its expression, and compute
6707 /// the appropriate ExceptionSpecificationType.
6708 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6709 ExceptionSpecificationType &EST);
6710
6711 CanThrowResult canThrow(const Stmt *E);
6712 /// Determine whether the callee of a particular function call can throw.
6713 /// E, D and Loc are all optional.
6714 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6715 SourceLocation Loc = SourceLocation());
6716 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
6717 const FunctionProtoType *FPT);
6718 void UpdateExceptionSpec(FunctionDecl *FD,
6719 const FunctionProtoType::ExceptionSpecInfo &ESI);
6720
6721 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6722 /// exception specification. Incomplete types, or pointers to incomplete types
6723 /// other than void are not allowed.
6724 ///
6725 /// \param[in,out] T The exception type. This will be decayed to a pointer
6726 /// type
6727 /// when the input is an array or a function type.
6728 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
6729
6730 /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6731 /// pointer to member to a function with an exception specification. This
6732 /// means that it is invalid to add another level of indirection.
6733 bool CheckDistantExceptionSpec(QualType T);
6734 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
6735
6736 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6737 /// exception specifications. Exception specifications are equivalent if
6738 /// they allow exactly the same set of exception types. It does not matter how
6739 /// that is achieved. See C++ [except.spec]p2.
6740 bool CheckEquivalentExceptionSpec(const FunctionProtoType *Old,
6741 SourceLocation OldLoc,
6742 const FunctionProtoType *New,
6743 SourceLocation NewLoc);
6744 bool CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
6745 const PartialDiagnostic &NoteID,
6746 const FunctionProtoType *Old,
6747 SourceLocation OldLoc,
6748 const FunctionProtoType *New,
6749 SourceLocation NewLoc);
6750 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6751
6752 /// CheckExceptionSpecSubset - Check whether the second function type's
6753 /// exception specification is a subset (or equivalent) of the first function
6754 /// type. This is used by override and pointer assignment checks.
6755 bool CheckExceptionSpecSubset(
6756 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6757 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6758 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6759 SourceLocation SuperLoc, const FunctionProtoType *Subset,
6760 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6761
6762 /// CheckParamExceptionSpec - Check if the parameter and return types of the
6763 /// two functions have equivalent exception specs. This is part of the
6764 /// assignment and override compatibility check. We do not check the
6765 /// parameters of parameter function pointers recursively, as no sane
6766 /// programmer would even be able to write such a function type.
6767 bool CheckParamExceptionSpec(
6768 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6769 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6770 SourceLocation TargetLoc, const FunctionProtoType *Source,
6771 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6772
6773 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6774
6775 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6776 /// spec is a subset of base spec.
6777 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6778 const CXXMethodDecl *Old);
6779
6780 ///@}
6781
6782 //
6783 //
6784 // -------------------------------------------------------------------------
6785 //
6786 //
6787
6788 /// \name Expressions
6789 /// Implementations are in SemaExpr.cpp
6790 ///@{
6791
6792public:
6793 /// Describes how the expressions currently being parsed are
6794 /// evaluated at run-time, if at all.
6795 enum class ExpressionEvaluationContext {
6796 /// The current expression and its subexpressions occur within an
6797 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6798 /// \c sizeof, where the type of the expression may be significant but
6799 /// no code will be generated to evaluate the value of the expression at
6800 /// run time.
6801 Unevaluated,
6802
6803 /// The current expression occurs within a braced-init-list within
6804 /// an unevaluated operand. This is mostly like a regular unevaluated
6805 /// context, except that we still instantiate constexpr functions that are
6806 /// referenced here so that we can perform narrowing checks correctly.
6807 UnevaluatedList,
6808
6809 /// The current expression occurs within a discarded statement.
6810 /// This behaves largely similarly to an unevaluated operand in preventing
6811 /// definitions from being required, but not in other ways.
6812 DiscardedStatement,
6813
6814 /// The current expression occurs within an unevaluated
6815 /// operand that unconditionally permits abstract references to
6816 /// fields, such as a SIZE operator in MS-style inline assembly.
6817 UnevaluatedAbstract,
6818
6819 /// The current context is "potentially evaluated" in C++11 terms,
6820 /// but the expression is evaluated at compile-time (like the values of
6821 /// cases in a switch statement).
6822 ConstantEvaluated,
6823
6824 /// In addition of being constant evaluated, the current expression
6825 /// occurs in an immediate function context - either a consteval function
6826 /// or a consteval if statement.
6827 ImmediateFunctionContext,
6828
6829 /// The current expression is potentially evaluated at run time,
6830 /// which means that code may be generated to evaluate the value of the
6831 /// expression at run time.
6832 PotentiallyEvaluated,
6833
6834 /// The current expression is potentially evaluated, but any
6835 /// declarations referenced inside that expression are only used if
6836 /// in fact the current expression is used.
6837 ///
6838 /// This value is used when parsing default function arguments, for which
6839 /// we would like to provide diagnostics (e.g., passing non-POD arguments
6840 /// through varargs) but do not want to mark declarations as "referenced"
6841 /// until the default argument is used.
6842 PotentiallyEvaluatedIfUsed
6843 };
6844
6845 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6846 /// to a variable (constant) that may or may not be odr-used in this Expr, and
6847 /// we won't know until all lvalue-to-rvalue and discarded value conversions
6848 /// have been applied to all subexpressions of the enclosing full expression.
6849 /// This is cleared at the end of each full expression.
6850 using MaybeODRUseExprSet = llvm::SmallSetVector<Expr *, 4>;
6851 MaybeODRUseExprSet MaybeODRUseExprs;
6852
6853 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6854
6855 /// Data structure used to record current or nested
6856 /// expression evaluation contexts.
6857 struct ExpressionEvaluationContextRecord {
6858 /// The expression evaluation context.
6859 ExpressionEvaluationContext Context;
6860
6861 /// Whether the enclosing context needed a cleanup.
6862 CleanupInfo ParentCleanup;
6863
6864 /// The number of active cleanup objects when we entered
6865 /// this expression evaluation context.
6866 unsigned NumCleanupObjects;
6867
6868 MaybeODRUseExprSet SavedMaybeODRUseExprs;
6869
6870 /// The lambdas that are present within this context, if it
6871 /// is indeed an unevaluated context.
6872 SmallVector<LambdaExpr *, 2> Lambdas;
6873
6874 /// The declaration that provides context for lambda expressions
6875 /// and block literals if the normal declaration context does not
6876 /// suffice, e.g., in a default function argument.
6877 Decl *ManglingContextDecl;
6878
6879 /// Declaration for initializer if one is currently being
6880 /// parsed. Used when an expression has a possibly unreachable
6881 /// diagnostic to reference the declaration as a whole.
6882 VarDecl *DeclForInitializer = nullptr;
6883
6884 /// If we are processing a decltype type, a set of call expressions
6885 /// for which we have deferred checking the completeness of the return type.
6886 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
6887
6888 /// If we are processing a decltype type, a set of temporary binding
6889 /// expressions for which we have deferred checking the destructor.
6890 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
6891
6892 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
6893
6894 /// Expressions appearing as the LHS of a volatile assignment in this
6895 /// context. We produce a warning for these when popping the context if
6896 /// they are not discarded-value expressions nor unevaluated operands.
6897 SmallVector<Expr *, 2> VolatileAssignmentLHSs;
6898
6899 /// Set of candidates for starting an immediate invocation.
6900 llvm::SmallVector<ImmediateInvocationCandidate, 4>
6901 ImmediateInvocationCandidates;
6902
6903 /// Set of DeclRefExprs referencing a consteval function when used in a
6904 /// context not already known to be immediately invoked.
6905 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
6906
6907 /// P2718R0 - Lifetime extension in range-based for loops.
6908 /// MaterializeTemporaryExprs in for-range-init expressions which need to
6909 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
6910 /// InLifetimeExtendingContext is true.
6911 SmallVector<MaterializeTemporaryExpr *, 8> ForRangeLifetimeExtendTemps;
6912
6913 /// Small set of gathered accesses to potentially misaligned members
6914 /// due to the packed attribute.
6915 SmallVector<MisalignedMember, 4> MisalignedMembers;
6916
6917 /// \brief Describes whether we are in an expression constext which we have
6918 /// to handle differently.
6919 enum ExpressionKind {
6920 EK_Decltype,
6921 EK_TemplateArgument,
6922 EK_AttrArgument,
6923 EK_VariableInit,
6924 EK_Other
6925 } ExprContext;
6926
6927 // A context can be nested in both a discarded statement context and
6928 // an immediate function context, so they need to be tracked independently.
6929 bool InDiscardedStatement;
6930 bool InImmediateFunctionContext;
6931 bool InImmediateEscalatingFunctionContext;
6932
6933 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
6934
6935 // We are in a constant context, but we also allow
6936 // non constant expressions, for example for array bounds (which may be
6937 // VLAs).
6938 bool InConditionallyConstantEvaluateContext = false;
6939
6940 /// Whether we are currently in a context in which all temporaries must be
6941 /// lifetime-extended, even if they're not bound to a reference (for
6942 /// example, in a for-range initializer).
6943 bool InLifetimeExtendingContext = false;
6944
6945 /// Whether evaluating an expression for a switch case label.
6946 bool IsCaseExpr = false;
6947
6948 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
6949 bool RebuildDefaultArgOrDefaultInit = false;
6950
6951 // When evaluating immediate functions in the initializer of a default
6952 // argument or default member initializer, this is the declaration whose
6953 // default initializer is being evaluated and the location of the call
6954 // or constructor definition.
6955 struct InitializationContext {
6956 InitializationContext(SourceLocation Loc, ValueDecl *Decl,
6957 DeclContext *Context)
6958 : Loc(Loc), Decl(Decl), Context(Context) {
6959 assert(Decl && Context && "invalid initialization context");
6960 }
6961
6962 SourceLocation Loc;
6963 ValueDecl *Decl = nullptr;
6964 DeclContext *Context = nullptr;
6965 };
6966 std::optional<InitializationContext> DelayedDefaultInitializationContext;
6967
6968 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
6969 unsigned NumCleanupObjects,
6970 CleanupInfo ParentCleanup,
6971 Decl *ManglingContextDecl,
6972 ExpressionKind ExprContext)
6973 : Context(Context), ParentCleanup(ParentCleanup),
6974 NumCleanupObjects(NumCleanupObjects),
6975 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
6976 InDiscardedStatement(false), InImmediateFunctionContext(false),
6977 InImmediateEscalatingFunctionContext(false) {}
6978
6979 bool isUnevaluated() const {
6980 return Context == ExpressionEvaluationContext::Unevaluated ||
6981 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
6982 Context == ExpressionEvaluationContext::UnevaluatedList;
6983 }
6984
6985 bool isPotentiallyEvaluated() const {
6986 return Context == ExpressionEvaluationContext::PotentiallyEvaluated ||
6987 Context ==
6988 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed ||
6989 Context == ExpressionEvaluationContext::ConstantEvaluated;
6990 }
6991
6992 bool isConstantEvaluated() const {
6993 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
6994 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
6995 }
6996
6997 bool isImmediateFunctionContext() const {
6998 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
6999 (Context == ExpressionEvaluationContext::DiscardedStatement &&
7000 InImmediateFunctionContext) ||
7001 // C++23 [expr.const]p14:
7002 // An expression or conversion is in an immediate function
7003 // context if it is potentially evaluated and either:
7004 // * its innermost enclosing non-block scope is a function
7005 // parameter scope of an immediate function, or
7006 // * its enclosing statement is enclosed by the compound-
7007 // statement of a consteval if statement.
7008 (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
7009 InImmediateFunctionContext);
7010 }
7011
7012 bool isDiscardedStatementContext() const {
7013 return Context == ExpressionEvaluationContext::DiscardedStatement ||
7014 ((Context ==
7015 ExpressionEvaluationContext::ImmediateFunctionContext ||
7016 isPotentiallyEvaluated()) &&
7017 InDiscardedStatement);
7018 }
7019 };
7020
7021 const ExpressionEvaluationContextRecord &currentEvaluationContext() const {
7022 assert(!ExprEvalContexts.empty() &&
7023 "Must be in an expression evaluation context");
7024 return ExprEvalContexts.back();
7025 }
7026
7027 ExpressionEvaluationContextRecord &currentEvaluationContext() {
7028 assert(!ExprEvalContexts.empty() &&
7029 "Must be in an expression evaluation context");
7030 return ExprEvalContexts.back();
7031 }
7032
7033 ExpressionEvaluationContextRecord &parentEvaluationContext() {
7034 assert(ExprEvalContexts.size() >= 2 &&
7035 "Must be in an expression evaluation context");
7036 return ExprEvalContexts[ExprEvalContexts.size() - 2];
7037 }
7038
7039 const ExpressionEvaluationContextRecord &parentEvaluationContext() const {
7040 return const_cast<Sema *>(this)->parentEvaluationContext();
7041 }
7042
7043 bool isAttrContext() const {
7044 return ExprEvalContexts.back().ExprContext ==
7045 ExpressionEvaluationContextRecord::ExpressionKind::EK_AttrArgument;
7046 }
7047
7048 /// Increment when we find a reference; decrement when we find an ignored
7049 /// assignment. Ultimately the value is 0 if every reference is an ignored
7050 /// assignment.
7051 ///
7052 /// Uses canonical VarDecl as key so in-class decls and out-of-class defs of
7053 /// static data members get tracked as a single entry.
7054 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
7055
7056 /// Used to control the generation of ExprWithCleanups.
7057 CleanupInfo Cleanup;
7058
7059 /// ExprCleanupObjects - This is the stack of objects requiring
7060 /// cleanup that are created by the current full expression.
7061 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
7062
7063 /// Determine whether the use of this declaration is valid, without
7064 /// emitting diagnostics.
7065 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
7066 // A version of DiagnoseUseOfDecl that should be used if overload resolution
7067 // has been used to find this declaration, which means we don't have to bother
7068 // checking the trailing requires clause.
7069 bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) {
7070 return DiagnoseUseOfDecl(
7071 D, Locs: Loc, /*UnknownObjCClass=*/UnknownObjCClass: nullptr, /*ObjCPropertyAccess=*/ObjCPropertyAccess: false,
7072 /*AvoidPartialAvailabilityChecks=*/AvoidPartialAvailabilityChecks: false, /*ClassReceiver=*/ClassReceiver: nullptr,
7073 /*SkipTrailingRequiresClause=*/SkipTrailingRequiresClause: true);
7074 }
7075
7076 /// Determine whether the use of this declaration is valid, and
7077 /// emit any corresponding diagnostics.
7078 ///
7079 /// This routine diagnoses various problems with referencing
7080 /// declarations that can occur when using a declaration. For example,
7081 /// it might warn if a deprecated or unavailable declaration is being
7082 /// used, or produce an error (and return true) if a C++0x deleted
7083 /// function is being used.
7084 ///
7085 /// \returns true if there was an error (this declaration cannot be
7086 /// referenced), false otherwise.
7087 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
7088 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
7089 bool ObjCPropertyAccess = false,
7090 bool AvoidPartialAvailabilityChecks = false,
7091 ObjCInterfaceDecl *ClassReceiver = nullptr,
7092 bool SkipTrailingRequiresClause = false);
7093
7094 /// Emit a note explaining that this function is deleted.
7095 void NoteDeletedFunction(FunctionDecl *FD);
7096
7097 /// DiagnoseSentinelCalls - This routine checks whether a call or
7098 /// message-send is to a declaration with the sentinel attribute, and
7099 /// if so, it checks that the requirements of the sentinel are
7100 /// satisfied.
7101 void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
7102 ArrayRef<Expr *> Args);
7103
7104 void PushExpressionEvaluationContext(
7105 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
7106 ExpressionEvaluationContextRecord::ExpressionKind Type =
7107 ExpressionEvaluationContextRecord::EK_Other);
7108
7109 void PushExpressionEvaluationContextForFunction(
7110 ExpressionEvaluationContext NewContext, FunctionDecl *FD);
7111
7112 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
7113 void PushExpressionEvaluationContext(
7114 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
7115 ExpressionEvaluationContextRecord::ExpressionKind Type =
7116 ExpressionEvaluationContextRecord::EK_Other);
7117 void PopExpressionEvaluationContext();
7118
7119 void DiscardCleanupsInEvaluationContext();
7120
7121 ExprResult TransformToPotentiallyEvaluated(Expr *E);
7122 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
7123 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
7124
7125 /// Check whether E, which is either a discarded-value expression or an
7126 /// unevaluated operand, is a simple-assignment to a volatlie-qualified
7127 /// lvalue, and if so, remove it from the list of volatile-qualified
7128 /// assignments that we are going to warn are deprecated.
7129 void CheckUnusedVolatileAssignment(Expr *E);
7130
7131 ExprResult ActOnConstantExpression(ExprResult Res);
7132
7133 // Functions for marking a declaration referenced. These functions also
7134 // contain the relevant logic for marking if a reference to a function or
7135 // variable is an odr-use (in the C++11 sense). There are separate variants
7136 // for expressions referring to a decl; these exist because odr-use marking
7137 // needs to be delayed for some constant variables when we build one of the
7138 // named expressions.
7139 //
7140 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
7141 // should usually be true. This only needs to be set to false if the lack of
7142 // odr-use cannot be determined from the current context (for instance,
7143 // because the name denotes a virtual function and was written without an
7144 // explicit nested-name-specifier).
7145 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
7146
7147 /// Mark a function referenced, and check whether it is odr-used
7148 /// (C++ [basic.def.odr]p2, C99 6.9p3)
7149 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
7150 bool MightBeOdrUse = true);
7151
7152 /// Mark a variable referenced, and check whether it is odr-used
7153 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
7154 /// used directly for normal expressions referring to VarDecl.
7155 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
7156
7157 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7158 ///
7159 /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7160 /// be handled with care if the DeclRefExpr is not newly-created.
7161 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7162
7163 /// Perform reference-marking and odr-use handling for a MemberExpr.
7164 void MarkMemberReferenced(MemberExpr *E);
7165
7166 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7167 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
7168 void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc,
7169 unsigned CapturingScopeIndex);
7170
7171 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
7172 void CleanupVarDeclMarking();
7173
7174 /// Try to capture the given variable.
7175 ///
7176 /// \param Var The variable to capture.
7177 ///
7178 /// \param Loc The location at which the capture occurs.
7179 ///
7180 /// \param Kind The kind of capture, which may be implicit (for either a
7181 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7182 ///
7183 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7184 /// an explicit lambda capture.
7185 ///
7186 /// \param BuildAndDiagnose Whether we are actually supposed to add the
7187 /// captures or diagnose errors. If false, this routine merely check whether
7188 /// the capture can occur without performing the capture itself or complaining
7189 /// if the variable cannot be captured.
7190 ///
7191 /// \param CaptureType Will be set to the type of the field used to capture
7192 /// this variable in the innermost block or lambda. Only valid when the
7193 /// variable can be captured.
7194 ///
7195 /// \param DeclRefType Will be set to the type of a reference to the capture
7196 /// from within the current scope. Only valid when the variable can be
7197 /// captured.
7198 ///
7199 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7200 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7201 /// This is useful when enclosing lambdas must speculatively capture
7202 /// variables that may or may not be used in certain specializations of
7203 /// a nested generic lambda.
7204 ///
7205 /// \returns true if an error occurred (i.e., the variable cannot be
7206 /// captured) and false if the capture succeeded.
7207 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7208 TryCaptureKind Kind, SourceLocation EllipsisLoc,
7209 bool BuildAndDiagnose, QualType &CaptureType,
7210 QualType &DeclRefType,
7211 const unsigned *const FunctionScopeIndexToStopAt);
7212
7213 /// Try to capture the given variable.
7214 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7215 TryCaptureKind Kind = TryCaptureKind::Implicit,
7216 SourceLocation EllipsisLoc = SourceLocation());
7217
7218 /// Checks if the variable must be captured.
7219 bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc);
7220
7221 /// Given a variable, determine the type that a reference to that
7222 /// variable will have in the given scope.
7223 QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc);
7224
7225 /// Mark all of the declarations referenced within a particular AST node as
7226 /// referenced. Used when template instantiation instantiates a non-dependent
7227 /// type -- entities referenced by the type are now referenced.
7228 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
7229
7230 /// Mark any declarations that appear within this expression or any
7231 /// potentially-evaluated subexpressions as "referenced".
7232 ///
7233 /// \param SkipLocalVariables If true, don't mark local variables as
7234 /// 'referenced'.
7235 /// \param StopAt Subexpressions that we shouldn't recurse into.
7236 void MarkDeclarationsReferencedInExpr(Expr *E,
7237 bool SkipLocalVariables = false,
7238 ArrayRef<const Expr *> StopAt = {});
7239
7240 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7241 /// conversion.
7242 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7243
7244 /// Conditionally issue a diagnostic based on the statements's reachability
7245 /// analysis.
7246 ///
7247 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7248 /// the function body is parsed, and then do a basic reachability analysis to
7249 /// determine if the statement is reachable. If it is unreachable, the
7250 /// diagnostic will not be emitted.
7251 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7252 const PartialDiagnostic &PD);
7253
7254 /// Conditionally issue a diagnostic based on the current
7255 /// evaluation context.
7256 ///
7257 /// \param Statement If Statement is non-null, delay reporting the
7258 /// diagnostic until the function body is parsed, and then do a basic
7259 /// reachability analysis to determine if the statement is reachable.
7260 /// If it is unreachable, the diagnostic will not be emitted.
7261 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7262 const PartialDiagnostic &PD);
7263 /// Similar, but diagnostic is only produced if all the specified statements
7264 /// are reachable.
7265 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7266 const PartialDiagnostic &PD);
7267
7268 // Primary Expressions.
7269 SourceRange getExprRange(Expr *E) const;
7270
7271 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7272 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7273 bool HasTrailingLParen, bool IsAddressOfOperand,
7274 CorrectionCandidateCallback *CCC = nullptr,
7275 bool IsInlineAsmIdentifier = false);
7276
7277 /// Decomposes the given name into a DeclarationNameInfo, its location, and
7278 /// possibly a list of template arguments.
7279 ///
7280 /// If this produces template arguments, it is permitted to call
7281 /// DecomposeTemplateName.
7282 ///
7283 /// This actually loses a lot of source location information for
7284 /// non-standard name kinds; we should consider preserving that in
7285 /// some way.
7286 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7287 TemplateArgumentListInfo &Buffer,
7288 DeclarationNameInfo &NameInfo,
7289 const TemplateArgumentListInfo *&TemplateArgs);
7290
7291 /// Diagnose a lookup that found results in an enclosing class during error
7292 /// recovery. This usually indicates that the results were found in a
7293 /// dependent base class that could not be searched as part of a template
7294 /// definition. Always issues a diagnostic (though this may be only a warning
7295 /// in MS compatibility mode).
7296 ///
7297 /// Return \c true if the error is unrecoverable, or \c false if the caller
7298 /// should attempt to recover using these lookup results.
7299 bool DiagnoseDependentMemberLookup(const LookupResult &R);
7300
7301 /// Diagnose an empty lookup.
7302 ///
7303 /// \return false if new lookup candidates were found
7304 bool
7305 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7306 CorrectionCandidateCallback &CCC,
7307 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7308 ArrayRef<Expr *> Args = {},
7309 DeclContext *LookupCtx = nullptr);
7310
7311 /// If \p D cannot be odr-used in the current expression evaluation context,
7312 /// return a reason explaining why. Otherwise, return NOUR_None.
7313 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
7314
7315 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7316 SourceLocation Loc,
7317 const CXXScopeSpec *SS = nullptr);
7318 DeclRefExpr *
7319 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7320 const DeclarationNameInfo &NameInfo,
7321 const CXXScopeSpec *SS = nullptr,
7322 NamedDecl *FoundD = nullptr,
7323 SourceLocation TemplateKWLoc = SourceLocation(),
7324 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7325
7326 /// BuildDeclRefExpr - Build an expression that references a
7327 /// declaration that does not require a closure capture.
7328 DeclRefExpr *
7329 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7330 const DeclarationNameInfo &NameInfo,
7331 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7332 SourceLocation TemplateKWLoc = SourceLocation(),
7333 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7334
7335 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7336 bool HasTrailingLParen);
7337
7338 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7339 /// declaration name, generally during template instantiation.
7340 /// There's a large number of things which don't need to be done along
7341 /// this path.
7342 ExprResult BuildQualifiedDeclarationNameExpr(
7343 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7344 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7345
7346 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7347 bool NeedsADL,
7348 bool AcceptInvalidDecl = false);
7349
7350 /// Complete semantic analysis for a reference to the given declaration.
7351 ExprResult BuildDeclarationNameExpr(
7352 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7353 NamedDecl *FoundD = nullptr,
7354 const TemplateArgumentListInfo *TemplateArgs = nullptr,
7355 bool AcceptInvalidDecl = false);
7356
7357 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7358 // where Tokens representing function local predefined macros (such as
7359 // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7360 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7361
7362 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7363 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7364 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7365
7366 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7367
7368 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7369 ExprResult ActOnCharacterConstant(const Token &Tok,
7370 Scope *UDLScope = nullptr);
7371 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7372 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7373 MultiExprArg Val);
7374 ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7375 unsigned NumUserSpecifiedExprs,
7376 SourceLocation InitLoc,
7377 SourceLocation LParenLoc,
7378 SourceLocation RParenLoc);
7379
7380 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7381 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle
7382 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7383 /// from multiple tokens. However, the common case is that StringToks points
7384 /// to one string.
7385 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7386 Scope *UDLScope = nullptr);
7387
7388 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7389
7390 /// ControllingExprOrType is either an opaque pointer coming out of a
7391 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7392 /// into two so we don't take a void *, but that's awkward because one of
7393 /// the operands is either a ParsedType or an Expr *, which doesn't lend
7394 /// itself to generic code very well.
7395 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7396 SourceLocation DefaultLoc,
7397 SourceLocation RParenLoc,
7398 bool PredicateIsExpr,
7399 void *ControllingExprOrType,
7400 ArrayRef<ParsedType> ArgTypes,
7401 ArrayRef<Expr *> ArgExprs);
7402 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7403 /// it'd be better to split this interface into two so we don't take a
7404 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7405 /// isn't a trivial change.
7406 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7407 SourceLocation DefaultLoc,
7408 SourceLocation RParenLoc,
7409 bool PredicateIsExpr,
7410 void *ControllingExprOrType,
7411 ArrayRef<TypeSourceInfo *> Types,
7412 ArrayRef<Expr *> Exprs);
7413
7414 // Binary/Unary Operators. 'Tok' is the token for the operator.
7415 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7416 Expr *InputExpr, bool IsAfterAmp = false);
7417 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7418 Expr *Input, bool IsAfterAmp = false);
7419
7420 /// Unary Operators. 'Tok' is the token for the operator.
7421 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7422 Expr *Input, bool IsAfterAmp = false);
7423
7424 /// Determine whether the given expression is a qualified member
7425 /// access expression, of a form that could be turned into a pointer to member
7426 /// with the address-of operator.
7427 bool isQualifiedMemberAccess(Expr *E);
7428 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7429 const Expr *Op,
7430 const CXXMethodDecl *MD);
7431
7432 /// CheckAddressOfOperand - The operand of & must be either a function
7433 /// designator or an lvalue designating an object. If it is an lvalue, the
7434 /// object cannot be declared with storage class register or be a bit field.
7435 /// Note: The usual conversions are *not* applied to the operand of the &
7436 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7437 /// In C++, the operand might be an overloaded function name, in which case
7438 /// we allow the '&' but retain the overloaded-function type.
7439 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7440
7441 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7442 /// _Alignas(type-name) .
7443 /// [dcl.align] An alignment-specifier of the form
7444 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7445 ///
7446 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7447 /// _Alignas(_Alignof(type-name)).
7448 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7449 SourceLocation OpLoc, SourceRange R);
7450 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7451 SourceLocation OpLoc, SourceRange R);
7452
7453 /// Build a sizeof or alignof expression given a type operand.
7454 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7455 SourceLocation OpLoc,
7456 UnaryExprOrTypeTrait ExprKind,
7457 SourceRange R);
7458
7459 /// Build a sizeof or alignof expression given an expression
7460 /// operand.
7461 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7462 UnaryExprOrTypeTrait ExprKind);
7463
7464 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7465 /// expr and the same for @c alignof and @c __alignof
7466 /// Note that the ArgRange is invalid if isType is false.
7467 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7468 UnaryExprOrTypeTrait ExprKind,
7469 bool IsType, void *TyOrEx,
7470 SourceRange ArgRange);
7471
7472 /// Check for operands with placeholder types and complain if found.
7473 /// Returns ExprError() if there was an error and no recovery was possible.
7474 ExprResult CheckPlaceholderExpr(Expr *E);
7475 bool CheckVecStepExpr(Expr *E);
7476
7477 /// Check the constraints on expression operands to unary type expression
7478 /// and type traits.
7479 ///
7480 /// Completes any types necessary and validates the constraints on the operand
7481 /// expression. The logic mostly mirrors the type-based overload, but may
7482 /// modify the expression as it completes the type for that expression through
7483 /// template instantiation, etc.
7484 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
7485
7486 /// Check the constraints on operands to unary expression and type
7487 /// traits.
7488 ///
7489 /// This will complete any types necessary, and validate the various
7490 /// constraints on those operands.
7491 ///
7492 /// The UsualUnaryConversions() function is *not* called by this routine.
7493 /// C99 6.3.2.1p[2-4] all state:
7494 /// Except when it is the operand of the sizeof operator ...
7495 ///
7496 /// C++ [expr.sizeof]p4
7497 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7498 /// standard conversions are not applied to the operand of sizeof.
7499 ///
7500 /// This policy is followed for all of the unary trait expressions.
7501 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7502 SourceRange ExprRange,
7503 UnaryExprOrTypeTrait ExprKind,
7504 StringRef KWName);
7505
7506 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7507 tok::TokenKind Kind, Expr *Input);
7508
7509 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7510 MultiExprArg ArgExprs,
7511 SourceLocation RLoc);
7512 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7513 Expr *Idx, SourceLocation RLoc);
7514
7515 ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx,
7516 SourceLocation RBLoc);
7517
7518 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7519 Expr *ColumnIdx,
7520 SourceLocation RBLoc);
7521
7522 /// ConvertArgumentsForCall - Converts the arguments specified in
7523 /// Args/NumArgs to the parameter types of the function FDecl with
7524 /// function prototype Proto. Call is the call expression itself, and
7525 /// Fn is the function expression. For a C++ member function, this
7526 /// routine does not attempt to convert the object argument. Returns
7527 /// true if the call is ill-formed.
7528 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7529 const FunctionProtoType *Proto,
7530 ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7531 bool ExecConfig = false);
7532
7533 /// CheckStaticArrayArgument - If the given argument corresponds to a static
7534 /// array parameter, check that it is non-null, and that if it is formed by
7535 /// array-to-pointer decay, the underlying array is sufficiently large.
7536 ///
7537 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7538 /// the array type derivation, then for each call to the function, the value
7539 /// of the corresponding actual argument shall provide access to the first
7540 /// element of an array with at least as many elements as specified by the
7541 /// size expression.
7542 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7543 const Expr *ArgExpr);
7544
7545 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7546 /// This provides the location of the left/right parens and a list of comma
7547 /// locations.
7548 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7549 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7550 Expr *ExecConfig = nullptr);
7551
7552 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7553 /// This provides the location of the left/right parens and a list of comma
7554 /// locations.
7555 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7556 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7557 Expr *ExecConfig = nullptr,
7558 bool IsExecConfig = false,
7559 bool AllowRecovery = false);
7560
7561 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7562 // with the specified CallArgs
7563 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7564 MultiExprArg CallArgs);
7565
7566 using ADLCallKind = CallExpr::ADLCallKind;
7567
7568 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7569 /// i.e. an expression not of \p OverloadTy. The expression should
7570 /// unary-convert to an expression of function-pointer or
7571 /// block-pointer type.
7572 ///
7573 /// \param NDecl the declaration being called, if available
7574 ExprResult
7575 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7576 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7577 Expr *Config = nullptr, bool IsExecConfig = false,
7578 ADLCallKind UsesADL = ADLCallKind::NotADL);
7579
7580 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D,
7581 ParsedType &Ty, SourceLocation RParenLoc,
7582 Expr *CastExpr);
7583
7584 /// Prepares for a scalar cast, performing all the necessary stages
7585 /// except the final cast and returning the kind required.
7586 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
7587
7588 /// Build an altivec or OpenCL literal.
7589 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
7590 SourceLocation RParenLoc, Expr *E,
7591 TypeSourceInfo *TInfo);
7592
7593 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7594 /// the ParenListExpr into a sequence of comma binary operators.
7595 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
7596
7597 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7598 SourceLocation RParenLoc, Expr *InitExpr);
7599
7600 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
7601 TypeSourceInfo *TInfo,
7602 SourceLocation RParenLoc,
7603 Expr *LiteralExpr);
7604
7605 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7606 SourceLocation RBraceLoc);
7607
7608 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7609 SourceLocation RBraceLoc, bool IsExplicit);
7610
7611 /// Binary Operators. 'Tok' is the token for the operator.
7612 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind,
7613 Expr *LHSExpr, Expr *RHSExpr);
7614 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7615 Expr *LHSExpr, Expr *RHSExpr,
7616 bool ForFoldExpression = false);
7617
7618 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7619 /// operator @p Opc at location @c TokLoc. This routine only supports
7620 /// built-in operations; ActOnBinOp handles overloaded operators.
7621 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
7622 Expr *LHSExpr, Expr *RHSExpr,
7623 bool ForFoldExpression = false);
7624 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7625 UnresolvedSetImpl &Functions);
7626
7627 /// Look for instances where it is likely the comma operator is confused with
7628 /// another operator. There is an explicit list of acceptable expressions for
7629 /// the left hand side of the comma operator, otherwise emit a warning.
7630 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7631
7632 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7633 /// in the case of a the GNU conditional expr extension.
7634 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
7635 SourceLocation ColonLoc, Expr *CondExpr,
7636 Expr *LHSExpr, Expr *RHSExpr);
7637
7638 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7639 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
7640 LabelDecl *TheDecl);
7641
7642 void ActOnStartStmtExpr();
7643 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7644 SourceLocation RPLoc);
7645 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
7646 SourceLocation RPLoc, unsigned TemplateDepth);
7647 // Handle the final expression in a statement expression.
7648 ExprResult ActOnStmtExprResult(ExprResult E);
7649 void ActOnStmtExprError();
7650
7651 /// __builtin_offsetof(type, a.b[123][456].c)
7652 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
7653 TypeSourceInfo *TInfo,
7654 const Designation &Desig,
7655 SourceLocation RParenLoc);
7656 ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
7657 SourceLocation TypeLoc,
7658 ParsedType ParsedArgTy,
7659 const Designation &Desig,
7660 SourceLocation RParenLoc);
7661
7662 // __builtin_choose_expr(constExpr, expr1, expr2)
7663 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7664 Expr *LHSExpr, Expr *RHSExpr,
7665 SourceLocation RPLoc);
7666
7667 // __builtin_va_arg(expr, type)
7668 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
7669 SourceLocation RPLoc);
7670 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
7671 TypeSourceInfo *TInfo, SourceLocation RPLoc);
7672
7673 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7674 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7675 ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind,
7676 SourceLocation BuiltinLoc,
7677 SourceLocation RPLoc);
7678
7679 // #embed
7680 ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
7681 StringLiteral *BinaryData, StringRef FileName);
7682
7683 // Build a potentially resolved SourceLocExpr.
7684 ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
7685 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7686 DeclContext *ParentContext);
7687
7688 // __null
7689 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
7690
7691 bool CheckCaseExpression(Expr *E);
7692
7693 //===------------------------- "Block" Extension ------------------------===//
7694
7695 /// ActOnBlockStart - This callback is invoked when a block literal is
7696 /// started.
7697 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7698
7699 /// ActOnBlockArguments - This callback allows processing of block arguments.
7700 /// If there are no arguments, this is still invoked.
7701 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7702 Scope *CurScope);
7703
7704 /// ActOnBlockError - If there is an error parsing a block, this callback
7705 /// is invoked to pop the information about the block from the action impl.
7706 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7707
7708 /// ActOnBlockStmtExpr - This is called when the body of a block statement
7709 /// literal was successfully completed. ^(int x){...}
7710 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
7711 Scope *CurScope);
7712
7713 //===---------------------------- Clang Extensions ----------------------===//
7714
7715 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7716 /// provided arguments.
7717 ///
7718 /// __builtin_convertvector( value, dst type )
7719 ///
7720 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7721 SourceLocation BuiltinLoc,
7722 SourceLocation RParenLoc);
7723
7724 //===---------------------------- OpenCL Features -----------------------===//
7725
7726 /// Parse a __builtin_astype expression.
7727 ///
7728 /// __builtin_astype( value, dst type )
7729 ///
7730 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7731 SourceLocation BuiltinLoc,
7732 SourceLocation RParenLoc);
7733
7734 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7735 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
7736 SourceLocation BuiltinLoc,
7737 SourceLocation RParenLoc);
7738
7739 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7740 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
7741 ArrayRef<Expr *> SubExprs,
7742 QualType T = QualType());
7743
7744 /// Cast a base object to a member's actual type.
7745 ///
7746 /// There are two relevant checks:
7747 ///
7748 /// C++ [class.access.base]p7:
7749 ///
7750 /// If a class member access operator [...] is used to access a non-static
7751 /// data member or non-static member function, the reference is ill-formed
7752 /// if the left operand [...] cannot be implicitly converted to a pointer to
7753 /// the naming class of the right operand.
7754 ///
7755 /// C++ [expr.ref]p7:
7756 ///
7757 /// If E2 is a non-static data member or a non-static member function, the
7758 /// program is ill-formed if the class of which E2 is directly a member is
7759 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7760 ///
7761 /// Note that the latter check does not consider access; the access of the
7762 /// "real" base class is checked as appropriate when checking the access of
7763 /// the member name.
7764 ExprResult PerformObjectMemberConversion(Expr *From,
7765 NestedNameSpecifier Qualifier,
7766 NamedDecl *FoundDecl,
7767 NamedDecl *Member);
7768
7769 /// CheckCallReturnType - Checks that a call expression's return type is
7770 /// complete. Returns true on failure. The location passed in is the location
7771 /// that best represents the call.
7772 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7773 CallExpr *CE, FunctionDecl *FD);
7774
7775 /// Emit a warning for all pending noderef expressions that we recorded.
7776 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
7777
7778private:
7779 /// Shared logic for building default member initializer which used in a
7780 /// constructor or an aggregate initialization.
7781 ///
7782 ///
7783 /// The caller enters that evaluation context and decides whether the result
7784 /// is finished as a full-expression. \p NestedDefaultChecking and
7785 /// \p NeedRebuild have to be sampled before entering it.
7786 ExprResult BuildCXXDefaultInitInternal(SourceLocation Loc, FieldDecl *Field,
7787 const InitializedEntity &Entity,
7788 bool NestedDefaultChecking,
7789 bool NeedRebuild);
7790
7791public:
7792 ExprResult BuildCXXCtorDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
7793 ExprResult
7794 BuildCXXAggregateDefaultInitExpr(SourceLocation Loc, FieldDecl *Field,
7795 const InitializedEntity &MemberEntity);
7796
7797 /// Instantiate or parse a C++ default argument expression as necessary.
7798 /// Return true on error.
7799 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7800 ParmVarDecl *Param, Expr *Init = nullptr,
7801 bool SkipImmediateInvocations = true);
7802
7803 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7804 /// the default expr if needed.
7805 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7806 ParmVarDecl *Param, Expr *Init = nullptr);
7807
7808 /// Wrap the expression in a ConstantExpr if it is a potential immediate
7809 /// invocation.
7810 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
7811
7812 void MarkExpressionAsImmediateEscalating(Expr *E);
7813
7814 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7815 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7816
7817 /// Abstract base class used for diagnosing integer constant
7818 /// expression violations.
7819 class VerifyICEDiagnoser {
7820 public:
7821 bool Suppress;
7822
7823 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) {}
7824
7825 virtual SemaDiagnosticBuilder
7826 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7827 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7828 SourceLocation Loc) = 0;
7829 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
7830 virtual ~VerifyICEDiagnoser() {}
7831 };
7832
7833 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7834 /// and reports the appropriate diagnostics. Returns false on success.
7835 /// Can optionally return the value of the expression.
7836 ExprResult
7837 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7838 VerifyICEDiagnoser &Diagnoser,
7839 AllowFoldKind CanFold = AllowFoldKind::No);
7840 ExprResult
7841 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7842 unsigned DiagID,
7843 AllowFoldKind CanFold = AllowFoldKind::No);
7844 ExprResult
7845 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7846 AllowFoldKind CanFold = AllowFoldKind::No);
7847 ExprResult
7848 VerifyIntegerConstantExpression(Expr *E,
7849 AllowFoldKind CanFold = AllowFoldKind::No) {
7850 return VerifyIntegerConstantExpression(E, Result: nullptr, CanFold);
7851 }
7852
7853 /// DiagnoseAssignmentAsCondition - Given that an expression is
7854 /// being used as a boolean condition, warn if it's an assignment.
7855 void DiagnoseAssignmentAsCondition(Expr *E);
7856
7857 /// Redundant parentheses over an equality comparison can indicate
7858 /// that the user intended an assignment used as condition.
7859 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7860
7861 class FullExprArg {
7862 public:
7863 FullExprArg() : E(nullptr) {}
7864 FullExprArg(Sema &actions) : E(nullptr) {}
7865
7866 ExprResult release() { return E; }
7867
7868 Expr *get() const { return E; }
7869
7870 Expr *operator->() { return E; }
7871
7872 private:
7873 // FIXME: No need to make the entire Sema class a friend when it's just
7874 // Sema::MakeFullExpr that needs access to the constructor below.
7875 friend class Sema;
7876
7877 explicit FullExprArg(Expr *expr) : E(expr) {}
7878
7879 Expr *E;
7880 };
7881
7882 FullExprArg MakeFullExpr(Expr *Arg) {
7883 return MakeFullExpr(Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation());
7884 }
7885 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
7886 return FullExprArg(
7887 ActOnFinishFullExpr(Expr: Arg, CC, /*DiscardedValue*/ DiscardedValue: false).get());
7888 }
7889 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
7890 ExprResult FE =
7891 ActOnFinishFullExpr(Expr: Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation(),
7892 /*DiscardedValue*/ DiscardedValue: true);
7893 return FullExprArg(FE.get());
7894 }
7895
7896 class ConditionResult {
7897 Decl *ConditionVar;
7898 ExprResult Condition;
7899 bool Invalid;
7900 std::optional<bool> KnownValue;
7901
7902 friend class Sema;
7903 ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
7904 bool IsConstexpr)
7905 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
7906 if (IsConstexpr && Condition.get()) {
7907 if (std::optional<llvm::APSInt> Val =
7908 Condition.get()->getIntegerConstantExpr(Ctx: S.Context)) {
7909 KnownValue = !!(*Val);
7910 }
7911 }
7912 }
7913 explicit ConditionResult(bool Invalid)
7914 : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
7915 KnownValue(std::nullopt) {}
7916
7917 public:
7918 ConditionResult() : ConditionResult(false) {}
7919 bool isInvalid() const { return Invalid; }
7920 std::pair<VarDecl *, Expr *> get() const {
7921 return std::make_pair(x: cast_or_null<VarDecl>(Val: ConditionVar),
7922 y: Condition.get());
7923 }
7924 std::optional<bool> getKnownValue() const { return KnownValue; }
7925 };
7926 static ConditionResult ConditionError() { return ConditionResult(true); }
7927
7928 /// CheckBooleanCondition - Diagnose problems involving the use of
7929 /// the given expression as a boolean condition (e.g. in an if
7930 /// statement). Also performs the standard function and array
7931 /// decays, possibly changing the input variable.
7932 ///
7933 /// \param Loc - A location associated with the condition, e.g. the
7934 /// 'if' keyword.
7935 /// \return true iff there were any errors
7936 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
7937 bool IsConstexpr = false);
7938
7939 enum class ConditionKind {
7940 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
7941 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
7942 Switch ///< An integral condition for a 'switch' statement.
7943 };
7944
7945 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
7946 ConditionKind CK, bool MissingOK = false);
7947
7948 QualType CheckConditionalOperands( // C99 6.5.15
7949 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
7950 ExprObjectKind &OK, SourceLocation QuestionLoc);
7951
7952 /// Emit a specialized diagnostic when one expression is a null pointer
7953 /// constant and the other is not a pointer. Returns true if a diagnostic is
7954 /// emitted.
7955 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7956 SourceLocation QuestionLoc);
7957
7958 /// type checking for vector binary operators.
7959 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7960 SourceLocation Loc, bool IsCompAssign,
7961 bool AllowBothBool, bool AllowBoolConversion,
7962 bool AllowBoolOperation);
7963
7964 /// Return a signed ext_vector_type that is of identical size and number of
7965 /// elements. For floating point vectors, return an integer type of identical
7966 /// size and number of elements. In the non ext_vector_type case, search from
7967 /// the largest type to the smallest type to avoid cases where long long ==
7968 /// long, where long gets picked over long long.
7969 QualType GetSignedVectorType(QualType V);
7970 QualType GetSignedSizelessVectorType(QualType V);
7971
7972 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7973 /// operates on extended vector types. Instead of producing an IntTy result,
7974 /// like a scalar comparison, a vector comparison produces a vector of integer
7975 /// types.
7976 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7977 SourceLocation Loc,
7978 BinaryOperatorKind Opc);
7979 QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7980 SourceLocation Loc,
7981 BinaryOperatorKind Opc);
7982 QualType CheckMatrixCompareOperands(ExprResult &LHS, ExprResult &RHS,
7983 SourceLocation Loc,
7984 BinaryOperatorKind Opc);
7985 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7986 SourceLocation Loc,
7987 BinaryOperatorKind Opc);
7988 QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7989 SourceLocation Loc,
7990 BinaryOperatorKind Opc);
7991 // type checking for sizeless vector binary operators.
7992 QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
7993 SourceLocation Loc, bool IsCompAssign,
7994 ArithConvKind OperationKind);
7995
7996 /// Type checking for matrix binary operators.
7997 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
7998 SourceLocation Loc,
7999 bool IsCompAssign);
8000 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
8001 SourceLocation Loc, bool IsCompAssign);
8002
8003 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
8004 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
8005 /// VLST) allowed?
8006 ///
8007 /// This will also return false if the two given types do not make sense from
8008 /// the perspective of SVE bitcasts.
8009 bool isValidSveBitcast(QualType srcType, QualType destType);
8010
8011 /// Are the two types matrix types and do they have the same dimensions i.e.
8012 /// do they have the same number of rows and the same number of columns?
8013 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
8014
8015 bool areVectorTypesSameSize(QualType srcType, QualType destType);
8016
8017 /// Are the two types lax-compatible vector types? That is, given
8018 /// that one of them is a vector, do they have equal storage sizes,
8019 /// where the storage size is the number of elements times the element
8020 /// size?
8021 ///
8022 /// This will also return false if either of the types is neither a
8023 /// vector nor a real type.
8024 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
8025
8026 /// Is this a legal conversion between two types, one of which is
8027 /// known to be a vector type?
8028 bool isLaxVectorConversion(QualType srcType, QualType destType);
8029
8030 // This returns true if at least one of the types is an altivec vector.
8031 bool anyAltivecTypes(QualType srcType, QualType destType);
8032
8033 // type checking C++ declaration initializers (C++ [dcl.init]).
8034
8035 /// Check a cast of an unknown-any type. We intentionally only
8036 /// trigger this for C-style casts.
8037 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8038 Expr *CastExpr, CastKind &CastKind,
8039 ExprValueKind &VK, CXXCastPath &Path);
8040
8041 /// Force an expression with unknown-type to an expression of the
8042 /// given type.
8043 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8044
8045 /// Type-check an expression that's being passed to an
8046 /// __unknown_anytype parameter.
8047 ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result,
8048 QualType &paramType);
8049
8050 // CheckMatrixCast - Check type constraints for matrix casts.
8051 // We allow casting between matrixes of the same dimensions i.e. when they
8052 // have the same number of rows and column. Returns true if the cast is
8053 // invalid.
8054 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8055 CastKind &Kind);
8056
8057 // CheckVectorCast - check type constraints for vectors.
8058 // Since vectors are an extension, there are no C standard reference for this.
8059 // We allow casting between vectors and integer datatypes of the same size.
8060 // returns true if the cast is invalid
8061 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8062 CastKind &Kind);
8063
8064 /// Prepare `SplattedExpr` for a vector splat operation, adding
8065 /// implicit casts if necessary.
8066 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8067
8068 /// Prepare `SplattedExpr` for a matrix splat operation, adding
8069 /// implicit casts if necessary.
8070 ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr);
8071
8072 // CheckExtVectorCast - check type constraints for extended vectors.
8073 // Since vectors are an extension, there are no C standard reference for this.
8074 // We allow casting between vectors and integer datatypes of the same size,
8075 // or vectors and the element type of that vector.
8076 // returns the cast expr
8077 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8078 CastKind &Kind);
8079
8080 QualType PreferredConditionType(ConditionKind K) const {
8081 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
8082 }
8083
8084 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
8085 // functions and arrays to their respective pointers (C99 6.3.2.1), and
8086 // promotes floating-piont types according to the language semantics.
8087 ExprResult UsualUnaryConversions(Expr *E);
8088
8089 // UsualUnaryFPConversions - promotes floating-point types according to the
8090 // current language semantics.
8091 ExprResult UsualUnaryFPConversions(Expr *E);
8092
8093 /// CallExprUnaryConversions - a special case of an unary conversion
8094 /// performed on a function designator of a call expression.
8095 ExprResult CallExprUnaryConversions(Expr *E);
8096
8097 // DefaultFunctionArrayConversion - converts functions and arrays
8098 // to their respective pointers (C99 6.3.2.1).
8099 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8100
8101 // DefaultFunctionArrayLvalueConversion - converts functions and
8102 // arrays to their respective pointers and performs the
8103 // lvalue-to-rvalue conversion.
8104 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8105 bool Diagnose = true);
8106
8107 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8108 // the operand. This function is a no-op if the operand has a function type
8109 // or an array type.
8110 ExprResult DefaultLvalueConversion(Expr *E);
8111
8112 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8113 // do not have a prototype. Integer promotions are performed on each
8114 // argument, and arguments that have type float are promoted to double.
8115 ExprResult DefaultArgumentPromotion(Expr *E);
8116
8117 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8118 const FunctionProtoType *Proto,
8119 Expr *Fn);
8120
8121 /// Determine the degree of POD-ness for an expression.
8122 /// Incomplete types are considered POD, since this check can be performed
8123 /// when we're in an unevaluated context.
8124 VarArgKind isValidVarArgType(const QualType &Ty);
8125
8126 /// Check to see if the given expression is a valid argument to a variadic
8127 /// function, issuing a diagnostic if not.
8128 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8129
8130 /// GatherArgumentsForCall - Collector argument expressions for various
8131 /// form of call prototypes.
8132 bool GatherArgumentsForCall(
8133 SourceLocation CallLoc, FunctionDecl *FDecl,
8134 const FunctionProtoType *Proto, unsigned FirstParam,
8135 ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs,
8136 VariadicCallType CallType = VariadicCallType::DoesNotApply,
8137 bool AllowExplicit = false, bool IsListInitialization = false);
8138
8139 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8140 // will create a runtime trap if the resulting type is not a POD type.
8141 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8142 FunctionDecl *FDecl);
8143
8144 // Check that the usual arithmetic conversions can be performed on this pair
8145 // of expressions that might be of enumeration type.
8146 void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc,
8147 ArithConvKind ACK);
8148
8149 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8150 // operands and then handles various conversions that are common to binary
8151 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8152 // routine returns the first non-arithmetic type found. The client is
8153 // responsible for emitting appropriate error diagnostics.
8154 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8155 SourceLocation Loc, ArithConvKind ACK);
8156
8157 bool IsAssignConvertCompatible(AssignConvertType ConvTy) {
8158 switch (ConvTy) {
8159 default:
8160 return false;
8161 case AssignConvertType::Compatible:
8162 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
8163 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
8164 return true;
8165 }
8166 llvm_unreachable("impossible");
8167 }
8168
8169 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8170 /// assignment conversion type specified by ConvTy. This returns true if the
8171 /// conversion was invalid or false if the conversion was accepted.
8172 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc,
8173 QualType DstType, QualType SrcType,
8174 Expr *SrcExpr, AssignmentAction Action,
8175 bool *Complained = nullptr);
8176
8177 /// CheckAssignmentConstraints - Perform type checking for assignment,
8178 /// argument passing, variable initialization, and function return values.
8179 /// C99 6.5.16.
8180 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8181 QualType LHSType,
8182 QualType RHSType);
8183
8184 /// Check assignment constraints and optionally prepare for a conversion of
8185 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8186 /// is true.
8187 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8188 ExprResult &RHS, CastKind &Kind,
8189 bool ConvertRHS = true);
8190
8191 /// Check assignment constraints for an assignment of RHS to LHSType.
8192 ///
8193 /// \param LHSType The destination type for the assignment.
8194 /// \param RHS The source expression for the assignment.
8195 /// \param Diagnose If \c true, diagnostics may be produced when checking
8196 /// for assignability. If a diagnostic is produced, \p RHS will be
8197 /// set to ExprError(). Note that this function may still return
8198 /// without producing a diagnostic, even for an invalid assignment.
8199 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8200 /// in an audited Core Foundation API and does not need to be checked
8201 /// for ARC retain issues.
8202 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8203 /// conversions necessary to perform the assignment. If \c false,
8204 /// \p Diagnose must also be \c false.
8205 AssignConvertType CheckSingleAssignmentConstraints(
8206 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8207 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8208
8209 // If the lhs type is a transparent union, check whether we
8210 // can initialize the transparent union with the given expression.
8211 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8212 ExprResult &RHS);
8213
8214 /// the following "Check" methods will return a valid/converted QualType
8215 /// or a null QualType (indicating an error diagnostic was issued).
8216
8217 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8218 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8219 ExprResult &RHS);
8220
8221 /// Diagnose cases where a scalar was implicitly converted to a vector and
8222 /// diagnose the underlying types. Otherwise, diagnose the error
8223 /// as invalid vector logical operands for non-C++ cases.
8224 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8225 ExprResult &RHS);
8226
8227 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8228 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8229 BinaryOperatorKind Opc);
8230 QualType CheckRemainderOperands( // C99 6.5.5
8231 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8232 bool IsCompAssign = false);
8233 QualType CheckAdditionOperands( // C99 6.5.6
8234 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8235 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8236 QualType CheckSubtractionOperands( // C99 6.5.6
8237 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8238 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8239 QualType CheckShiftOperands( // C99 6.5.7
8240 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8241 BinaryOperatorKind Opc, bool IsCompAssign = false);
8242 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
8243 QualType CheckCompareOperands( // C99 6.5.8/9
8244 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8245 BinaryOperatorKind Opc);
8246 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8247 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8248 BinaryOperatorKind Opc);
8249 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8250 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8251 BinaryOperatorKind Opc);
8252 // CheckAssignmentOperands is used for both simple and compound assignment.
8253 // For simple assignment, pass both expressions and a null converted type.
8254 // For compound assignment, pass both expressions and the converted type.
8255 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8256 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8257 BinaryOperatorKind Opc);
8258
8259 /// To be used for checking whether the arguments being passed to
8260 /// function exceeds the number of parameters expected for it.
8261 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8262 bool PartialOverloading = false) {
8263 // We check whether we're just after a comma in code-completion.
8264 if (NumArgs > 0 && PartialOverloading)
8265 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8266 return NumArgs > NumParams;
8267 }
8268
8269 /// Whether the AST is currently being rebuilt to correct immediate
8270 /// invocations. Immediate invocation candidates and references to consteval
8271 /// functions aren't tracked when this is set.
8272 bool RebuildingImmediateInvocation = false;
8273
8274 bool isAlwaysConstantEvaluatedContext() const {
8275 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8276 return (Ctx.isConstantEvaluated() || isConstantEvaluatedOverride) &&
8277 !Ctx.InConditionallyConstantEvaluateContext;
8278 }
8279
8280 /// Determines whether we are currently in a context that
8281 /// is not evaluated as per C++ [expr] p5.
8282 bool isUnevaluatedContext() const {
8283 return currentEvaluationContext().isUnevaluated();
8284 }
8285
8286 bool isImmediateFunctionContext() const {
8287 return currentEvaluationContext().isImmediateFunctionContext();
8288 }
8289
8290 bool isInLifetimeExtendingContext() const {
8291 return currentEvaluationContext().InLifetimeExtendingContext;
8292 }
8293
8294 bool needsRebuildOfDefaultArgOrInit() const {
8295 return currentEvaluationContext().RebuildDefaultArgOrDefaultInit;
8296 }
8297
8298 bool isCheckingDefaultArgumentOrInitializer() const {
8299 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8300 return (Ctx.Context ==
8301 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) ||
8302 Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer;
8303 }
8304
8305 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8306 InnermostDeclarationWithDelayedImmediateInvocations() const {
8307 assert(!ExprEvalContexts.empty() &&
8308 "Must be in an expression evaluation context");
8309 for (const auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8310 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8311 Ctx.DelayedDefaultInitializationContext)
8312 return Ctx.DelayedDefaultInitializationContext;
8313 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8314 Ctx.isUnevaluated())
8315 break;
8316 }
8317 return std::nullopt;
8318 }
8319
8320 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8321 OutermostDeclarationWithDelayedImmediateInvocations() const {
8322 assert(!ExprEvalContexts.empty() &&
8323 "Must be in an expression evaluation context");
8324 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8325 for (auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8326 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8327 !Ctx.DelayedDefaultInitializationContext && Res)
8328 break;
8329 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8330 Ctx.isUnevaluated())
8331 break;
8332 Res = Ctx.DelayedDefaultInitializationContext;
8333 }
8334 return Res;
8335 }
8336
8337 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8338 /// SelfAssigned when inside a CXXMethodDecl.
8339 const FieldDecl *
8340 getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
8341
8342 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
8343
8344 template <typename... Ts>
8345 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
8346 const Ts &...Args) {
8347 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8348 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8349 }
8350
8351 template <typename... Ts>
8352 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8353 const Ts &...Args) {
8354 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8355 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
8356 }
8357
8358 /// Abstract class used to diagnose incomplete types.
8359 struct TypeDiagnoser {
8360 TypeDiagnoser() {}
8361
8362 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
8363 virtual ~TypeDiagnoser() {}
8364 };
8365
8366 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8367 protected:
8368 unsigned DiagID;
8369 std::tuple<const Ts &...> Args;
8370
8371 template <std::size_t... Is>
8372 void emit(const SemaDiagnosticBuilder &DB,
8373 std::index_sequence<Is...>) const {
8374 // Apply all tuple elements to the builder in order.
8375 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8376 (void)Dummy;
8377 }
8378
8379 public:
8380 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8381 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8382 assert(DiagID != 0 && "no diagnostic for type diagnoser");
8383 }
8384
8385 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8386 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8387 emit(DB, std::index_sequence_for<Ts...>());
8388 DB << T;
8389 }
8390 };
8391
8392 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8393 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8394 /// For example, a diagnostic with no other parameters would generally have
8395 /// the form "...%select{incomplete|sizeless}0 type %1...".
8396 template <typename... Ts>
8397 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
8398 public:
8399 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8400 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8401
8402 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8403 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8404 this->emit(DB, std::index_sequence_for<Ts...>());
8405 DB << T->isSizelessType() << T;
8406 }
8407 };
8408
8409 /// Check an argument list for placeholders that we won't try to
8410 /// handle later.
8411 bool CheckArgsForPlaceholders(MultiExprArg args);
8412
8413 /// The C++ "std::source_location::__impl" struct, defined in
8414 /// \<source_location>.
8415 RecordDecl *StdSourceLocationImplDecl;
8416
8417 /// A stack of expression evaluation contexts.
8418 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
8419
8420 // Set of failed immediate invocations to avoid double diagnosing.
8421 llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
8422
8423 /// List of SourceLocations where 'self' is implicitly retained inside a
8424 /// block.
8425 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
8426 ImplicitlyRetainedSelfLocs;
8427
8428 /// Do an explicit extend of the given block pointer if we're in ARC.
8429 void maybeExtendBlockObject(ExprResult &E);
8430
8431 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8432 SourceLocation LocationOfExcessPrecisionNotSatisfied;
8433 void DiagnosePrecisionLossInComplexDivision();
8434
8435private:
8436 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8437
8438 /// Methods for marking which expressions involve dereferencing a pointer
8439 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8440 /// they are parsed, meaning that a noderef pointer may not be accessed. For
8441 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8442 /// `*p`, but need to check that `address of` is called on it. This requires
8443 /// keeping a container of all pending expressions and checking if the address
8444 /// of them are eventually taken.
8445 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8446 void CheckAddressOfNoDeref(const Expr *E);
8447
8448 ///@}
8449
8450 //
8451 //
8452 // -------------------------------------------------------------------------
8453 //
8454 //
8455
8456 /// \name C++ Expressions
8457 /// Implementations are in SemaExprCXX.cpp
8458 ///@{
8459
8460public:
8461 /// The C++ "std::bad_alloc" class, which is defined by the C++
8462 /// standard library.
8463 LazyDeclPtr StdBadAlloc;
8464
8465 /// The C++ "std::align_val_t" enum class, which is defined by the C++
8466 /// standard library.
8467 LazyDeclPtr StdAlignValT;
8468
8469 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
8470 RecordDecl *CXXTypeInfoDecl;
8471
8472 /// A flag to remember whether the implicit forms of operator new and delete
8473 /// have been declared.
8474 bool GlobalNewDeleteDeclared;
8475
8476 /// Delete-expressions to be analyzed at the end of translation unit
8477 ///
8478 /// This list contains class members, and locations of delete-expressions
8479 /// that could not be proven as to whether they mismatch with new-expression
8480 /// used in initializer of the field.
8481 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8482
8483 /// Handle the result of the special case name lookup for inheriting
8484 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8485 /// constructor names in member using declarations, even if 'X' is not the
8486 /// name of the corresponding type.
8487 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
8488 SourceLocation NameLoc,
8489 const IdentifierInfo &Name);
8490
8491 ParsedType getConstructorName(const IdentifierInfo &II,
8492 SourceLocation NameLoc, Scope *S,
8493 CXXScopeSpec &SS, bool EnteringContext);
8494 ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc,
8495 Scope *S, CXXScopeSpec &SS,
8496 ParsedType ObjectType, bool EnteringContext);
8497
8498 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
8499 ParsedType ObjectType);
8500
8501 /// Build a C++ typeid expression with a type operand.
8502 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8503 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8504
8505 /// Build a C++ typeid expression with an expression operand.
8506 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8507 Expr *Operand, SourceLocation RParenLoc);
8508
8509 /// ActOnCXXTypeid - Parse typeid( something ).
8510 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
8511 bool isType, void *TyOrExpr,
8512 SourceLocation RParenLoc);
8513
8514 /// Build a Microsoft __uuidof expression with a type operand.
8515 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8516 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8517
8518 /// Build a Microsoft __uuidof expression with an expression operand.
8519 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8520 Expr *Operand, SourceLocation RParenLoc);
8521
8522 /// ActOnCXXUuidof - Parse __uuidof( something ).
8523 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
8524 bool isType, void *TyOrExpr,
8525 SourceLocation RParenLoc);
8526
8527 //// ActOnCXXThis - Parse 'this' pointer.
8528 ExprResult ActOnCXXThis(SourceLocation Loc);
8529
8530 /// Check whether the type of 'this' is valid in the current context.
8531 bool CheckCXXThisType(SourceLocation Loc, QualType Type);
8532
8533 /// Build a CXXThisExpr and mark it referenced in the current context.
8534 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8535 void MarkThisReferenced(CXXThisExpr *This);
8536
8537 /// Try to retrieve the type of the 'this' pointer.
8538 ///
8539 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8540 QualType getCurrentThisType();
8541
8542 /// When non-NULL, the C++ 'this' expression is allowed despite the
8543 /// current context not being a non-static member function. In such cases,
8544 /// this provides the type used for 'this'.
8545 QualType CXXThisTypeOverride;
8546
8547 /// RAII object used to temporarily allow the C++ 'this' expression
8548 /// to be used, with the given qualifiers on the current class type.
8549 class CXXThisScopeRAII {
8550 Sema &S;
8551 QualType OldCXXThisTypeOverride;
8552 bool Enabled;
8553
8554 public:
8555 /// Introduce a new scope where 'this' may be allowed (when enabled),
8556 /// using the given declaration (which is either a class template or a
8557 /// class) along with the given qualifiers.
8558 /// along with the qualifiers placed on '*this'.
8559 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8560 bool Enabled = true);
8561
8562 ~CXXThisScopeRAII();
8563 CXXThisScopeRAII(const CXXThisScopeRAII &) = delete;
8564 CXXThisScopeRAII &operator=(const CXXThisScopeRAII &) = delete;
8565 };
8566
8567 /// Make sure the value of 'this' is actually available in the current
8568 /// context, if it is a potentially evaluated context.
8569 ///
8570 /// \param Loc The location at which the capture of 'this' occurs.
8571 ///
8572 /// \param Explicit Whether 'this' is explicitly captured in a lambda
8573 /// capture list.
8574 ///
8575 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8576 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8577 /// This is useful when enclosing lambdas must speculatively capture
8578 /// 'this' that may or may not be used in certain specializations of
8579 /// a nested generic lambda (depending on whether the name resolves to
8580 /// a non-static member function or a static function).
8581 /// \return returns 'true' if failed, 'false' if success.
8582 bool CheckCXXThisCapture(
8583 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8584 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8585 bool ByCopy = false);
8586
8587 /// Determine whether the given type is the type of *this that is used
8588 /// outside of the body of a member function for a type that is currently
8589 /// being defined.
8590 bool isThisOutsideMemberFunctionBody(QualType BaseType);
8591
8592 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8593 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
8594
8595 /// Build a boolean-typed literal expression.
8596 ExprResult BuildBoolLiteral(SourceLocation Loc, bool Value);
8597
8598 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8599 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
8600
8601 //// ActOnCXXThrow - Parse throw expressions.
8602 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
8603 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
8604 bool IsThrownVarInScope);
8605
8606 /// CheckCXXThrowOperand - Validate the operand of a throw.
8607 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8608
8609 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8610 /// Can be interpreted either as function-style casting ("int(x)")
8611 /// or class type construction ("ClassType(x,y,z)")
8612 /// or creation of a value-initialized type ("int()").
8613 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
8614 SourceLocation LParenOrBraceLoc,
8615 MultiExprArg Exprs,
8616 SourceLocation RParenOrBraceLoc,
8617 bool ListInitialization);
8618
8619 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
8620 SourceLocation LParenLoc,
8621 MultiExprArg Exprs,
8622 SourceLocation RParenLoc,
8623 bool ListInitialization);
8624
8625 /// Parsed a C++ 'new' expression (C++ 5.3.4).
8626 ///
8627 /// E.g.:
8628 /// @code new (memory) int[size][4] @endcode
8629 /// or
8630 /// @code ::new Foo(23, "hello") @endcode
8631 ///
8632 /// \param StartLoc The first location of the expression.
8633 /// \param UseGlobal True if 'new' was prefixed with '::'.
8634 /// \param PlacementLParen Opening paren of the placement arguments.
8635 /// \param PlacementArgs Placement new arguments.
8636 /// \param PlacementRParen Closing paren of the placement arguments.
8637 /// \param TypeIdParens If the type is in parens, the source range.
8638 /// \param D The type to be allocated, as well as array dimensions.
8639 /// \param Initializer The initializing expression or initializer-list, or
8640 /// null if there is none.
8641 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8642 SourceLocation PlacementLParen,
8643 MultiExprArg PlacementArgs,
8644 SourceLocation PlacementRParen,
8645 SourceRange TypeIdParens, Declarator &D,
8646 Expr *Initializer);
8647 ExprResult
8648 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8649 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8650 SourceRange TypeIdParens, QualType AllocType,
8651 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8652 SourceRange DirectInitRange, Expr *Initializer);
8653
8654 /// Determine whether \p FD is an aligned allocation or deallocation
8655 /// function that is unavailable.
8656 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
8657
8658 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8659 /// function that is unavailable.
8660 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
8661 SourceLocation Loc);
8662
8663 /// Checks that a type is suitable as the allocated type
8664 /// in a new-expression.
8665 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8666 SourceRange R);
8667
8668 /// Finds the overloads of operator new and delete that are appropriate
8669 /// for the allocation.
8670 std::optional<ResolvedAllocation> FindAllocationFunctions(
8671 SourceLocation StartLoc, SourceRange Range,
8672 AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope,
8673 QualType AllocType, bool IsArray, const ImplicitAllocationParameters &IAP,
8674 MultiExprArg PlaceArgs, bool Diagnose = true);
8675
8676 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8677 /// delete. These are:
8678 /// @code
8679 /// // C++03:
8680 /// void* operator new(std::size_t) throw(std::bad_alloc);
8681 /// void* operator new[](std::size_t) throw(std::bad_alloc);
8682 /// void operator delete(void *) throw();
8683 /// void operator delete[](void *) throw();
8684 /// // C++11:
8685 /// void* operator new(std::size_t);
8686 /// void* operator new[](std::size_t);
8687 /// void operator delete(void *) noexcept;
8688 /// void operator delete[](void *) noexcept;
8689 /// // C++1y:
8690 /// void* operator new(std::size_t);
8691 /// void* operator new[](std::size_t);
8692 /// void operator delete(void *) noexcept;
8693 /// void operator delete[](void *) noexcept;
8694 /// void operator delete(void *, std::size_t) noexcept;
8695 /// void operator delete[](void *, std::size_t) noexcept;
8696 /// @endcode
8697 /// Note that the placement and nothrow forms of new are *not* implicitly
8698 /// declared. Their use requires including \<new\>.
8699 void DeclareGlobalNewDelete();
8700 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
8701 ArrayRef<QualType> Params);
8702
8703 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
8704 DeclarationName Name, FunctionDecl *&Operator,
8705 ImplicitDeallocationParameters,
8706 bool Diagnose = true);
8707 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
8708 ImplicitDeallocationParameters,
8709 DeclarationName Name,
8710 bool Diagnose = true);
8711 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
8712 CXXRecordDecl *RD,
8713 bool Diagnose,
8714 bool LookForGlobal,
8715 DeclarationName Name);
8716
8717 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8718 /// @code ::delete ptr; @endcode
8719 /// or
8720 /// @code delete [] ptr; @endcode
8721 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8722 bool ArrayForm, Expr *Operand);
8723 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
8724 bool IsDelete, bool CallCanBeVirtual,
8725 bool WarnOnNonAbstractTypes,
8726 SourceLocation DtorLoc);
8727
8728 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
8729 Expr *Operand, SourceLocation RParen);
8730 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8731 SourceLocation RParen);
8732
8733 ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base,
8734 SourceLocation OpLoc,
8735 tok::TokenKind OpKind,
8736 ParsedType &ObjectType,
8737 bool &MayBePseudoDestructor);
8738
8739 ExprResult BuildPseudoDestructorExpr(
8740 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8741 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8742 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8743
8744 ExprResult ActOnPseudoDestructorExpr(
8745 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8746 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8747 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8748
8749 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
8750 SourceLocation OpLoc,
8751 tok::TokenKind OpKind,
8752 SourceLocation TildeLoc,
8753 const DeclSpec &DS);
8754
8755 /// MaybeCreateExprWithCleanups - If the current full-expression
8756 /// requires any cleanups, surround it with a ExprWithCleanups node.
8757 /// Otherwise, just returns the passed-in expression.
8758 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
8759 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
8760 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
8761
8762 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8763 return ActOnFinishFullExpr(
8764 Expr, CC: Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8765 }
8766 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
8767 bool DiscardedValue, bool IsConstexpr = false,
8768 bool IsTemplateArgument = false);
8769 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
8770
8771 /// Process the expression contained within a decltype. For such expressions,
8772 /// certain semantic checks on temporaries are delayed until this point, and
8773 /// are omitted for the 'topmost' call in the decltype expression. If the
8774 /// topmost call bound a temporary, strip that temporary off the expression.
8775 ExprResult ActOnDecltypeExpression(Expr *E);
8776
8777 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8778 bool IsUDSuffix);
8779
8780 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
8781
8782 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8783 SourceLocation StmtLoc,
8784 ConditionKind CK);
8785
8786 /// Check the use of the given variable as a C++ condition in an if,
8787 /// while, do-while, or switch statement.
8788 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
8789 SourceLocation StmtLoc, ConditionKind CK);
8790
8791 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8792 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8793
8794 /// Helper function to determine whether this is the (deprecated) C++
8795 /// conversion from a string literal to a pointer to non-const char or
8796 /// non-const wchar_t (for narrow and wide string literals,
8797 /// respectively).
8798 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8799
8800 /// PerformImplicitConversion - Perform an implicit conversion of the
8801 /// expression From to the type ToType using the pre-computed implicit
8802 /// conversion sequence ICS. Returns the converted
8803 /// expression. Action is the kind of conversion we're performing,
8804 /// used in the error message.
8805 ExprResult PerformImplicitConversion(
8806 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8807 AssignmentAction Action,
8808 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
8809
8810 /// PerformImplicitConversion - Perform an implicit conversion of the
8811 /// expression From to the type ToType by following the standard
8812 /// conversion sequence SCS. Returns the converted
8813 /// expression. Flavor is the context in which we're performing this
8814 /// conversion, for use in error messages.
8815 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8816 const StandardConversionSequence &SCS,
8817 AssignmentAction Action,
8818 CheckedConversionKind CCK);
8819
8820 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8821
8822 /// Parsed one of the type trait support pseudo-functions.
8823 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8824 ArrayRef<ParsedType> Args,
8825 SourceLocation RParenLoc);
8826 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8827 ArrayRef<TypeSourceInfo *> Args,
8828 SourceLocation RParenLoc);
8829
8830 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8831 /// pseudo-functions.
8832 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8833 ParsedType LhsTy, Expr *DimExpr,
8834 SourceLocation RParen);
8835
8836 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8837 TypeSourceInfo *TSInfo, Expr *DimExpr,
8838 SourceLocation RParen);
8839
8840 /// ActOnExpressionTrait - Parsed one of the unary type trait support
8841 /// pseudo-functions.
8842 ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8843 Expr *Queried, SourceLocation RParen);
8844
8845 ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8846 Expr *Queried, SourceLocation RParen);
8847
8848 QualType CheckPointerToMemberOperands( // C++ 5.5
8849 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc,
8850 bool isIndirect);
8851 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
8852 ExprResult &RHS,
8853 SourceLocation QuestionLoc);
8854
8855 //// Determines if a type is trivially relocatable
8856 /// according to the C++26 rules.
8857 // FIXME: This is in Sema because it requires
8858 // overload resolution, can we move to ASTContext?
8859 bool IsCXXTriviallyRelocatableType(QualType T);
8860 bool IsCXXTriviallyRelocatableType(const CXXRecordDecl &RD);
8861
8862 /// Check the operands of ?: under C++ semantics.
8863 ///
8864 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8865 /// extension. In this case, LHS == Cond. (But they're not aliases.)
8866 ///
8867 /// This function also implements GCC's vector extension and the
8868 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8869 /// permit the use of a?b:c where the type of a is that of a integer vector
8870 /// with the same number of elements and size as the vectors of b and c. If
8871 /// one of either b or c is a scalar it is implicitly converted to match the
8872 /// type of the vector. Otherwise the expression is ill-formed. If both b and
8873 /// c are scalars, then b and c are checked and converted to the type of a if
8874 /// possible.
8875 ///
8876 /// The expressions are evaluated differently for GCC's and OpenCL's
8877 /// extensions. For the GCC extension, the ?: operator is evaluated as
8878 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8879 /// For the OpenCL extensions, the ?: operator is evaluated as
8880 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
8881 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
8882 QualType CXXCheckConditionalOperands( // C++ 5.16
8883 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8884 ExprObjectKind &OK, SourceLocation questionLoc);
8885
8886 /// Find a merged pointer type and convert the two expressions to it.
8887 ///
8888 /// This finds the composite pointer type for \p E1 and \p E2 according to
8889 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8890 /// it. It does not emit diagnostics (FIXME: that's not true if \p
8891 /// ConvertArgs is \c true).
8892 ///
8893 /// \param Loc The location of the operator requiring these two expressions to
8894 /// be converted to the composite pointer type.
8895 ///
8896 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
8897 /// type.
8898 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8899 bool ConvertArgs = true);
8900 QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1,
8901 ExprResult &E2, bool ConvertArgs = true) {
8902 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8903 QualType Composite =
8904 FindCompositePointerType(Loc, E1&: E1Tmp, E2&: E2Tmp, ConvertArgs);
8905 E1 = E1Tmp;
8906 E2 = E2Tmp;
8907 return Composite;
8908 }
8909
8910 /// MaybeBindToTemporary - If the passed in expression has a record type with
8911 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
8912 /// it simply returns the passed in expression.
8913 ExprResult MaybeBindToTemporary(Expr *E);
8914
8915 /// IgnoredValueConversions - Given that an expression's result is
8916 /// syntactically ignored, perform any conversions that are
8917 /// required.
8918 ExprResult IgnoredValueConversions(Expr *E);
8919
8920 ExprResult CheckUnevaluatedOperand(Expr *E);
8921
8922 IfExistsResult
8923 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
8924 const DeclarationNameInfo &TargetNameInfo);
8925
8926 IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S,
8927 SourceLocation KeywordLoc,
8928 bool IsIfExists, CXXScopeSpec &SS,
8929 UnqualifiedId &Name);
8930
8931 RequiresExprBodyDecl *
8932 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8933 ArrayRef<ParmVarDecl *> LocalParameters,
8934 Scope *BodyScope);
8935 void ActOnFinishRequiresExpr();
8936 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8937 concepts::Requirement *ActOnTypeRequirement(SourceLocation TypenameKWLoc,
8938 CXXScopeSpec &SS,
8939 SourceLocation NameLoc,
8940 const IdentifierInfo *TypeName,
8941 TemplateIdAnnotation *TemplateId);
8942 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8943 SourceLocation NoexceptLoc);
8944 concepts::Requirement *ActOnCompoundRequirement(
8945 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8946 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8947 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8948 concepts::ExprRequirement *BuildExprRequirement(
8949 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8950 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8951 concepts::ExprRequirement *BuildExprRequirement(
8952 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8953 bool IsSatisfied, SourceLocation NoexceptLoc,
8954 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8955 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8956 concepts::TypeRequirement *BuildTypeRequirement(
8957 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8958 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8959 concepts::NestedRequirement *
8960 BuildNestedRequirement(StringRef InvalidConstraintEntity,
8961 const ASTConstraintSatisfaction &Satisfaction);
8962 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8963 RequiresExprBodyDecl *Body,
8964 SourceLocation LParenLoc,
8965 ArrayRef<ParmVarDecl *> LocalParameters,
8966 SourceLocation RParenLoc,
8967 ArrayRef<concepts::Requirement *> Requirements,
8968 SourceLocation ClosingBraceLoc);
8969
8970private:
8971 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
8972 bool IsDelete);
8973
8974 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8975 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8976 bool DeleteWasArrayForm);
8977
8978 std::optional<AllocationArgumentSet>
8979 resolveAllocationArguments(LookupResult &R,
8980 const ImplicitAllocationParameters &,
8981 ArrayRef<Expr *> PlacementArguments);
8982
8983 // Attempts to construct the type identity argument for the call to a
8984 // type aware operator new. Returns null on failure.
8985 Expr *tryGetTypeIdentityArgument(QualType Type, SourceLocation);
8986
8987 Expr *AllocationSizeExpr = nullptr;
8988 Expr *AllocationAlignmentExpr = nullptr;
8989 llvm::DenseMap<QualType, Expr *> AllocationTypeIdentityArguments;
8990
8991 ///@}
8992
8993 //
8994 //
8995 // -------------------------------------------------------------------------
8996 //
8997 //
8998
8999 /// \name Member Access Expressions
9000 /// Implementations are in SemaExprMember.cpp
9001 ///@{
9002
9003public:
9004 /// Check whether an expression might be an implicit class member access.
9005 bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R,
9006 bool IsAddressOfOperand);
9007
9008 /// Builds an expression which might be an implicit member expression.
9009 ExprResult BuildPossibleImplicitMemberExpr(
9010 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
9011 const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
9012
9013 /// Builds an implicit member access expression. The current context
9014 /// is known to be an instance method, and the given unqualified lookup
9015 /// set is known to contain only instance members, at least one of which
9016 /// is from an appropriate type.
9017 ExprResult
9018 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9019 LookupResult &R,
9020 const TemplateArgumentListInfo *TemplateArgs,
9021 bool IsDefiniteInstance, const Scope *S);
9022
9023 ExprResult ActOnDependentMemberExpr(
9024 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
9025 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9026 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9027 const TemplateArgumentListInfo *TemplateArgs);
9028
9029 /// The main callback when the parser finds something like
9030 /// expression . [nested-name-specifier] identifier
9031 /// expression -> [nested-name-specifier] identifier
9032 /// where 'identifier' encompasses a fairly broad spectrum of
9033 /// possibilities, including destructor and operator references.
9034 ///
9035 /// \param OpKind either tok::arrow or tok::period
9036 /// \param ObjCImpDecl the current Objective-C \@implementation
9037 /// decl; this is an ugly hack around the fact that Objective-C
9038 /// \@implementations aren't properly put in the context chain
9039 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
9040 tok::TokenKind OpKind, CXXScopeSpec &SS,
9041 SourceLocation TemplateKWLoc,
9042 UnqualifiedId &Member, Decl *ObjCImpDecl);
9043
9044 MemberExpr *
9045 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
9046 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
9047 ValueDecl *Member, DeclAccessPair FoundDecl,
9048 bool HadMultipleCandidates,
9049 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
9050 ExprValueKind VK, ExprObjectKind OK,
9051 const TemplateArgumentListInfo *TemplateArgs = nullptr);
9052
9053 // Check whether the declarations we found through a nested-name
9054 // specifier in a member expression are actually members of the base
9055 // type. The restriction here is:
9056 //
9057 // C++ [expr.ref]p2:
9058 // ... In these cases, the id-expression shall name a
9059 // member of the class or of one of its base classes.
9060 //
9061 // So it's perfectly legitimate for the nested-name specifier to name
9062 // an unrelated class, and for us to find an overload set including
9063 // decls from classes which are not superclasses, as long as the decl
9064 // we actually pick through overload resolution is from a superclass.
9065 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
9066 const CXXScopeSpec &SS,
9067 const LookupResult &R);
9068
9069 // This struct is for use by ActOnMemberAccess to allow
9070 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
9071 // changing the access operator from a '.' to a '->' (to see if that is the
9072 // change needed to fix an error about an unknown member, e.g. when the class
9073 // defines a custom operator->).
9074 struct ActOnMemberAccessExtraArgs {
9075 Scope *S;
9076 UnqualifiedId &Id;
9077 Decl *ObjCImpDecl;
9078 };
9079
9080 ExprResult BuildMemberReferenceExpr(
9081 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
9082 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9083 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9084 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
9085 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9086
9087 ExprResult
9088 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
9089 bool IsArrow, const CXXScopeSpec &SS,
9090 SourceLocation TemplateKWLoc,
9091 NamedDecl *FirstQualifierInScope, LookupResult &R,
9092 const TemplateArgumentListInfo *TemplateArgs,
9093 const Scope *S, bool SuppressQualifierCheck = false,
9094 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9095
9096 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
9097 SourceLocation OpLoc,
9098 const CXXScopeSpec &SS, FieldDecl *Field,
9099 DeclAccessPair FoundDecl,
9100 const DeclarationNameInfo &MemberNameInfo);
9101
9102 /// Perform conversions on the LHS of a member access expression.
9103 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
9104
9105 ExprResult BuildAnonymousStructUnionMemberReference(
9106 const CXXScopeSpec &SS, SourceLocation nameLoc,
9107 IndirectFieldDecl *indirectField,
9108 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none),
9109 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
9110
9111private:
9112 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
9113
9114 ///@}
9115
9116 //
9117 //
9118 // -------------------------------------------------------------------------
9119 //
9120 //
9121
9122 /// \name Initializers
9123 /// Implementations are in SemaInit.cpp
9124 ///@{
9125
9126public:
9127 /// Stack of types that correspond to the parameter entities that are
9128 /// currently being copy-initialized. Can be empty.
9129 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
9130
9131 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
9132 AggregateDeductionCandidates;
9133
9134 bool IsStringInit(Expr *Init, const ArrayType *AT);
9135
9136 /// Determine whether we can perform aggregate initialization for the purposes
9137 /// of overload resolution.
9138 bool CanPerformAggregateInitializationForOverloadResolution(
9139 const InitializedEntity &Entity, InitListExpr *From);
9140
9141 ExprResult ActOnDesignatedInitializer(Designation &Desig,
9142 SourceLocation EqualOrColonLoc,
9143 bool GNUSyntax, ExprResult Init);
9144
9145 /// Check that the lifetime of the initializer (and its subobjects) is
9146 /// sufficient for initializing the entity, and perform lifetime extension
9147 /// (when permitted) if not.
9148 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
9149
9150 MaterializeTemporaryExpr *
9151 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
9152 bool BoundToLvalueReference);
9153
9154 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9155 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9156 /// we don't have xvalues there.
9157 ExprResult TemporaryMaterializationConversion(Expr *E);
9158
9159 ExprResult PerformQualificationConversion(
9160 Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
9161 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
9162
9163 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
9164 ExprResult Init);
9165 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
9166 SourceLocation EqualLoc, ExprResult Init,
9167 bool TopLevelOfInitList = false,
9168 bool AllowExplicit = false);
9169
9170 QualType DeduceTemplateSpecializationFromInitializer(
9171 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9172 const InitializationKind &Kind, MultiExprArg Init);
9173
9174 ///@}
9175
9176 //
9177 //
9178 // -------------------------------------------------------------------------
9179 //
9180 //
9181
9182 /// \name C++ Lambda Expressions
9183 /// Implementations are in SemaLambda.cpp
9184 ///@{
9185
9186public:
9187 /// Create a new lambda closure type.
9188 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
9189 TypeSourceInfo *Info,
9190 unsigned LambdaDependencyKind,
9191 LambdaCaptureDefault CaptureDefault);
9192
9193 /// Number lambda for linkage purposes if necessary.
9194 void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method,
9195 std::optional<CXXRecordDecl::LambdaNumbering>
9196 NumberingOverride = std::nullopt);
9197
9198 /// Endow the lambda scope info with the relevant properties.
9199 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9200 SourceRange IntroducerRange,
9201 LambdaCaptureDefault CaptureDefault,
9202 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9203 bool Mutable);
9204
9205 CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange,
9206 CXXRecordDecl *Class);
9207
9208 void AddTemplateParametersToLambdaCallOperator(
9209 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9210 TemplateParameterList *TemplateParams);
9211
9212 void
9213 CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc,
9214 SourceLocation CallOperatorLoc,
9215 const AssociatedConstraint &TrailingRequiresClause,
9216 TypeSourceInfo *MethodTyInfo,
9217 ConstexprSpecKind ConstexprKind, StorageClass SC,
9218 ArrayRef<ParmVarDecl *> Params,
9219 bool HasExplicitResultType);
9220
9221 /// Returns true if the explicit object parameter was invalid.
9222 bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method,
9223 SourceLocation CallLoc);
9224
9225 /// Perform initialization analysis of the init-capture and perform
9226 /// any implicit conversions such as an lvalue-to-rvalue conversion if
9227 /// not being used to initialize a reference.
9228 ParsedType actOnLambdaInitCaptureInitialization(
9229 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9230 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9231 return ParsedType::make(P: buildLambdaInitCaptureInitialization(
9232 Loc, ByRef, EllipsisLoc, NumExpansions: std::nullopt, Id,
9233 DirectInit: InitKind != LambdaCaptureInitKind::CopyInit, Init));
9234 }
9235 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
9236 SourceLocation EllipsisLoc,
9237 UnsignedOrNone NumExpansions,
9238 IdentifierInfo *Id,
9239 bool DirectInit, Expr *&Init);
9240
9241 /// Create a dummy variable within the declcontext of the lambda's
9242 /// call operator, for name lookup purposes for a lambda init capture.
9243 ///
9244 /// CodeGen handles emission of lambda captures, ignoring these dummy
9245 /// variables appropriately.
9246 VarDecl *createLambdaInitCaptureVarDecl(
9247 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9248 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9249
9250 /// Add an init-capture to a lambda scope.
9251 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9252
9253 /// Note that we have finished the explicit captures for the
9254 /// given lambda.
9255 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
9256
9257 /// Deduce a block or lambda's return type based on the return
9258 /// statements present in the body.
9259 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
9260
9261 /// Once the Lambdas capture are known, we can start to create the closure,
9262 /// call operator method, and keep track of the captures.
9263 /// We do the capture lookup here, but they are not actually captured until
9264 /// after we know what the qualifiers of the call operator are.
9265 void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
9266 Scope *CurContext);
9267
9268 /// This is called after parsing the explicit template parameter list
9269 /// on a lambda (if it exists) in C++2a.
9270 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
9271 SourceLocation LAngleLoc,
9272 ArrayRef<NamedDecl *> TParams,
9273 SourceLocation RAngleLoc,
9274 ExprResult RequiresClause);
9275
9276 void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
9277 SourceLocation MutableLoc);
9278
9279 void ActOnLambdaClosureParameters(
9280 Scope *LambdaScope,
9281 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo);
9282
9283 /// ActOnStartOfLambdaDefinition - This is called just before we start
9284 /// parsing the body of a lambda; it analyzes the explicit captures and
9285 /// arguments, and sets up various data-structures for the body of the
9286 /// lambda.
9287 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
9288 Declarator &ParamInfo, const DeclSpec &DS);
9289
9290 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9291 /// is invoked to pop the information about the lambda.
9292 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9293 bool IsInstantiation = false);
9294
9295 /// ActOnLambdaExpr - This is called when the body of a lambda expression
9296 /// was successfully completed.
9297 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body);
9298
9299 /// Does copying/destroying the captured variable have side effects?
9300 bool CaptureHasSideEffects(const sema::Capture &From);
9301
9302 /// Diagnose if an explicit lambda capture is unused. Returns true if a
9303 /// diagnostic is emitted.
9304 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9305 SourceRange FixItRange,
9306 const sema::Capture &From);
9307
9308 /// Build a FieldDecl suitable to hold the given capture.
9309 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture,
9310 bool IsOpenMP = false);
9311
9312 /// Initialize the given capture with a suitable expression.
9313 ExprResult BuildCaptureInit(const sema::Capture &Capture,
9314 SourceLocation ImplicitCaptureLoc,
9315 bool IsOpenMPMapping = false);
9316
9317 /// Complete a lambda-expression having processed and attached the
9318 /// lambda body.
9319 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc);
9320
9321 /// Get the return type to use for a lambda's conversion function(s) to
9322 /// function pointer type, given the type of the call operator.
9323 QualType
9324 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
9325 CallingConv CC);
9326
9327 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
9328 SourceLocation ConvLocation,
9329 CXXConversionDecl *Conv, Expr *Src);
9330
9331 class LambdaScopeForCallOperatorInstantiationRAII
9332 : private FunctionScopeRAII {
9333 public:
9334 LambdaScopeForCallOperatorInstantiationRAII(
9335 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9336 LocalInstantiationScope &Scope,
9337 bool ShouldAddDeclsFromParentScope = true);
9338 };
9339
9340 /// Compute the mangling number context for a lambda expression or
9341 /// block literal. Also return the extra mangling decl if any.
9342 ///
9343 /// \param DC - The DeclContext containing the lambda expression or
9344 /// block literal.
9345 std::tuple<MangleNumberingContext *, Decl *>
9346 getCurrentMangleNumberContext(const DeclContext *DC);
9347
9348 ///@}
9349
9350 //
9351 //
9352 // -------------------------------------------------------------------------
9353 //
9354 //
9355
9356 /// \name Name Lookup
9357 ///
9358 /// These routines provide name lookup that is used during semantic
9359 /// analysis to resolve the various kinds of names (identifiers,
9360 /// overloaded operator names, constructor names, etc.) into zero or
9361 /// more declarations within a particular scope. The major entry
9362 /// points are LookupName, which performs unqualified name lookup,
9363 /// and LookupQualifiedName, which performs qualified name lookup.
9364 ///
9365 /// All name lookup is performed based on some specific criteria,
9366 /// which specify what names will be visible to name lookup and how
9367 /// far name lookup should work. These criteria are important both
9368 /// for capturing language semantics (certain lookups will ignore
9369 /// certain names, for example) and for performance, since name
9370 /// lookup is often a bottleneck in the compilation of C++. Name
9371 /// lookup criteria is specified via the LookupCriteria enumeration.
9372 ///
9373 /// The results of name lookup can vary based on the kind of name
9374 /// lookup performed, the current language, and the translation
9375 /// unit. In C, for example, name lookup will either return nothing
9376 /// (no entity found) or a single declaration. In C++, name lookup
9377 /// can additionally refer to a set of overloaded functions or
9378 /// result in an ambiguity. All of the possible results of name
9379 /// lookup are captured by the LookupResult class, which provides
9380 /// the ability to distinguish among them.
9381 ///
9382 /// Implementations are in SemaLookup.cpp
9383 ///@{
9384
9385public:
9386 /// Tracks whether we are in a context where typo correction is
9387 /// disabled.
9388 bool DisableTypoCorrection;
9389
9390 /// The number of typos corrected by CorrectTypo.
9391 unsigned TyposCorrected;
9392
9393 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9394 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9395
9396 /// A cache containing identifiers for which typo correction failed and
9397 /// their locations, so that repeated attempts to correct an identifier in a
9398 /// given location are ignored if typo correction already failed for it.
9399 IdentifierSourceLocations TypoCorrectionFailures;
9400
9401 /// SpecialMemberOverloadResult - The overloading result for a special member
9402 /// function.
9403 ///
9404 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9405 /// integer are used to determine whether overload resolution succeeded.
9406 class SpecialMemberOverloadResult {
9407 public:
9408 enum Kind { NoMemberOrDeleted, Ambiguous, Success };
9409
9410 private:
9411 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9412
9413 public:
9414 SpecialMemberOverloadResult() {}
9415 SpecialMemberOverloadResult(CXXMethodDecl *MD)
9416 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9417
9418 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
9419 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9420
9421 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
9422 void setKind(Kind K) { Pair.setInt(K); }
9423 };
9424
9425 using SpecialMemberCacheKey = std::pair<const CXXRecordDecl *, unsigned>;
9426
9427 /// A cache of special member function overload resolution results
9428 /// for C++ records.
9429 llvm::DenseMap<SpecialMemberCacheKey, SpecialMemberOverloadResult>
9430 SpecialMemberCache;
9431
9432 enum class AcceptableKind { Visible, Reachable };
9433
9434 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9435 // TODO: make this is a typesafe union.
9436 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
9437 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
9438
9439 /// Describes the kind of name lookup to perform.
9440 enum LookupNameKind {
9441 /// Ordinary name lookup, which finds ordinary names (functions,
9442 /// variables, typedefs, etc.) in C and most kinds of names
9443 /// (functions, variables, members, types, etc.) in C++.
9444 LookupOrdinaryName = 0,
9445 /// Tag name lookup, which finds the names of enums, classes,
9446 /// structs, and unions.
9447 LookupTagName,
9448 /// Label name lookup.
9449 LookupLabel,
9450 /// Member name lookup, which finds the names of
9451 /// class/struct/union members.
9452 LookupMemberName,
9453 /// Look up of an operator name (e.g., operator+) for use with
9454 /// operator overloading. This lookup is similar to ordinary name
9455 /// lookup, but will ignore any declarations that are class members.
9456 LookupOperatorName,
9457 /// Look up a name following ~ in a destructor name. This is an ordinary
9458 /// lookup, but prefers tags to typedefs.
9459 LookupDestructorName,
9460 /// Look up of a name that precedes the '::' scope resolution
9461 /// operator in C++. This lookup completely ignores operator, object,
9462 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9463 LookupNestedNameSpecifierName,
9464 /// Look up a namespace name within a C++ using directive or
9465 /// namespace alias definition, ignoring non-namespace names (C++
9466 /// [basic.lookup.udir]p1).
9467 LookupNamespaceName,
9468 /// Look up all declarations in a scope with the given name,
9469 /// including resolved using declarations. This is appropriate
9470 /// for checking redeclarations for a using declaration.
9471 LookupUsingDeclName,
9472 /// Look up an ordinary name that is going to be redeclared as a
9473 /// name with linkage. This lookup ignores any declarations that
9474 /// are outside of the current scope unless they have linkage. See
9475 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9476 LookupRedeclarationWithLinkage,
9477 /// Look up a friend of a local class. This lookup does not look
9478 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9479 LookupLocalFriendName,
9480 /// Look up the name of an Objective-C protocol.
9481 LookupObjCProtocolName,
9482 /// Look up implicit 'self' parameter of an objective-c method.
9483 LookupObjCImplicitSelfParam,
9484 /// Look up the name of an OpenMP user-defined reduction operation.
9485 LookupOMPReductionName,
9486 /// Look up the name of an OpenMP user-defined mapper.
9487 LookupOMPMapperName,
9488 /// Look up any declaration with any name.
9489 LookupAnyName
9490 };
9491
9492 /// The possible outcomes of name lookup for a literal operator.
9493 enum LiteralOperatorLookupResult {
9494 /// The lookup resulted in an error.
9495 LOLR_Error,
9496 /// The lookup found no match but no diagnostic was issued.
9497 LOLR_ErrorNoDiagnostic,
9498 /// The lookup found a single 'cooked' literal operator, which
9499 /// expects a normal literal to be built and passed to it.
9500 LOLR_Cooked,
9501 /// The lookup found a single 'raw' literal operator, which expects
9502 /// a string literal containing the spelling of the literal token.
9503 LOLR_Raw,
9504 /// The lookup found an overload set of literal operator templates,
9505 /// which expect the characters of the spelling of the literal token to be
9506 /// passed as a non-type template argument pack.
9507 LOLR_Template,
9508 /// The lookup found an overload set of literal operator templates,
9509 /// which expect the character type and characters of the spelling of the
9510 /// string literal token to be passed as template arguments.
9511 LOLR_StringTemplatePack,
9512 };
9513
9514 SpecialMemberOverloadResult
9515 LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg,
9516 bool VolatileArg, bool RValueThis, bool ConstThis,
9517 bool VolatileThis);
9518
9519 RedeclarationKind forRedeclarationInCurContext() const;
9520
9521 /// Look up a name, looking for a single declaration. Return
9522 /// null if the results were absent, ambiguous, or overloaded.
9523 ///
9524 /// It is preferable to use the elaborated form and explicitly handle
9525 /// ambiguity and overloaded.
9526 NamedDecl *LookupSingleName(
9527 Scope *S, DeclarationName Name, SourceLocation Loc,
9528 LookupNameKind NameKind,
9529 RedeclarationKind Redecl = RedeclarationKind::NotForRedeclaration);
9530
9531 /// Lookup a builtin function, when name lookup would otherwise
9532 /// fail.
9533 bool LookupBuiltin(LookupResult &R);
9534 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9535
9536 /// Perform unqualified name lookup starting from a given
9537 /// scope.
9538 ///
9539 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9540 /// used to find names within the current scope. For example, 'x' in
9541 /// @code
9542 /// int x;
9543 /// int f() {
9544 /// return x; // unqualified name look finds 'x' in the global scope
9545 /// }
9546 /// @endcode
9547 ///
9548 /// Different lookup criteria can find different names. For example, a
9549 /// particular scope can have both a struct and a function of the same
9550 /// name, and each can be found by certain lookup criteria. For more
9551 /// information about lookup criteria, see the documentation for the
9552 /// class LookupCriteria.
9553 ///
9554 /// @param S The scope from which unqualified name lookup will
9555 /// begin. If the lookup criteria permits, name lookup may also search
9556 /// in the parent scopes.
9557 ///
9558 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9559 /// look up and the lookup kind), and is updated with the results of lookup
9560 /// including zero or more declarations and possibly additional information
9561 /// used to diagnose ambiguities.
9562 ///
9563 /// @returns \c true if lookup succeeded and false otherwise.
9564 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9565 bool ForceNoCPlusPlus = false);
9566
9567 /// Perform qualified name lookup into a given context.
9568 ///
9569 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9570 /// names when the context of those names is explicit specified, e.g.,
9571 /// "std::vector" or "x->member", or as part of unqualified name lookup.
9572 ///
9573 /// Different lookup criteria can find different names. For example, a
9574 /// particular scope can have both a struct and a function of the same
9575 /// name, and each can be found by certain lookup criteria. For more
9576 /// information about lookup criteria, see the documentation for the
9577 /// class LookupCriteria.
9578 ///
9579 /// \param R captures both the lookup criteria and any lookup results found.
9580 ///
9581 /// \param LookupCtx The context in which qualified name lookup will
9582 /// search. If the lookup criteria permits, name lookup may also search
9583 /// in the parent contexts or (for C++ classes) base classes.
9584 ///
9585 /// \param InUnqualifiedLookup true if this is qualified name lookup that
9586 /// occurs as part of unqualified name lookup.
9587 ///
9588 /// \returns true if lookup succeeded, false if it failed.
9589 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9590 bool InUnqualifiedLookup = false);
9591
9592 /// Performs qualified name lookup or special type of lookup for
9593 /// "__super::" scope specifier.
9594 ///
9595 /// This routine is a convenience overload meant to be called from contexts
9596 /// that need to perform a qualified name lookup with an optional C++ scope
9597 /// specifier that might require special kind of lookup.
9598 ///
9599 /// \param R captures both the lookup criteria and any lookup results found.
9600 ///
9601 /// \param LookupCtx The context in which qualified name lookup will
9602 /// search.
9603 ///
9604 /// \param SS An optional C++ scope-specifier.
9605 ///
9606 /// \returns true if lookup succeeded, false if it failed.
9607 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9608 CXXScopeSpec &SS);
9609
9610 /// Performs name lookup for a name that was parsed in the
9611 /// source code, and may contain a C++ scope specifier.
9612 ///
9613 /// This routine is a convenience routine meant to be called from
9614 /// contexts that receive a name and an optional C++ scope specifier
9615 /// (e.g., "N::M::x"). It will then perform either qualified or
9616 /// unqualified name lookup (with LookupQualifiedName or LookupName,
9617 /// respectively) on the given name and return those results. It will
9618 /// perform a special type of lookup for "__super::" scope specifier.
9619 ///
9620 /// @param S The scope from which unqualified name lookup will
9621 /// begin.
9622 ///
9623 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
9624 ///
9625 /// @param EnteringContext Indicates whether we are going to enter the
9626 /// context of the scope-specifier SS (if present).
9627 ///
9628 /// @returns True if any decls were found (but possibly ambiguous)
9629 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
9630 QualType ObjectType, bool AllowBuiltinCreation = false,
9631 bool EnteringContext = false);
9632
9633 /// Perform qualified name lookup into all base classes of the given
9634 /// class.
9635 ///
9636 /// \param R captures both the lookup criteria and any lookup results found.
9637 ///
9638 /// \param Class The context in which qualified name lookup will
9639 /// search. Name lookup will search in all base classes merging the results.
9640 ///
9641 /// @returns True if any decls were found (but possibly ambiguous)
9642 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
9643
9644 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
9645 UnresolvedSetImpl &Functions);
9646
9647 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9648 /// If GnuLabelLoc is a valid source location, then this is a definition
9649 /// of an __label__ label name, otherwise it is a normal label definition
9650 /// or use. If IsLabelStmt is true, then this is the label of a
9651 /// labeled-statement.
9652 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
9653 SourceLocation GnuLabelLoc = SourceLocation(),
9654 bool IsLabelStmt = false);
9655
9656 /// Perform a name lookup for a label with the specified name; this does not
9657 /// create a new label if the lookup fails.
9658 LabelDecl *LookupExistingLabel(IdentifierInfo *II, SourceLocation IdentLoc);
9659
9660 /// Look up the constructors for the given class.
9661 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
9662
9663 /// Look up the default constructor for the given class.
9664 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
9665
9666 /// Look up the copying constructor for the given class.
9667 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
9668 unsigned Quals);
9669
9670 /// Look up the copying assignment operator for the given class.
9671 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
9672 bool RValueThis, unsigned ThisQuals);
9673
9674 /// Look up the moving constructor for the given class.
9675 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
9676 unsigned Quals);
9677
9678 /// Look up the moving assignment operator for the given class.
9679 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
9680 bool RValueThis, unsigned ThisQuals);
9681
9682 /// Look for the destructor of the given class.
9683 ///
9684 /// During semantic analysis, this routine should be used in lieu of
9685 /// CXXRecordDecl::getDestructor().
9686 ///
9687 /// \returns The destructor for this class.
9688 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
9689
9690 /// Force the declaration of any implicitly-declared members of this
9691 /// class.
9692 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
9693
9694 /// Make a merged definition of an existing hidden definition \p ND
9695 /// visible at the specified location.
9696 void makeMergedDefinitionVisible(NamedDecl *ND);
9697
9698 /// Check ODR hashes for C/ObjC when merging types from modules.
9699 /// Differently from C++, actually parse the body and reject in case
9700 /// of a mismatch.
9701 template <typename T,
9702 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
9703 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
9704 if (Duplicate->getODRHash() != Previous->getODRHash())
9705 return false;
9706
9707 // Make the previous decl visible.
9708 makeMergedDefinitionVisible(ND: Previous);
9709 return true;
9710 }
9711
9712 /// Get the set of additional modules that should be checked during
9713 /// name lookup. A module and its imports become visible when instanting a
9714 /// template defined within it.
9715 llvm::DenseSet<Module *> &getLookupModules();
9716
9717 bool hasVisibleMergedDefinition(const NamedDecl *Def);
9718 bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
9719
9720 /// Determine if the template parameter \p D has a visible default argument.
9721 bool
9722 hasVisibleDefaultArgument(const NamedDecl *D,
9723 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9724 /// Determine if the template parameter \p D has a reachable default argument.
9725 bool hasReachableDefaultArgument(
9726 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9727 /// Determine if the template parameter \p D has a reachable default argument.
9728 bool hasAcceptableDefaultArgument(const NamedDecl *D,
9729 llvm::SmallVectorImpl<Module *> *Modules,
9730 Sema::AcceptableKind Kind);
9731
9732 /// Determine if there is a visible declaration of \p D that is an explicit
9733 /// specialization declaration for a specialization of a template. (For a
9734 /// member specialization, use hasVisibleMemberSpecialization.)
9735 bool hasVisibleExplicitSpecialization(
9736 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9737 /// Determine if there is a reachable declaration of \p D that is an explicit
9738 /// specialization declaration for a specialization of a template. (For a
9739 /// member specialization, use hasReachableMemberSpecialization.)
9740 bool hasReachableExplicitSpecialization(
9741 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9742
9743 /// Determine if there is a visible declaration of \p D that is a member
9744 /// specialization declaration (as opposed to an instantiated declaration).
9745 bool hasVisibleMemberSpecialization(
9746 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9747 /// Determine if there is a reachable declaration of \p D that is a member
9748 /// specialization declaration (as opposed to an instantiated declaration).
9749 bool hasReachableMemberSpecialization(
9750 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9751
9752 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9753
9754 /// Determine whether any declaration of an entity is visible.
9755 bool
9756 hasVisibleDeclaration(const NamedDecl *D,
9757 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9758 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9759 }
9760
9761 bool hasVisibleDeclarationSlow(const NamedDecl *D,
9762 llvm::SmallVectorImpl<Module *> *Modules);
9763 /// Determine whether any declaration of an entity is reachable.
9764 bool
9765 hasReachableDeclaration(const NamedDecl *D,
9766 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9767 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9768 }
9769 bool hasReachableDeclarationSlow(
9770 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9771
9772 void diagnoseTypo(const TypoCorrection &Correction,
9773 const PartialDiagnostic &TypoDiag,
9774 bool ErrorRecovery = true);
9775
9776 /// Diagnose a successfully-corrected typo. Separated from the correction
9777 /// itself to allow external validation of the result, etc.
9778 ///
9779 /// \param Correction The result of performing typo correction.
9780 /// \param TypoDiag The diagnostic to produce. This will have the corrected
9781 /// string added to it (and usually also a fixit).
9782 /// \param PrevNote A note to use when indicating the location of the entity
9783 /// to which we are correcting. Will have the correction string added
9784 /// to it.
9785 /// \param ErrorRecovery If \c true (the default), the caller is going to
9786 /// recover from the typo as if the corrected string had been typed.
9787 /// In this case, \c PDiag must be an error, and we will attach a fixit
9788 /// to it.
9789 void diagnoseTypo(const TypoCorrection &Correction,
9790 const PartialDiagnostic &TypoDiag,
9791 const PartialDiagnostic &PrevNote,
9792 bool ErrorRecovery = true);
9793
9794 /// Find the associated classes and namespaces for
9795 /// argument-dependent lookup for a call with the given set of
9796 /// arguments.
9797 ///
9798 /// This routine computes the sets of associated classes and associated
9799 /// namespaces searched by argument-dependent lookup
9800 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9801 void FindAssociatedClassesAndNamespaces(
9802 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9803 AssociatedNamespaceSet &AssociatedNamespaces,
9804 AssociatedClassSet &AssociatedClasses);
9805
9806 /// Produce a diagnostic describing the ambiguity that resulted
9807 /// from name lookup.
9808 ///
9809 /// \param Result The result of the ambiguous lookup to be diagnosed.
9810 void DiagnoseAmbiguousLookup(LookupResult &Result);
9811
9812 /// LookupLiteralOperator - Determine which literal operator should be used
9813 /// for a user-defined literal, per C++11 [lex.ext].
9814 ///
9815 /// Normal overload resolution is not used to select which literal operator to
9816 /// call for a user-defined literal. Look up the provided literal operator
9817 /// name, and filter the results to the appropriate set for the given argument
9818 /// types.
9819 LiteralOperatorLookupResult
9820 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
9821 bool AllowRaw, bool AllowTemplate,
9822 bool AllowStringTemplate, bool DiagnoseMissing,
9823 StringLiteral *StringLit = nullptr);
9824
9825 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
9826 ArrayRef<Expr *> Args, ADLResult &Functions);
9827
9828 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9829 VisibleDeclConsumer &Consumer,
9830 bool IncludeGlobalScope = true,
9831 bool LoadExternal = true);
9832 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9833 VisibleDeclConsumer &Consumer,
9834 bool IncludeGlobalScope = true,
9835 bool IncludeDependentBases = false,
9836 bool LoadExternal = true);
9837
9838 /// Try to "correct" a typo in the source code by finding
9839 /// visible declarations whose names are similar to the name that was
9840 /// present in the source code.
9841 ///
9842 /// \param TypoName the \c DeclarationNameInfo structure that contains
9843 /// the name that was present in the source code along with its location.
9844 ///
9845 /// \param LookupKind the name-lookup criteria used to search for the name.
9846 ///
9847 /// \param S the scope in which name lookup occurs.
9848 ///
9849 /// \param SS the nested-name-specifier that precedes the name we're
9850 /// looking for, if present.
9851 ///
9852 /// \param CCC A CorrectionCandidateCallback object that provides further
9853 /// validation of typo correction candidates. It also provides flags for
9854 /// determining the set of keywords permitted.
9855 ///
9856 /// \param MemberContext if non-NULL, the context in which to look for
9857 /// a member access expression.
9858 ///
9859 /// \param EnteringContext whether we're entering the context described by
9860 /// the nested-name-specifier SS.
9861 ///
9862 /// \param OPT when non-NULL, the search for visible declarations will
9863 /// also walk the protocols in the qualified interfaces of \p OPT.
9864 ///
9865 /// \returns a \c TypoCorrection containing the corrected name if the typo
9866 /// along with information such as the \c NamedDecl where the corrected name
9867 /// was declared, and any additional \c NestedNameSpecifier needed to access
9868 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9869 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
9870 Sema::LookupNameKind LookupKind, Scope *S,
9871 CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9872 CorrectTypoKind Mode,
9873 DeclContext *MemberContext = nullptr,
9874 bool EnteringContext = false,
9875 const ObjCObjectPointerType *OPT = nullptr,
9876 bool RecordFailure = true);
9877
9878 /// Kinds of missing import. Note, the values of these enumerators correspond
9879 /// to %select values in diagnostics.
9880 enum class MissingImportKind {
9881 Declaration,
9882 Definition,
9883 DefaultArgument,
9884 ExplicitSpecialization,
9885 PartialSpecialization
9886 };
9887
9888 /// Diagnose that the specified declaration needs to be visible but
9889 /// isn't, and suggest a module import that would resolve the problem.
9890 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9891 MissingImportKind MIK, bool Recover = true);
9892 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9893 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
9894 MissingImportKind MIK, bool Recover);
9895
9896 /// Called on #pragma clang __debug dump II
9897 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9898
9899 /// Called on #pragma clang __debug dump E
9900 void ActOnPragmaDump(Expr *E);
9901
9902private:
9903 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
9904 //
9905 // The boolean value will be true to indicate that the namespace was loaded
9906 // from an AST/PCH file, or false otherwise.
9907 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
9908
9909 /// Whether we have already loaded known namespaces from an extenal
9910 /// source.
9911 bool LoadedExternalKnownNamespaces;
9912
9913 bool CppLookupName(LookupResult &R, Scope *S);
9914
9915 /// Determine if we could use all the declarations in the module.
9916 bool isUsableModule(const Module *M);
9917
9918 /// Helper for CorrectTypo used to create and populate a new
9919 /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
9920 /// skipped entirely.
9921 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
9922 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
9923 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9924 DeclContext *MemberContext, bool EnteringContext,
9925 const ObjCObjectPointerType *OPT, bool ErrorRecovery);
9926
9927 /// Cache for module units which is usable for current module.
9928 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
9929
9930 /// Record the typo correction failure and return an empty correction.
9931 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
9932 bool RecordFailure = true) {
9933 if (RecordFailure)
9934 TypoCorrectionFailures[Typo].insert(V: TypoLoc);
9935 return TypoCorrection();
9936 }
9937
9938 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
9939
9940 /// Determine whether two declarations should be linked together, given that
9941 /// the old declaration might not be visible and the new declaration might
9942 /// not have external linkage.
9943 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
9944 const NamedDecl *New) {
9945 if (isVisible(D: Old))
9946 return true;
9947 // See comment in below overload for why it's safe to compute the linkage
9948 // of the new declaration here.
9949 if (New->isExternallyDeclarable()) {
9950 assert(Old->isExternallyDeclarable() &&
9951 "should not have found a non-externally-declarable previous decl");
9952 return true;
9953 }
9954 return false;
9955 }
9956 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
9957
9958 ///@}
9959
9960 //
9961 //
9962 // -------------------------------------------------------------------------
9963 //
9964 //
9965
9966 /// \name Modules
9967 /// Implementations are in SemaModule.cpp
9968 ///@{
9969
9970public:
9971 /// Get the module unit whose scope we are currently within.
9972 Module *getCurrentModule() const {
9973 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
9974 }
9975
9976 /// Is the module scope we are an implementation unit?
9977 bool currentModuleIsImplementation() const {
9978 if (ModuleScopes.empty())
9979 return false;
9980 const Module *M = ModuleScopes.back().Module;
9981 return M->isModuleImplementation() || M->isModulePartitionImplementation();
9982 }
9983
9984 // When loading a non-modular PCH files, this is used to restore module
9985 // visibility.
9986 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
9987 VisibleModules.setVisible(M: Mod, Loc: ImportLoc);
9988 }
9989
9990 enum class ModuleDeclKind {
9991 Interface, ///< 'export module X;'
9992 Implementation, ///< 'module X;'
9993 PartitionInterface, ///< 'export module X:Y;'
9994 PartitionImplementation, ///< 'module X:Y;'
9995 };
9996
9997 /// An enumeration to represent the transition of states in parsing module
9998 /// fragments and imports. If we are not parsing a C++20 TU, or we find
9999 /// an error in state transition, the state is set to NotACXX20Module.
10000 enum class ModuleImportState {
10001 FirstDecl, ///< Parsing the first decl in a TU.
10002 GlobalFragment, ///< after 'module;' but before 'module X;'
10003 ImportAllowed, ///< after 'module X;' but before any non-import decl.
10004 ImportFinished, ///< after any non-import decl.
10005 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
10006 ///< non-import decl.
10007 PrivateFragmentImportFinished, ///< after 'module :private;' but a
10008 ///< non-import decl has already been seen.
10009 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
10010 };
10011
10012 /// The parser has processed a module-declaration that begins the definition
10013 /// of a module interface or implementation.
10014 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
10015 SourceLocation ModuleLoc, ModuleDeclKind MDK,
10016 ModuleIdPath Path, ModuleIdPath Partition,
10017 ModuleImportState &ImportState,
10018 bool SeenNoTrivialPPDirective);
10019
10020 /// The parser has processed a global-module-fragment declaration that begins
10021 /// the definition of the global module fragment of the current module unit.
10022 /// \param ModuleLoc The location of the 'module' keyword.
10023 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
10024
10025 /// The parser has processed a private-module-fragment declaration that begins
10026 /// the definition of the private module fragment of the current module unit.
10027 /// \param ModuleLoc The location of the 'module' keyword.
10028 /// \param PrivateLoc The location of the 'private' keyword.
10029 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
10030 SourceLocation PrivateLoc);
10031
10032 /// The parser has processed a module import declaration.
10033 ///
10034 /// \param StartLoc The location of the first token in the declaration. This
10035 /// could be the location of an '@', 'export', or 'import'.
10036 /// \param ExportLoc The location of the 'export' keyword, if any.
10037 /// \param ImportLoc The location of the 'import' keyword.
10038 /// \param Path The module toplevel name as an access path.
10039 /// \param IsPartition If the name is for a partition.
10040 DeclResult ActOnModuleImport(SourceLocation StartLoc,
10041 SourceLocation ExportLoc,
10042 SourceLocation ImportLoc, ModuleIdPath Path,
10043 bool IsPartition = false);
10044 DeclResult ActOnModuleImport(SourceLocation StartLoc,
10045 SourceLocation ExportLoc,
10046 SourceLocation ImportLoc, Module *M,
10047 ModuleIdPath Path = {});
10048
10049 /// The parser has processed a module import translated from a
10050 /// #include or similar preprocessing directive.
10051 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10052 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10053
10054 /// The parsed has entered a submodule.
10055 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
10056 /// The parser has left a submodule.
10057 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
10058
10059 /// Create an implicit import of the given module at the given
10060 /// source location, for error recovery, if possible.
10061 ///
10062 /// This routine is typically used when an entity found by name lookup
10063 /// is actually hidden within a module that we know about but the user
10064 /// has forgotten to import.
10065 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
10066 Module *Mod);
10067
10068 /// We have parsed the start of an export declaration, including the '{'
10069 /// (if present).
10070 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
10071 SourceLocation LBraceLoc);
10072
10073 /// Complete the definition of an export declaration.
10074 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
10075 SourceLocation RBraceLoc);
10076
10077private:
10078 /// The parser has begun a translation unit to be compiled as a C++20
10079 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
10080 void HandleStartOfHeaderUnit();
10081
10082 struct ModuleScope {
10083 SourceLocation BeginLoc;
10084 clang::Module *Module = nullptr;
10085 VisibleModuleSet OuterVisibleModules;
10086 };
10087 /// The modules we're currently parsing.
10088 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
10089
10090 /// For an interface unit, this is the implicitly imported interface unit.
10091 clang::Module *ThePrimaryInterface = nullptr;
10092
10093 /// The explicit global module fragment of the current translation unit.
10094 /// The explicit Global Module Fragment, as specified in C++
10095 /// [module.global.frag].
10096 clang::Module *TheGlobalModuleFragment = nullptr;
10097
10098 /// The implicit global module fragments of the current translation unit.
10099 ///
10100 /// The contents in the implicit global module fragment can't be discarded.
10101 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
10102
10103 /// Namespace definitions that we will export when they finish.
10104 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
10105
10106 /// In a C++ standard module, inline declarations require a definition to be
10107 /// present at the end of a definition domain. This set holds the decls to
10108 /// be checked at the end of the TU.
10109 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
10110
10111 /// Helper function to judge if we are in module purview.
10112 /// Return false if we are not in a module.
10113 bool isCurrentModulePurview() const;
10114
10115 /// Enter the scope of the explicit global module fragment.
10116 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
10117 /// Leave the scope of the explicit global module fragment.
10118 void PopGlobalModuleFragment();
10119
10120 /// Enter the scope of an implicit global module fragment.
10121 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
10122 /// Leave the scope of an implicit global module fragment.
10123 void PopImplicitGlobalModuleFragment();
10124
10125 VisibleModuleSet VisibleModules;
10126
10127 /// Whether we had imported any named modules.
10128 bool HadImportedNamedModules = false;
10129 /// The set of instantiations we need to check if they references TU-local
10130 /// entity from TUs. This only makes sense if we imported any named modules.
10131 llvm::SmallVector<std::pair<FunctionDecl *, SourceLocation>>
10132 PendingCheckReferenceForTULocal;
10133 /// Implement [basic.link]p18, which requires that we can't use TU-local
10134 /// entities from other TUs (ignoring header units).
10135 void checkReferenceToTULocalFromOtherTU(FunctionDecl *FD,
10136 SourceLocation PointOfInstantiation);
10137 /// Implement [basic.link]p17, which diagnose for non TU local exposure in
10138 /// module interface or module partition.
10139 void checkExposure(const TranslationUnitDecl *TU);
10140
10141 ///@}
10142
10143 //
10144 //
10145 // -------------------------------------------------------------------------
10146 //
10147 //
10148
10149 /// \name C++ Overloading
10150 /// Implementations are in SemaOverload.cpp
10151 ///@{
10152
10153public:
10154 /// Whether deferrable diagnostics should be deferred.
10155 bool DeferDiags = false;
10156
10157 /// RAII class to control scope of DeferDiags.
10158 class DeferDiagsRAII {
10159 Sema &S;
10160 bool SavedDeferDiags = false;
10161
10162 public:
10163 DeferDiagsRAII(Sema &S, bool DeferDiags)
10164 : S(S), SavedDeferDiags(S.DeferDiags) {
10165 S.DeferDiags = SavedDeferDiags || DeferDiags;
10166 }
10167 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
10168 DeferDiagsRAII(const DeferDiagsRAII &) = delete;
10169 DeferDiagsRAII &operator=(const DeferDiagsRAII &) = delete;
10170 };
10171
10172 /// Flag indicating if Sema is building a recovery call expression.
10173 ///
10174 /// This flag is used to avoid building recovery call expressions
10175 /// if Sema is already doing so, which would cause infinite recursions.
10176 bool IsBuildingRecoveryCallExpr;
10177
10178 /// Determine whether the given New declaration is an overload of the
10179 /// declarations in Old. This routine returns OverloadKind::Match or
10180 /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
10181 /// New has the same signature as some function in Old (C++ 1.3.10) or if the
10182 /// Old declarations aren't functions (or function templates) at all. When it
10183 /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
10184 /// will point to the decl that New cannot be overloaded with. This decl may
10185 /// be a UsingShadowDecl on top of the underlying declaration.
10186 ///
10187 /// Example: Given the following input:
10188 ///
10189 /// void f(int, float); // #1
10190 /// void f(int, int); // #2
10191 /// int f(int, int); // #3
10192 ///
10193 /// When we process #1, there is no previous declaration of "f", so IsOverload
10194 /// will not be used.
10195 ///
10196 /// When we process #2, Old contains only the FunctionDecl for #1. By
10197 /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10198 /// they have different signatures), so this routine returns
10199 /// OverloadKind::Overload; MatchedDecl is unchanged.
10200 ///
10201 /// When we process #3, Old is an overload set containing #1 and #2. We
10202 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10203 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10204 /// types of functions are not part of the signature), IsOverload returns
10205 /// OverloadKind::Match and MatchedDecl will be set to point to the
10206 /// FunctionDecl for #2.
10207 ///
10208 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10209 /// class by a using declaration. The rules for whether to hide shadow
10210 /// declarations ignore some properties which otherwise figure into a function
10211 /// template's signature.
10212 OverloadKind CheckOverload(Scope *S, FunctionDecl *New,
10213 const LookupResult &OldDecls, NamedDecl *&OldDecl,
10214 bool UseMemberUsingDeclRules);
10215 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
10216 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10217
10218 // Checks whether MD constitutes an override the base class method BaseMD.
10219 // When checking for overrides, the object object members are ignored.
10220 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10221 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10222
10223 enum class AllowedExplicit {
10224 /// Allow no explicit functions to be used.
10225 None,
10226 /// Allow explicit conversion functions but not explicit constructors.
10227 Conversions,
10228 /// Allow both explicit conversion functions and explicit constructors.
10229 All
10230 };
10231
10232 ImplicitConversionSequence TryImplicitConversion(
10233 Expr *From, QualType ToType, bool SuppressUserConversions,
10234 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10235 bool AllowObjCWritebackConversion);
10236
10237 /// PerformImplicitConversion - Perform an implicit conversion of the
10238 /// expression From to the type ToType. Returns the
10239 /// converted expression. Flavor is the kind of conversion we're
10240 /// performing, used in the error message. If @p AllowExplicit,
10241 /// explicit user-defined conversions are permitted.
10242 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10243 AssignmentAction Action,
10244 bool AllowExplicit = false);
10245
10246 /// IsIntegralPromotion - Determines whether the conversion from the
10247 /// expression From (whose potentially-adjusted type is FromType) to
10248 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10249 /// sets PromotedType to the promoted type.
10250 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10251
10252 /// IsFloatingPointPromotion - Determines whether the conversion from
10253 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10254 /// returns true and sets PromotedType to the promoted type.
10255 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10256
10257 /// Determine if a conversion is a complex promotion.
10258 ///
10259 /// A complex promotion is defined as a complex -> complex conversion
10260 /// where the conversion between the underlying real types is a
10261 /// floating-point or integral promotion.
10262 bool IsComplexPromotion(QualType FromType, QualType ToType);
10263
10264 /// IsOverflowBehaviorTypePromotion - Determines whether the conversion from
10265 /// FromType to ToType involves an OverflowBehaviorType FromType being
10266 /// promoted to an OverflowBehaviorType ToType which has a larger bitwidth.
10267 /// If so, returns true and sets FromType to ToType.
10268 bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType);
10269
10270 /// IsOverflowBehaviorTypeConversion - Determines whether the conversion from
10271 /// FromType to ToType necessarily involves both an OverflowBehaviorType and
10272 /// a non-OverflowBehaviorType. If so, returns true and sets FromType to
10273 /// ToType.
10274 bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType);
10275
10276 /// IsPointerConversion - Determines whether the conversion of the
10277 /// expression From, which has the (possibly adjusted) type FromType,
10278 /// can be converted to the type ToType via a pointer conversion (C++
10279 /// 4.10). If so, returns true and places the converted type (that
10280 /// might differ from ToType in its cv-qualifiers at some level) into
10281 /// ConvertedType.
10282 ///
10283 /// This routine also supports conversions to and from block pointers
10284 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10285 /// pointers to interfaces. FIXME: Once we've determined the
10286 /// appropriate overloading rules for Objective-C, we may want to
10287 /// split the Objective-C checks into a different routine; however,
10288 /// GCC seems to consider all of these conversions to be pointer
10289 /// conversions, so for now they live here. IncompatibleObjC will be
10290 /// set if the conversion is an allowed Objective-C conversion that
10291 /// should result in a warning.
10292 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10293 bool InOverloadResolution, QualType &ConvertedType,
10294 bool &IncompatibleObjC);
10295
10296 /// isObjCPointerConversion - Determines whether this is an
10297 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10298 /// with the same arguments and return values.
10299 bool isObjCPointerConversion(QualType FromType, QualType ToType,
10300 QualType &ConvertedType, bool &IncompatibleObjC);
10301 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10302 QualType &ConvertedType);
10303
10304 /// FunctionParamTypesAreEqual - This routine checks two function proto types
10305 /// for equality of their parameter types. Caller has already checked that
10306 /// they have same number of parameters. If the parameters are different,
10307 /// ArgPos will have the parameter index of the first different parameter.
10308 /// If `Reversed` is true, the parameters of `NewType` will be compared in
10309 /// reverse order. That's useful if one of the functions is being used as a
10310 /// C++20 synthesized operator overload with a reversed parameter order.
10311 bool FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
10312 ArrayRef<QualType> New,
10313 unsigned *ArgPos = nullptr,
10314 bool Reversed = false);
10315
10316 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
10317 const FunctionProtoType *NewType,
10318 unsigned *ArgPos = nullptr,
10319 bool Reversed = false);
10320
10321 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10322 const FunctionDecl *NewFunction,
10323 unsigned *ArgPos = nullptr,
10324 bool Reversed = false);
10325
10326 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10327 /// function types. Catches different number of parameter, mismatch in
10328 /// parameter types, and different return types.
10329 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType,
10330 QualType ToType);
10331
10332 /// CheckPointerConversion - Check the pointer conversion from the
10333 /// expression From to the type ToType. This routine checks for
10334 /// ambiguous or inaccessible derived-to-base pointer
10335 /// conversions for which IsPointerConversion has already returned
10336 /// true. It returns true and produces a diagnostic if there was an
10337 /// error, or returns false otherwise.
10338 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10339 CXXCastPath &BasePath, bool IgnoreBaseAccess,
10340 bool Diagnose = true);
10341
10342 /// IsMemberPointerConversion - Determines whether the conversion of the
10343 /// expression From, which has the (possibly adjusted) type FromType, can be
10344 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10345 /// If so, returns true and places the converted type (that might differ from
10346 /// ToType in its cv-qualifiers at some level) into ConvertedType.
10347 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10348 bool InOverloadResolution,
10349 QualType &ConvertedType);
10350
10351 enum class MemberPointerConversionResult {
10352 Success,
10353 DifferentPointee,
10354 NotDerived,
10355 Ambiguous,
10356 Virtual,
10357 Inaccessible
10358 };
10359 enum class MemberPointerConversionDirection : bool { Downcast, Upcast };
10360 /// CheckMemberPointerConversion - Check the member pointer conversion from
10361 /// the expression From to the type ToType. This routine checks for ambiguous
10362 /// or virtual or inaccessible base-to-derived member pointer conversions for
10363 /// which IsMemberPointerConversion has already returned true. It produces a
10364 // diagnostic if there was an error.
10365 MemberPointerConversionResult CheckMemberPointerConversion(
10366 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10367 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10368 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10369
10370 /// IsQualificationConversion - Determines whether the conversion from
10371 /// an rvalue of type FromType to ToType is a qualification conversion
10372 /// (C++ 4.4).
10373 ///
10374 /// \param ObjCLifetimeConversion Output parameter that will be set to
10375 /// indicate when the qualification conversion involves a change in the
10376 /// Objective-C object lifetime.
10377 bool IsQualificationConversion(QualType FromType, QualType ToType,
10378 bool CStyle, bool &ObjCLifetimeConversion);
10379
10380 /// Determine whether the conversion from FromType to ToType is a valid
10381 /// conversion of ExtInfo/ExtProtoInfo on the nested function type.
10382 /// More precisely, this method checks whether FromType can be transformed
10383 /// into an exact match for ToType, by transforming its extended function
10384 /// type information in legal manner (e.g. by strictly stripping "noreturn"
10385 /// or "noexcept", or by stripping "noescape" for arguments).
10386 bool IsFunctionConversion(QualType FromType, QualType ToType) const;
10387
10388 /// Same as `IsFunctionConversion`, but if this would return true, it sets
10389 /// `ResultTy` to `ToType`.
10390 bool TryFunctionConversion(QualType FromType, QualType ToType,
10391 QualType &ResultTy) const;
10392
10393 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
10394 void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
10395 DeclarationName Name,
10396 OverloadCandidateSet &CandidateSet,
10397 FunctionDecl *Fn, MultiExprArg Args,
10398 bool IsMember = false);
10399
10400 ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
10401 FunctionDecl *Fun);
10402 ExprResult PerformImplicitObjectArgumentInitialization(
10403 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
10404 CXXMethodDecl *Method);
10405
10406 /// PerformContextuallyConvertToBool - Perform a contextual conversion
10407 /// of the expression From to bool (C++0x [conv]p3).
10408 ExprResult PerformContextuallyConvertToBool(Expr *From);
10409
10410 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10411 /// conversion of the expression From to an Objective-C pointer type.
10412 /// Returns a valid but null ExprResult if no conversion sequence exists.
10413 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
10414
10415 ExprResult BuildConvertedConstantExpression(Expr *From, QualType T,
10416 CCEKind CCE,
10417 NamedDecl *Dest = nullptr);
10418
10419 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10420 llvm::APSInt &Value, CCEKind CCE);
10421 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10422 APValue &Value, CCEKind CCE,
10423 NamedDecl *Dest = nullptr);
10424
10425 /// EvaluateConvertedConstantExpression - Evaluate an Expression
10426 /// That is a converted constant expression
10427 /// (which was built with BuildConvertedConstantExpression)
10428 ExprResult
10429 EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
10430 CCEKind CCE, bool RequireInt,
10431 const APValue &PreNarrowingValue);
10432
10433 /// Abstract base class used to perform a contextual implicit
10434 /// conversion from an expression to any type passing a filter.
10435 class ContextualImplicitConverter {
10436 public:
10437 bool Suppress;
10438 bool SuppressConversion;
10439
10440 ContextualImplicitConverter(bool Suppress = false,
10441 bool SuppressConversion = false)
10442 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
10443
10444 /// Determine whether the specified type is a valid destination type
10445 /// for this conversion.
10446 virtual bool match(QualType T) = 0;
10447
10448 /// Emits a diagnostic complaining that the expression does not have
10449 /// integral or enumeration type.
10450 virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10451 QualType T) = 0;
10452
10453 /// Emits a diagnostic when the expression has incomplete class type.
10454 virtual SemaDiagnosticBuilder
10455 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
10456
10457 /// Emits a diagnostic when the only matching conversion function
10458 /// is explicit.
10459 virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S,
10460 SourceLocation Loc,
10461 QualType T,
10462 QualType ConvTy) = 0;
10463
10464 /// Emits a note for the explicit conversion function.
10465 virtual SemaDiagnosticBuilder
10466 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10467
10468 /// Emits a diagnostic when there are multiple possible conversion
10469 /// functions.
10470 virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10471 QualType T) = 0;
10472
10473 /// Emits a note for one of the candidate conversions.
10474 virtual SemaDiagnosticBuilder
10475 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10476
10477 /// Emits a diagnostic when we picked a conversion function
10478 /// (for cases when we are not allowed to pick a conversion function).
10479 virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S,
10480 SourceLocation Loc,
10481 QualType T,
10482 QualType ConvTy) = 0;
10483
10484 virtual ~ContextualImplicitConverter() {}
10485 };
10486
10487 class ICEConvertDiagnoser : public ContextualImplicitConverter {
10488 bool AllowScopedEnumerations;
10489
10490 public:
10491 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10492 bool SuppressConversion)
10493 : ContextualImplicitConverter(Suppress, SuppressConversion),
10494 AllowScopedEnumerations(AllowScopedEnumerations) {}
10495
10496 /// Match an integral or (possibly scoped) enumeration type.
10497 bool match(QualType T) override;
10498
10499 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10500 QualType T) override {
10501 return diagnoseNotInt(S, Loc, T);
10502 }
10503
10504 /// Emits a diagnostic complaining that the expression does not have
10505 /// integral or enumeration type.
10506 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10507 QualType T) = 0;
10508 };
10509
10510 /// Perform a contextual implicit conversion.
10511 ExprResult
10512 PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE,
10513 ContextualImplicitConverter &Converter);
10514
10515 /// ReferenceCompareResult - Expresses the result of comparing two
10516 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10517 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10518 enum ReferenceCompareResult {
10519 /// Ref_Incompatible - The two types are incompatible, so direct
10520 /// reference binding is not possible.
10521 Ref_Incompatible = 0,
10522 /// Ref_Related - The two types are reference-related, which means
10523 /// that their unqualified forms (T1 and T2) are either the same
10524 /// or T1 is a base class of T2.
10525 Ref_Related,
10526 /// Ref_Compatible - The two types are reference-compatible.
10527 Ref_Compatible
10528 };
10529
10530 // Fake up a scoped enumeration that still contextually converts to bool.
10531 struct ReferenceConversionsScope {
10532 /// The conversions that would be performed on an lvalue of type T2 when
10533 /// binding a reference of type T1 to it, as determined when evaluating
10534 /// whether T1 is reference-compatible with T2.
10535 enum ReferenceConversions {
10536 Qualification = 0x1,
10537 NestedQualification = 0x2,
10538 Function = 0x4,
10539 DerivedToBase = 0x8,
10540 ObjC = 0x10,
10541 ObjCLifetime = 0x20,
10542
10543 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
10544 };
10545 };
10546 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
10547
10548 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10549 /// determine whether they are reference-compatible,
10550 /// reference-related, or incompatible, for use in C++ initialization by
10551 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10552 /// type, and the first type (T1) is the pointee type of the reference
10553 /// type being initialized.
10554 ReferenceCompareResult
10555 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
10556 ReferenceConversions *Conv = nullptr);
10557
10558 /// AddOverloadCandidate - Adds the given function to the set of
10559 /// candidate functions, using the given function call arguments. If
10560 /// @p SuppressUserConversions, then don't allow user-defined
10561 /// conversions via constructors or conversion operators.
10562 ///
10563 /// \param PartialOverloading true if we are performing "partial" overloading
10564 /// based on an incomplete set of function arguments. This feature is used by
10565 /// code completion.
10566 void AddOverloadCandidate(
10567 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
10568 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10569 bool PartialOverloading = false, bool AllowExplicit = true,
10570 bool AllowExplicitConversion = false,
10571 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10572 ConversionSequenceList EarlyConversions = {},
10573 OverloadCandidateParamOrder PO = {},
10574 bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10575
10576 /// Add all of the function declarations in the given function set to
10577 /// the overload candidate set.
10578 void AddFunctionCandidates(
10579 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10580 OverloadCandidateSet &CandidateSet,
10581 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10582 bool SuppressUserConversions = false, bool PartialOverloading = false,
10583 bool FirstArgumentIsBase = false);
10584
10585 /// AddMethodCandidate - Adds a named decl (which is some kind of
10586 /// method) as a method candidate to the given overload set.
10587 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10588 Expr::Classification ObjectClassification,
10589 ArrayRef<Expr *> Args,
10590 OverloadCandidateSet &CandidateSet,
10591 bool SuppressUserConversion = false,
10592 OverloadCandidateParamOrder PO = {});
10593
10594 /// AddMethodCandidate - Adds the given C++ member function to the set
10595 /// of candidate functions, using the given function call arguments
10596 /// and the object argument (@c Object). For example, in a call
10597 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10598 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10599 /// allow user-defined conversions via constructors or conversion
10600 /// operators.
10601 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10602 CXXRecordDecl *ActingContext, QualType ObjectType,
10603 Expr::Classification ObjectClassification,
10604 ArrayRef<Expr *> Args,
10605 OverloadCandidateSet &CandidateSet,
10606 bool SuppressUserConversions = false,
10607 bool PartialOverloading = false,
10608 ConversionSequenceList EarlyConversions = {},
10609 OverloadCandidateParamOrder PO = {},
10610 bool StrictPackMatch = false);
10611
10612 /// Add a C++ member function template as a candidate to the candidate
10613 /// set, using template argument deduction to produce an appropriate member
10614 /// function template specialization.
10615 void AddMethodTemplateCandidate(
10616 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10617 CXXRecordDecl *ActingContext,
10618 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10619 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10620 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10621 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10622
10623 /// Add a C++ function template specialization as a candidate
10624 /// in the candidate set, using template argument deduction to produce
10625 /// an appropriate function template specialization.
10626 void AddTemplateOverloadCandidate(
10627 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10628 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10629 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10630 bool PartialOverloading = false, bool AllowExplicit = true,
10631 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10632 OverloadCandidateParamOrder PO = {},
10633 bool AggregateCandidateDeduction = false);
10634
10635 struct CheckNonDependentConversionsFlag {
10636 /// Do not consider any user-defined conversions when constructing the
10637 /// initializing sequence.
10638 bool SuppressUserConversions;
10639
10640 /// Before constructing the initializing sequence, we check whether the
10641 /// parameter type and argument type contain any user defined conversions.
10642 /// If so, do not initialize them. This effectively bypasses some undesired
10643 /// instantiation before checking constaints, which might otherwise result
10644 /// in non-SFINAE errors e.g. recursive constraints.
10645 bool OnlyInitializeNonUserDefinedConversions;
10646
10647 CheckNonDependentConversionsFlag(
10648 bool SuppressUserConversions,
10649 bool OnlyInitializeNonUserDefinedConversions)
10650 : SuppressUserConversions(SuppressUserConversions),
10651 OnlyInitializeNonUserDefinedConversions(
10652 OnlyInitializeNonUserDefinedConversions) {}
10653 };
10654
10655 /// Check that implicit conversion sequences can be formed for each argument
10656 /// whose corresponding parameter has a non-dependent type, per DR1391's
10657 /// [temp.deduct.call]p10.
10658 bool CheckNonDependentConversions(
10659 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
10660 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10661 ConversionSequenceList &Conversions,
10662 CheckNonDependentConversionsFlag UserConversionFlag,
10663 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10664 Expr::Classification ObjectClassification = {},
10665 OverloadCandidateParamOrder PO = {});
10666
10667 /// AddConversionCandidate - Add a C++ conversion function as a
10668 /// candidate in the candidate set (C++ [over.match.conv],
10669 /// C++ [over.match.copy]). From is the expression we're converting from,
10670 /// and ToType is the type that we're eventually trying to convert to
10671 /// (which may or may not be the same type as the type that the
10672 /// conversion function produces).
10673 void AddConversionCandidate(
10674 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10675 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10676 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10677 bool AllowExplicit, bool AllowResultConversion = true,
10678 bool StrictPackMatch = false);
10679
10680 /// Adds a conversion function template specialization
10681 /// candidate to the overload set, using template argument deduction
10682 /// to deduce the template arguments of the conversion function
10683 /// template from the type that we are converting to (C++
10684 /// [temp.deduct.conv]).
10685 void AddTemplateConversionCandidate(
10686 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10687 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10688 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10689 bool AllowExplicit, bool AllowResultConversion = true);
10690
10691 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10692 /// converts the given @c Object to a function pointer via the
10693 /// conversion function @c Conversion, and then attempts to call it
10694 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10695 /// the type of function that we'll eventually be calling.
10696 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10697 DeclAccessPair FoundDecl,
10698 CXXRecordDecl *ActingContext,
10699 const FunctionProtoType *Proto, Expr *Object,
10700 ArrayRef<Expr *> Args,
10701 OverloadCandidateSet &CandidateSet);
10702
10703 /// Add all of the non-member operator function declarations in the given
10704 /// function set to the overload candidate set.
10705 void AddNonMemberOperatorCandidates(
10706 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10707 OverloadCandidateSet &CandidateSet,
10708 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10709
10710 /// Add overload candidates for overloaded operators that are
10711 /// member functions.
10712 ///
10713 /// Add the overloaded operator candidates that are member functions
10714 /// for the operator Op that was used in an operator expression such
10715 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10716 /// CandidateSet will store the added overload candidates. (C++
10717 /// [over.match.oper]).
10718 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
10719 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10720 OverloadCandidateSet &CandidateSet,
10721 OverloadCandidateParamOrder PO = {});
10722
10723 /// AddBuiltinCandidate - Add a candidate for a built-in
10724 /// operator. ResultTy and ParamTys are the result and parameter types
10725 /// of the built-in candidate, respectively. Args and NumArgs are the
10726 /// arguments being passed to the candidate. IsAssignmentOperator
10727 /// should be true when this built-in candidate is an assignment
10728 /// operator. NumContextualBoolArguments is the number of arguments
10729 /// (at the beginning of the argument list) that will be contextually
10730 /// converted to bool.
10731 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10732 OverloadCandidateSet &CandidateSet,
10733 bool IsAssignmentOperator = false,
10734 unsigned NumContextualBoolArguments = 0);
10735
10736 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10737 /// operator overloads to the candidate set (C++ [over.built]), based
10738 /// on the operator @p Op and the arguments given. For example, if the
10739 /// operator is a binary '+', this routine might add "int
10740 /// operator+(int, int)" to cover integer addition.
10741 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10742 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10743 OverloadCandidateSet &CandidateSet);
10744
10745 /// Add function candidates found via argument-dependent lookup
10746 /// to the set of overloading candidates.
10747 ///
10748 /// This routine performs argument-dependent name lookup based on the
10749 /// given function name (which may also be an operator name) and adds
10750 /// all of the overload candidates found by ADL to the overload
10751 /// candidate set (C++ [basic.lookup.argdep]).
10752 void AddArgumentDependentLookupCandidates(
10753 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10754 TemplateArgumentListInfo *ExplicitTemplateArgs,
10755 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10756
10757 /// Check the enable_if expressions on the given function. Returns the first
10758 /// failing attribute, or NULL if they were all successful.
10759 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10760 ArrayRef<Expr *> Args,
10761 bool MissingImplicitThis = false);
10762
10763 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10764 /// non-ArgDependent DiagnoseIfAttrs.
10765 ///
10766 /// Argument-dependent diagnose_if attributes should be checked each time a
10767 /// function is used as a direct callee of a function call.
10768 ///
10769 /// Returns true if any errors were emitted.
10770 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10771 const Expr *ThisArg,
10772 ArrayRef<const Expr *> Args,
10773 SourceLocation Loc);
10774
10775 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10776 /// ArgDependent DiagnoseIfAttrs.
10777 ///
10778 /// Argument-independent diagnose_if attributes should be checked on every use
10779 /// of a function.
10780 ///
10781 /// Returns true if any errors were emitted.
10782 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10783 SourceLocation Loc);
10784
10785 /// Determine if \p A and \p B are equivalent internal linkage declarations
10786 /// from different modules, and thus an ambiguity error can be downgraded to
10787 /// an extension warning.
10788 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10789 const NamedDecl *B);
10790 void diagnoseEquivalentInternalLinkageDeclarations(
10791 SourceLocation Loc, const NamedDecl *D,
10792 ArrayRef<const NamedDecl *> Equiv);
10793
10794 // Emit as a 'note' the specific overload candidate
10795 void NoteOverloadCandidate(
10796 const NamedDecl *Found, const FunctionDecl *Fn,
10797 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
10798 QualType DestType = QualType(), bool TakingAddress = false);
10799
10800 // Emit as a series of 'note's all template and non-templates identified by
10801 // the expression Expr
10802 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10803 bool TakingAddress = false);
10804
10805 /// Returns whether the given function's address can be taken or not,
10806 /// optionally emitting a diagnostic if the address can't be taken.
10807 ///
10808 /// Returns false if taking the address of the function is illegal.
10809 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10810 bool Complain = false,
10811 SourceLocation Loc = SourceLocation());
10812
10813 // [PossiblyAFunctionType] --> [Return]
10814 // NonFunctionType --> NonFunctionType
10815 // R (A) --> R(A)
10816 // R (*)(A) --> R (A)
10817 // R (&)(A) --> R (A)
10818 // R (S::*)(A) --> R (A)
10819 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10820
10821 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10822 /// an overloaded function (C++ [over.over]), where @p From is an
10823 /// expression with overloaded function type and @p ToType is the type
10824 /// we're trying to resolve to. For example:
10825 ///
10826 /// @code
10827 /// int f(double);
10828 /// int f(int);
10829 ///
10830 /// int (*pfd)(double) = f; // selects f(double)
10831 /// @endcode
10832 ///
10833 /// This routine returns the resulting FunctionDecl if it could be
10834 /// resolved, and NULL otherwise. When @p Complain is true, this
10835 /// routine will emit diagnostics if there is an error.
10836 FunctionDecl *
10837 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10838 bool Complain, DeclAccessPair &Found,
10839 bool *pHadMultipleCandidates = nullptr);
10840
10841 /// Given an expression that refers to an overloaded function, try to
10842 /// resolve that function to a single function that can have its address
10843 /// taken. This will modify `Pair` iff it returns non-null.
10844 ///
10845 /// This routine can only succeed if from all of the candidates in the
10846 /// overload set for SrcExpr that can have their addresses taken, there is one
10847 /// candidate that is more constrained than the rest.
10848 FunctionDecl *
10849 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10850
10851 /// Given an overloaded function, tries to turn it into a non-overloaded
10852 /// function reference using resolveAddressOfSingleOverloadCandidate. This
10853 /// will perform access checks, diagnose the use of the resultant decl, and,
10854 /// if requested, potentially perform a function-to-pointer decay.
10855 ///
10856 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10857 /// Otherwise, returns true. This may emit diagnostics and return true.
10858 bool resolveAndFixAddressOfSingleOverloadCandidate(
10859 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10860
10861 /// Given an expression that refers to an overloaded function, try to
10862 /// resolve that overloaded function expression down to a single function.
10863 ///
10864 /// This routine can only resolve template-ids that refer to a single function
10865 /// template, where that template-id refers to a single template whose
10866 /// template arguments are either provided by the template-id or have
10867 /// defaults, as described in C++0x [temp.arg.explicit]p3.
10868 ///
10869 /// If no template-ids are found, no diagnostics are emitted and NULL is
10870 /// returned.
10871 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(
10872 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10873 TemplateSpecCandidateSet *FailedTSC = nullptr,
10874 bool ForTypeDeduction = false);
10875
10876 // Resolve and fix an overloaded expression that can be resolved
10877 // because it identifies a single function template specialization.
10878 //
10879 // Last three arguments should only be supplied if Complain = true
10880 //
10881 // Return true if it was logically possible to so resolve the
10882 // expression, regardless of whether or not it succeeded. Always
10883 // returns true if 'complain' is set.
10884 bool ResolveAndFixSingleFunctionTemplateSpecialization(
10885 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10886 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10887 QualType DestTypeForComplaining = QualType(),
10888 unsigned DiagIDForComplaining = 0);
10889
10890 /// Add the overload candidates named by callee and/or found by argument
10891 /// dependent lookup to the given overload set.
10892 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10893 ArrayRef<Expr *> Args,
10894 OverloadCandidateSet &CandidateSet,
10895 bool PartialOverloading = false);
10896
10897 /// Add the call candidates from the given set of lookup results to the given
10898 /// overload set. Non-function lookup results are ignored.
10899 void AddOverloadedCallCandidates(
10900 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
10901 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
10902
10903 // An enum used to represent the different possible results of building a
10904 // range-based for loop.
10905 enum ForRangeStatus {
10906 FRS_Success,
10907 FRS_NoViableFunction,
10908 FRS_DiagnosticIssued
10909 };
10910
10911 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
10912 /// given LookupResult is non-empty, it is assumed to describe a member which
10913 /// will be invoked. Otherwise, the function will be found via argument
10914 /// dependent lookup.
10915 /// CallExpr is set to a valid expression and FRS_Success returned on success,
10916 /// otherwise CallExpr is set to ExprError() and some non-success value
10917 /// is returned.
10918 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
10919 SourceLocation RangeLoc,
10920 const DeclarationNameInfo &NameInfo,
10921 LookupResult &MemberLookup,
10922 OverloadCandidateSet *CandidateSet,
10923 Expr *Range, ExprResult *CallExpr);
10924
10925 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10926 /// (which eventually refers to the declaration Func) and the call
10927 /// arguments Args/NumArgs, attempt to resolve the function call down
10928 /// to a specific function. If overload resolution succeeds, returns
10929 /// the call expression produced by overload resolution.
10930 /// Otherwise, emits diagnostics and returns ExprError.
10931 ExprResult BuildOverloadedCallExpr(
10932 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
10933 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
10934 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
10935
10936 /// Constructs and populates an OverloadedCandidateSet from
10937 /// the given function.
10938 /// \returns true when an the ExprResult output parameter has been set.
10939 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
10940 MultiExprArg Args, SourceLocation RParenLoc,
10941 OverloadCandidateSet *CandidateSet,
10942 ExprResult *Result);
10943
10944 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
10945 NestedNameSpecifierLoc NNSLoc,
10946 DeclarationNameInfo DNI,
10947 const UnresolvedSetImpl &Fns,
10948 bool PerformADL = true);
10949
10950 /// Perform lookup for an overloaded unary operator.
10951 void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet,
10952 OverloadedOperatorKind Op,
10953 const UnresolvedSetImpl &Fns,
10954 ArrayRef<Expr *> Args, bool RequiresADL = true);
10955
10956 /// Create a unary operation that may resolve to an overloaded
10957 /// operator.
10958 ///
10959 /// \param OpLoc The location of the operator itself (e.g., '*').
10960 ///
10961 /// \param Opc The UnaryOperatorKind that describes this operator.
10962 ///
10963 /// \param Fns The set of non-member functions that will be
10964 /// considered by overload resolution. The caller needs to build this
10965 /// set based on the context using, e.g.,
10966 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10967 /// set should not contain any member functions; those will be added
10968 /// by CreateOverloadedUnaryOp().
10969 ///
10970 /// \param Input The input argument.
10971 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
10972 UnaryOperatorKind Opc,
10973 const UnresolvedSetImpl &Fns, Expr *input,
10974 bool RequiresADL = true);
10975
10976 /// Perform lookup for an overloaded binary operator.
10977 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
10978 OverloadedOperatorKind Op,
10979 const UnresolvedSetImpl &Fns,
10980 ArrayRef<Expr *> Args, bool RequiresADL = true);
10981
10982 /// Create a binary operation that may resolve to an overloaded
10983 /// operator.
10984 ///
10985 /// \param OpLoc The location of the operator itself (e.g., '+').
10986 ///
10987 /// \param Opc The BinaryOperatorKind that describes this operator.
10988 ///
10989 /// \param Fns The set of non-member functions that will be
10990 /// considered by overload resolution. The caller needs to build this
10991 /// set based on the context using, e.g.,
10992 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10993 /// set should not contain any member functions; those will be added
10994 /// by CreateOverloadedBinOp().
10995 ///
10996 /// \param LHS Left-hand argument.
10997 /// \param RHS Right-hand argument.
10998 /// \param PerformADL Whether to consider operator candidates found by ADL.
10999 /// \param AllowRewrittenCandidates Whether to consider candidates found by
11000 /// C++20 operator rewrites.
11001 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
11002 /// the function in question. Such a function is never a candidate in
11003 /// our overload resolution. This also enables synthesizing a three-way
11004 /// comparison from < and == as described in C++20 [class.spaceship]p1.
11005 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
11006 const UnresolvedSetImpl &Fns, Expr *LHS,
11007 Expr *RHS, bool RequiresADL = true,
11008 bool AllowRewrittenCandidates = true,
11009 FunctionDecl *DefaultedFn = nullptr);
11010 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
11011 const UnresolvedSetImpl &Fns,
11012 Expr *LHS, Expr *RHS,
11013 FunctionDecl *DefaultedFn);
11014
11015 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11016 SourceLocation RLoc, Expr *Base,
11017 MultiExprArg Args);
11018
11019 /// BuildCallToMemberFunction - Build a call to a member
11020 /// function. MemExpr is the expression that refers to the member
11021 /// function (and includes the object parameter), Args/NumArgs are the
11022 /// arguments to the function call (not including the object
11023 /// parameter). The caller needs to validate that the member
11024 /// expression refers to a non-static member function or an overloaded
11025 /// member function.
11026 ExprResult BuildCallToMemberFunction(
11027 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
11028 SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
11029 bool IsExecConfig = false, bool AllowRecovery = false);
11030
11031 /// BuildCallToObjectOfClassType - Build a call to an object of class
11032 /// type (C++ [over.call.object]), which can end up invoking an
11033 /// overloaded function call operator (@c operator()) or performing a
11034 /// user-defined conversion on the object argument.
11035 ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object,
11036 SourceLocation LParenLoc,
11037 MultiExprArg Args,
11038 SourceLocation RParenLoc);
11039
11040 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11041 /// (if one exists), where @c Base is an expression of class type and
11042 /// @c Member is the name of the member we're trying to find.
11043 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
11044 SourceLocation OpLoc,
11045 bool *NoArrowOperatorFound = nullptr);
11046
11047 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
11048 CXXConversionDecl *Method,
11049 bool HadMultipleCandidates);
11050
11051 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
11052 /// to a literal operator described by the provided lookup results.
11053 ExprResult BuildLiteralOperatorCall(
11054 LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args,
11055 SourceLocation LitEndLoc,
11056 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
11057
11058 /// FixOverloadedFunctionReference - E is an expression that refers to
11059 /// a C++ overloaded function (possibly with some parentheses and
11060 /// perhaps a '&' around it). We have resolved the overloaded function
11061 /// to the function declaration Fn, so patch up the expression E to
11062 /// refer (possibly indirectly) to Fn. Returns the new expr.
11063 ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl,
11064 FunctionDecl *Fn);
11065 ExprResult FixOverloadedFunctionReference(ExprResult,
11066 DeclAccessPair FoundDecl,
11067 FunctionDecl *Fn);
11068
11069 /// - Returns a selector which best matches given argument list or
11070 /// nullptr if none could be found
11071 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
11072 bool IsInstance,
11073 SmallVectorImpl<ObjCMethodDecl *> &Methods);
11074
11075 ///@}
11076
11077 //
11078 //
11079 // -------------------------------------------------------------------------
11080 //
11081 //
11082
11083 /// \name Statements
11084 /// Implementations are in SemaStmt.cpp
11085 ///@{
11086
11087public:
11088 /// Stack of active SEH __finally scopes. Can be empty.
11089 SmallVector<Scope *, 2> CurrentSEHFinally;
11090
11091 /// Stack of '_Defer' statements that are currently being parsed, as well
11092 /// as the locations of their '_Defer' keywords. Can be empty.
11093 SmallVector<std::pair<Scope *, SourceLocation>, 2> CurrentDefer;
11094
11095 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
11096 StmtResult ActOnExprStmtError();
11097
11098 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
11099 bool HasLeadingEmptyMacro = false);
11100
11101 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc,
11102 SourceLocation EndLoc);
11103 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
11104
11105 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
11106 /// whose result is unused, warn.
11107 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
11108
11109 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
11110 void ActOnAfterCompoundStatementLeadingPragmas();
11111 void ActOnFinishOfCompoundStmt();
11112 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
11113 ArrayRef<Stmt *> Elts, bool isStmtExpr);
11114
11115 sema::CompoundScopeInfo &getCurCompoundScope() const;
11116
11117 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
11118 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
11119 SourceLocation DotDotDotLoc, ExprResult RHS,
11120 SourceLocation ColonLoc);
11121
11122 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
11123 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
11124
11125 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
11126 SourceLocation ColonLoc, Stmt *SubStmt,
11127 Scope *CurScope);
11128 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
11129 SourceLocation ColonLoc, Stmt *SubStmt);
11130
11131 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
11132 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
11133 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
11134 Stmt *SubStmt);
11135
11136 /// Check whether the given statement can have musttail applied to it,
11137 /// issuing a diagnostic and returning false if not. In the success case,
11138 /// the statement is rewritten to remove implicit nodes from the return
11139 /// value.
11140 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11141
11142 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11143 SourceLocation LParenLoc, Stmt *InitStmt,
11144 ConditionResult Cond, SourceLocation RParenLoc,
11145 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11146 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11147 SourceLocation LParenLoc, Stmt *InitStmt,
11148 ConditionResult Cond, SourceLocation RParenLoc,
11149 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11150
11151 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11152
11153 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
11154 SourceLocation LParenLoc, Stmt *InitStmt,
11155 ConditionResult Cond,
11156 SourceLocation RParenLoc);
11157 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
11158 Stmt *Body);
11159
11160 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11161 /// integer not in the range of enum values.
11162 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11163 Expr *SrcExpr);
11164
11165 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
11166 ConditionResult Cond, SourceLocation RParenLoc,
11167 Stmt *Body);
11168 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
11169 SourceLocation WhileLoc, SourceLocation CondLParen,
11170 Expr *Cond, SourceLocation CondRParen);
11171
11172 StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
11173 Stmt *First, ConditionResult Second,
11174 FullExprArg Third, SourceLocation RParenLoc,
11175 Stmt *Body);
11176
11177 /// In an Objective C collection iteration statement:
11178 /// for (x in y)
11179 /// x can be an arbitrary l-value expression. Bind it up as a
11180 /// full-expression.
11181 StmtResult ActOnForEachLValueExpr(Expr *E);
11182
11183 enum BuildForRangeKind {
11184 /// Initial building of a for-range statement.
11185 BFRK_Build,
11186 /// Instantiation or recovery rebuild of a for-range statement. Don't
11187 /// attempt any typo-correction.
11188 BFRK_Rebuild,
11189 /// Determining whether a for-range statement could be built. Avoid any
11190 /// unnecessary or irreversible actions.
11191 BFRK_Check
11192 };
11193
11194 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
11195 ///
11196 /// C++11 [stmt.ranged]:
11197 /// A range-based for statement is equivalent to
11198 ///
11199 /// {
11200 /// auto && __range = range-init;
11201 /// for ( auto __begin = begin-expr,
11202 /// __end = end-expr;
11203 /// __begin != __end;
11204 /// ++__begin ) {
11205 /// for-range-declaration = *__begin;
11206 /// statement
11207 /// }
11208 /// }
11209 ///
11210 /// The body of the loop is not available yet, since it cannot be analysed
11211 /// until we have determined the type of the for-range-declaration.
11212 StmtResult ActOnCXXForRangeStmt(
11213 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11214 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11215 SourceLocation RParenLoc, BuildForRangeKind Kind,
11216 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11217
11218 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11219 StmtResult BuildCXXForRangeStmt(
11220 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11221 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11222 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11223 BuildForRangeKind Kind,
11224 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11225
11226 /// Set the type of a for-range declaration whose for-range or expansion
11227 /// initialiser is dependent.
11228 void ActOnDependentForRangeInitializer(VarDecl *LoopVar,
11229 BuildForRangeKind BFRK);
11230
11231 /// Holds the 'begin' and 'end' variables of a range-based for loop or
11232 /// expansion statement; begin-expr and end-expr are also provided; the
11233 /// latter are used in some diagnostics.
11234 struct ForRangeBeginEndInfo {
11235 VarDecl *BeginVar = nullptr;
11236 VarDecl *EndVar = nullptr;
11237 Expr *BeginExpr = nullptr;
11238 Expr *EndExpr = nullptr;
11239 bool isValid() const { return BeginVar != nullptr && EndVar != nullptr; }
11240 };
11241
11242 /// Determine begin-expr and end-expr and build variable declarations for
11243 /// them as per [stmt.ranged].
11244 ForRangeBeginEndInfo BuildCXXForRangeBeginEndVars(
11245 Scope *S, VarDecl *RangeVar, SourceLocation ColonLoc,
11246 SourceLocation CoawaitLoc,
11247 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps,
11248 BuildForRangeKind Kind, bool IsConstexpr,
11249 StmtResult *RebuildResult = nullptr,
11250 llvm::function_ref<StmtResult()> RebuildWithDereference = {},
11251 IdentifierInfo *BeginName = nullptr, IdentifierInfo *EndName = nullptr);
11252
11253 /// Helper used by the expansion statements and for-range code to build
11254 /// a variable declaration for e.g. 'begin' and 'end'.
11255 VarDecl *BuildForRangeVarDecl(SourceLocation Loc, QualType Type,
11256 IdentifierInfo *Name, bool IsConstexpr);
11257
11258 /// Build the range variable of a range-based for loop or iterating
11259 /// expansion statement and return its DeclStmt.
11260 StmtResult BuildCXXForRangeRangeVar(Scope *S, Expr *Range, QualType Type,
11261 bool IsConstexpr = false);
11262
11263 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11264 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11265 /// body cannot be performed until after the type of the range variable is
11266 /// determined.
11267 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11268
11269 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11270 LabelDecl *TheDecl);
11271 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11272 SourceLocation StarLoc, Expr *DestExp);
11273 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
11274 LabelDecl *Label, SourceLocation LabelLoc);
11275 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
11276 LabelDecl *Label, SourceLocation LabelLoc);
11277
11278 void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope);
11279 void ActOnDeferStmtError(Scope *CurScope);
11280 StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope);
11281
11282 struct NamedReturnInfo {
11283 const VarDecl *Candidate;
11284
11285 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
11286 Status S;
11287
11288 bool isMoveEligible() const { return S != None; };
11289 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
11290 };
11291 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
11292
11293 /// Determine whether the given expression might be move-eligible or
11294 /// copy-elidable in either a (co_)return statement or throw expression,
11295 /// without considering function return type, if applicable.
11296 ///
11297 /// \param E The expression being returned from the function or block,
11298 /// being thrown, or being co_returned from a coroutine. This expression
11299 /// might be modified by the implementation.
11300 ///
11301 /// \param Mode Overrides detection of current language mode
11302 /// and uses the rules for C++23.
11303 ///
11304 /// \returns An aggregate which contains the Candidate and isMoveEligible
11305 /// and isCopyElidable methods. If Candidate is non-null, it means
11306 /// isMoveEligible() would be true under the most permissive language
11307 /// standard.
11308 NamedReturnInfo getNamedReturnInfo(
11309 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
11310
11311 /// Determine whether the given NRVO candidate variable is move-eligible or
11312 /// copy-elidable, without considering function return type.
11313 ///
11314 /// \param VD The NRVO candidate variable.
11315 ///
11316 /// \returns An aggregate which contains the Candidate and isMoveEligible
11317 /// and isCopyElidable methods. If Candidate is non-null, it means
11318 /// isMoveEligible() would be true under the most permissive language
11319 /// standard.
11320 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11321
11322 /// Updates given NamedReturnInfo's move-eligible and
11323 /// copy-elidable statuses, considering the function
11324 /// return type criteria as applicable to return statements.
11325 ///
11326 /// \param Info The NamedReturnInfo object to update.
11327 ///
11328 /// \param ReturnType This is the return type of the function.
11329 /// \returns The copy elision candidate, in case the initial return expression
11330 /// was copy elidable, or nullptr otherwise.
11331 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11332 QualType ReturnType);
11333
11334 /// Perform the initialization of a potentially-movable value, which
11335 /// is the result of return value.
11336 ///
11337 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11338 /// treat returned lvalues as rvalues in certain cases (to prefer move
11339 /// construction), then falls back to treating them as lvalues if that failed.
11340 ExprResult
11341 PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
11342 const NamedReturnInfo &NRInfo, Expr *Value,
11343 bool SupressSimplerImplicitMoves = false);
11344
11345 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
11346
11347 /// Deduce the return type for a function from a returned expression, per
11348 /// C++1y [dcl.spec.auto]p6.
11349 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
11350 SourceLocation ReturnLoc, Expr *RetExpr,
11351 const AutoType *AT);
11352
11353 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11354 Scope *CurScope);
11355 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11356 bool AllowRecovery = false);
11357
11358 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11359 /// for capturing scopes.
11360 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11361 NamedReturnInfo &NRInfo,
11362 bool SupressSimplerImplicitMoves);
11363
11364 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11365 /// and creates a proper catch handler from them.
11366 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
11367 Stmt *HandlerBlock);
11368
11369 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11370 /// handlers and creates a try statement from them.
11371 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
11372 ArrayRef<Stmt *> Handlers);
11373
11374 void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11375
11376 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11377 SourceLocation TryLoc, Stmt *TryBlock,
11378 Stmt *Handler);
11379 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
11380 Stmt *Block);
11381 void ActOnStartSEHFinallyBlock();
11382 void ActOnAbortSEHFinallyBlock();
11383 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
11384 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
11385
11386 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
11387 bool IsIfExists,
11388 NestedNameSpecifierLoc QualifierLoc,
11389 DeclarationNameInfo NameInfo,
11390 Stmt *Nested);
11391 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
11392 bool IsIfExists, CXXScopeSpec &SS,
11393 UnqualifiedId &Name, Stmt *Nested);
11394
11395 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11396 CapturedRegionKind Kind, unsigned NumParams);
11397 typedef std::pair<StringRef, QualType> CapturedParamNameType;
11398 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11399 CapturedRegionKind Kind,
11400 ArrayRef<CapturedParamNameType> Params,
11401 unsigned OpenMPCaptureLevel = 0);
11402 StmtResult ActOnCapturedRegionEnd(Stmt *S);
11403 void ActOnCapturedRegionError();
11404 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
11405 SourceLocation Loc,
11406 unsigned NumParams);
11407
11408 void ApplyForRangeOrExpansionStatementLifetimeExtension(
11409 VarDecl *RangeVar, ArrayRef<MaterializeTemporaryExpr *> Temporaries);
11410
11411private:
11412 /// Check whether the given statement can have musttail applied to it,
11413 /// issuing a diagnostic and returning false if not.
11414 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11415
11416 ///@}
11417
11418 //
11419 //
11420 // -------------------------------------------------------------------------
11421 //
11422 //
11423
11424 /// \name `inline asm` Statement
11425 /// Implementations are in SemaStmtAsm.cpp
11426 ///@{
11427
11428public:
11429 ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel);
11430 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11431 bool IsVolatile, unsigned NumOutputs,
11432 unsigned NumInputs, IdentifierInfo **Names,
11433 MultiExprArg Constraints, MultiExprArg Exprs,
11434 Expr *AsmString, MultiExprArg Clobbers,
11435 unsigned NumLabels, SourceLocation RParenLoc);
11436
11437 void FillInlineAsmIdentifierInfo(Expr *Res,
11438 llvm::InlineAsmIdentifierInfo &Info);
11439 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
11440 SourceLocation TemplateKWLoc,
11441 UnqualifiedId &Id,
11442 bool IsUnevaluatedContext);
11443 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11444 SourceLocation AsmLoc);
11445 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
11446 SourceLocation AsmLoc);
11447 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
11448 ArrayRef<Token> AsmToks, StringRef AsmString,
11449 unsigned NumOutputs, unsigned NumInputs,
11450 ArrayRef<StringRef> Constraints,
11451 ArrayRef<StringRef> Clobbers,
11452 ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11453 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11454 SourceLocation Location, bool AlwaysCreate);
11455
11456 ///@}
11457
11458 //
11459 //
11460 // -------------------------------------------------------------------------
11461 //
11462 //
11463
11464 /// \name Statement Attribute Handling
11465 /// Implementations are in SemaStmtAttr.cpp
11466 ///@{
11467
11468public:
11469 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11470 const AttributeCommonInfo &A);
11471 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11472 const AttributeCommonInfo &A);
11473
11474 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11475 bool CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs);
11476
11477 /// Process the attributes before creating an attributed statement. Returns
11478 /// the semantic attributes that have been processed.
11479 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11480 SmallVectorImpl<const Attr *> &OutAttrs);
11481
11482 ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A,
11483 SourceRange Range);
11484 ExprResult BuildCXXAssumeExpr(Expr *Assumption,
11485 const IdentifierInfo *AttrName,
11486 SourceRange Range);
11487
11488 ///@}
11489
11490 //
11491 //
11492 // -------------------------------------------------------------------------
11493 //
11494 //
11495
11496 /// \name C++ Templates
11497 /// Implementations are in SemaTemplate.cpp
11498 ///@{
11499
11500public:
11501 // Saves the current floating-point pragma stack and clear it in this Sema.
11502 class FpPragmaStackSaveRAII {
11503 public:
11504 FpPragmaStackSaveRAII(Sema &S)
11505 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11506 S.FpPragmaStack.Stack.clear();
11507 }
11508 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11509 FpPragmaStackSaveRAII(const FpPragmaStackSaveRAII &) = delete;
11510 FpPragmaStackSaveRAII &operator=(const FpPragmaStackSaveRAII &) = delete;
11511
11512 private:
11513 Sema &S;
11514 PragmaStack<FPOptionsOverride> SavedStack;
11515 };
11516
11517 void resetFPOptions(FPOptions FPO) {
11518 CurFPFeatures = FPO;
11519 FpPragmaStack.CurrentValue = FPO.getChangesFrom(Base: FPOptions(LangOpts));
11520 }
11521
11522 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
11523 return llvm::ArrayRef(InventedParameterInfos.begin() +
11524 InventedParameterInfosStart,
11525 InventedParameterInfos.end());
11526 }
11527
11528 ArrayRef<sema::FunctionScopeInfo *> getFunctionScopes() const {
11529 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
11530 FunctionScopes.end());
11531 }
11532
11533 typedef llvm::MapVector<const FunctionDecl *,
11534 std::unique_ptr<LateParsedTemplate>>
11535 LateParsedTemplateMapT;
11536 LateParsedTemplateMapT LateParsedTemplateMap;
11537
11538 /// Determine the number of levels of enclosing template parameters. This is
11539 /// only usable while parsing. Note that this does not include dependent
11540 /// contexts in which no template parameters have yet been declared, such as
11541 /// in a terse function template or generic lambda before the first 'auto' is
11542 /// encountered.
11543 unsigned getTemplateDepth(Scope *S) const;
11544
11545 void FilterAcceptableTemplateNames(LookupResult &R,
11546 bool AllowFunctionTemplates = true,
11547 bool AllowDependent = true);
11548 bool hasAnyAcceptableTemplateNames(LookupResult &R,
11549 bool AllowFunctionTemplates = true,
11550 bool AllowDependent = true,
11551 bool AllowNonTemplateFunctions = false);
11552 /// Try to interpret the lookup result D as a template-name.
11553 ///
11554 /// \param D A declaration found by name lookup.
11555 /// \param AllowFunctionTemplates Whether function templates should be
11556 /// considered valid results.
11557 /// \param AllowDependent Whether unresolved using declarations (that might
11558 /// name templates) should be considered valid results.
11559 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
11560 bool AllowFunctionTemplates = true,
11561 bool AllowDependent = true);
11562
11563 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
11564 /// Whether and why a template name is required in this lookup.
11565 class RequiredTemplateKind {
11566 public:
11567 /// Template name is required if TemplateKWLoc is valid.
11568 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
11569 : TemplateKW(TemplateKWLoc) {}
11570 /// Template name is unconditionally required.
11571 RequiredTemplateKind(TemplateNameIsRequiredTag) {}
11572
11573 SourceLocation getTemplateKeywordLoc() const {
11574 return TemplateKW.value_or(u: SourceLocation());
11575 }
11576 bool hasTemplateKeyword() const {
11577 return getTemplateKeywordLoc().isValid();
11578 }
11579 bool isRequired() const { return TemplateKW != SourceLocation(); }
11580 explicit operator bool() const { return isRequired(); }
11581
11582 private:
11583 std::optional<SourceLocation> TemplateKW;
11584 };
11585
11586 enum class AssumedTemplateKind {
11587 /// This is not assumed to be a template name.
11588 None,
11589 /// This is assumed to be a template name because lookup found nothing.
11590 FoundNothing,
11591 /// This is assumed to be a template name because lookup found one or more
11592 /// functions (but no function templates).
11593 FoundFunctions,
11594 };
11595
11596 bool
11597 LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
11598 QualType ObjectType, bool EnteringContext,
11599 RequiredTemplateKind RequiredTemplate = SourceLocation(),
11600 AssumedTemplateKind *ATK = nullptr,
11601 bool AllowTypoCorrection = true);
11602
11603 TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS,
11604 bool hasTemplateKeyword,
11605 const UnqualifiedId &Name,
11606 ParsedType ObjectType, bool EnteringContext,
11607 TemplateTy &Template,
11608 bool &MemberOfUnknownSpecialization,
11609 bool AllowTypoCorrection = true);
11610
11611 /// Try to resolve an undeclared template name as a type template.
11612 ///
11613 /// Sets II to the identifier corresponding to the template name, and updates
11614 /// Name to a corresponding (typo-corrected) type template name and TNK to
11615 /// the corresponding kind, if possible.
11616 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
11617 TemplateNameKind &TNK,
11618 SourceLocation NameLoc,
11619 IdentifierInfo *&II);
11620
11621 /// Determine whether a particular identifier might be the name in a C++1z
11622 /// deduction-guide declaration.
11623 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11624 SourceLocation NameLoc, CXXScopeSpec &SS,
11625 ParsedTemplateTy *Template = nullptr);
11626
11627 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
11628 SourceLocation IILoc, Scope *S,
11629 const CXXScopeSpec *SS,
11630 TemplateTy &SuggestedTemplate,
11631 TemplateNameKind &SuggestedKind);
11632
11633 /// Determine whether we would be unable to instantiate this template (because
11634 /// it either has no definition, or is in the process of being instantiated).
11635 bool DiagnoseUninstantiableTemplate(
11636 SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11637 bool InstantiatedFromMember, const NamedDecl *Pattern,
11638 const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11639 bool Complain = true, bool *Unreachable = nullptr);
11640
11641 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11642 /// that the template parameter 'PrevDecl' is being shadowed by a new
11643 /// declaration at location Loc. Returns true to indicate that this is
11644 /// an error, and false otherwise.
11645 ///
11646 /// \param Loc The location of the declaration that shadows a template
11647 /// parameter.
11648 ///
11649 /// \param PrevDecl The template parameter that the declaration shadows.
11650 ///
11651 /// \param SupportedForCompatibility Whether to issue the diagnostic as
11652 /// a warning for compatibility with older versions of clang.
11653 /// Ignored when MSVC compatibility is enabled.
11654 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
11655 bool SupportedForCompatibility = false);
11656
11657 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11658 /// the parameter D to reference the templated declaration and return a
11659 /// pointer to the template declaration. Otherwise, do nothing to D and return
11660 /// null.
11661 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
11662
11663 /// ActOnTypeParameter - Called when a C++ template type parameter
11664 /// (e.g., "typename T") has been parsed. Typename specifies whether
11665 /// the keyword "typename" was used to declare the type parameter
11666 /// (otherwise, "class" was used), and KeyLoc is the location of the
11667 /// "class" or "typename" keyword. ParamName is the name of the
11668 /// parameter (NULL indicates an unnamed template parameter) and
11669 /// ParamNameLoc is the location of the parameter name (if any).
11670 /// If the type parameter has a default argument, it will be added
11671 /// later via ActOnTypeParameterDefault.
11672 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
11673 SourceLocation EllipsisLoc,
11674 SourceLocation KeyLoc,
11675 IdentifierInfo *ParamName,
11676 SourceLocation ParamNameLoc, unsigned Depth,
11677 unsigned Position, SourceLocation EqualLoc,
11678 ParsedType DefaultArg, bool HasTypeConstraint);
11679
11680 bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint);
11681
11682 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11683 TemplateIdAnnotation *TypeConstraint,
11684 TemplateTypeParmDecl *ConstrainedParameter,
11685 SourceLocation EllipsisLoc);
11686 bool BuildTypeConstraint(const CXXScopeSpec &SS,
11687 TemplateIdAnnotation *TypeConstraint,
11688 TemplateTypeParmDecl *ConstrainedParameter,
11689 SourceLocation EllipsisLoc,
11690 bool AllowUnexpandedPack);
11691
11692 /// Attach a type-constraint to a template parameter.
11693 /// \returns true if an error occurred. This can happen if the
11694 /// immediately-declared constraint could not be formed (e.g. incorrect number
11695 /// of arguments for the named concept).
11696 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
11697 DeclarationNameInfo NameInfo,
11698 TemplateName NamedConcept, NamedDecl *FoundDecl,
11699 const TemplateArgumentListInfo *TemplateArgs,
11700 TemplateTypeParmDecl *ConstrainedParameter,
11701 SourceLocation EllipsisLoc);
11702
11703 bool AttachTypeConstraint(AutoTypeLoc TL,
11704 NonTypeTemplateParmDecl *NewConstrainedParm,
11705 NonTypeTemplateParmDecl *OrigConstrainedParm,
11706 SourceLocation EllipsisLoc);
11707
11708 /// Require the given type to be a structural type, and diagnose if it is not.
11709 ///
11710 /// \return \c true if an error was produced.
11711 bool RequireStructuralType(QualType T, SourceLocation Loc);
11712
11713 /// Check that the type of a non-type template parameter is
11714 /// well-formed.
11715 ///
11716 /// \returns the (possibly-promoted) parameter type if valid;
11717 /// otherwise, produces a diagnostic and returns a NULL type.
11718 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
11719 SourceLocation Loc);
11720 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
11721
11722 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
11723 unsigned Depth, unsigned Position,
11724 SourceLocation EqualLoc,
11725 Expr *DefaultArg);
11726
11727 /// ActOnTemplateTemplateParameter - Called when a C++ template template
11728 /// parameter (e.g. T in template <template \<typename> class T> class array)
11729 /// has been parsed. S is the current scope.
11730 NamedDecl *ActOnTemplateTemplateParameter(
11731 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind,
11732 bool TypenameKeyword, TemplateParameterList *Params,
11733 SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11734 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11735 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11736
11737 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11738 /// constrained by RequiresClause, that contains the template parameters in
11739 /// Params.
11740 TemplateParameterList *ActOnTemplateParameterList(
11741 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11742 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11743 SourceLocation RAngleLoc, Expr *RequiresClause);
11744
11745 /// The context in which we are checking a template parameter list.
11746 enum TemplateParamListContext {
11747 // For this context, Class, Variable, TypeAlias, and non-pack Template
11748 // Template Parameters are treated uniformly.
11749 TPC_Other,
11750
11751 TPC_FunctionTemplate,
11752 TPC_ClassTemplateMember,
11753 TPC_FriendClassTemplate,
11754 TPC_FriendFunctionTemplate,
11755 TPC_FriendFunctionTemplateDefinition,
11756 TPC_TemplateTemplateParameterPack,
11757 };
11758
11759 /// Checks the validity of a template parameter list, possibly
11760 /// considering the template parameter list from a previous
11761 /// declaration.
11762 ///
11763 /// If an "old" template parameter list is provided, it must be
11764 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11765 /// template parameter list.
11766 ///
11767 /// \param NewParams Template parameter list for a new template
11768 /// declaration. This template parameter list will be updated with any
11769 /// default arguments that are carried through from the previous
11770 /// template parameter list.
11771 ///
11772 /// \param OldParams If provided, template parameter list from a
11773 /// previous declaration of the same template. Default template
11774 /// arguments will be merged from the old template parameter list to
11775 /// the new template parameter list.
11776 ///
11777 /// \param TPC Describes the context in which we are checking the given
11778 /// template parameter list.
11779 ///
11780 /// \param SkipBody If we might have already made a prior merged definition
11781 /// of this template visible, the corresponding body-skipping information.
11782 /// Default argument redefinition is not an error when skipping such a body,
11783 /// because (under the ODR) we can assume the default arguments are the same
11784 /// as the prior merged definition.
11785 ///
11786 /// \returns true if an error occurred, false otherwise.
11787 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
11788 TemplateParameterList *OldParams,
11789 TemplateParamListContext TPC,
11790 SkipBodyInfo *SkipBody = nullptr);
11791
11792 /// Match the given template parameter lists to the given scope
11793 /// specifier, returning the template parameter list that applies to the
11794 /// name.
11795 ///
11796 /// \param DeclStartLoc the start of the declaration that has a scope
11797 /// specifier or a template parameter list.
11798 ///
11799 /// \param DeclLoc The location of the declaration itself.
11800 ///
11801 /// \param SS the scope specifier that will be matched to the given template
11802 /// parameter lists. This scope specifier precedes a qualified name that is
11803 /// being declared.
11804 ///
11805 /// \param TemplateId The template-id following the scope specifier, if there
11806 /// is one. Used to check for a missing 'template<>'.
11807 ///
11808 /// \param ParamLists the template parameter lists, from the outermost to the
11809 /// innermost template parameter lists.
11810 ///
11811 /// \param IsFriend Whether to apply the slightly different rules for
11812 /// matching template parameters to scope specifiers in friend
11813 /// declarations.
11814 ///
11815 /// \param IsMemberSpecialization will be set true if the scope specifier
11816 /// denotes a fully-specialized type, and therefore this is a declaration of
11817 /// a member specialization.
11818 ///
11819 /// \returns the template parameter list, if any, that corresponds to the
11820 /// name that is preceded by the scope specifier @p SS. This template
11821 /// parameter list may have template parameters (if we're declaring a
11822 /// template) or may have no template parameters (if we're declaring a
11823 /// template specialization), or may be NULL (if what we're declaring isn't
11824 /// itself a template).
11825 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
11826 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11827 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11828 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11829 bool &IsMemberSpecialization, bool &Invalid,
11830 bool SuppressDiagnostic = false);
11831
11832 /// Returns the template parameter list with all default template argument
11833 /// information.
11834 TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD);
11835
11836 DeclResult CheckClassTemplate(
11837 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11838 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11839 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11840 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11841 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11842 TemplateParameterList **OuterTemplateParamLists,
11843 bool IsMemberSpecialization, SkipBodyInfo *SkipBody = nullptr);
11844
11845 /// Translates template arguments as provided by the parser
11846 /// into template arguments used by semantic analysis.
11847 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
11848 TemplateArgumentListInfo &Out);
11849
11850 /// Convert a parsed type into a parsed template argument. This is mostly
11851 /// trivial, except that we may have parsed a C++17 deduced class template
11852 /// specialization type, in which case we should form a template template
11853 /// argument instead of a type template argument.
11854 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
11855
11856 void NoteAllFoundTemplates(TemplateName Name);
11857
11858 QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
11859 TemplateName Template,
11860 SourceLocation TemplateLoc,
11861 TemplateArgumentListInfo &TemplateArgs,
11862 Scope *Scope, bool ForNestedNameSpecifier);
11863
11864 TypeResult
11865 ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
11866 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
11867 SourceLocation TemplateKWLoc, TemplateTy Template,
11868 const IdentifierInfo *TemplateII,
11869 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11870 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11871 bool IsCtorOrDtorName = false, bool IsClassName = false,
11872 ImplicitTypenameContext AllowImplicitTypename =
11873 ImplicitTypenameContext::No);
11874
11875 /// Parsed an elaborated-type-specifier that refers to a template-id,
11876 /// such as \c class T::template apply<U>.
11877 TypeResult ActOnTagTemplateIdType(
11878 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11879 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11880 SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11881 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11882
11883 DeclResult ActOnVarTemplateSpecialization(
11884 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
11885 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11886 StorageClass SC, bool IsPartialSpecialization);
11887
11888 /// Get the specialization of the given variable template corresponding to
11889 /// the specified argument list, or a null-but-valid result if the arguments
11890 /// are dependent.
11891 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
11892 SourceLocation TemplateLoc,
11893 SourceLocation TemplateNameLoc,
11894 const TemplateArgumentListInfo &TemplateArgs,
11895 bool SetWrittenArgs);
11896
11897 /// Form a reference to the specialization of the given variable template
11898 /// corresponding to the specified argument list, or a null-but-valid result
11899 /// if the arguments are dependent.
11900 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
11901 const DeclarationNameInfo &NameInfo,
11902 VarTemplateDecl *Template, NamedDecl *FoundD,
11903 SourceLocation TemplateLoc,
11904 const TemplateArgumentListInfo *TemplateArgs);
11905
11906 ExprResult CheckVarOrConceptTemplateTemplateId(
11907 const DeclarationNameInfo &NameInfo, TemplateName Template,
11908 const TemplateArgumentListInfo *TemplateArgs);
11909
11910 ExprResult
11911 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11912 const DeclarationNameInfo &ConceptNameInfo,
11913 NamedDecl *FoundDecl, TemplateDecl *NamedConcept,
11914 const TemplateArgumentListInfo *TemplateArgs,
11915 bool DoCheckConstraintSatisfaction = true);
11916
11917 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
11918 void diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
11919 bool TemplateKeyword, TemplateDecl *TD,
11920 SourceLocation Loc);
11921
11922 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
11923 SourceLocation TemplateKWLoc, LookupResult &R,
11924 bool RequiresADL,
11925 const TemplateArgumentListInfo *TemplateArgs);
11926
11927 // We actually only call this from template instantiation.
11928 ExprResult
11929 BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11930 const DeclarationNameInfo &NameInfo,
11931 const TemplateArgumentListInfo *TemplateArgs,
11932 bool IsAddressOfOperand);
11933
11934 UnsignedOrNone getPackIndex(TemplateArgument Pack) const {
11935 return Pack.pack_size() - 1 - *ArgPackSubstIndex;
11936 }
11937
11938 TemplateArgument
11939 getPackSubstitutedTemplateArgument(TemplateArgument Arg) const {
11940 Arg = Arg.pack_elements()[*ArgPackSubstIndex];
11941 if (Arg.isPackExpansion())
11942 Arg = Arg.getPackExpansionPattern();
11943 return Arg;
11944 }
11945
11946 ExprResult
11947 BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
11948 QualType ParamType, SourceLocation loc,
11949 TemplateArgument Replacement,
11950 UnsignedOrNone PackIndex, bool Final);
11951
11952 /// Form a template name from a name that is syntactically required to name a
11953 /// template, either due to use of the 'template' keyword or because a name in
11954 /// this syntactic context is assumed to name a template (C++
11955 /// [temp.names]p2-4).
11956 ///
11957 /// This action forms a template name given the name of the template and its
11958 /// optional scope specifier. This is used when the 'template' keyword is used
11959 /// or when the parsing context unambiguously treats a following '<' as
11960 /// introducing a template argument list. Note that this may produce a
11961 /// non-dependent template name if we can perform the lookup now and identify
11962 /// the named template.
11963 ///
11964 /// For example, given "x.MetaFun::template apply", the scope specifier
11965 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
11966 /// of the "template" keyword, and "apply" is the \p Name.
11967 TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS,
11968 SourceLocation TemplateKWLoc,
11969 const UnqualifiedId &Name,
11970 ParsedType ObjectType,
11971 bool EnteringContext, TemplateTy &Template,
11972 bool AllowInjectedClassName = false);
11973
11974 DeclResult ActOnClassTemplateSpecialization(
11975 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11976 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
11977 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
11978 MultiTemplateParamsArg TemplateParameterLists,
11979 SkipBodyInfo *SkipBody = nullptr);
11980
11981 /// Check the non-type template arguments of a class template
11982 /// partial specialization according to C++ [temp.class.spec]p9.
11983 ///
11984 /// \param TemplateNameLoc the location of the template name.
11985 /// \param PrimaryTemplate the template parameters of the primary class
11986 /// template.
11987 /// \param NumExplicit the number of explicitly-specified template arguments.
11988 /// \param TemplateArgs the template arguments of the class template
11989 /// partial specialization.
11990 ///
11991 /// \returns \c true if there was an error, \c false otherwise.
11992 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
11993 TemplateDecl *PrimaryTemplate,
11994 unsigned NumExplicitArgs,
11995 ArrayRef<TemplateArgument> Args);
11996 void CheckTemplatePartialSpecialization(
11997 ClassTemplatePartialSpecializationDecl *Partial);
11998 void CheckTemplatePartialSpecialization(
11999 VarTemplatePartialSpecializationDecl *Partial);
12000
12001 Decl *ActOnTemplateDeclarator(Scope *S,
12002 MultiTemplateParamsArg TemplateParameterLists,
12003 Declarator &D);
12004
12005 /// Diagnose cases where we have an explicit template specialization
12006 /// before/after an explicit template instantiation, producing diagnostics
12007 /// for those cases where they are required and determining whether the
12008 /// new specialization/instantiation will have any effect.
12009 ///
12010 /// \param NewLoc the location of the new explicit specialization or
12011 /// instantiation.
12012 ///
12013 /// \param NewTSK the kind of the new explicit specialization or
12014 /// instantiation.
12015 ///
12016 /// \param PrevDecl the previous declaration of the entity.
12017 ///
12018 /// \param PrevTSK the kind of the old explicit specialization or
12019 /// instantiatin.
12020 ///
12021 /// \param PrevPointOfInstantiation if valid, indicates where the previous
12022 /// declaration was instantiated (either implicitly or explicitly).
12023 ///
12024 /// \param HasNoEffect will be set to true to indicate that the new
12025 /// specialization or instantiation has no effect and should be ignored.
12026 ///
12027 /// \returns true if there was an error that should prevent the introduction
12028 /// of the new declaration into the AST, false otherwise.
12029 bool CheckSpecializationInstantiationRedecl(
12030 SourceLocation NewLoc,
12031 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
12032 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
12033 SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
12034
12035 /// Perform semantic analysis for the given dependent function
12036 /// template specialization.
12037 ///
12038 /// The only possible way to get a dependent function template specialization
12039 /// is with a friend declaration, like so:
12040 ///
12041 /// \code
12042 /// template \<class T> void foo(T);
12043 /// template \<class T> class A {
12044 /// friend void foo<>(T);
12045 /// };
12046 /// \endcode
12047 ///
12048 /// There really isn't any useful analysis we can do here, so we
12049 /// just store the information.
12050 bool CheckDependentFunctionTemplateSpecialization(
12051 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
12052 LookupResult &Previous);
12053
12054 /// Perform semantic analysis for the given function template
12055 /// specialization.
12056 ///
12057 /// This routine performs all of the semantic analysis required for an
12058 /// explicit function template specialization. On successful completion,
12059 /// the function declaration \p FD will become a function template
12060 /// specialization.
12061 ///
12062 /// \param FD the function declaration, which will be updated to become a
12063 /// function template specialization.
12064 ///
12065 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
12066 /// if any. Note that this may be valid info even when 0 arguments are
12067 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
12068 /// as it anyway contains info on the angle brackets locations.
12069 ///
12070 /// \param Previous the set of declarations that may be specialized by
12071 /// this function specialization.
12072 ///
12073 /// \param QualifiedFriend whether this is a lookup for a qualified friend
12074 /// declaration with no explicit template argument list that might be
12075 /// befriending a function template specialization.
12076 bool CheckFunctionTemplateSpecialization(
12077 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
12078 LookupResult &Previous, bool QualifiedFriend = false);
12079
12080 /// Perform semantic analysis for the given non-template member
12081 /// specialization.
12082 ///
12083 /// This routine performs all of the semantic analysis required for an
12084 /// explicit member function specialization. On successful completion,
12085 /// the function declaration \p FD will become a member function
12086 /// specialization.
12087 ///
12088 /// \param Member the member declaration, which will be updated to become a
12089 /// specialization.
12090 ///
12091 /// \param Previous the set of declarations, one of which may be specialized
12092 /// by this function specialization; the set will be modified to contain the
12093 /// redeclared member.
12094 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12095 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12096
12097 // Explicit instantiation of a class template specialization
12098 DeclResult ActOnExplicitInstantiation(
12099 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
12100 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
12101 TemplateTy Template, SourceLocation TemplateNameLoc,
12102 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
12103 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
12104
12105 // Explicit instantiation of a member class of a class template.
12106 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12107 SourceLocation TemplateLoc,
12108 unsigned TagSpec, SourceLocation KWLoc,
12109 CXXScopeSpec &SS, IdentifierInfo *Name,
12110 SourceLocation NameLoc,
12111 const ParsedAttributesView &Attr);
12112
12113 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12114 SourceLocation TemplateLoc,
12115 Declarator &D);
12116
12117 /// If the given template parameter has a default template
12118 /// argument, substitute into that default template argument and
12119 /// return the corresponding template argument.
12120 TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(
12121 TemplateDecl *Template, SourceLocation TemplateKWLoc,
12122 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
12123 ArrayRef<TemplateArgument> SugaredConverted,
12124 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
12125
12126 /// Returns the top most location responsible for the definition of \p N.
12127 /// If \p N is a a template specialization, this is the location
12128 /// of the top of the instantiation stack.
12129 /// Otherwise, the location of \p N is returned.
12130 SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const;
12131
12132 /// Specifies the context in which a particular template
12133 /// argument is being checked.
12134 enum CheckTemplateArgumentKind {
12135 /// The template argument was specified in the code or was
12136 /// instantiated with some deduced template arguments.
12137 CTAK_Specified,
12138
12139 /// The template argument was deduced via template argument
12140 /// deduction.
12141 CTAK_Deduced,
12142
12143 /// The template argument was deduced from an array bound
12144 /// via template argument deduction.
12145 CTAK_DeducedFromArrayBound
12146 };
12147
12148 struct CheckTemplateArgumentInfo {
12149 explicit CheckTemplateArgumentInfo(bool PartialOrdering = false,
12150 bool MatchingTTP = false)
12151 : PartialOrdering(PartialOrdering), MatchingTTP(MatchingTTP) {}
12152 CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &) = delete;
12153 CheckTemplateArgumentInfo &
12154 operator=(const CheckTemplateArgumentInfo &) = delete;
12155
12156 /// The checked, converted argument will be added to the
12157 /// end of these vectors.
12158 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
12159
12160 /// The check is being performed in the context of partial ordering.
12161 bool PartialOrdering;
12162
12163 /// If true, assume these template arguments are
12164 /// the injected template arguments for a template template parameter.
12165 /// This will relax the requirement that all its possible uses are valid:
12166 /// TTP checking is loose, and assumes that invalid uses will be diagnosed
12167 /// during instantiation.
12168 bool MatchingTTP;
12169
12170 /// Is set to true when, in the context of TTP matching, a pack parameter
12171 /// matches non-pack arguments.
12172 bool StrictPackMatch = false;
12173 };
12174
12175 /// Check that the given template argument corresponds to the given
12176 /// template parameter.
12177 ///
12178 /// \param Param The template parameter against which the argument will be
12179 /// checked.
12180 ///
12181 /// \param Arg The template argument, which may be updated due to conversions.
12182 ///
12183 /// \param Template The template in which the template argument resides.
12184 ///
12185 /// \param TemplateLoc The location of the template name for the template
12186 /// whose argument list we're matching.
12187 ///
12188 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
12189 /// the template argument list.
12190 ///
12191 /// \param ArgumentPackIndex The index into the argument pack where this
12192 /// argument will be placed. Only valid if the parameter is a parameter pack.
12193 ///
12194 /// \param CTAK Describes how we arrived at this particular template argument:
12195 /// explicitly written, deduced, etc.
12196 ///
12197 /// \returns true on error, false otherwise.
12198 bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
12199 NamedDecl *Template, SourceLocation TemplateLoc,
12200 SourceLocation RAngleLoc,
12201 unsigned ArgumentPackIndex,
12202 CheckTemplateArgumentInfo &CTAI,
12203 CheckTemplateArgumentKind CTAK);
12204
12205 /// Check that the given template arguments can be provided to
12206 /// the given template, converting the arguments along the way.
12207 ///
12208 /// \param Template The template to which the template arguments are being
12209 /// provided.
12210 ///
12211 /// \param TemplateLoc The location of the template name in the source.
12212 ///
12213 /// \param TemplateArgs The list of template arguments. If the template is
12214 /// a template template parameter, this function may extend the set of
12215 /// template arguments to also include substituted, defaulted template
12216 /// arguments.
12217 ///
12218 /// \param PartialTemplateArgs True if the list of template arguments is
12219 /// intentionally partial, e.g., because we're checking just the initial
12220 /// set of template arguments.
12221 ///
12222 /// \param Converted Will receive the converted, canonicalized template
12223 /// arguments.
12224 ///
12225 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
12226 /// contain the converted forms of the template arguments as written.
12227 /// Otherwise, \p TemplateArgs will not be modified.
12228 ///
12229 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
12230 /// receive true if the cause for the error is the associated constraints of
12231 /// the template not being satisfied by the template arguments.
12232 ///
12233 /// \param DefaultArgs any default arguments from template specialization
12234 /// deduction.
12235 ///
12236 /// \returns true if an error occurred, false otherwise.
12237 bool CheckTemplateArgumentList(TemplateDecl *Template,
12238 SourceLocation TemplateLoc,
12239 TemplateArgumentListInfo &TemplateArgs,
12240 const DefaultArguments &DefaultArgs,
12241 bool PartialTemplateArgs,
12242 CheckTemplateArgumentInfo &CTAI,
12243 bool UpdateArgsWithConversions = true,
12244 bool *ConstraintsNotSatisfied = nullptr);
12245
12246 bool CheckTemplateArgumentList(
12247 TemplateDecl *Template, TemplateParameterList *Params,
12248 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
12249 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
12250 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions = true,
12251 bool *ConstraintsNotSatisfied = nullptr);
12252
12253 bool CheckTemplateTypeArgument(
12254 TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
12255 SmallVectorImpl<TemplateArgument> &SugaredConverted,
12256 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
12257
12258 /// Check a template argument against its corresponding
12259 /// template type parameter.
12260 ///
12261 /// This routine implements the semantics of C++ [temp.arg.type]. It
12262 /// returns true if an error occurred, and false otherwise.
12263 bool CheckTemplateArgument(TypeSourceInfo *Arg);
12264
12265 /// Check a template argument against its corresponding
12266 /// non-type template parameter.
12267 ///
12268 /// This routine implements the semantics of C++ [temp.arg.nontype].
12269 /// If an error occurred, it returns ExprError(); otherwise, it
12270 /// returns the converted template argument. \p ParamType is the
12271 /// type of the non-type template parameter after it has been instantiated.
12272 ExprResult CheckTemplateArgument(NamedDecl *Param,
12273 QualType InstantiatedParamType, Expr *Arg,
12274 TemplateArgument &SugaredConverted,
12275 TemplateArgument &CanonicalConverted,
12276 bool StrictCheck,
12277 CheckTemplateArgumentKind CTAK);
12278
12279 /// Check a template argument against its corresponding
12280 /// template template parameter.
12281 ///
12282 /// This routine implements the semantics of C++ [temp.arg.template].
12283 /// It returns true if an error occurred, and false otherwise.
12284 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
12285 TemplateParameterList *Params,
12286 TemplateArgumentLoc &Arg,
12287 bool PartialOrdering,
12288 bool *StrictPackMatch);
12289
12290 bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template,
12291 TemplateTemplateParmDecl *Param,
12292 const TemplateArgumentLoc &Arg);
12293
12294 void NoteTemplateLocation(const NamedDecl &Decl,
12295 std::optional<SourceRange> ParamRange = {});
12296 void NoteTemplateParameterLocation(const NamedDecl &Decl);
12297
12298 /// Given a non-type template argument that refers to a
12299 /// declaration and the type of its corresponding non-type template
12300 /// parameter, produce an expression that properly refers to that
12301 /// declaration.
12302 /// FIXME: This is used in some contexts where the resulting expression
12303 /// doesn't need to live too long. It would be useful if this function
12304 /// could return a temporary expression.
12305 ExprResult BuildExpressionFromDeclTemplateArgument(
12306 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc);
12307 ExprResult
12308 BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
12309 SourceLocation Loc);
12310
12311 /// Enumeration describing how template parameter lists are compared
12312 /// for equality.
12313 enum TemplateParameterListEqualKind {
12314 /// We are matching the template parameter lists of two templates
12315 /// that might be redeclarations.
12316 ///
12317 /// \code
12318 /// template<typename T> struct X;
12319 /// template<typename T> struct X;
12320 /// \endcode
12321 TPL_TemplateMatch,
12322
12323 /// We are matching the template parameter lists of two template
12324 /// template parameters as part of matching the template parameter lists
12325 /// of two templates that might be redeclarations.
12326 ///
12327 /// \code
12328 /// template<template<int I> class TT> struct X;
12329 /// template<template<int Value> class Other> struct X;
12330 /// \endcode
12331 TPL_TemplateTemplateParmMatch,
12332
12333 /// We are determining whether the template-parameters are equivalent
12334 /// according to C++ [temp.over.link]/6. This comparison does not consider
12335 /// constraints.
12336 ///
12337 /// \code
12338 /// template<C1 T> void f(T);
12339 /// template<C2 T> void f(T);
12340 /// \endcode
12341 TPL_TemplateParamsEquivalent,
12342 };
12343
12344 // A struct to represent the 'new' declaration, which is either itself just
12345 // the named decl, or the important information we need about it in order to
12346 // do constraint comparisons.
12347 class TemplateCompareNewDeclInfo {
12348 const NamedDecl *ND = nullptr;
12349 const DeclContext *DC = nullptr;
12350 const DeclContext *LexicalDC = nullptr;
12351 SourceLocation Loc;
12352
12353 public:
12354 TemplateCompareNewDeclInfo(const NamedDecl *ND) : ND(ND) {}
12355 TemplateCompareNewDeclInfo(const DeclContext *DeclCtx,
12356 const DeclContext *LexicalDeclCtx,
12357 SourceLocation Loc)
12358
12359 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12360 assert(DC && LexicalDC &&
12361 "Constructor only for cases where we have the information to put "
12362 "in here");
12363 }
12364
12365 // If this was constructed with no information, we cannot do substitution
12366 // for constraint comparison, so make sure we can check that.
12367 bool isInvalid() const { return !ND && !DC; }
12368
12369 const NamedDecl *getDecl() const { return ND; }
12370
12371 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12372
12373 const DeclContext *getLexicalDeclContext() const {
12374 return ND ? ND->getLexicalDeclContext() : LexicalDC;
12375 }
12376
12377 const DeclContext *getDeclContext() const {
12378 return ND ? ND->getDeclContext() : DC;
12379 }
12380
12381 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12382 };
12383
12384 /// Determine whether the given template parameter lists are
12385 /// equivalent.
12386 ///
12387 /// \param New The new template parameter list, typically written in the
12388 /// source code as part of a new template declaration.
12389 ///
12390 /// \param Old The old template parameter list, typically found via
12391 /// name lookup of the template declared with this template parameter
12392 /// list.
12393 ///
12394 /// \param Complain If true, this routine will produce a diagnostic if
12395 /// the template parameter lists are not equivalent.
12396 ///
12397 /// \param Kind describes how we are to match the template parameter lists.
12398 ///
12399 /// \param TemplateArgLoc If this source location is valid, then we
12400 /// are actually checking the template parameter list of a template
12401 /// argument (New) against the template parameter list of its
12402 /// corresponding template template parameter (Old). We produce
12403 /// slightly different diagnostics in this scenario.
12404 ///
12405 /// \returns True if the template parameter lists are equal, false
12406 /// otherwise.
12407 bool TemplateParameterListsAreEqual(
12408 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12409 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12410 TemplateParameterListEqualKind Kind,
12411 SourceLocation TemplateArgLoc = SourceLocation());
12412
12413 bool TemplateParameterListsAreEqual(
12414 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12415 TemplateParameterListEqualKind Kind,
12416 SourceLocation TemplateArgLoc = SourceLocation()) {
12417 return TemplateParameterListsAreEqual(NewInstFrom: nullptr, New, OldInstFrom: nullptr, Old, Complain,
12418 Kind, TemplateArgLoc);
12419 }
12420
12421 /// Check whether a template can be declared within this scope.
12422 ///
12423 /// If the template declaration is valid in this scope, returns
12424 /// false. Otherwise, issues a diagnostic and returns true.
12425 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12426
12427 /// Called when the parser has parsed a C++ typename
12428 /// specifier, e.g., "typename T::type".
12429 ///
12430 /// \param S The scope in which this typename type occurs.
12431 /// \param TypenameLoc the location of the 'typename' keyword
12432 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12433 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12434 /// \param IdLoc the location of the identifier.
12435 /// \param IsImplicitTypename context where T::type refers to a type.
12436 TypeResult ActOnTypenameType(
12437 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12438 const IdentifierInfo &II, SourceLocation IdLoc,
12439 ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No);
12440
12441 /// Called when the parser has parsed a C++ typename
12442 /// specifier that ends in a template-id, e.g.,
12443 /// "typename MetaFun::template apply<T1, T2>".
12444 ///
12445 /// \param S The scope in which this typename type occurs.
12446 /// \param TypenameLoc the location of the 'typename' keyword
12447 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12448 /// \param TemplateLoc the location of the 'template' keyword, if any.
12449 /// \param TemplateName The template name.
12450 /// \param TemplateII The identifier used to name the template.
12451 /// \param TemplateIILoc The location of the template name.
12452 /// \param LAngleLoc The location of the opening angle bracket ('<').
12453 /// \param TemplateArgs The template arguments.
12454 /// \param RAngleLoc The location of the closing angle bracket ('>').
12455 TypeResult
12456 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12457 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12458 TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12459 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12460 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12461
12462 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12463 SourceLocation KeywordLoc,
12464 NestedNameSpecifierLoc QualifierLoc,
12465 const IdentifierInfo &II, SourceLocation IILoc,
12466 TypeSourceInfo **TSI, bool DeducedTSTContext);
12467
12468 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12469 SourceLocation KeywordLoc,
12470 NestedNameSpecifierLoc QualifierLoc,
12471 const IdentifierInfo &II, SourceLocation IILoc,
12472 bool DeducedTSTContext = true);
12473
12474 /// Rebuilds a type within the context of the current instantiation.
12475 ///
12476 /// The type \p T is part of the type of an out-of-line member definition of
12477 /// a class template (or class template partial specialization) that was
12478 /// parsed and constructed before we entered the scope of the class template
12479 /// (or partial specialization thereof). This routine will rebuild that type
12480 /// now that we have entered the declarator's scope, which may produce
12481 /// different canonical types, e.g.,
12482 ///
12483 /// \code
12484 /// template<typename T>
12485 /// struct X {
12486 /// typedef T* pointer;
12487 /// pointer data();
12488 /// };
12489 ///
12490 /// template<typename T>
12491 /// typename X<T>::pointer X<T>::data() { ... }
12492 /// \endcode
12493 ///
12494 /// Here, the type "typename X<T>::pointer" will be created as a
12495 /// DependentNameType, since we do not know that we can look into X<T> when we
12496 /// parsed the type. This function will rebuild the type, performing the
12497 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12498 /// canonical type is the same as the canonical type of T*, allowing the
12499 /// return types of the out-of-line definition and the declaration to match.
12500 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
12501 SourceLocation Loc,
12502 DeclarationName Name);
12503 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
12504
12505 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
12506
12507 /// Rebuild the template parameters now that we know we're in a current
12508 /// instantiation.
12509 bool
12510 RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params);
12511
12512 /// Produces a formatted string that describes the binding of
12513 /// template parameters to template arguments.
12514 std::string
12515 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12516 const TemplateArgumentList &Args);
12517
12518 std::string
12519 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12520 const TemplateArgument *Args,
12521 unsigned NumArgs);
12522
12523 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
12524 SourceLocation Less,
12525 SourceLocation Greater);
12526
12527 /// ActOnDependentIdExpression - Handle a dependent id-expression that
12528 /// was just parsed. This is only possible with an explicit scope
12529 /// specifier naming a dependent type.
12530 ExprResult ActOnDependentIdExpression(
12531 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12532 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12533 const TemplateArgumentListInfo *TemplateArgs);
12534
12535 ExprResult
12536 BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
12537 SourceLocation TemplateKWLoc,
12538 const DeclarationNameInfo &NameInfo,
12539 const TemplateArgumentListInfo *TemplateArgs);
12540
12541 // Calculates whether the expression Constraint depends on an enclosing
12542 // template, for the purposes of [temp.friend] p9.
12543 // TemplateDepth is the 'depth' of the friend function, which is used to
12544 // compare whether a declaration reference is referring to a containing
12545 // template, or just the current friend function. A 'lower' TemplateDepth in
12546 // the AST refers to a 'containing' template. As the constraint is
12547 // uninstantiated, this is relative to the 'top' of the TU.
12548 bool
12549 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
12550 unsigned TemplateDepth,
12551 const Expr *Constraint);
12552
12553 /// Find the failed Boolean condition within a given Boolean
12554 /// constant expression, and describe it with a string.
12555 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12556
12557 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
12558
12559 ConceptDecl *ActOnStartConceptDefinition(
12560 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12561 const IdentifierInfo *Name, SourceLocation NameLoc);
12562
12563 ConceptDecl *ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
12564 Expr *ConstraintExpr,
12565 const ParsedAttributesView &Attrs);
12566
12567 void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
12568 bool &AddToScope);
12569 bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc);
12570
12571 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12572 const CXXScopeSpec &SS,
12573 const IdentifierInfo *Name,
12574 SourceLocation TagLoc, SourceLocation NameLoc);
12575
12576 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
12577 CachedTokens &Toks);
12578 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
12579 bool IsInsideALocalClassWithinATemplateFunction();
12580
12581 /// We've found a use of a templated declaration that would trigger an
12582 /// implicit instantiation. Check that any relevant explicit specializations
12583 /// and partial specializations are visible/reachable, and diagnose if not.
12584 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
12585 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
12586
12587 ///@}
12588
12589 //
12590 //
12591 // -------------------------------------------------------------------------
12592 //
12593 //
12594
12595 /// \name C++ Template Argument Deduction
12596 /// Implementations are in SemaTemplateDeduction.cpp
12597 ///@{
12598
12599public:
12600 class SFINAETrap;
12601
12602 struct SFINAEContextBase {
12603 SFINAEContextBase(Sema &S, SFINAETrap *Cur)
12604 : S(S), Prev(std::exchange(obj&: S.CurrentSFINAEContext, new_val&: Cur)) {}
12605
12606 protected:
12607 Sema &S;
12608 ~SFINAEContextBase() { S.CurrentSFINAEContext = Prev; }
12609 SFINAEContextBase(const SFINAEContextBase &) = delete;
12610 SFINAEContextBase &operator=(const SFINAEContextBase &) = delete;
12611
12612 private:
12613 SFINAETrap *Prev;
12614 };
12615
12616 struct NonSFINAEContext : SFINAEContextBase {
12617 NonSFINAEContext(Sema &S) : SFINAEContextBase(S, nullptr) {}
12618 };
12619
12620 /// RAII class used to determine whether SFINAE has
12621 /// trapped any errors that occur during template argument
12622 /// deduction.
12623 class SFINAETrap : SFINAEContextBase {
12624 bool HasErrorOcurred = false;
12625 bool WithAccessChecking = false;
12626 bool PrevLastDiagnosticIgnored =
12627 S.getDiagnostics().isLastDiagnosticIgnored();
12628 sema::TemplateDeductionInfo *DeductionInfo = nullptr;
12629
12630 SFINAETrap(Sema &S, sema::TemplateDeductionInfo *Info,
12631 bool WithAccessChecking)
12632 : SFINAEContextBase(S, this), WithAccessChecking(WithAccessChecking),
12633 DeductionInfo(Info) {}
12634
12635 public:
12636 /// \param WithAccessChecking If true, discard all diagnostics (from the
12637 /// immediate context) instead of adding them to the currently active
12638 /// \ref TemplateDeductionInfo.
12639 explicit SFINAETrap(Sema &S, bool WithAccessChecking = false)
12640 : SFINAETrap(S, /*Info=*/nullptr, WithAccessChecking) {}
12641
12642 SFINAETrap(Sema &S, sema::TemplateDeductionInfo &Info)
12643 : SFINAETrap(S, &Info, /*WithAccessChecking=*/false) {}
12644
12645 ~SFINAETrap() {
12646 S.getDiagnostics().setLastDiagnosticIgnored(PrevLastDiagnosticIgnored);
12647 }
12648
12649 SFINAETrap(const SFINAETrap &) = delete;
12650 SFINAETrap &operator=(const SFINAETrap &) = delete;
12651
12652 sema::TemplateDeductionInfo *getDeductionInfo() const {
12653 return DeductionInfo;
12654 }
12655
12656 /// Determine whether any SFINAE errors have been trapped.
12657 bool hasErrorOccurred() const { return HasErrorOcurred; }
12658 void setErrorOccurred() { HasErrorOcurred = true; }
12659
12660 bool withAccessChecking() const { return WithAccessChecking; }
12661 };
12662
12663 /// RAII class used to indicate that we are performing provisional
12664 /// semantic analysis to determine the validity of a construct, so
12665 /// typo-correction and diagnostics in the immediate context (not within
12666 /// implicitly-instantiated templates) should be suppressed.
12667 class TentativeAnalysisScope {
12668 Sema &SemaRef;
12669 // FIXME: Using a SFINAETrap for this is a hack.
12670 SFINAETrap Trap;
12671 bool PrevDisableTypoCorrection;
12672
12673 public:
12674 explicit TentativeAnalysisScope(Sema &SemaRef)
12675 : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12676 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12677 SemaRef.DisableTypoCorrection = true;
12678 }
12679 ~TentativeAnalysisScope() {
12680 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12681 }
12682
12683 TentativeAnalysisScope(const TentativeAnalysisScope &) = delete;
12684 TentativeAnalysisScope &operator=(const TentativeAnalysisScope &) = delete;
12685 };
12686
12687 /// For each declaration that involved template argument deduction, the
12688 /// set of diagnostics that were suppressed during that template argument
12689 /// deduction.
12690 ///
12691 /// FIXME: Serialize this structure to the AST file.
12692 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12693 SuppressedDiagnosticsMap;
12694 SuppressedDiagnosticsMap SuppressedDiagnostics;
12695
12696 /// Compare types for equality with respect to possibly compatible
12697 /// function types (noreturn adjustment, implicit calling conventions). If any
12698 /// of parameter and argument is not a function, just perform type comparison.
12699 ///
12700 /// \param P the template parameter type.
12701 ///
12702 /// \param A the argument type.
12703 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
12704
12705 /// Allocate a TemplateArgumentLoc where all locations have
12706 /// been initialized to the given location.
12707 ///
12708 /// \param Arg The template argument we are producing template argument
12709 /// location information for.
12710 ///
12711 /// \param NTTPType For a declaration template argument, the type of
12712 /// the non-type template parameter that corresponds to this template
12713 /// argument. Can be null if no type sugar is available to add to the
12714 /// type from the template argument.
12715 ///
12716 /// \param Loc The source location to use for the resulting template
12717 /// argument.
12718 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
12719 QualType NTTPType,
12720 SourceLocation Loc);
12721
12722 /// Get a template argument mapping the given template parameter to itself,
12723 /// e.g. for X in \c template<int X>, this would return an expression template
12724 /// argument referencing X.
12725 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
12726 SourceLocation Location);
12727
12728 /// Adjust the type \p ArgFunctionType to match the calling convention,
12729 /// noreturn, and optionally the exception specification of \p FunctionType.
12730 /// Deduction often wants to ignore these properties when matching function
12731 /// types.
12732 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
12733 bool AdjustExceptionSpec = false);
12734
12735 TemplateDeductionResult
12736 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
12737 ArrayRef<TemplateArgument> TemplateArgs,
12738 sema::TemplateDeductionInfo &Info);
12739
12740 TemplateDeductionResult
12741 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
12742 ArrayRef<TemplateArgument> TemplateArgs,
12743 sema::TemplateDeductionInfo &Info);
12744
12745 /// Deduce the template arguments of the given template from \p FromType.
12746 /// Used to implement the IsDeducible constraint for alias CTAD per C++
12747 /// [over.match.class.deduct]p4.
12748 ///
12749 /// It only supports class or type alias templates.
12750 TemplateDeductionResult
12751 DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType,
12752 sema::TemplateDeductionInfo &Info);
12753
12754 TemplateDeductionResult DeduceTemplateArguments(
12755 TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps,
12756 ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info,
12757 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12758 bool NumberOfArgumentsMustMatch);
12759
12760 /// Substitute the explicitly-provided template arguments into the
12761 /// given function template according to C++ [temp.arg.explicit].
12762 ///
12763 /// \param FunctionTemplate the function template into which the explicit
12764 /// template arguments will be substituted.
12765 ///
12766 /// \param ExplicitTemplateArgs the explicitly-specified template
12767 /// arguments.
12768 ///
12769 /// \param Deduced the deduced template arguments, which will be populated
12770 /// with the converted and checked explicit template arguments.
12771 ///
12772 /// \param ParamTypes will be populated with the instantiated function
12773 /// parameters.
12774 ///
12775 /// \param FunctionType if non-NULL, the result type of the function template
12776 /// will also be instantiated and the pointed-to value will be updated with
12777 /// the instantiated function type.
12778 ///
12779 /// \param Info if substitution fails for any reason, this object will be
12780 /// populated with more information about the failure.
12781 ///
12782 /// \returns TemplateDeductionResult::Success if substitution was successful,
12783 /// or some failure condition.
12784 TemplateDeductionResult SubstituteExplicitTemplateArguments(
12785 FunctionTemplateDecl *FunctionTemplate,
12786 TemplateArgumentListInfo &ExplicitTemplateArgs,
12787 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12788 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
12789 sema::TemplateDeductionInfo &Info);
12790
12791 /// brief A function argument from which we performed template argument
12792 // deduction for a call.
12793 struct OriginalCallArg {
12794 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
12795 unsigned ArgIdx, QualType OriginalArgType)
12796 : OriginalParamType(OriginalParamType),
12797 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
12798 OriginalArgType(OriginalArgType) {}
12799
12800 QualType OriginalParamType;
12801 bool DecomposedParam;
12802 unsigned ArgIdx;
12803 QualType OriginalArgType;
12804 };
12805
12806 /// Finish template argument deduction for a function template,
12807 /// checking the deduced template arguments for completeness and forming
12808 /// the function template specialization.
12809 ///
12810 /// \param OriginalCallArgs If non-NULL, the original call arguments against
12811 /// which the deduced argument types should be compared.
12812 /// \param CheckNonDependent Callback before substituting into the declaration
12813 /// with the deduced template arguments.
12814 /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12815 /// some breakages introduced by CWG2369, where non-user-defined conversions
12816 /// are checked first before the constraints.
12817 TemplateDeductionResult FinishTemplateArgumentDeduction(
12818 FunctionTemplateDecl *FunctionTemplate,
12819 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12820 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12821 sema::TemplateDeductionInfo &Info,
12822 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12823 bool PartialOverloading, bool PartialOrdering,
12824 bool ForOverloadSetAddressResolution,
12825 llvm::function_ref<bool(bool)> CheckNonDependent =
12826 [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12827 return false;
12828 });
12829
12830 /// Perform [temp.friend] p5 template argument deduction for a dependent
12831 /// friend declaration and a candidate class template specialization.
12832 bool DeduceTemplateArguments(FriendTemplateDecl *FTD,
12833 ClassTemplateDecl *PatternCTD,
12834 ClassTemplateDecl *CandidateCTD,
12835 ArrayRef<TemplateParameterList *> TPLs,
12836 ArrayRef<TemplateArgument> PatternArgs,
12837 ArrayRef<TemplateArgument> CandidateArgs,
12838 SourceLocation Loc,
12839 TemplateSpecCandidateSet *FailedTSC,
12840 MultiLevelTemplateArgumentList &DeducedArgs);
12841
12842 /// Perform template argument deduction from a function call
12843 /// (C++ [temp.deduct.call]).
12844 ///
12845 /// \param FunctionTemplate the function template for which we are performing
12846 /// template argument deduction.
12847 ///
12848 /// \param ExplicitTemplateArgs the explicit template arguments provided
12849 /// for this call.
12850 ///
12851 /// \param Args the function call arguments
12852 ///
12853 /// \param Specialization if template argument deduction was successful,
12854 /// this will be set to the function template specialization produced by
12855 /// template argument deduction.
12856 ///
12857 /// \param Info the argument will be updated to provide additional information
12858 /// about template argument deduction.
12859 ///
12860 /// \param CheckNonDependent A callback to invoke to check conversions for
12861 /// non-dependent parameters, between deduction and substitution, per DR1391.
12862 /// If this returns true, substitution will be skipped and we return
12863 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12864 /// passed the parameter types (after substituting explicit template
12865 /// arguments).
12866 ///
12867 /// \returns the result of template argument deduction.
12868 TemplateDeductionResult DeduceTemplateArguments(
12869 FunctionTemplateDecl *FunctionTemplate,
12870 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12871 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12872 bool PartialOverloading, bool AggregateDeductionCandidate,
12873 bool PartialOrdering, QualType ObjectType,
12874 Expr::Classification ObjectClassification,
12875 bool ForOverloadSetAddressResolution,
12876 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12877
12878 /// Deduce template arguments when taking the address of a function
12879 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12880 /// a template.
12881 ///
12882 /// \param FunctionTemplate the function template for which we are performing
12883 /// template argument deduction.
12884 ///
12885 /// \param ExplicitTemplateArgs the explicitly-specified template
12886 /// arguments.
12887 ///
12888 /// \param ArgFunctionType the function type that will be used as the
12889 /// "argument" type (A) when performing template argument deduction from the
12890 /// function template's function type. This type may be NULL, if there is no
12891 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
12892 ///
12893 /// \param Specialization if template argument deduction was successful,
12894 /// this will be set to the function template specialization produced by
12895 /// template argument deduction.
12896 ///
12897 /// \param Info the argument will be updated to provide additional information
12898 /// about template argument deduction.
12899 ///
12900 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12901 /// the address of a function template per [temp.deduct.funcaddr] and
12902 /// [over.over]. If \c false, we are looking up a function template
12903 /// specialization based on its signature, per [temp.deduct.decl].
12904 ///
12905 /// \returns the result of template argument deduction.
12906 TemplateDeductionResult DeduceTemplateArguments(
12907 FunctionTemplateDecl *FunctionTemplate,
12908 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
12909 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12910 bool IsAddressOfFunction = false);
12911
12912 /// Deduce template arguments for a templated conversion
12913 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
12914 /// conversion function template specialization.
12915 TemplateDeductionResult DeduceTemplateArguments(
12916 FunctionTemplateDecl *FunctionTemplate, QualType ObjectType,
12917 Expr::Classification ObjectClassification, QualType ToType,
12918 CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info);
12919
12920 /// Deduce template arguments for a function template when there is
12921 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
12922 ///
12923 /// \param FunctionTemplate the function template for which we are performing
12924 /// template argument deduction.
12925 ///
12926 /// \param ExplicitTemplateArgs the explicitly-specified template
12927 /// arguments.
12928 ///
12929 /// \param Specialization if template argument deduction was successful,
12930 /// this will be set to the function template specialization produced by
12931 /// template argument deduction.
12932 ///
12933 /// \param Info the argument will be updated to provide additional information
12934 /// about template argument deduction.
12935 ///
12936 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12937 /// the address of a function template in a context where we do not have a
12938 /// target type, per [over.over]. If \c false, we are looking up a function
12939 /// template specialization based on its signature, which only happens when
12940 /// deducing a function parameter type from an argument that is a template-id
12941 /// naming a function template specialization.
12942 ///
12943 /// \returns the result of template argument deduction.
12944 TemplateDeductionResult
12945 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
12946 TemplateArgumentListInfo *ExplicitTemplateArgs,
12947 FunctionDecl *&Specialization,
12948 sema::TemplateDeductionInfo &Info,
12949 bool IsAddressOfFunction = false);
12950
12951 /// Substitute Replacement for \p auto in \p TypeWithAuto
12952 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
12953 /// Substitute Replacement for auto in TypeWithAuto
12954 TypeSourceInfo *SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12955 QualType Replacement);
12956
12957 // Substitute auto in TypeWithAuto for a Dependent auto type
12958 QualType SubstAutoTypeDependent(QualType TypeWithAuto);
12959
12960 // Substitute auto in TypeWithAuto for a Dependent auto type
12961 TypeSourceInfo *
12962 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
12963
12964 /// Completely replace the \c auto in \p TypeWithAuto by
12965 /// \p Replacement. This does not retain any \c auto type sugar.
12966 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
12967 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12968 QualType Replacement);
12969
12970 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
12971 ///
12972 /// Note that this is done even if the initializer is dependent. (This is
12973 /// necessary to support partial ordering of templates using 'auto'.)
12974 /// A dependent type will be produced when deducing from a dependent type.
12975 ///
12976 /// \param Type the type pattern using the auto type-specifier.
12977 /// \param Init the initializer for the variable whose type is to be deduced.
12978 /// \param Result if type deduction was successful, this will be set to the
12979 /// deduced type.
12980 /// \param Info the argument will be updated to provide additional information
12981 /// about template argument deduction.
12982 /// \param DependentDeduction Set if we should permit deduction in
12983 /// dependent cases. This is necessary for template partial ordering
12984 /// with 'auto' template parameters. The template parameter depth to be
12985 /// used should be specified in the 'Info' parameter.
12986 /// \param IgnoreConstraints Set if we should not fail if the deduced type
12987 /// does not satisfy the type-constraint in the auto
12988 /// type.
12989 TemplateDeductionResult
12990 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result,
12991 sema::TemplateDeductionInfo &Info,
12992 bool DependentDeduction = false,
12993 bool IgnoreConstraints = false,
12994 TemplateSpecCandidateSet *FailedTSC = nullptr);
12995 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
12996 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
12997 bool Diagnose = true);
12998
12999 bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD,
13000 SourceLocation Loc);
13001
13002 /// Returns the more specialized class template partial specialization
13003 /// according to the rules of partial ordering of class template partial
13004 /// specializations (C++ [temp.class.order]).
13005 ///
13006 /// \param PS1 the first class template partial specialization
13007 ///
13008 /// \param PS2 the second class template partial specialization
13009 ///
13010 /// \returns the more specialized class template partial specialization. If
13011 /// neither partial specialization is more specialized, returns NULL.
13012 ClassTemplatePartialSpecializationDecl *
13013 getMoreSpecializedPartialSpecialization(
13014 ClassTemplatePartialSpecializationDecl *PS1,
13015 ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
13016
13017 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
13018 sema::TemplateDeductionInfo &Info);
13019
13020 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
13021 VarTemplatePartialSpecializationDecl *PS1,
13022 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
13023
13024 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
13025 sema::TemplateDeductionInfo &Info);
13026
13027 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
13028 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
13029 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
13030 bool PartialOrdering, bool *StrictPackMatch);
13031
13032 /// Mark which template parameters are used in a given expression.
13033 ///
13034 /// \param E the expression from which template parameters will be deduced.
13035 ///
13036 /// \param Used a bit vector whose elements will be set to \c true
13037 /// to indicate when the corresponding template parameter will be
13038 /// deduced.
13039 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
13040 unsigned Depth, llvm::SmallBitVector &Used);
13041
13042 /// Mark which template parameters are named in a given expression.
13043 ///
13044 /// Unlike MarkUsedTemplateParameters, this excludes parameter that
13045 /// are used but not directly named by an expression - i.e. it excludes
13046 /// any template parameter that denotes the type of a referenced NTTP.
13047 ///
13048 /// \param Used a bit vector whose elements will be set to \c true
13049 /// to indicate when the corresponding template parameter will be
13050 /// deduced.
13051 void MarkUsedTemplateParametersForSubsumptionParameterMapping(
13052 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used);
13053
13054 /// Mark which template parameters can be deduced from a given
13055 /// template argument list.
13056 ///
13057 /// \param TemplateArgs the template argument list from which template
13058 /// parameters will be deduced.
13059 ///
13060 /// \param Used a bit vector whose elements will be set to \c true
13061 /// to indicate when the corresponding template parameter will be
13062 /// deduced.
13063 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
13064 bool OnlyDeduced, unsigned Depth,
13065 llvm::SmallBitVector &Used);
13066
13067 void MarkUsedTemplateParameters(ArrayRef<TemplateArgument> TemplateArgs,
13068 bool OnlyDeduced, unsigned Depth,
13069 llvm::SmallBitVector &Used);
13070
13071 void MarkUsedTemplateParameters(ArrayRef<TemplateArgumentLoc> TemplateArgs,
13072 unsigned Depth, llvm::SmallBitVector &Used);
13073
13074 void
13075 MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate,
13076 llvm::SmallBitVector &Deduced) {
13077 return MarkDeducedTemplateParameters(Ctx&: Context, FunctionTemplate, Deduced);
13078 }
13079
13080 /// Marks all of the template parameters that will be deduced by a
13081 /// call to the given function template.
13082 static void
13083 MarkDeducedTemplateParameters(ASTContext &Ctx,
13084 const FunctionTemplateDecl *FunctionTemplate,
13085 llvm::SmallBitVector &Deduced);
13086
13087 /// Returns the more specialized function template according
13088 /// to the rules of function template partial ordering (C++
13089 /// [temp.func.order]).
13090 ///
13091 /// \param FT1 the first function template
13092 ///
13093 /// \param FT2 the second function template
13094 ///
13095 /// \param TPOC the context in which we are performing partial ordering of
13096 /// function templates.
13097 ///
13098 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
13099 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
13100 /// when calling a member function.
13101 ///
13102 /// \param RawObj1Ty The type of the object parameter of FT1 if a member
13103 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
13104 /// template from a member function
13105 ///
13106 /// \param RawObj2Ty The type of the object parameter of FT2 if a member
13107 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
13108 /// template from a member function
13109 ///
13110 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
13111 /// candidate with a reversed parameter order. In this case, the corresponding
13112 /// P/A pairs between FT1 and FT2 are reversed.
13113 ///
13114 /// \returns the more specialized function template. If neither
13115 /// template is more specialized, returns NULL.
13116 FunctionTemplateDecl *getMoreSpecializedTemplate(
13117 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
13118 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
13119 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
13120 bool PartialOverloading = false);
13121
13122 /// Retrieve the most specialized of the given function template
13123 /// specializations.
13124 ///
13125 /// \param SpecBegin the start iterator of the function template
13126 /// specializations that we will be comparing.
13127 ///
13128 /// \param SpecEnd the end iterator of the function template
13129 /// specializations, paired with \p SpecBegin.
13130 ///
13131 /// \param Loc the location where the ambiguity or no-specializations
13132 /// diagnostic should occur.
13133 ///
13134 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
13135 /// no matching candidates.
13136 ///
13137 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
13138 /// occurs.
13139 ///
13140 /// \param CandidateDiag partial diagnostic used for each function template
13141 /// specialization that is a candidate in the ambiguous ordering. One
13142 /// parameter in this diagnostic should be unbound, which will correspond to
13143 /// the string describing the template arguments for the function template
13144 /// specialization.
13145 ///
13146 /// \returns the most specialized function template specialization, if
13147 /// found. Otherwise, returns SpecEnd.
13148 UnresolvedSetIterator
13149 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
13150 TemplateSpecCandidateSet &FailedCandidates,
13151 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
13152 const PartialDiagnostic &AmbigDiag,
13153 const PartialDiagnostic &CandidateDiag,
13154 bool Complain = true, QualType TargetType = QualType());
13155
13156 /// Returns the more constrained function according to the rules of
13157 /// partial ordering by constraints (C++ [temp.constr.order]).
13158 ///
13159 /// \param FD1 the first function
13160 ///
13161 /// \param FD2 the second function
13162 ///
13163 /// \returns the more constrained function. If neither function is
13164 /// more constrained, returns NULL.
13165 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
13166 FunctionDecl *FD2);
13167
13168 ///@}
13169
13170 //
13171 //
13172 // -------------------------------------------------------------------------
13173 //
13174 //
13175
13176 /// \name C++ Template Deduction Guide
13177 /// Implementations are in SemaTemplateDeductionGuide.cpp
13178 ///@{
13179
13180 /// Declare implicit deduction guides for a class template if we've
13181 /// not already done so.
13182 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
13183 SourceLocation Loc);
13184
13185 CXXDeductionGuideDecl *DeclareAggregateDeductionGuideFromInitList(
13186 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
13187 SourceLocation Loc);
13188
13189 ///@}
13190
13191 //
13192 //
13193 // -------------------------------------------------------------------------
13194 //
13195 //
13196
13197 /// \name C++ Template Instantiation
13198 /// Implementations are in SemaTemplateInstantiate.cpp
13199 ///@{
13200
13201public:
13202 /// A helper class for building up ExtParameterInfos.
13203 class ExtParameterInfoBuilder {
13204 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
13205 bool HasInteresting = false;
13206
13207 public:
13208 /// Set the ExtParameterInfo for the parameter at the given index,
13209 ///
13210 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
13211 assert(Infos.size() <= index);
13212 Infos.resize(N: index);
13213 Infos.push_back(Elt: info);
13214
13215 if (!HasInteresting)
13216 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
13217 }
13218
13219 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
13220 /// ExtParameterInfo array we've built up.
13221 const FunctionProtoType::ExtParameterInfo *
13222 getPointerOrNull(unsigned numParams) {
13223 if (!HasInteresting)
13224 return nullptr;
13225 Infos.resize(N: numParams);
13226 return Infos.data();
13227 }
13228 };
13229
13230 /// The current instantiation scope used to store local
13231 /// variables.
13232 LocalInstantiationScope *CurrentInstantiationScope;
13233
13234 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
13235 UnparsedDefaultArgInstantiationsMap;
13236
13237 /// A mapping from parameters with unparsed default arguments to the
13238 /// set of instantiations of each parameter.
13239 ///
13240 /// This mapping is a temporary data structure used when parsing
13241 /// nested class templates or nested classes of class templates,
13242 /// where we might end up instantiating an inner class before the
13243 /// default arguments of its methods have been parsed.
13244 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
13245
13246 using InstantiatingSpecializationsKey = llvm::PointerIntPair<Decl *, 2>;
13247
13248 struct RecursiveInstGuard {
13249 enum class Kind {
13250 Template,
13251 DefaultArgument,
13252 ExceptionSpec,
13253 };
13254
13255 RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
13256 : S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
13257 auto [_, Created] = S.InstantiatingSpecializations.insert(V: Key);
13258 if (!Created)
13259 Key = {};
13260 }
13261
13262 ~RecursiveInstGuard() {
13263 if (Key.getOpaqueValue()) {
13264 [[maybe_unused]] bool Erased =
13265 S.InstantiatingSpecializations.erase(V: Key);
13266 assert(Erased);
13267 }
13268 }
13269
13270 RecursiveInstGuard(const RecursiveInstGuard &) = delete;
13271 RecursiveInstGuard &operator=(const RecursiveInstGuard &) = delete;
13272
13273 operator bool() const { return Key.getOpaqueValue() == nullptr; }
13274
13275 private:
13276 Sema &S;
13277 Sema::InstantiatingSpecializationsKey Key;
13278 };
13279
13280 /// A context in which code is being synthesized (where a source location
13281 /// alone is not sufficient to identify the context). This covers template
13282 /// instantiation and various forms of implicitly-generated functions.
13283 struct CodeSynthesisContext {
13284 /// The kind of template instantiation we are performing
13285 enum SynthesisKind {
13286 /// We are instantiating a template declaration. The entity is
13287 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
13288 TemplateInstantiation,
13289
13290 /// We are instantiating a default argument for a template
13291 /// parameter. The Entity is the template parameter whose argument is
13292 /// being instantiated, the Template is the template, and the
13293 /// TemplateArgs/NumTemplateArguments provide the template arguments as
13294 /// specified.
13295 DefaultTemplateArgumentInstantiation,
13296
13297 /// We are instantiating a default argument for a function.
13298 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
13299 /// provides the template arguments as specified.
13300 DefaultFunctionArgumentInstantiation,
13301
13302 /// We are substituting explicit template arguments provided for
13303 /// a function template. The entity is a FunctionTemplateDecl.
13304 ExplicitTemplateArgumentSubstitution,
13305
13306 /// We are substituting template argument determined as part of
13307 /// template argument deduction for either a class template
13308 /// partial specialization or a function template. The
13309 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
13310 /// a TemplateDecl.
13311 DeducedTemplateArgumentSubstitution,
13312
13313 /// We are substituting into a lambda expression.
13314 LambdaExpressionSubstitution,
13315
13316 /// We are substituting prior template arguments into a new
13317 /// template parameter. The template parameter itself is either a
13318 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
13319 PriorTemplateArgumentSubstitution,
13320
13321 /// We are checking the validity of a default template argument that
13322 /// has been used when naming a template-id.
13323 DefaultTemplateArgumentChecking,
13324
13325 /// We are computing the exception specification for a defaulted special
13326 /// member function.
13327 ExceptionSpecEvaluation,
13328
13329 /// We are instantiating the exception specification for a function
13330 /// template which was deferred until it was needed.
13331 ExceptionSpecInstantiation,
13332
13333 /// We are instantiating a requirement of a requires expression.
13334 RequirementInstantiation,
13335
13336 /// We are checking the satisfaction of a nested requirement of a requires
13337 /// expression.
13338 NestedRequirementConstraintsCheck,
13339
13340 /// We are declaring an implicit special member function.
13341 DeclaringSpecialMember,
13342
13343 /// We are declaring an implicit 'operator==' for a defaulted
13344 /// 'operator<=>'.
13345 DeclaringImplicitEqualityComparison,
13346
13347 /// We are defining a synthesized function (such as a defaulted special
13348 /// member).
13349 DefiningSynthesizedFunction,
13350
13351 // We are checking the constraints associated with a constrained entity or
13352 // the constraint expression of a concept. This includes the checks that
13353 // atomic constraints have the type 'bool' and that they can be constant
13354 // evaluated.
13355 ConstraintsCheck,
13356
13357 // We are substituting template arguments into a constraint expression.
13358 ConstraintSubstitution,
13359
13360 // Instantiating a Requires Expression parameter clause.
13361 RequirementParameterInstantiation,
13362
13363 // We are substituting into the parameter mapping of an atomic constraint
13364 // during normalization.
13365 ParameterMappingSubstitution,
13366
13367 /// We are rewriting a comparison operator in terms of an operator<=>.
13368 RewritingOperatorAsSpaceship,
13369
13370 /// We are initializing a structured binding.
13371 InitializingStructuredBinding,
13372
13373 /// We are marking a class as __dllexport.
13374 MarkingClassDllexported,
13375
13376 /// We are building an implied call from __builtin_dump_struct. The
13377 /// arguments are in CallArgs.
13378 BuildingBuiltinDumpStructCall,
13379
13380 /// Added for Template instantiation observation.
13381 /// Memoization means we are _not_ instantiating a template because
13382 /// it is already instantiated (but we entered a context where we
13383 /// would have had to if it was not already instantiated).
13384 Memoization,
13385
13386 /// We are building deduction guides for a class.
13387 BuildingDeductionGuides,
13388
13389 /// We are instantiating a type alias template declaration.
13390 TypeAliasTemplateInstantiation,
13391
13392 /// We are performing partial ordering for template template parameters.
13393 PartialOrderingTTP,
13394
13395 /// We are performing name lookup for a function template or variable
13396 /// template named 'sycl_kernel_launch'.
13397 SYCLKernelLaunchLookup,
13398
13399 /// We are performing overload resolution for a call to a function
13400 /// template or variable template named 'sycl_kernel_launch'.
13401 SYCLKernelLaunchOverloadResolution,
13402
13403 /// We are instantiating an expansion statement.
13404 ExpansionStmtInstantiation,
13405 } Kind;
13406
13407 /// Whether we're substituting into constraints.
13408 bool InConstraintSubstitution;
13409
13410 /// Whether we're substituting into the parameter mapping of a constraint.
13411 bool InParameterMappingSubstitution;
13412
13413 /// The point of instantiation or synthesis within the source code.
13414 SourceLocation PointOfInstantiation;
13415
13416 /// The entity that is being synthesized.
13417 Decl *Entity;
13418
13419 /// The template (or partial specialization) in which we are
13420 /// performing the instantiation, for substitutions of prior template
13421 /// arguments.
13422 NamedDecl *Template;
13423
13424 union {
13425 /// The list of template arguments we are substituting, if they
13426 /// are not part of the entity.
13427 const TemplateArgument *TemplateArgs;
13428
13429 /// The list of argument expressions in a synthesized call.
13430 const Expr *const *CallArgs;
13431 };
13432
13433 // FIXME: Wrap this union around more members, or perhaps store the
13434 // kind-specific members in the RAII object owning the context.
13435 union {
13436 /// The number of template arguments in TemplateArgs.
13437 unsigned NumTemplateArgs;
13438
13439 /// The number of expressions in CallArgs.
13440 unsigned NumCallArgs;
13441
13442 /// The special member being declared or defined.
13443 CXXSpecialMemberKind SpecialMember;
13444 };
13445
13446 ArrayRef<TemplateArgument> template_arguments() const {
13447 assert(Kind != DeclaringSpecialMember);
13448 return {TemplateArgs, NumTemplateArgs};
13449 }
13450
13451 /// The source range that covers the construct that cause
13452 /// the instantiation, e.g., the template-id that causes a class
13453 /// template instantiation.
13454 SourceRange InstantiationRange;
13455
13456 CodeSynthesisContext()
13457 : Kind(TemplateInstantiation), InConstraintSubstitution(false),
13458 InParameterMappingSubstitution(false), Entity(nullptr),
13459 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0) {}
13460
13461 /// Determines whether this template is an actual instantiation
13462 /// that should be counted toward the maximum instantiation depth.
13463 bool isInstantiationRecord() const;
13464 };
13465
13466 /// A stack object to be created when performing template
13467 /// instantiation.
13468 ///
13469 /// Construction of an object of type \c InstantiatingTemplate
13470 /// pushes the current instantiation onto the stack of active
13471 /// instantiations. If the size of this stack exceeds the maximum
13472 /// number of recursive template instantiations, construction
13473 /// produces an error and evaluates true.
13474 ///
13475 /// Destruction of this object will pop the named instantiation off
13476 /// the stack.
13477 struct InstantiatingTemplate {
13478 /// Note that we are instantiating a class template,
13479 /// function template, variable template, alias template,
13480 /// or a member thereof.
13481 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13482 Decl *Entity,
13483 SourceRange InstantiationRange = SourceRange());
13484
13485 struct ExceptionSpecification {};
13486 /// Note that we are instantiating an exception specification
13487 /// of a function template.
13488 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13489 FunctionDecl *Entity, ExceptionSpecification,
13490 SourceRange InstantiationRange = SourceRange());
13491
13492 /// Note that we are instantiating a type alias template declaration.
13493 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13494 TypeAliasTemplateDecl *Entity,
13495 ArrayRef<TemplateArgument> TemplateArgs,
13496 SourceRange InstantiationRange = SourceRange());
13497
13498 /// Note that we are instantiating a default argument in a
13499 /// template-id.
13500 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13501 TemplateParameter Param, TemplateDecl *Template,
13502 ArrayRef<TemplateArgument> TemplateArgs,
13503 SourceRange InstantiationRange = SourceRange());
13504
13505 /// Note that we are substituting either explicitly-specified or
13506 /// deduced template arguments during function template argument deduction.
13507 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13508 FunctionTemplateDecl *FunctionTemplate,
13509 ArrayRef<TemplateArgument> TemplateArgs,
13510 CodeSynthesisContext::SynthesisKind Kind,
13511 SourceRange InstantiationRange = SourceRange());
13512
13513 /// Note that we are instantiating as part of template
13514 /// argument deduction for a class template declaration.
13515 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13516 TemplateDecl *Template,
13517 ArrayRef<TemplateArgument> TemplateArgs,
13518 SourceRange InstantiationRange = SourceRange());
13519
13520 /// Note that we are instantiating as part of template
13521 /// argument deduction for a class template partial
13522 /// specialization.
13523 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13524 ClassTemplatePartialSpecializationDecl *PartialSpec,
13525 ArrayRef<TemplateArgument> TemplateArgs,
13526 SourceRange InstantiationRange = SourceRange());
13527
13528 /// Note that we are instantiating as part of template
13529 /// argument deduction for a variable template partial
13530 /// specialization.
13531 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13532 VarTemplatePartialSpecializationDecl *PartialSpec,
13533 ArrayRef<TemplateArgument> TemplateArgs,
13534 SourceRange InstantiationRange = SourceRange());
13535
13536 /// Note that we are instantiating a default argument for a function
13537 /// parameter.
13538 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13539 ParmVarDecl *Param,
13540 ArrayRef<TemplateArgument> TemplateArgs,
13541 SourceRange InstantiationRange = SourceRange());
13542
13543 /// Note that we are substituting prior template arguments into a
13544 /// non-type parameter.
13545 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13546 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
13547 ArrayRef<TemplateArgument> TemplateArgs,
13548 SourceRange InstantiationRange);
13549
13550 /// Note that we are substituting prior template arguments into a
13551 /// template template parameter.
13552 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13553 NamedDecl *Template, TemplateTemplateParmDecl *Param,
13554 ArrayRef<TemplateArgument> TemplateArgs,
13555 SourceRange InstantiationRange);
13556
13557 /// Note that we are checking the default template argument
13558 /// against the template parameter for a given template-id.
13559 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13560 TemplateDecl *Template, NamedDecl *Param,
13561 ArrayRef<TemplateArgument> TemplateArgs,
13562 SourceRange InstantiationRange);
13563
13564 struct ConstraintsCheck {};
13565 /// \brief Note that we are checking the constraints associated with some
13566 /// constrained entity (a concept declaration or a template with associated
13567 /// constraints).
13568 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13569 ConstraintsCheck, NamedDecl *Template,
13570 ArrayRef<TemplateArgument> TemplateArgs,
13571 SourceRange InstantiationRange);
13572
13573 struct ConstraintSubstitution {};
13574 /// \brief Note that we are checking a constraint expression associated
13575 /// with a template declaration or as part of the satisfaction check of a
13576 /// concept.
13577 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13578 ConstraintSubstitution, NamedDecl *Template,
13579 SourceRange InstantiationRange);
13580
13581 struct ParameterMappingSubstitution {};
13582 /// \brief Note that we are subtituting into the parameter mapping of an
13583 /// atomic constraint during constraint normalization.
13584 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13585 ParameterMappingSubstitution, NamedDecl *Template,
13586 SourceRange InstantiationRange);
13587
13588 /// \brief Note that we are substituting template arguments into a part of
13589 /// a requirement of a requires expression.
13590 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13591 concepts::Requirement *Req,
13592 SourceRange InstantiationRange = SourceRange());
13593
13594 /// \brief Note that we are substituting the body of an expansion statement.
13595 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13596 CXXExpansionStmtPattern *ExpansionStmt,
13597 ArrayRef<TemplateArgument> TArgs,
13598 SourceRange InstantiationRange);
13599
13600 /// \brief Note that we are checking the satisfaction of the constraint
13601 /// expression inside of a nested requirement.
13602 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13603 concepts::NestedRequirement *Req, ConstraintsCheck,
13604 SourceRange InstantiationRange = SourceRange());
13605
13606 /// \brief Note that we are checking a requires clause.
13607 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13608 const RequiresExpr *E,
13609 SourceRange InstantiationRange);
13610
13611 struct BuildingDeductionGuidesTag {};
13612 /// \brief Note that we are building deduction guides.
13613 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13614 TemplateDecl *Entity, BuildingDeductionGuidesTag,
13615 SourceRange InstantiationRange = SourceRange());
13616
13617 struct PartialOrderingTTP {};
13618 /// \brief Note that we are partial ordering template template parameters.
13619 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13620 PartialOrderingTTP, TemplateDecl *PArg,
13621 SourceRange InstantiationRange = SourceRange());
13622
13623 /// Note that we have finished instantiating this template.
13624 void Clear();
13625
13626 ~InstantiatingTemplate() { Clear(); }
13627
13628 /// Determines whether we have exceeded the maximum
13629 /// recursive template instantiations.
13630 bool isInvalid() const { return Invalid; }
13631
13632 private:
13633 Sema &SemaRef;
13634 bool Invalid;
13635
13636 InstantiatingTemplate(Sema &SemaRef,
13637 CodeSynthesisContext::SynthesisKind Kind,
13638 SourceLocation PointOfInstantiation,
13639 SourceRange InstantiationRange, Decl *Entity,
13640 NamedDecl *Template = nullptr,
13641 ArrayRef<TemplateArgument> TemplateArgs = {});
13642
13643 InstantiatingTemplate(const InstantiatingTemplate &) = delete;
13644
13645 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13646 };
13647
13648 bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13649 const MultiLevelTemplateArgumentList &TemplateArgs,
13650 TemplateArgumentLoc &Output,
13651 SourceLocation Loc = {},
13652 const DeclarationName &Entity = {});
13653 bool
13654 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13655 const MultiLevelTemplateArgumentList &TemplateArgs,
13656 TemplateArgumentListInfo &Outputs);
13657
13658 /// Substitute concept template arguments in the constraint expression
13659 /// of a concept-id. This is used to implement [temp.constr.normal].
13660 ExprResult
13661 SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE,
13662 const Expr *ConstraintExpr,
13663 const MultiLevelTemplateArgumentList &MLTAL);
13664
13665 bool SubstTemplateArgumentsInParameterMapping(
13666 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
13667 const MultiLevelTemplateArgumentList &TemplateArgs,
13668 TemplateArgumentListInfo &Out);
13669
13670 /// Retrieve the template argument list(s) that should be used to
13671 /// instantiate the definition of the given declaration.
13672 ///
13673 /// \param ND the declaration for which we are computing template
13674 /// instantiation arguments.
13675 ///
13676 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13677 /// the decl context where it will be created. In this case, the `Innermost`
13678 /// should likely be provided. If ND is non-null, this is ignored.
13679 ///
13680 /// \param Innermost if non-NULL, specifies a template argument list for the
13681 /// template declaration passed as ND.
13682 ///
13683 /// \param RelativeToPrimary true if we should get the template
13684 /// arguments relative to the primary template, even when we're
13685 /// dealing with a specialization. This is only relevant for function
13686 /// template specializations.
13687 ///
13688 /// \param Pattern If non-NULL, indicates the pattern from which we will be
13689 /// instantiating the definition of the given declaration, \p ND. This is
13690 /// used to determine the proper set of template instantiation arguments for
13691 /// friend function template specializations.
13692 ///
13693 /// \param ForConstraintInstantiation when collecting arguments,
13694 /// ForConstraintInstantiation indicates we should continue looking when
13695 /// encountering a lambda generic call operator, and continue looking for
13696 /// arguments on an enclosing class template.
13697 ///
13698 /// \param SkipForSpecialization when specified, any template specializations
13699 /// in a traversal would be ignored.
13700 ///
13701 /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13702 /// when encountering a specialized member function template, rather than
13703 /// returning immediately.
13704 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13705 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13706 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13707 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13708 bool ForConstraintInstantiation = false,
13709 bool SkipForSpecialization = false,
13710 bool ForDefaultArgumentSubstitution = false);
13711
13712 /// RAII object to handle the state changes required to synthesize
13713 /// a function body.
13714 class SynthesizedFunctionScope {
13715 Sema &S;
13716 Sema::ContextRAII SavedContext;
13717 bool PushedCodeSynthesisContext = false;
13718
13719 public:
13720 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
13721 : S(S), SavedContext(S, DC) {
13722 auto *FD = dyn_cast<FunctionDecl>(Val: DC);
13723 S.PushFunctionScope();
13724 S.PushExpressionEvaluationContextForFunction(
13725 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, FD);
13726 if (FD)
13727 FD->setWillHaveBody(true);
13728 else
13729 assert(isa<ObjCMethodDecl>(DC));
13730 }
13731
13732 void addContextNote(SourceLocation UseLoc) {
13733 assert(!PushedCodeSynthesisContext);
13734
13735 Sema::CodeSynthesisContext Ctx;
13736 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
13737 Ctx.PointOfInstantiation = UseLoc;
13738 Ctx.Entity = cast<Decl>(Val: S.CurContext);
13739 S.pushCodeSynthesisContext(Ctx);
13740
13741 PushedCodeSynthesisContext = true;
13742 }
13743
13744 ~SynthesizedFunctionScope() {
13745 if (PushedCodeSynthesisContext)
13746 S.popCodeSynthesisContext();
13747 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
13748 FD->setWillHaveBody(false);
13749 S.CheckImmediateEscalatingFunctionDefinition(FD, FSI: S.getCurFunction());
13750 }
13751 S.PopExpressionEvaluationContext();
13752 S.PopFunctionScopeInfo();
13753 }
13754
13755 SynthesizedFunctionScope(const SynthesizedFunctionScope &) = delete;
13756 SynthesizedFunctionScope &
13757 operator=(const SynthesizedFunctionScope &) = delete;
13758 };
13759
13760 /// RAII object to ensure that a code synthesis context is popped on scope
13761 /// exit.
13762 class ScopedCodeSynthesisContext {
13763 Sema &S;
13764
13765 public:
13766 ScopedCodeSynthesisContext(Sema &S, const CodeSynthesisContext &Ctx)
13767 : S(S) {
13768 S.pushCodeSynthesisContext(Ctx);
13769 }
13770
13771 ~ScopedCodeSynthesisContext() { S.popCodeSynthesisContext(); }
13772 ScopedCodeSynthesisContext(const ScopedCodeSynthesisContext &) = delete;
13773 ScopedCodeSynthesisContext &
13774 operator=(const ScopedCodeSynthesisContext &) = delete;
13775 };
13776
13777 /// List of active code synthesis contexts.
13778 ///
13779 /// This vector is treated as a stack. As synthesis of one entity requires
13780 /// synthesis of another, additional contexts are pushed onto the stack.
13781 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
13782
13783 /// Specializations whose definitions are currently being instantiated.
13784 llvm::DenseSet<InstantiatingSpecializationsKey> InstantiatingSpecializations;
13785
13786 /// Non-dependent types used in templates that have already been instantiated
13787 /// by some template instantiation.
13788 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13789
13790 /// Extra modules inspected when performing a lookup during a template
13791 /// instantiation. Computed lazily.
13792 SmallVector<Module *, 16> CodeSynthesisContextLookupModules;
13793
13794 /// Cache of additional modules that should be used for name lookup
13795 /// within the current template instantiation. Computed lazily; use
13796 /// getLookupModules() to get a complete set.
13797 llvm::DenseSet<Module *> LookupModulesCache;
13798
13799 /// Map from the most recent declaration of a namespace to the most
13800 /// recent visible declaration of that namespace.
13801 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13802
13803 SFINAETrap *CurrentSFINAEContext = nullptr;
13804
13805 /// The number of \p CodeSynthesisContexts that are not template
13806 /// instantiations and, therefore, should not be counted as part of the
13807 /// instantiation depth.
13808 ///
13809 /// When the instantiation depth reaches the user-configurable limit
13810 /// \p LangOptions::InstantiationDepth we will abort instantiation.
13811 // FIXME: Should we have a similar limit for other forms of synthesis?
13812 unsigned NonInstantiationEntries;
13813
13814 /// The depth of the context stack at the point when the most recent
13815 /// error or warning was produced.
13816 ///
13817 /// This value is used to suppress printing of redundant context stacks
13818 /// when there are multiple errors or warnings in the same instantiation.
13819 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13820 unsigned LastEmittedCodeSynthesisContextDepth = 0;
13821
13822 /// The current index into pack expansion arguments that will be
13823 /// used for substitution of parameter packs.
13824 ///
13825 /// The pack expansion index will be none to indicate that parameter packs
13826 /// should be instantiated as themselves. Otherwise, the index specifies
13827 /// which argument within the parameter pack will be used for substitution.
13828 UnsignedOrNone ArgPackSubstIndex;
13829
13830 /// RAII object used to change the argument pack substitution index
13831 /// within a \c Sema object.
13832 ///
13833 /// See \c ArgPackSubstIndex for more information.
13834 class ArgPackSubstIndexRAII {
13835 Sema &Self;
13836 UnsignedOrNone OldSubstIndex;
13837
13838 public:
13839 ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
13840 : Self(Self),
13841 OldSubstIndex(std::exchange(obj&: Self.ArgPackSubstIndex, new_val&: NewSubstIndex)) {}
13842
13843 ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13844 ArgPackSubstIndexRAII(const ArgPackSubstIndexRAII &) = delete;
13845 ArgPackSubstIndexRAII &operator=(const ArgPackSubstIndexRAII &) = delete;
13846 };
13847
13848 bool pushCodeSynthesisContext(CodeSynthesisContext Ctx);
13849 void popCodeSynthesisContext();
13850
13851 void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc) {
13852 if (!CodeSynthesisContexts.empty() &&
13853 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
13854 PrintInstantiationStack(DiagFunc);
13855 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
13856 }
13857 if (PragmaAttributeCurrentTargetDecl)
13858 PrintPragmaAttributeInstantiationPoint(DiagFunc);
13859 }
13860 void PrintContextStack() { PrintContextStack(DiagFunc: getDefaultDiagFunc()); }
13861 /// Prints the current instantiation stack through a series of
13862 /// notes.
13863 void PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc);
13864 void PrintInstantiationStack() {
13865 PrintInstantiationStack(DiagFunc: getDefaultDiagFunc());
13866 }
13867
13868 /// Returns a pointer to the current SFINAE context, if any.
13869 [[nodiscard]] SFINAETrap *getSFINAEContext() const {
13870 return CurrentSFINAEContext;
13871 }
13872 [[nodiscard]] bool isSFINAEContext() const {
13873 return CurrentSFINAEContext != nullptr;
13874 }
13875
13876 /// Perform substitution on the type T with a given set of template
13877 /// arguments.
13878 ///
13879 /// This routine substitutes the given template arguments into the
13880 /// type T and produces the instantiated type.
13881 ///
13882 /// \param T the type into which the template arguments will be
13883 /// substituted. If this type is not dependent, it will be returned
13884 /// immediately.
13885 ///
13886 /// \param Args the template arguments that will be
13887 /// substituted for the top-level template parameters within T.
13888 ///
13889 /// \param Loc the location in the source code where this substitution
13890 /// is being performed. It will typically be the location of the
13891 /// declarator (if we're instantiating the type of some declaration)
13892 /// or the location of the type in the source code (if, e.g., we're
13893 /// instantiating the type of a cast expression).
13894 ///
13895 /// \param Entity the name of the entity associated with a declaration
13896 /// being instantiated (if any). May be empty to indicate that there
13897 /// is no such entity (if, e.g., this is a type that occurs as part of
13898 /// a cast expression) or that the entity has no name (e.g., an
13899 /// unnamed function parameter).
13900 ///
13901 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
13902 /// acceptable as the top level type of the result.
13903 ///
13904 /// \param IsIncompleteSubstitution If provided, the pointee will be set
13905 /// whenever substitution would perform a replacement with a null or
13906 /// non-existent template argument.
13907 ///
13908 /// \returns If the instantiation succeeds, the instantiated
13909 /// type. Otherwise, produces diagnostics and returns a NULL type.
13910 TypeSourceInfo *SubstType(TypeSourceInfo *T,
13911 const MultiLevelTemplateArgumentList &TemplateArgs,
13912 SourceLocation Loc, DeclarationName Entity,
13913 bool AllowDeducedTST = false);
13914
13915 QualType SubstType(QualType T,
13916 const MultiLevelTemplateArgumentList &TemplateArgs,
13917 SourceLocation Loc, DeclarationName Entity,
13918 bool *IsIncompleteSubstitution = nullptr);
13919
13920 TypeSourceInfo *SubstType(TypeLoc TL,
13921 const MultiLevelTemplateArgumentList &TemplateArgs,
13922 SourceLocation Loc, DeclarationName Entity);
13923
13924 TypeSourceInfo *
13925 SubstFriendType(TypeSourceInfo *TSI,
13926 const MultiLevelTemplateArgumentList &TemplateArgs,
13927 SourceLocation Loc, DeclarationName Entity);
13928
13929 /// A form of SubstType intended specifically for instantiating the
13930 /// type of a FunctionDecl. Its purpose is solely to force the
13931 /// instantiation of default-argument expressions and to avoid
13932 /// instantiating an exception-specification.
13933 TypeSourceInfo *SubstFunctionDeclType(
13934 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
13935 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
13936 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
13937 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
13938 const MultiLevelTemplateArgumentList &Args);
13939 bool SubstExceptionSpec(SourceLocation Loc,
13940 FunctionProtoType::ExceptionSpecInfo &ESI,
13941 SmallVectorImpl<QualType> &ExceptionStorage,
13942 const MultiLevelTemplateArgumentList &Args);
13943 ParmVarDecl *
13944 SubstParmVarDecl(ParmVarDecl *D,
13945 const MultiLevelTemplateArgumentList &TemplateArgs,
13946 int indexAdjustment, UnsignedOrNone NumExpansions,
13947 bool ExpectParameterPack, bool EvaluateConstraints = true);
13948
13949 /// Substitute the given template arguments into the given set of
13950 /// parameters, producing the set of parameter types that would be generated
13951 /// from such a substitution.
13952 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
13953 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
13954 const MultiLevelTemplateArgumentList &TemplateArgs,
13955 SmallVectorImpl<QualType> &ParamTypes,
13956 SmallVectorImpl<ParmVarDecl *> *OutParams,
13957 ExtParameterInfoBuilder &ParamInfos);
13958
13959 /// Substitute the given template arguments into the default argument.
13960 bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param,
13961 const MultiLevelTemplateArgumentList &TemplateArgs,
13962 bool ForCallExpr = false);
13963 ExprResult SubstExpr(Expr *E,
13964 const MultiLevelTemplateArgumentList &TemplateArgs);
13965 /// Substitute an expression as if it is a address-of-operand, which makes it
13966 /// act like a CXXIdExpression rather than an attempt to call.
13967 ExprResult SubstCXXIdExpr(Expr *E,
13968 const MultiLevelTemplateArgumentList &TemplateArgs);
13969
13970 // Must be used instead of SubstExpr at 'constraint checking' time.
13971 ExprResult
13972 SubstConstraintExpr(Expr *E,
13973 const MultiLevelTemplateArgumentList &TemplateArgs);
13974 // Unlike the above, this does not evaluate constraints.
13975 ExprResult SubstConstraintExprWithoutSatisfaction(
13976 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
13977
13978 /// Substitute the given template arguments into a list of
13979 /// expressions, expanding pack expansions if required.
13980 ///
13981 /// \param Exprs The list of expressions to substitute into.
13982 ///
13983 /// \param IsCall Whether this is some form of call, in which case
13984 /// default arguments will be dropped.
13985 ///
13986 /// \param TemplateArgs The set of template arguments to substitute.
13987 ///
13988 /// \param Outputs Will receive all of the substituted arguments.
13989 ///
13990 /// \returns true if an error occurred, false otherwise.
13991 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
13992 const MultiLevelTemplateArgumentList &TemplateArgs,
13993 SmallVectorImpl<Expr *> &Outputs);
13994
13995 StmtResult SubstStmt(Stmt *S,
13996 const MultiLevelTemplateArgumentList &TemplateArgs);
13997
13998 ExprResult
13999 SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs,
14000 bool CXXDirectInit);
14001
14002 /// Perform substitution on the base class specifiers of the
14003 /// given class template specialization.
14004 ///
14005 /// Produces a diagnostic and returns true on error, returns false and
14006 /// attaches the instantiated base classes to the class template
14007 /// specialization if successful.
14008 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
14009 const MultiLevelTemplateArgumentList &TemplateArgs);
14010
14011 /// Instantiate the definition of a class from a given pattern.
14012 ///
14013 /// \param PointOfInstantiation The point of instantiation within the
14014 /// source code.
14015 ///
14016 /// \param Instantiation is the declaration whose definition is being
14017 /// instantiated. This will be either a class template specialization
14018 /// or a member class of a class template specialization.
14019 ///
14020 /// \param Pattern is the pattern from which the instantiation
14021 /// occurs. This will be either the declaration of a class template or
14022 /// the declaration of a member class of a class template.
14023 ///
14024 /// \param TemplateArgs The template arguments to be substituted into
14025 /// the pattern.
14026 ///
14027 /// \param TSK the kind of implicit or explicit instantiation to perform.
14028 ///
14029 /// \param Complain whether to complain if the class cannot be instantiated
14030 /// due to the lack of a definition.
14031 ///
14032 /// \returns true if an error occurred, false otherwise.
14033 bool InstantiateClass(SourceLocation PointOfInstantiation,
14034 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
14035 const MultiLevelTemplateArgumentList &TemplateArgs,
14036 TemplateSpecializationKind TSK, bool Complain = true);
14037
14038private:
14039 bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
14040 CXXRecordDecl *Instantiation,
14041 CXXRecordDecl *Pattern,
14042 const MultiLevelTemplateArgumentList &TemplateArgs,
14043 TemplateSpecializationKind TSK, bool Complain);
14044
14045public:
14046 /// Instantiate the definition of an enum from a given pattern.
14047 ///
14048 /// \param PointOfInstantiation The point of instantiation within the
14049 /// source code.
14050 /// \param Instantiation is the declaration whose definition is being
14051 /// instantiated. This will be a member enumeration of a class
14052 /// temploid specialization, or a local enumeration within a
14053 /// function temploid specialization.
14054 /// \param Pattern The templated declaration from which the instantiation
14055 /// occurs.
14056 /// \param TemplateArgs The template arguments to be substituted into
14057 /// the pattern.
14058 /// \param TSK The kind of implicit or explicit instantiation to perform.
14059 ///
14060 /// \return \c true if an error occurred, \c false otherwise.
14061 bool InstantiateEnum(SourceLocation PointOfInstantiation,
14062 EnumDecl *Instantiation, EnumDecl *Pattern,
14063 const MultiLevelTemplateArgumentList &TemplateArgs,
14064 TemplateSpecializationKind TSK);
14065
14066 /// Instantiate the definition of a field from the given pattern.
14067 ///
14068 /// \param PointOfInstantiation The point of instantiation within the
14069 /// source code.
14070 /// \param Instantiation is the declaration whose definition is being
14071 /// instantiated. This will be a class of a class temploid
14072 /// specialization, or a local enumeration within a function temploid
14073 /// specialization.
14074 /// \param Pattern The templated declaration from which the instantiation
14075 /// occurs.
14076 /// \param TemplateArgs The template arguments to be substituted into
14077 /// the pattern.
14078 ///
14079 /// \return \c true if an error occurred, \c false otherwise.
14080 bool InstantiateInClassInitializer(
14081 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
14082 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
14083
14084 bool usesPartialOrExplicitSpecialization(
14085 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
14086
14087 bool InstantiateClassTemplateSpecialization(
14088 SourceLocation PointOfInstantiation,
14089 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14090 TemplateSpecializationKind TSK, bool Complain,
14091 bool PrimaryStrictPackMatch);
14092
14093 /// Instantiates the definitions of all of the member
14094 /// of the given class, which is an instantiation of a class template
14095 /// or a member class of a template.
14096 void
14097 InstantiateClassMembers(SourceLocation PointOfInstantiation,
14098 CXXRecordDecl *Instantiation,
14099 const MultiLevelTemplateArgumentList &TemplateArgs,
14100 TemplateSpecializationKind TSK);
14101
14102 /// Instantiate the definitions of all of the members of the
14103 /// given class template specialization, which was named as part of an
14104 /// explicit instantiation.
14105 void InstantiateClassTemplateSpecializationMembers(
14106 SourceLocation PointOfInstantiation,
14107 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14108 TemplateSpecializationKind TSK);
14109
14110 NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(
14111 NestedNameSpecifierLoc NNS,
14112 const MultiLevelTemplateArgumentList &TemplateArgs);
14113
14114 /// Do template substitution on declaration name info.
14115 DeclarationNameInfo
14116 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
14117 const MultiLevelTemplateArgumentList &TemplateArgs);
14118 TemplateName
14119 SubstTemplateName(SourceLocation TemplateKWLoc,
14120 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
14121 SourceLocation NameLoc,
14122 const MultiLevelTemplateArgumentList &TemplateArgs);
14123
14124 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
14125 const MultiLevelTemplateArgumentList &TemplateArgs,
14126 bool EvaluateConstraint);
14127
14128 /// Determine whether we are currently performing template instantiation.
14129 bool inTemplateInstantiation() const {
14130 return CodeSynthesisContexts.size() > NonInstantiationEntries;
14131 }
14132
14133 /// Determine whether we are currently performing constraint substitution.
14134 bool inConstraintSubstitution() const {
14135 return !CodeSynthesisContexts.empty() &&
14136 CodeSynthesisContexts.back().InConstraintSubstitution;
14137 }
14138
14139 bool inParameterMappingSubstitution() const {
14140 return !CodeSynthesisContexts.empty() &&
14141 CodeSynthesisContexts.back().InParameterMappingSubstitution &&
14142 !inConstraintSubstitution();
14143 }
14144
14145 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
14146
14147 /// \brief create a Requirement::SubstitutionDiagnostic with only a
14148 /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
14149 concepts::Requirement::SubstitutionDiagnostic *
14150 createSubstDiagAt(SourceLocation Location, EntityPrinter Printer);
14151
14152 ///@}
14153
14154 //
14155 //
14156 // -------------------------------------------------------------------------
14157 //
14158 //
14159
14160 /// \name C++ Template Declaration Instantiation
14161 /// Implementations are in SemaTemplateInstantiateDecl.cpp
14162 ///@{
14163
14164public:
14165 /// An entity for which implicit template instantiation is required.
14166 ///
14167 /// The source location associated with the declaration is the first place in
14168 /// the source code where the declaration was "used". It is not necessarily
14169 /// the point of instantiation (which will be either before or after the
14170 /// namespace-scope declaration that triggered this implicit instantiation),
14171 /// However, it is the location that diagnostics should generally refer to,
14172 /// because users will need to know what code triggered the instantiation.
14173 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
14174
14175 /// The queue of implicit template instantiations that are required
14176 /// but have not yet been performed.
14177 std::deque<PendingImplicitInstantiation> PendingInstantiations;
14178
14179 /// Queue of implicit template instantiations that cannot be performed
14180 /// eagerly.
14181 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
14182
14183 SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses;
14184 SmallVector<std::deque<PendingImplicitInstantiation>, 8>
14185 SavedPendingInstantiations;
14186
14187 /// The queue of implicit template instantiations that are required
14188 /// and must be performed within the current local scope.
14189 ///
14190 /// This queue is only used for member functions of local classes in
14191 /// templates, which must be instantiated in the same scope as their
14192 /// enclosing function, so that they can reference function-local
14193 /// types, static variables, enumerators, etc.
14194 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
14195
14196 class LocalEagerInstantiationScope {
14197 public:
14198 LocalEagerInstantiationScope(Sema &S, bool AtEndOfTU)
14199 : S(S), AtEndOfTU(AtEndOfTU) {
14200 SavedPendingLocalImplicitInstantiations.swap(
14201 x&: S.PendingLocalImplicitInstantiations);
14202 }
14203
14204 void perform() {
14205 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: true,
14206 /*AtEndOfTU=*/AtEndOfTU);
14207 }
14208
14209 ~LocalEagerInstantiationScope() {
14210 assert(S.PendingLocalImplicitInstantiations.empty() &&
14211 "there shouldn't be any pending local implicit instantiations");
14212 SavedPendingLocalImplicitInstantiations.swap(
14213 x&: S.PendingLocalImplicitInstantiations);
14214 }
14215
14216 LocalEagerInstantiationScope(const LocalEagerInstantiationScope &) = delete;
14217 LocalEagerInstantiationScope &
14218 operator=(const LocalEagerInstantiationScope &) = delete;
14219
14220 private:
14221 Sema &S;
14222 bool AtEndOfTU;
14223 std::deque<PendingImplicitInstantiation>
14224 SavedPendingLocalImplicitInstantiations;
14225 };
14226
14227 /// Records and restores the CurFPFeatures state on entry/exit of compound
14228 /// statements.
14229 class FPFeaturesStateRAII {
14230 public:
14231 FPFeaturesStateRAII(Sema &S);
14232 ~FPFeaturesStateRAII();
14233 FPFeaturesStateRAII(const FPFeaturesStateRAII &) = delete;
14234 FPFeaturesStateRAII &operator=(const FPFeaturesStateRAII &) = delete;
14235 FPOptionsOverride getOverrides() { return OldOverrides; }
14236
14237 private:
14238 Sema &S;
14239 FPOptions OldFPFeaturesState;
14240 FPOptionsOverride OldOverrides;
14241 LangOptions::FPEvalMethodKind OldEvalMethod;
14242 SourceLocation OldFPPragmaLocation;
14243 };
14244
14245 class GlobalEagerInstantiationScope {
14246 public:
14247 GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
14248 : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
14249 if (!Enabled)
14250 return;
14251
14252 S.SavedPendingInstantiations.emplace_back();
14253 S.SavedPendingInstantiations.back().swap(x&: S.PendingInstantiations);
14254
14255 S.SavedVTableUses.emplace_back();
14256 S.SavedVTableUses.back().swap(RHS&: S.VTableUses);
14257 }
14258
14259 void perform() {
14260 if (Enabled) {
14261 S.DefineUsedVTables();
14262 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: false,
14263 /*AtEndOfTU=*/AtEndOfTU);
14264 }
14265 }
14266
14267 ~GlobalEagerInstantiationScope() {
14268 if (!Enabled)
14269 return;
14270
14271 // Restore the set of pending vtables.
14272 assert(S.VTableUses.empty() &&
14273 "VTableUses should be empty before it is discarded.");
14274 S.VTableUses.swap(RHS&: S.SavedVTableUses.back());
14275 S.SavedVTableUses.pop_back();
14276
14277 // Restore the set of pending implicit instantiations.
14278 if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
14279 AtEndOfTU) {
14280 assert(S.PendingInstantiations.empty() &&
14281 "PendingInstantiations should be empty before it is discarded.");
14282 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14283 S.SavedPendingInstantiations.pop_back();
14284 } else {
14285 // Template instantiations in the PCH may be delayed until the TU.
14286 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14287 S.PendingInstantiations.insert(
14288 position: S.PendingInstantiations.end(),
14289 first: S.SavedPendingInstantiations.back().begin(),
14290 last: S.SavedPendingInstantiations.back().end());
14291 S.SavedPendingInstantiations.pop_back();
14292 }
14293 }
14294
14295 GlobalEagerInstantiationScope(const GlobalEagerInstantiationScope &) =
14296 delete;
14297 GlobalEagerInstantiationScope &
14298 operator=(const GlobalEagerInstantiationScope &) = delete;
14299
14300 private:
14301 Sema &S;
14302 bool Enabled;
14303 bool AtEndOfTU;
14304 };
14305
14306 ExplicitSpecifier instantiateExplicitSpecifier(
14307 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
14308
14309 struct LateInstantiatedAttribute {
14310 const Attr *TmplAttr;
14311 LocalInstantiationScope *Scope;
14312 Decl *NewDecl;
14313
14314 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
14315 Decl *D)
14316 : TmplAttr(A), Scope(S), NewDecl(D) {}
14317 };
14318 typedef SmallVector<LateInstantiatedAttribute, 1> LateInstantiatedAttrVec;
14319
14320 /// Recheck instantiated thread-safety attributes that could not be validated
14321 /// on the dependent pattern declaration.
14322 bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A);
14323
14324 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14325 const Decl *Pattern, Decl *Inst,
14326 LateInstantiatedAttrVec *LateAttrs = nullptr,
14327 LocalInstantiationScope *OuterMostScope = nullptr);
14328
14329 /// Update instantiation attributes after template was late parsed.
14330 ///
14331 /// Some attributes are evaluated based on the body of template. If it is
14332 /// late parsed, such attributes cannot be evaluated when declaration is
14333 /// instantiated. This function is used to update instantiation attributes
14334 /// when template definition is ready.
14335 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
14336
14337 void
14338 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
14339 const Decl *Pattern, Decl *Inst,
14340 LateInstantiatedAttrVec *LateAttrs = nullptr,
14341 LocalInstantiationScope *OuterMostScope = nullptr);
14342
14343 bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor,
14344 bool IsCopy = false);
14345
14346 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
14347 ParmVarDecl *Param);
14348 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
14349 FunctionDecl *Function);
14350
14351 /// Instantiate (or find existing instantiation of) a function template with a
14352 /// given set of template arguments.
14353 ///
14354 /// Usually this should not be used, and template argument deduction should be
14355 /// used in its place.
14356 FunctionDecl *InstantiateFunctionDeclaration(
14357 FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
14358 SourceLocation Loc,
14359 CodeSynthesisContext::SynthesisKind CSC =
14360 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution);
14361
14362 /// Instantiate the definition of the given function 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 function, but it's close.
14368 ///
14369 /// \param Function the already-instantiated declaration of a
14370 /// function template specialization or member function of a class template
14371 /// specialization.
14372 ///
14373 /// \param Recursive if true, recursively instantiates any functions that
14374 /// are required by this instantiation.
14375 ///
14376 /// \param DefinitionRequired if true, then we are performing an explicit
14377 /// instantiation where the body of the function is required. Complain if
14378 /// there is no such body.
14379 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
14380 FunctionDecl *Function,
14381 bool Recursive = false,
14382 bool DefinitionRequired = false,
14383 bool AtEndOfTU = false);
14384 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
14385 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
14386 const TemplateArgumentList *PartialSpecArgs,
14387 SmallVectorImpl<TemplateArgument> &Converted,
14388 SourceLocation PointOfInstantiation,
14389 LateInstantiatedAttrVec *LateAttrs = nullptr,
14390 LocalInstantiationScope *StartingScope = nullptr);
14391
14392 /// Instantiates a variable template specialization by completing it
14393 /// with appropriate type information and initializer.
14394 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
14395 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14396 const MultiLevelTemplateArgumentList &TemplateArgs);
14397
14398 /// BuildVariableInstantiation - Used after a new variable has been created.
14399 /// Sets basic variable data and decides whether to postpone the
14400 /// variable instantiation.
14401 void
14402 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
14403 const MultiLevelTemplateArgumentList &TemplateArgs,
14404 LateInstantiatedAttrVec *LateAttrs,
14405 DeclContext *Owner,
14406 LocalInstantiationScope *StartingScope,
14407 bool InstantiatingVarTemplate = false,
14408 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14409
14410 /// Instantiate the initializer of a variable.
14411 void InstantiateVariableInitializer(
14412 VarDecl *Var, VarDecl *OldVar,
14413 const MultiLevelTemplateArgumentList &TemplateArgs);
14414
14415 /// Instantiate the definition of the given variable from its
14416 /// template.
14417 ///
14418 /// \param PointOfInstantiation the point at which the instantiation was
14419 /// required. Note that this is not precisely a "point of instantiation"
14420 /// for the variable, but it's close.
14421 ///
14422 /// \param Var the already-instantiated declaration of a templated variable.
14423 ///
14424 /// \param Recursive if true, recursively instantiates any functions that
14425 /// are required by this instantiation.
14426 ///
14427 /// \param DefinitionRequired if true, then we are performing an explicit
14428 /// instantiation where a definition of the variable is required. Complain
14429 /// if there is no such definition.
14430 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14431 VarDecl *Var, bool Recursive = false,
14432 bool DefinitionRequired = false,
14433 bool AtEndOfTU = false);
14434
14435 void InstantiateMemInitializers(
14436 CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl,
14437 const MultiLevelTemplateArgumentList &TemplateArgs);
14438
14439 /// Find the instantiation of the given declaration within the
14440 /// current instantiation.
14441 ///
14442 /// This routine is intended to be used when \p D is a declaration
14443 /// referenced from within a template, that needs to mapped into the
14444 /// corresponding declaration within an instantiation. For example,
14445 /// given:
14446 ///
14447 /// \code
14448 /// template<typename T>
14449 /// struct X {
14450 /// enum Kind {
14451 /// KnownValue = sizeof(T)
14452 /// };
14453 ///
14454 /// bool getKind() const { return KnownValue; }
14455 /// };
14456 ///
14457 /// template struct X<int>;
14458 /// \endcode
14459 ///
14460 /// In the instantiation of X<int>::getKind(), we need to map the \p
14461 /// EnumConstantDecl for \p KnownValue (which refers to
14462 /// X<T>::<Kind>::KnownValue) to its instantiation
14463 /// (X<int>::<Kind>::KnownValue).
14464 /// \p FindInstantiatedDecl performs this mapping from within the
14465 /// instantiation of X<int>.
14466 NamedDecl *
14467 FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
14468 const MultiLevelTemplateArgumentList &TemplateArgs,
14469 bool FindingInstantiatedContext = false);
14470
14471 /// Finds the instantiation of the given declaration context
14472 /// within the current instantiation.
14473 ///
14474 /// \returns NULL if there was an error
14475 DeclContext *
14476 FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
14477 const MultiLevelTemplateArgumentList &TemplateArgs);
14478
14479 Decl *SubstDecl(Decl *D, DeclContext *Owner,
14480 const MultiLevelTemplateArgumentList &TemplateArgs);
14481
14482 /// Substitute the name and return type of a defaulted 'operator<=>' to form
14483 /// an implicit 'operator=='.
14484 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
14485 FunctionDecl *Spaceship);
14486
14487 /// Performs template instantiation for all implicit template
14488 /// instantiations we have seen until this point.
14489 void PerformPendingInstantiations(bool LocalOnly = false,
14490 bool AtEndOfTU = true);
14491
14492 TemplateParameterList *
14493 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
14494 const MultiLevelTemplateArgumentList &TemplateArgs,
14495 bool EvaluateConstraints = true);
14496
14497 void PerformDependentDiagnostics(
14498 const DeclContext *Pattern,
14499 const MultiLevelTemplateArgumentList &TemplateArgs);
14500
14501private:
14502 /// Introduce the instantiated local variables into the local
14503 /// instantiation scope.
14504 void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14505 const FunctionDecl *PatternDecl,
14506 LocalInstantiationScope &Scope);
14507 /// Introduce the instantiated function parameters into the local
14508 /// instantiation scope, and set the parameter names to those used
14509 /// in the template.
14510 bool addInstantiatedParametersToScope(
14511 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14512 LocalInstantiationScope &Scope,
14513 const MultiLevelTemplateArgumentList &TemplateArgs);
14514
14515 /// Introduce the instantiated captures of the lambda into the local
14516 /// instantiation scope.
14517 bool addInstantiatedCapturesToScope(
14518 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14519 LocalInstantiationScope &Scope,
14520 const MultiLevelTemplateArgumentList &TemplateArgs);
14521
14522 int ParsingClassDepth = 0;
14523
14524 class SavePendingParsedClassStateRAII {
14525 public:
14526 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14527
14528 ~SavePendingParsedClassStateRAII() {
14529 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14530 "there shouldn't be any pending delayed exception spec checks");
14531 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14532 "there shouldn't be any pending delayed exception spec checks");
14533 swapSavedState();
14534 }
14535
14536 SavePendingParsedClassStateRAII(const SavePendingParsedClassStateRAII &) =
14537 delete;
14538 SavePendingParsedClassStateRAII &
14539 operator=(const SavePendingParsedClassStateRAII &) = delete;
14540
14541 private:
14542 Sema &S;
14543 decltype(DelayedOverridingExceptionSpecChecks)
14544 SavedOverridingExceptionSpecChecks;
14545 decltype(DelayedEquivalentExceptionSpecChecks)
14546 SavedEquivalentExceptionSpecChecks;
14547
14548 void swapSavedState() {
14549 SavedOverridingExceptionSpecChecks.swap(
14550 RHS&: S.DelayedOverridingExceptionSpecChecks);
14551 SavedEquivalentExceptionSpecChecks.swap(
14552 RHS&: S.DelayedEquivalentExceptionSpecChecks);
14553 }
14554 };
14555
14556 ///@}
14557
14558 //
14559 //
14560 // -------------------------------------------------------------------------
14561 //
14562 //
14563
14564 /// \name C++ Variadic Templates
14565 /// Implementations are in SemaTemplateVariadic.cpp
14566 ///@{
14567
14568public:
14569 /// Determine whether an unexpanded parameter pack might be permitted in this
14570 /// location. Useful for error recovery.
14571 bool isUnexpandedParameterPackPermitted();
14572
14573 /// The context in which an unexpanded parameter pack is
14574 /// being diagnosed.
14575 ///
14576 /// Note that the values of this enumeration line up with the first
14577 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14578 enum UnexpandedParameterPackContext {
14579 /// An arbitrary expression.
14580 UPPC_Expression = 0,
14581
14582 /// The base type of a class type.
14583 UPPC_BaseType,
14584
14585 /// The type of an arbitrary declaration.
14586 UPPC_DeclarationType,
14587
14588 /// The type of a data member.
14589 UPPC_DataMemberType,
14590
14591 /// The size of a bit-field.
14592 UPPC_BitFieldWidth,
14593
14594 /// The expression in a static assertion.
14595 UPPC_StaticAssertExpression,
14596
14597 /// The fixed underlying type of an enumeration.
14598 UPPC_FixedUnderlyingType,
14599
14600 /// The enumerator value.
14601 UPPC_EnumeratorValue,
14602
14603 /// A using declaration.
14604 UPPC_UsingDeclaration,
14605
14606 /// A friend declaration.
14607 UPPC_FriendDeclaration,
14608
14609 /// A declaration qualifier.
14610 UPPC_DeclarationQualifier,
14611
14612 /// An initializer.
14613 UPPC_Initializer,
14614
14615 /// A default argument.
14616 UPPC_DefaultArgument,
14617
14618 /// The type of a non-type template parameter.
14619 UPPC_NonTypeTemplateParameterType,
14620
14621 /// The type of an exception.
14622 UPPC_ExceptionType,
14623
14624 /// Explicit specialization.
14625 UPPC_ExplicitSpecialization,
14626
14627 /// Partial specialization.
14628 UPPC_PartialSpecialization,
14629
14630 /// Microsoft __if_exists.
14631 UPPC_IfExists,
14632
14633 /// Microsoft __if_not_exists.
14634 UPPC_IfNotExists,
14635
14636 /// Lambda expression.
14637 UPPC_Lambda,
14638
14639 /// Block expression.
14640 UPPC_Block,
14641
14642 /// A type constraint.
14643 UPPC_TypeConstraint,
14644
14645 // A requirement in a requires-expression.
14646 UPPC_Requirement,
14647
14648 // A requires-clause.
14649 UPPC_RequiresClause,
14650 };
14651
14652 /// Diagnose unexpanded parameter packs.
14653 ///
14654 /// \param Loc The location at which we should emit the diagnostic.
14655 ///
14656 /// \param UPPC The context in which we are diagnosing unexpanded
14657 /// parameter packs.
14658 ///
14659 /// \param Unexpanded the set of unexpanded parameter packs.
14660 ///
14661 /// \returns true if an error occurred, false otherwise.
14662 bool DiagnoseUnexpandedParameterPacks(
14663 SourceLocation Loc, UnexpandedParameterPackContext UPPC,
14664 ArrayRef<UnexpandedParameterPack> Unexpanded);
14665
14666 /// If the given type contains an unexpanded parameter pack,
14667 /// diagnose the error.
14668 ///
14669 /// \param Loc The source location where a diagnostc should be emitted.
14670 ///
14671 /// \param T The type that is being checked for unexpanded parameter
14672 /// packs.
14673 ///
14674 /// \returns true if an error occurred, false otherwise.
14675 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
14676 UnexpandedParameterPackContext UPPC);
14677
14678 /// If the given expression contains an unexpanded parameter
14679 /// pack, diagnose the error.
14680 ///
14681 /// \param E The expression that is being checked for unexpanded
14682 /// parameter packs.
14683 ///
14684 /// \returns true if an error occurred, false otherwise.
14685 bool DiagnoseUnexpandedParameterPack(
14686 Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression);
14687
14688 /// If the given requirees-expression contains an unexpanded reference to one
14689 /// of its own parameter packs, diagnose the error.
14690 ///
14691 /// \param RE The requiress-expression that is being checked for unexpanded
14692 /// parameter packs.
14693 ///
14694 /// \returns true if an error occurred, false otherwise.
14695 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
14696
14697 /// If the given nested-name-specifier contains an unexpanded
14698 /// parameter pack, diagnose the error.
14699 ///
14700 /// \param SS The nested-name-specifier that is being checked for
14701 /// unexpanded parameter packs.
14702 ///
14703 /// \returns true if an error occurred, false otherwise.
14704 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
14705 UnexpandedParameterPackContext UPPC);
14706
14707 /// If the given name contains an unexpanded parameter pack,
14708 /// diagnose the error.
14709 ///
14710 /// \param NameInfo The name (with source location information) that
14711 /// is being checked for unexpanded parameter packs.
14712 ///
14713 /// \returns true if an error occurred, false otherwise.
14714 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
14715 UnexpandedParameterPackContext UPPC);
14716
14717 /// If the given template name contains an unexpanded parameter pack,
14718 /// diagnose the error.
14719 ///
14720 /// \param Loc The location of the template name.
14721 ///
14722 /// \param Template The template name that is being checked for unexpanded
14723 /// parameter packs.
14724 ///
14725 /// \returns true if an error occurred, false otherwise.
14726 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
14727 TemplateName Template,
14728 UnexpandedParameterPackContext UPPC);
14729
14730 /// If the given template argument contains an unexpanded parameter
14731 /// pack, diagnose the error.
14732 ///
14733 /// \param Arg The template argument that is being checked for unexpanded
14734 /// parameter packs.
14735 ///
14736 /// \returns true if an error occurred, false otherwise.
14737 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
14738 UnexpandedParameterPackContext UPPC);
14739
14740 /// Collect the set of unexpanded parameter packs within the given
14741 /// template argument.
14742 ///
14743 /// \param Arg The template argument that will be traversed to find
14744 /// unexpanded parameter packs.
14745 void collectUnexpandedParameterPacks(
14746 TemplateArgument Arg,
14747 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14748
14749 /// Collect the set of unexpanded parameter packs within the given
14750 /// template argument.
14751 ///
14752 /// \param Arg The template argument that will be traversed to find
14753 /// unexpanded parameter packs.
14754 void collectUnexpandedParameterPacks(
14755 TemplateArgumentLoc Arg,
14756 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14757
14758 /// Collect the set of unexpanded parameter packs within the given
14759 /// type.
14760 ///
14761 /// \param T The type that will be traversed to find
14762 /// unexpanded parameter packs.
14763 void collectUnexpandedParameterPacks(
14764 QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14765
14766 /// Collect the set of unexpanded parameter packs within the given
14767 /// template name.
14768 ///
14769 /// \param Template The template name that will be traversed to find
14770 /// unexpanded parameter packs.
14771 void collectUnexpandedParameterPacks(
14772 TemplateName Template,
14773 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14774
14775 /// Collect the set of unexpanded parameter packs within the given
14776 /// type.
14777 ///
14778 /// \param TL The type that will be traversed to find
14779 /// unexpanded parameter packs.
14780 void collectUnexpandedParameterPacks(
14781 TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14782
14783 /// Collect the set of unexpanded parameter packs within the given
14784 /// nested-name-specifier.
14785 ///
14786 /// \param NNS The nested-name-specifier that will be traversed to find
14787 /// unexpanded parameter packs.
14788 void collectUnexpandedParameterPacks(
14789 NestedNameSpecifierLoc NNS,
14790 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14791
14792 /// Collect the set of unexpanded parameter packs within the given
14793 /// name.
14794 ///
14795 /// \param NameInfo The name that will be traversed to find
14796 /// unexpanded parameter packs.
14797 void collectUnexpandedParameterPacks(
14798 const DeclarationNameInfo &NameInfo,
14799 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14800
14801 /// Collect the set of unexpanded parameter packs within the given
14802 /// expression.
14803 static void collectUnexpandedParameterPacks(
14804 Expr *E, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14805
14806 /// Invoked when parsing a template argument.
14807 ///
14808 /// \param Arg the template argument, which may already be invalid.
14809 ///
14810 /// If it is followed by ellipsis, this function is called before
14811 /// `ActOnPackExpansion`.
14812 ParsedTemplateArgument
14813 ActOnTemplateTemplateArgument(const ParsedTemplateArgument &Arg);
14814
14815 /// Invoked when parsing a template argument followed by an
14816 /// ellipsis, which creates a pack expansion.
14817 ///
14818 /// \param Arg The template argument preceding the ellipsis, which
14819 /// may already be invalid.
14820 ///
14821 /// \param EllipsisLoc The location of the ellipsis.
14822 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
14823 SourceLocation EllipsisLoc);
14824
14825 /// Invoked when parsing a type followed by an ellipsis, which
14826 /// creates a pack expansion.
14827 ///
14828 /// \param Type The type preceding the ellipsis, which will become
14829 /// the pattern of the pack expansion.
14830 ///
14831 /// \param EllipsisLoc The location of the ellipsis.
14832 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
14833
14834 /// Construct a pack expansion type from the pattern of the pack
14835 /// expansion.
14836 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
14837 SourceLocation EllipsisLoc,
14838 UnsignedOrNone NumExpansions);
14839
14840 /// Construct a pack expansion type from the pattern of the pack
14841 /// expansion.
14842 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14843 SourceLocation EllipsisLoc,
14844 UnsignedOrNone NumExpansions);
14845
14846 /// Invoked when parsing an expression followed by an ellipsis, which
14847 /// creates a pack expansion.
14848 ///
14849 /// \param Pattern The expression preceding the ellipsis, which will become
14850 /// the pattern of the pack expansion.
14851 ///
14852 /// \param EllipsisLoc The location of the ellipsis.
14853 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14854
14855 /// Invoked when parsing an expression followed by an ellipsis, which
14856 /// creates a pack expansion.
14857 ///
14858 /// \param Pattern The expression preceding the ellipsis, which will become
14859 /// the pattern of the pack expansion.
14860 ///
14861 /// \param EllipsisLoc The location of the ellipsis.
14862 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14863 UnsignedOrNone NumExpansions);
14864
14865 /// Determine whether we could expand a pack expansion with the
14866 /// given set of parameter packs into separate arguments by repeatedly
14867 /// transforming the pattern.
14868 ///
14869 /// \param EllipsisLoc The location of the ellipsis that identifies the
14870 /// pack expansion.
14871 ///
14872 /// \param PatternRange The source range that covers the entire pattern of
14873 /// the pack expansion.
14874 ///
14875 /// \param Unexpanded The set of unexpanded parameter packs within the
14876 /// pattern.
14877 ///
14878 /// \param ShouldExpand Will be set to \c true if the transformer should
14879 /// expand the corresponding pack expansions into separate arguments. When
14880 /// set, \c NumExpansions must also be set.
14881 ///
14882 /// \param RetainExpansion Whether the caller should add an unexpanded
14883 /// pack expansion after all of the expanded arguments. This is used
14884 /// when extending explicitly-specified template argument packs per
14885 /// C++0x [temp.arg.explicit]p9.
14886 ///
14887 /// \param NumExpansions The number of separate arguments that will be in
14888 /// the expanded form of the corresponding pack expansion. This is both an
14889 /// input and an output parameter, which can be set by the caller if the
14890 /// number of expansions is known a priori (e.g., due to a prior substitution)
14891 /// and will be set by the callee when the number of expansions is known.
14892 /// The callee must set this value when \c ShouldExpand is \c true; it may
14893 /// set this value in other cases.
14894 ///
14895 /// \returns true if an error occurred (e.g., because the parameter packs
14896 /// are to be instantiated with arguments of different lengths), false
14897 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
14898 /// must be set.
14899 bool CheckParameterPacksForExpansion(
14900 SourceLocation EllipsisLoc, SourceRange PatternRange,
14901 ArrayRef<UnexpandedParameterPack> Unexpanded,
14902 const MultiLevelTemplateArgumentList &TemplateArgs,
14903 bool FailOnPackProducingTemplates, bool &ShouldExpand,
14904 bool &RetainExpansion, UnsignedOrNone &NumExpansions,
14905 bool Diagnose = true);
14906
14907 /// Determine the number of arguments in the given pack expansion
14908 /// type.
14909 ///
14910 /// This routine assumes that the number of arguments in the expansion is
14911 /// consistent across all of the unexpanded parameter packs in its pattern.
14912 ///
14913 /// Returns an empty Optional if the type can't be expanded.
14914 UnsignedOrNone getNumArgumentsInExpansion(
14915 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
14916
14917 UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(
14918 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
14919 const MultiLevelTemplateArgumentList &TemplateArgs);
14920
14921 /// Determine whether the given declarator contains any unexpanded
14922 /// parameter packs.
14923 ///
14924 /// This routine is used by the parser to disambiguate function declarators
14925 /// with an ellipsis prior to the ')', e.g.,
14926 ///
14927 /// \code
14928 /// void f(T...);
14929 /// \endcode
14930 ///
14931 /// To determine whether we have an (unnamed) function parameter pack or
14932 /// a variadic function.
14933 ///
14934 /// \returns true if the declarator contains any unexpanded parameter packs,
14935 /// false otherwise.
14936 bool containsUnexpandedParameterPacks(Declarator &D);
14937
14938 /// Returns the pattern of the pack expansion for a template argument.
14939 ///
14940 /// \param OrigLoc The template argument to expand.
14941 ///
14942 /// \param Ellipsis Will be set to the location of the ellipsis.
14943 ///
14944 /// \param NumExpansions Will be set to the number of expansions that will
14945 /// be generated from this pack expansion, if known a priori.
14946 TemplateArgumentLoc
14947 getTemplateArgumentPackExpansionPattern(TemplateArgumentLoc OrigLoc,
14948 SourceLocation &Ellipsis,
14949 UnsignedOrNone &NumExpansions) const;
14950
14951 /// Given a template argument that contains an unexpanded parameter pack, but
14952 /// which has already been substituted, attempt to determine the number of
14953 /// elements that will be produced once this argument is fully-expanded.
14954 ///
14955 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
14956 /// avoid actually expanding the pack where possible.
14957 UnsignedOrNone getFullyPackExpandedSize(TemplateArgument Arg);
14958
14959 /// Called when an expression computing the size of a parameter pack
14960 /// is parsed.
14961 ///
14962 /// \code
14963 /// template<typename ...Types> struct count {
14964 /// static const unsigned value = sizeof...(Types);
14965 /// };
14966 /// \endcode
14967 ///
14968 //
14969 /// \param OpLoc The location of the "sizeof" keyword.
14970 /// \param Name The name of the parameter pack whose size will be determined.
14971 /// \param NameLoc The source location of the name of the parameter pack.
14972 /// \param RParenLoc The location of the closing parentheses.
14973 ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc,
14974 IdentifierInfo &Name,
14975 SourceLocation NameLoc,
14976 SourceLocation RParenLoc);
14977
14978 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
14979 SourceLocation EllipsisLoc,
14980 SourceLocation LSquareLoc, Expr *IndexExpr,
14981 SourceLocation RSquareLoc);
14982
14983 ExprResult BuildPackIndexingExpr(Expr *PackExpression,
14984 SourceLocation EllipsisLoc, Expr *IndexExpr,
14985 SourceLocation RSquareLoc,
14986 ArrayRef<Expr *> ExpandedExprs = {},
14987 bool FullySubstituted = false);
14988
14989 TemplateName ActOnPackIndexingTemplateName(TemplateName Pattern,
14990 SourceLocation NameLoc,
14991 Expr *IndexExpr);
14992
14993 TemplateName
14994 BuildPackIndexingTemplateName(TemplateName Pattern, Expr *IndexExpr,
14995 bool FullySubstituted = false,
14996 ArrayRef<TemplateName> Expansions = {});
14997
14998 TypeResult
14999 ActOnPackIndexingDeducedTemplateSpecializationType(TemplateName Name,
15000 SourceLocation NameLoc);
15001
15002 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
15003 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
15004 tok::TokenKind Operator,
15005 SourceLocation EllipsisLoc, Expr *RHS,
15006 SourceLocation RParenLoc);
15007 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
15008 SourceLocation LParenLoc, Expr *LHS,
15009 BinaryOperatorKind Operator,
15010 SourceLocation EllipsisLoc, Expr *RHS,
15011 SourceLocation RParenLoc,
15012 UnsignedOrNone NumExpansions);
15013 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
15014 BinaryOperatorKind Operator);
15015
15016 ///@}
15017
15018 //
15019 //
15020 // -------------------------------------------------------------------------
15021 //
15022 //
15023
15024 /// \name Constraints and Concepts
15025 /// Implementations are in SemaConcept.cpp
15026 ///@{
15027
15028public:
15029 ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI);
15030
15031 ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc,
15032 TypeSourceInfo *TSI);
15033
15034public:
15035 void PushSatisfactionStackEntry(const NamedDecl *D,
15036 const llvm::FoldingSetNodeID &ID) {
15037 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
15038 SatisfactionStack.emplace_back(Args&: Can, Args: ID);
15039 }
15040
15041 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
15042
15043 bool SatisfactionStackContains(const NamedDecl *D,
15044 const llvm::FoldingSetNodeID &ID) const {
15045 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
15046 return llvm::is_contained(Range: SatisfactionStack,
15047 Element: SatisfactionStackEntryTy{Can, ID});
15048 }
15049
15050 using SatisfactionStackEntryTy =
15051 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
15052
15053 // Resets the current SatisfactionStack for cases where we are instantiating
15054 // constraints as a 'side effect' of normal instantiation in a way that is not
15055 // indicative of recursive definition.
15056 class SatisfactionStackResetRAII {
15057 llvm::SmallVector<SatisfactionStackEntryTy, 10> BackupSatisfactionStack;
15058 Sema &SemaRef;
15059
15060 public:
15061 SatisfactionStackResetRAII(Sema &S) : SemaRef(S) {
15062 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
15063 }
15064
15065 ~SatisfactionStackResetRAII() {
15066 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
15067 }
15068
15069 SatisfactionStackResetRAII(const SatisfactionStackResetRAII &) = delete;
15070 SatisfactionStackResetRAII &
15071 operator=(const SatisfactionStackResetRAII &) = delete;
15072 };
15073
15074 void SwapSatisfactionStack(
15075 llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) {
15076 SatisfactionStack.swap(RHS&: NewSS);
15077 }
15078
15079 using ConstrainedDeclOrNestedRequirement =
15080 llvm::PointerUnion<const NamedDecl *,
15081 const concepts::NestedRequirement *>;
15082
15083 /// Check whether the given expression is a valid constraint expression.
15084 /// A diagnostic is emitted if it is not, false is returned, and
15085 /// PossibleNonPrimary will be set to true if the failure might be due to a
15086 /// non-primary expression being used as an atomic constraint.
15087 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
15088 bool *PossibleNonPrimary = nullptr,
15089 bool IsTrailingRequiresClause = false);
15090
15091 /// \brief Check whether the given list of constraint expressions are
15092 /// satisfied (as if in a 'conjunction') given template arguments.
15093 /// \param Template the template-like entity that triggered the constraints
15094 /// check (either a concept or a constrained entity).
15095 /// \param ConstraintExprs a list of constraint expressions, treated as if
15096 /// they were 'AND'ed together.
15097 /// \param TemplateArgLists the list of template arguments to substitute into
15098 /// the constraint expression.
15099 /// \param TemplateIDRange The source range of the template id that
15100 /// caused the constraints check.
15101 /// \param Satisfaction if true is returned, will contain details of the
15102 /// satisfaction, with enough information to diagnose an unsatisfied
15103 /// expression.
15104 /// \returns true if an error occurred and satisfaction could not be checked,
15105 /// false otherwise.
15106 bool CheckConstraintSatisfaction(
15107 ConstrainedDeclOrNestedRequirement Entity,
15108 ArrayRef<AssociatedConstraint> AssociatedConstraints,
15109 const MultiLevelTemplateArgumentList &TemplateArgLists,
15110 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
15111 const ConceptReference *TopLevelConceptId = nullptr,
15112 Expr **ConvertedExpr = nullptr);
15113
15114 /// Check whether the given function decl's trailing requires clause is
15115 /// satisfied, if any. Returns false and updates Satisfaction with the
15116 /// satisfaction verdict if successful, emits a diagnostic and returns true if
15117 /// an error occurred and satisfaction could not be determined.
15118 ///
15119 /// \returns true if an error occurred, false otherwise.
15120 bool CheckFunctionConstraints(const FunctionDecl *FD,
15121 ConstraintSatisfaction &Satisfaction,
15122 SourceLocation UsageLoc = SourceLocation(),
15123 bool ForOverloadResolution = false);
15124
15125 // Calculates whether two constraint expressions are equal irrespective of a
15126 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
15127 // 'New', which are the "source" of the constraint, since this is necessary
15128 // for figuring out the relative 'depth' of the constraint. The depth of the
15129 // 'primary template' and the 'instantiated from' templates aren't necessarily
15130 // the same, such as a case when one is a 'friend' defined in a class.
15131 bool AreConstraintExpressionsEqual(const NamedDecl *Old,
15132 const Expr *OldConstr,
15133 const TemplateCompareNewDeclInfo &New,
15134 const Expr *NewConstr);
15135
15136 // Calculates whether the friend function depends on an enclosing template for
15137 // the purposes of [temp.friend] p9.
15138 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
15139
15140 /// \brief Ensure that the given template arguments satisfy the constraints
15141 /// associated with the given template, emitting a diagnostic if they do not.
15142 ///
15143 /// \param Template The template to which the template arguments are being
15144 /// provided.
15145 ///
15146 /// \param TemplateArgs The converted, canonicalized template arguments.
15147 ///
15148 /// \param TemplateIDRange The source range of the template id that
15149 /// caused the constraints check.
15150 ///
15151 /// \returns true if the constrains are not satisfied or could not be checked
15152 /// for satisfaction, false if the constraints are satisfied.
15153 bool EnsureTemplateArgumentListConstraints(
15154 TemplateDecl *Template,
15155 const MultiLevelTemplateArgumentList &TemplateArgs,
15156 SourceRange TemplateIDRange);
15157
15158 bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
15159 FunctionDecl *Decl,
15160 ArrayRef<TemplateArgument> TemplateArgs,
15161 ConstraintSatisfaction &Satisfaction);
15162
15163 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15164 /// unsatisfied.
15165 /// \param First whether this is the first time an unsatisfied constraint is
15166 /// diagnosed for this error.
15167 void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
15168 SourceLocation Loc = {},
15169 bool First = true);
15170
15171 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15172 /// unsatisfied.
15173 void
15174 DiagnoseUnsatisfiedConstraint(const ConceptSpecializationExpr *ConstraintExpr,
15175 bool First = true);
15176
15177 void DiagnoseUnsatisfiedRequiresExpr(const RequiresExpr *RequiresExpr,
15178 bool First = true);
15179
15180 const NormalizedConstraint *getNormalizedAssociatedConstraints(
15181 ConstrainedDeclOrNestedRequirement Entity,
15182 ArrayRef<AssociatedConstraint> AssociatedConstraints);
15183
15184 /// \brief Check whether the given declaration's associated constraints are
15185 /// at least as constrained than another declaration's according to the
15186 /// partial ordering of constraints.
15187 ///
15188 /// \param Result If no error occurred, receives the result of true if D1 is
15189 /// at least constrained than D2, and false otherwise.
15190 ///
15191 /// \returns true if an error occurred, false otherwise.
15192 bool IsAtLeastAsConstrained(const NamedDecl *D1,
15193 MutableArrayRef<AssociatedConstraint> AC1,
15194 const NamedDecl *D2,
15195 MutableArrayRef<AssociatedConstraint> AC2,
15196 bool &Result);
15197
15198 /// If D1 was not at least as constrained as D2, but would've been if a pair
15199 /// of atomic constraints involved had been declared in a concept and not
15200 /// repeated in two separate places in code.
15201 /// \returns true if such a diagnostic was emitted, false otherwise.
15202 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(
15203 const NamedDecl *D1, ArrayRef<AssociatedConstraint> AC1,
15204 const NamedDecl *D2, ArrayRef<AssociatedConstraint> AC2);
15205
15206private:
15207 friend class ConstraintSatisfactionChecker;
15208 friend class SubstituteParameterMappings;
15209
15210 UnsignedOrNone EvaluateFoldExpandedConstraintSize(
15211 const Expr *Pattern, const MultiLevelTemplateArgumentList &MLTAL);
15212
15213 /// Cache the satisfaction of an atomic constraint.
15214 /// The key is based on the unsubstituted expression and the parameter
15215 /// mapping. This lets us not substituting the mapping more than once,
15216 /// which is (very!) expensive.
15217 llvm::DenseMap<llvm::FoldingSetNodeID,
15218 UnsubstitutedConstraintSatisfactionCacheResult>
15219 UnsubstitutedConstraintSatisfactionCache;
15220
15221 /// Cache the instantiation results of template parameter mappings within
15222 /// concepts. Substituting into normalized concepts can be extremely expensive
15223 /// due to the redundancy of template parameters. This cache is intended for
15224 /// use by TemplateInstantiator to avoid redundant semantic checking.
15225 llvm::DenseMap<llvm::FoldingSetNodeID, TemplateArgumentLoc>
15226 *CurrentCachedTemplateArgs = nullptr;
15227
15228 /// Caches pairs of template-like decls whose associated constraints were
15229 /// checked for subsumption and whether or not the first's constraints did in
15230 /// fact subsume the second's.
15231 llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
15232 SubsumptionCache;
15233 /// Caches the normal form of constraint expressions (and their pack
15234 /// substitution index). These are shared by e.g. the members of all
15235 /// specializations of a class template. If an error occurred while
15236 /// normalizing an expression, nullptr will be cached here.
15237 llvm::DenseMap<std::pair<const Expr *, unsigned>, NormalizedConstraint *>
15238 NormalizedConstraintExprCache;
15239
15240 /// Cache whether the associated constraint of a declaration
15241 /// is satisfied.
15242 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
15243 SatisfactionCache;
15244
15245 // The current stack of constraint satisfactions, so we can exit-early.
15246 llvm::SmallVector<SatisfactionStackEntryTy, 10> SatisfactionStack;
15247
15248 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
15249 /// LocalInstantiationScope of the current non-lambda function. For lambdas,
15250 /// use LambdaScopeForCallOperatorInstantiationRAII.
15251 bool
15252 SetupConstraintScope(FunctionDecl *FD,
15253 std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15254 const MultiLevelTemplateArgumentList &MLTAL,
15255 LocalInstantiationScope &Scope);
15256
15257 /// Used during constraint checking, sets up the constraint template argument
15258 /// lists, and calls SetupConstraintScope to set up the
15259 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
15260 std::optional<MultiLevelTemplateArgumentList>
15261 SetupConstraintCheckingTemplateArgumentsAndScope(
15262 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15263 LocalInstantiationScope &Scope);
15264
15265 ///@}
15266
15267 //
15268 //
15269 // -------------------------------------------------------------------------
15270 //
15271 //
15272
15273 /// \name Types
15274 /// Implementations are in SemaType.cpp
15275 ///@{
15276
15277public:
15278 /// A mapping that describes the nullability we've seen in each header file.
15279 FileNullabilityMap NullabilityMap;
15280
15281 static int getPrintable(int I) { return I; }
15282 static unsigned getPrintable(unsigned I) { return I; }
15283 static bool getPrintable(bool B) { return B; }
15284 static const char *getPrintable(const char *S) { return S; }
15285 static StringRef getPrintable(StringRef S) { return S; }
15286 static const std::string &getPrintable(const std::string &S) { return S; }
15287 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
15288 return II;
15289 }
15290 static DeclarationName getPrintable(DeclarationName N) { return N; }
15291 static QualType getPrintable(QualType T) { return T; }
15292 static SourceRange getPrintable(SourceRange R) { return R; }
15293 static SourceRange getPrintable(SourceLocation L) { return L; }
15294 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
15295 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange(); }
15296
15297 enum class CompleteTypeKind {
15298 /// Apply the normal rules for complete types. In particular,
15299 /// treat all sizeless types as incomplete.
15300 Normal,
15301
15302 /// Relax the normal rules for complete types so that they include
15303 /// sizeless built-in types.
15304 AcceptSizeless,
15305
15306 // FIXME: Eventually we should flip the default to Normal and opt in
15307 // to AcceptSizeless rather than opt out of it.
15308 Default = AcceptSizeless
15309 };
15310
15311 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
15312 const DeclSpec *DS = nullptr);
15313 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
15314 const DeclSpec *DS = nullptr);
15315
15316 /// Build a pointer type.
15317 ///
15318 /// \param T The type to which we'll be building a pointer.
15319 ///
15320 /// \param Loc The location of the entity whose type involves this
15321 /// pointer type or, if there is no such entity, the location of the
15322 /// type that will have pointer type.
15323 ///
15324 /// \param Entity The name of the entity that involves the pointer
15325 /// type, if known.
15326 ///
15327 /// \returns A suitable pointer type, if there are no
15328 /// errors. Otherwise, returns a NULL type.
15329 QualType BuildPointerType(QualType T, SourceLocation Loc,
15330 DeclarationName Entity);
15331
15332 /// Build a reference type.
15333 ///
15334 /// \param T The type to which we'll be building a reference.
15335 ///
15336 /// \param Loc The location of the entity whose type involves this
15337 /// reference type or, if there is no such entity, the location of the
15338 /// type that will have reference type.
15339 ///
15340 /// \param Entity The name of the entity that involves the reference
15341 /// type, if known.
15342 ///
15343 /// \returns A suitable reference type, if there are no
15344 /// errors. Otherwise, returns a NULL type.
15345 QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc,
15346 DeclarationName Entity);
15347
15348 /// Build an array type.
15349 ///
15350 /// \param T The type of each element in the array.
15351 ///
15352 /// \param ASM C99 array size modifier (e.g., '*', 'static').
15353 ///
15354 /// \param ArraySize Expression describing the size of the array.
15355 ///
15356 /// \param Brackets The range from the opening '[' to the closing ']'.
15357 ///
15358 /// \param Entity The name of the entity that involves the array
15359 /// type, if known.
15360 ///
15361 /// \returns A suitable array type, if there are no errors. Otherwise,
15362 /// returns a NULL type.
15363 QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize,
15364 unsigned Quals, SourceRange Brackets,
15365 DeclarationName Entity);
15366
15367 /// Diagnose an array of \p NumElements elements of type \p ElementType
15368 /// that is too large. Returns true if a diagnostic was emitted.
15369 bool checkArrayTooLarge(QualType ElementType, const llvm::APSInt &NumElements,
15370 SourceLocation Loc,
15371 SourceRange Range = SourceRange());
15372 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
15373
15374 /// Build an ext-vector type.
15375 ///
15376 /// Run the required checks for the extended vector type.
15377 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
15378 SourceLocation AttrLoc);
15379 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
15380 SourceLocation AttrLoc);
15381
15382 QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy,
15383 Expr *CountExpr,
15384 bool CountInBytes,
15385 bool OrNull);
15386
15387 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
15388 /// expression is uninstantiated. If instantiated it will apply the
15389 /// appropriate address space to the type. This function allows dependent
15390 /// template variables to be used in conjunction with the address_space
15391 /// attribute
15392 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
15393 SourceLocation AttrLoc);
15394
15395 /// Same as above, but constructs the AddressSpace index if not provided.
15396 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
15397 SourceLocation AttrLoc);
15398
15399 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
15400
15401 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
15402
15403 /// Build a function type.
15404 ///
15405 /// This routine checks the function type according to C++ rules and
15406 /// under the assumption that the result type and parameter types have
15407 /// just been instantiated from a template. It therefore duplicates
15408 /// some of the behavior of GetTypeForDeclarator, but in a much
15409 /// simpler form that is only suitable for this narrow use case.
15410 ///
15411 /// \param T The return type of the function.
15412 ///
15413 /// \param ParamTypes The parameter types of the function. This array
15414 /// will be modified to account for adjustments to the types of the
15415 /// function parameters.
15416 ///
15417 /// \param Loc The location of the entity whose type involves this
15418 /// function type or, if there is no such entity, the location of the
15419 /// type that will have function type.
15420 ///
15421 /// \param Entity The name of the entity that involves the function
15422 /// type, if known.
15423 ///
15424 /// \param EPI Extra information about the function type. Usually this will
15425 /// be taken from an existing function with the same prototype.
15426 ///
15427 /// \returns A suitable function type, if there are no errors. The
15428 /// unqualified type will always be a FunctionProtoType.
15429 /// Otherwise, returns a NULL type.
15430 QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes,
15431 SourceLocation Loc, DeclarationName Entity,
15432 const FunctionProtoType::ExtProtoInfo &EPI);
15433
15434 /// Build a member pointer type \c T Class::*.
15435 ///
15436 /// \param T the type to which the member pointer refers.
15437 /// \param Class the class type into which the member pointer points.
15438 /// \param Loc the location where this type begins
15439 /// \param Entity the name of the entity that will have this member pointer
15440 /// type
15441 ///
15442 /// \returns a member pointer type, if successful, or a NULL type if there was
15443 /// an error.
15444 QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS,
15445 CXXRecordDecl *Cls, SourceLocation Loc,
15446 DeclarationName Entity);
15447
15448 /// Build a block pointer type.
15449 ///
15450 /// \param T The type to which we'll be building a block pointer.
15451 ///
15452 /// \param Loc The source location, used for diagnostics.
15453 ///
15454 /// \param Entity The name of the entity that involves the block pointer
15455 /// type, if known.
15456 ///
15457 /// \returns A suitable block pointer type, if there are no
15458 /// errors. Otherwise, returns a NULL type.
15459 QualType BuildBlockPointerType(QualType T, SourceLocation Loc,
15460 DeclarationName Entity);
15461
15462 /// Build a paren type including \p T.
15463 QualType BuildParenType(QualType T);
15464 QualType BuildAtomicType(QualType T, SourceLocation Loc);
15465
15466 /// Build a Read-only Pipe type.
15467 ///
15468 /// \param T The type to which we'll be building a Pipe.
15469 ///
15470 /// \param Loc We do not use it for now.
15471 ///
15472 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15473 /// a NULL type.
15474 QualType BuildReadPipeType(QualType T, SourceLocation Loc);
15475
15476 /// Build a Write-only Pipe type.
15477 ///
15478 /// \param T The type to which we'll be building a Pipe.
15479 ///
15480 /// \param Loc We do not use it for now.
15481 ///
15482 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15483 /// a NULL type.
15484 QualType BuildWritePipeType(QualType T, SourceLocation Loc);
15485
15486 /// Build a bit-precise integer type.
15487 ///
15488 /// \param IsUnsigned Boolean representing the signedness of the type.
15489 ///
15490 /// \param BitWidth Size of this int type in bits, or an expression
15491 /// representing that.
15492 ///
15493 /// \param Loc Location of the keyword.
15494 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15495
15496 /// GetTypeForDeclarator - Convert the type for the specified
15497 /// declarator to Type instances.
15498 ///
15499 /// The result of this call will never be null, but the associated
15500 /// type may be a null type if there's an unrecoverable error.
15501 TypeSourceInfo *GetTypeForDeclarator(Declarator &D);
15502 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
15503
15504 /// Package the given type and TSI into a ParsedType.
15505 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
15506 static QualType GetTypeFromParser(ParsedType Ty,
15507 TypeSourceInfo **TInfo = nullptr);
15508
15509 TypeResult ActOnTypeName(Declarator &D);
15510
15511 // Check whether the size of array element of type \p EltTy is a multiple of
15512 // its alignment and return false if it isn't.
15513 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
15514
15515 void
15516 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15517 SourceLocation FallbackLoc,
15518 SourceLocation ConstQualLoc = SourceLocation(),
15519 SourceLocation VolatileQualLoc = SourceLocation(),
15520 SourceLocation RestrictQualLoc = SourceLocation(),
15521 SourceLocation AtomicQualLoc = SourceLocation(),
15522 SourceLocation UnalignedQualLoc = SourceLocation());
15523
15524 /// Retrieve the keyword associated
15525 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
15526
15527 /// Adjust the calling convention of a method to be the ABI default if it
15528 /// wasn't specified explicitly. This handles method types formed from
15529 /// function type typedefs and typename template arguments.
15530 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15531 bool IsCtorOrDtor, SourceLocation Loc);
15532
15533 // Check if there is an explicit attribute, but only look through parens.
15534 // The intent is to look for an attribute on the current declarator, but not
15535 // one that came from a typedef.
15536 bool hasExplicitCallingConv(QualType T);
15537
15538 /// Check whether a nullability type specifier can be added to the given
15539 /// type through some means not written in source (e.g. API notes).
15540 ///
15541 /// \param Type The type to which the nullability specifier will be
15542 /// added. On success, this type will be updated appropriately.
15543 ///
15544 /// \param Nullability The nullability specifier to add.
15545 ///
15546 /// \param DiagLoc The location to use for diagnostics.
15547 ///
15548 /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15549 /// array type (e.g., because it will decay to a pointer).
15550 ///
15551 /// \param OverrideExisting Whether to override an existing, locally-specified
15552 /// nullability specifier rather than complaining about the conflict.
15553 ///
15554 /// \returns true if nullability cannot be applied, false otherwise.
15555 bool CheckImplicitNullabilityTypeSpecifier(QualType &Type,
15556 NullabilityKind Nullability,
15557 SourceLocation DiagLoc,
15558 bool AllowArrayTypes,
15559 bool OverrideExisting);
15560
15561 /// Check whether the given variable declaration has a size that fits within
15562 /// the address space it is declared in. This issues a diagnostic if not.
15563 ///
15564 /// \param VD The variable declaration to check the size of.
15565 ///
15566 /// \param AS The address space to check the size of \p VD against.
15567 ///
15568 /// \returns true if the variable's size fits within the address space, false
15569 /// otherwise.
15570 bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS);
15571
15572 /// Get the type of expression E, triggering instantiation to complete the
15573 /// type if necessary -- that is, if the expression refers to a templated
15574 /// static data member of incomplete array type.
15575 ///
15576 /// May still return an incomplete type if instantiation was not possible or
15577 /// if the type is incomplete for a different reason. Use
15578 /// RequireCompleteExprType instead if a diagnostic is expected for an
15579 /// incomplete expression type.
15580 QualType getCompletedType(Expr *E);
15581
15582 void completeExprArrayBound(Expr *E);
15583
15584 /// Ensure that the type of the given expression is complete.
15585 ///
15586 /// This routine checks whether the expression \p E has a complete type. If
15587 /// the expression refers to an instantiable construct, that instantiation is
15588 /// performed as needed to complete its type. Furthermore
15589 /// Sema::RequireCompleteType is called for the expression's type (or in the
15590 /// case of a reference type, the referred-to type).
15591 ///
15592 /// \param E The expression whose type is required to be complete.
15593 /// \param Kind Selects which completeness rules should be applied.
15594 /// \param Diagnoser The object that will emit a diagnostic if the type is
15595 /// incomplete.
15596 ///
15597 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15598 /// otherwise.
15599 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
15600 TypeDiagnoser &Diagnoser);
15601 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15602
15603 template <typename... Ts>
15604 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15605 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15606 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
15607 }
15608
15609 // Returns the underlying type of a decltype with the given expression.
15610 QualType getDecltypeForExpr(Expr *E);
15611
15612 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
15613 /// If AsUnevaluated is false, E is treated as though it were an evaluated
15614 /// context, such as when building a type for decltype(auto).
15615 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15616
15617 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15618 SourceLocation Loc,
15619 SourceLocation EllipsisLoc);
15620 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15621 SourceLocation Loc, SourceLocation EllipsisLoc,
15622 bool FullySubstituted = false,
15623 ArrayRef<QualType> Expansions = {});
15624
15625 using UTTKind = UnaryTransformType::UTTKind;
15626 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
15627 SourceLocation Loc);
15628 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
15629 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
15630 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
15631 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
15632 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
15633 SourceLocation Loc);
15634 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
15635 SourceLocation Loc);
15636 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
15637 SourceLocation Loc);
15638
15639 QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc) {
15640 return BuiltinRemoveReference(BaseType, UKind: UTTKind::RemoveCVRef, Loc);
15641 }
15642
15643 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
15644 SourceLocation Loc);
15645 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
15646 SourceLocation Loc);
15647
15648 bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15649
15650 /// Ensure that the type T is a literal type.
15651 ///
15652 /// This routine checks whether the type @p T is a literal type. If @p T is an
15653 /// incomplete type, an attempt is made to complete it. If @p T is a literal
15654 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15655 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15656 /// it the type @p T), along with notes explaining why the type is not a
15657 /// literal type, and returns true.
15658 ///
15659 /// @param Loc The location in the source that the non-literal type
15660 /// diagnostic should refer to.
15661 ///
15662 /// @param T The type that this routine is examining for literalness.
15663 ///
15664 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15665 ///
15666 /// @returns @c true if @p T is not a literal type and a diagnostic was
15667 /// emitted, @c false otherwise.
15668 bool RequireLiteralType(SourceLocation Loc, QualType T,
15669 TypeDiagnoser &Diagnoser);
15670 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15671
15672 template <typename... Ts>
15673 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15674 const Ts &...Args) {
15675 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15676 return RequireLiteralType(Loc, T, Diagnoser);
15677 }
15678
15679 bool isCompleteType(SourceLocation Loc, QualType T,
15680 CompleteTypeKind Kind = CompleteTypeKind::Default) {
15681 return !RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser: nullptr);
15682 }
15683
15684 /// Ensure that the type T is a complete type.
15685 ///
15686 /// This routine checks whether the type @p T is complete in any
15687 /// context where a complete type is required. If @p T is a complete
15688 /// type, returns false. If @p T is a class template specialization,
15689 /// this routine then attempts to perform class template
15690 /// instantiation. If instantiation fails, or if @p T is incomplete
15691 /// and cannot be completed, issues the diagnostic @p diag (giving it
15692 /// the type @p T) and returns true.
15693 ///
15694 /// @param Loc The location in the source that the incomplete type
15695 /// diagnostic should refer to.
15696 ///
15697 /// @param T The type that this routine is examining for completeness.
15698 ///
15699 /// @param Kind Selects which completeness rules should be applied.
15700 ///
15701 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15702 /// @c false otherwise.
15703 bool RequireCompleteType(SourceLocation Loc, QualType T,
15704 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15705 bool RequireCompleteType(SourceLocation Loc, QualType T,
15706 CompleteTypeKind Kind, unsigned DiagID);
15707
15708 bool RequireCompleteType(SourceLocation Loc, QualType T,
15709 TypeDiagnoser &Diagnoser) {
15710 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, Diagnoser);
15711 }
15712 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15713 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, DiagID);
15714 }
15715
15716 template <typename... Ts>
15717 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15718 const Ts &...Args) {
15719 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15720 return RequireCompleteType(Loc, T, Diagnoser);
15721 }
15722
15723 /// Determine whether a declaration is visible to name lookup.
15724 bool isVisible(const NamedDecl *D) {
15725 return D->isUnconditionallyVisible() ||
15726 isAcceptableSlow(D, Kind: AcceptableKind::Visible);
15727 }
15728
15729 /// Determine whether a declaration is reachable.
15730 bool isReachable(const NamedDecl *D) {
15731 // All visible declarations are reachable.
15732 return D->isUnconditionallyVisible() ||
15733 isAcceptableSlow(D, Kind: AcceptableKind::Reachable);
15734 }
15735
15736 /// Determine whether a declaration is acceptable (visible/reachable).
15737 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
15738 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15739 }
15740
15741 /// Determine if \p D and \p Suggested have a structurally compatible
15742 /// layout as described in C11 6.2.7/1.
15743 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15744
15745 /// Determine if \p D has a visible definition. If not, suggest a declaration
15746 /// that should be made visible to expose the definition.
15747 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15748 bool OnlyNeedComplete = false);
15749 bool hasVisibleDefinition(const NamedDecl *D) {
15750 NamedDecl *Hidden;
15751 return hasVisibleDefinition(D: const_cast<NamedDecl *>(D), Suggested: &Hidden);
15752 }
15753 /// Determine if \p D has a definition which allows we redefine it in current
15754 /// TU. \p Suggested is the definition that should be made visible to expose
15755 /// the definition.
15756 bool isRedefinitionAllowedFor(NamedDecl *D, SourceLocation NewDefinitionLoc,
15757 NamedDecl **Suggested, bool &Visible);
15758 bool isRedefinitionAllowedFor(const NamedDecl *D, SourceLocation NewLoc,
15759 bool &Visible) {
15760 NamedDecl *Hidden;
15761 return isRedefinitionAllowedFor(D: const_cast<NamedDecl *>(D), NewDefinitionLoc: NewLoc, Suggested: &Hidden,
15762 Visible);
15763 }
15764
15765 /// Determine if \p D has a reachable definition. If not, suggest a
15766 /// declaration that should be made reachable to expose the definition.
15767 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15768 bool OnlyNeedComplete = false);
15769 bool hasReachableDefinition(NamedDecl *D) {
15770 NamedDecl *Hidden;
15771 return hasReachableDefinition(D, Suggested: &Hidden);
15772 }
15773
15774 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15775 AcceptableKind Kind,
15776 bool OnlyNeedComplete = false);
15777 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
15778 NamedDecl *Hidden;
15779 return hasAcceptableDefinition(D, Suggested: &Hidden, Kind);
15780 }
15781
15782 /// Determine if a definition at \p NewLoc coincides with \p PrevD.
15783 ///
15784 /// Including the same header as a non-modular and a modular allows to process
15785 /// its content twice despite guards against multiple inclusions. To handle
15786 /// such cases this method allows to detect if a currently-parsed decl is at
15787 /// the same location as an existing decl imported from a module.
15788 bool isFromSameSingleIncludeHeader(const Decl *PrevD, SourceLocation NewLoc);
15789
15790 /// Try to parse the conditional expression attached to an effect attribute
15791 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15792 /// optional on error.
15793 std::optional<FunctionEffectMode>
15794 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15795
15796 void ActOnCleanupAttr(Decl *D, const Attr *A);
15797 void ActOnInitPriorityAttr(Decl *D, const Attr *A);
15798
15799private:
15800 /// The implementation of RequireCompleteType
15801 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15802 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15803
15804 /// Nullability type specifiers.
15805 IdentifierInfo *Ident__Nonnull = nullptr;
15806 IdentifierInfo *Ident__Nullable = nullptr;
15807 IdentifierInfo *Ident__Nullable_result = nullptr;
15808 IdentifierInfo *Ident__Null_unspecified = nullptr;
15809
15810 ///@}
15811
15812 //
15813 //
15814 // -------------------------------------------------------------------------
15815 //
15816 //
15817
15818 /// \name FixIt Helpers
15819 /// Implementations are in SemaFixItUtils.cpp
15820 ///@{
15821
15822public:
15823 /// Get a string to suggest for zero-initialization of a type.
15824 std::string getFixItZeroInitializerForType(QualType T,
15825 SourceLocation Loc) const;
15826 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15827
15828 ///@}
15829
15830 //
15831 //
15832 // -------------------------------------------------------------------------
15833 //
15834 //
15835
15836 /// \name Function Effects
15837 /// Implementations are in SemaFunctionEffects.cpp
15838 ///@{
15839public:
15840 struct FunctionEffectDiff {
15841 enum class Kind { Added, Removed, ConditionMismatch };
15842
15843 FunctionEffect::Kind EffectKind;
15844 Kind DiffKind;
15845 std::optional<FunctionEffectWithCondition>
15846 Old; // Invalid when 'Kind' is 'Added'.
15847 std::optional<FunctionEffectWithCondition>
15848 New; // Invalid when 'Kind' is 'Removed'.
15849
15850 StringRef effectName() const {
15851 if (Old)
15852 return Old.value().Effect.name();
15853 return New.value().Effect.name();
15854 }
15855
15856 /// Describes the result of effects differing between a base class's virtual
15857 /// method and an overriding method in a subclass.
15858 enum class OverrideResult {
15859 NoAction,
15860 Warn,
15861 Merge // Merge missing effect from base to derived.
15862 };
15863
15864 /// Return true if adding or removing the effect as part of a type
15865 /// conversion should generate a diagnostic.
15866 bool shouldDiagnoseConversion(QualType SrcType,
15867 const FunctionEffectsRef &SrcFX,
15868 QualType DstType,
15869 const FunctionEffectsRef &DstFX) const;
15870
15871 /// Return true if adding or removing the effect in a redeclaration should
15872 /// generate a diagnostic.
15873 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
15874 const FunctionEffectsRef &OldFX,
15875 const FunctionDecl &NewFunction,
15876 const FunctionEffectsRef &NewFX) const;
15877
15878 /// Return true if adding or removing the effect in a C++ virtual method
15879 /// override should generate a diagnostic.
15880 OverrideResult shouldDiagnoseMethodOverride(
15881 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
15882 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
15883 };
15884
15885 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
15886 /// Caller should short-circuit by checking for equality first.
15887 FunctionEffectDiffVector(const FunctionEffectsRef &Old,
15888 const FunctionEffectsRef &New);
15889 };
15890
15891 /// All functions/lambdas/blocks which have bodies and which have a non-empty
15892 /// FunctionEffectsRef to be verified.
15893 SmallVector<const Decl *> DeclsWithEffectsToVerify;
15894
15895 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
15896 /// are all null.
15897 FunctionEffectKindSet AllEffectsToVerify;
15898
15899public:
15900 /// Warn and return true if adding a function effect to a set would create a
15901 /// conflict.
15902 bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX,
15903 const FunctionEffectWithCondition &EC,
15904 SourceLocation NewAttrLoc);
15905
15906 // Report a failure to merge function effects between declarations due to a
15907 // conflict.
15908 void
15909 diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs,
15910 SourceLocation NewLoc,
15911 SourceLocation OldLoc);
15912
15913 /// Inline checks from the start of maybeAddDeclWithEffects, to
15914 /// minimize performance impact on code not using effects.
15915 template <class FuncOrBlockDecl>
15916 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
15917 if (Context.hasAnyFunctionEffects())
15918 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
15919 maybeAddDeclWithEffects(D, FX);
15920 }
15921
15922 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
15923 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15924
15925 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
15926 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15927
15928 void performFunctionEffectAnalysis(TranslationUnitDecl *TU);
15929
15930 ///@}
15931
15932 //
15933 //
15934 // -------------------------------------------------------------------------
15935 //
15936 //
15937
15938 /// \name Expansion Statements
15939 /// Implementations are in SemaExpand.cpp
15940 ///@{
15941public:
15942 CXXExpansionStmtDecl *ActOnCXXExpansionStmtDecl(unsigned TemplateDepth,
15943 SourceLocation TemplateKWLoc);
15944
15945 CXXExpansionStmtDecl *
15946 BuildCXXExpansionStmtDecl(DeclContext *Ctx, SourceLocation TemplateKWLoc,
15947 NonTypeTemplateParmDecl *NTTP);
15948
15949 ExprResult ActOnCXXExpansionInitList(MultiExprArg SubExprs,
15950 SourceLocation LBraceLoc,
15951 SourceLocation RBraceLoc);
15952
15953 StmtResult ActOnCXXExpansionStmtPattern(
15954 CXXExpansionStmtDecl *ESD, Stmt *Init, Stmt *ExpansionVarStmt,
15955 Expr *ExpansionInitializer, SourceLocation LParenLoc,
15956 SourceLocation ColonLoc, SourceLocation RParenLoc,
15957 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps);
15958
15959 StmtResult FinishCXXExpansionStmt(Stmt *Expansion, Stmt *Body);
15960
15961 StmtResult BuildCXXEnumeratingExpansionStmtPattern(Decl *ESD, Stmt *Init,
15962 Stmt *ExpansionVar,
15963 SourceLocation LParenLoc,
15964 SourceLocation ColonLoc,
15965 SourceLocation RParenLoc);
15966
15967 StmtResult BuildNonEnumeratingCXXExpansionStmtPattern(
15968 CXXExpansionStmtDecl *ESD, Stmt *Init, DeclStmt *ExpansionVarStmt,
15969 Expr *ExpansionInitializer, SourceLocation LParenLoc,
15970 SourceLocation ColonLoc, SourceLocation RParenLoc,
15971 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
15972
15973 ExprResult BuildCXXExpansionSelectExpr(InitListExpr *Range, Expr *Idx);
15974
15975 std::optional<uint64_t>
15976 ComputeExpansionSize(CXXExpansionStmtPattern *Expansion);
15977 ///@}
15978};
15979
15980DeductionFailureInfo
15981MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK,
15982 sema::TemplateDeductionInfo &Info);
15983
15984/// Contains a late templated function.
15985/// Will be parsed at the end of the translation unit, used by Sema & Parser.
15986struct LateParsedTemplate {
15987 CachedTokens Toks;
15988 /// The template function declaration to be late parsed.
15989 Decl *D;
15990 /// Floating-point options in the point of definition.
15991 FPOptions FPO;
15992};
15993
15994template <>
15995void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
15996 PragmaMsStackAction Action,
15997 llvm::StringRef StackSlotLabel,
15998 AlignPackInfo Value);
15999
16000} // end namespace clang
16001
16002#endif
16003