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/Builtins.h"
39#include "clang/Basic/CapturedStmt.h"
40#include "clang/Basic/Cuda.h"
41#include "clang/Basic/DiagnosticSema.h"
42#include "clang/Basic/ExceptionSpecificationType.h"
43#include "clang/Basic/ExpressionTraits.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/Basic/TypeTraits.h"
58#include "clang/Sema/AnalysisBasedWarnings.h"
59#include "clang/Sema/Attr.h"
60#include "clang/Sema/CleanupInfo.h"
61#include "clang/Sema/DeclSpec.h"
62#include "clang/Sema/ExternalSemaSource.h"
63#include "clang/Sema/IdentifierResolver.h"
64#include "clang/Sema/Ownership.h"
65#include "clang/Sema/ParsedAttr.h"
66#include "clang/Sema/Redeclaration.h"
67#include "clang/Sema/Scope.h"
68#include "clang/Sema/SemaBase.h"
69#include "clang/Sema/SemaConcept.h"
70#include "clang/Sema/SemaRISCV.h"
71#include "clang/Sema/TypoCorrection.h"
72#include "clang/Sema/Weak.h"
73#include "llvm/ADT/APInt.h"
74#include "llvm/ADT/ArrayRef.h"
75#include "llvm/ADT/BitmaskEnum.h"
76#include "llvm/ADT/DenseMap.h"
77#include "llvm/ADT/DenseSet.h"
78#include "llvm/ADT/FloatingPointMode.h"
79#include "llvm/ADT/FoldingSet.h"
80#include "llvm/ADT/MapVector.h"
81#include "llvm/ADT/PointerIntPair.h"
82#include "llvm/ADT/PointerUnion.h"
83#include "llvm/ADT/STLExtras.h"
84#include "llvm/ADT/STLForwardCompat.h"
85#include "llvm/ADT/STLFunctionalExtras.h"
86#include "llvm/ADT/SetVector.h"
87#include "llvm/ADT/SmallBitVector.h"
88#include "llvm/ADT/SmallPtrSet.h"
89#include "llvm/ADT/SmallSet.h"
90#include "llvm/ADT/SmallVector.h"
91#include "llvm/ADT/StringExtras.h"
92#include "llvm/ADT/StringMap.h"
93#include "llvm/ADT/TinyPtrVector.h"
94#include "llvm/Support/Allocator.h"
95#include "llvm/Support/Compiler.h"
96#include "llvm/Support/Error.h"
97#include "llvm/Support/ErrorHandling.h"
98#include <cassert>
99#include <climits>
100#include <cstddef>
101#include <cstdint>
102#include <deque>
103#include <functional>
104#include <iterator>
105#include <memory>
106#include <optional>
107#include <string>
108#include <tuple>
109#include <type_traits>
110#include <utility>
111#include <vector>
112
113namespace llvm {
114struct InlineAsmIdentifierInfo;
115} // namespace llvm
116
117namespace clang {
118class ADLResult;
119class APValue;
120struct ASTConstraintSatisfaction;
121class ASTConsumer;
122class ASTContext;
123class ASTDeclReader;
124class ASTMutationListener;
125class ASTReader;
126class ASTWriter;
127class CXXBasePath;
128class CXXBasePaths;
129class CXXFieldCollector;
130class CodeCompleteConsumer;
131enum class ComparisonCategoryType : unsigned char;
132class ConstraintSatisfaction;
133class DarwinSDKInfo;
134class DeclGroupRef;
135class DeducedTemplateArgument;
136struct DeductionFailureInfo;
137class DependentDiagnostic;
138class Designation;
139class IdentifierInfo;
140class ImplicitConversionSequence;
141typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
142class InitializationKind;
143class InitializationSequence;
144class InitializedEntity;
145enum class LangAS : unsigned int;
146class LocalInstantiationScope;
147class LookupResult;
148class MangleNumberingContext;
149typedef ArrayRef<IdentifierLoc> ModuleIdPath;
150class ModuleLoader;
151class MultiLevelTemplateArgumentList;
152struct NormalizedConstraint;
153class ObjCInterfaceDecl;
154class ObjCMethodDecl;
155struct OverloadCandidate;
156enum class OverloadCandidateParamOrder : char;
157enum OverloadCandidateRewriteKind : unsigned;
158class OverloadCandidateSet;
159class Preprocessor;
160class SemaAMDGPU;
161class SemaARM;
162class SemaAVR;
163class SemaBPF;
164class SemaCodeCompletion;
165class SemaCUDA;
166class SemaDirectX;
167class SemaHLSL;
168class SemaHexagon;
169class SemaLoongArch;
170class SemaM68k;
171class SemaMIPS;
172class SemaMSP430;
173class SemaNVPTX;
174class SemaObjC;
175class SemaOpenACC;
176class SemaOpenCL;
177class SemaOpenMP;
178class SemaPPC;
179class SemaPseudoObject;
180class SemaRISCV;
181class SemaSPIRV;
182class SemaSYCL;
183class SemaSwift;
184class SemaSystemZ;
185class SemaWasm;
186class SemaX86;
187class StandardConversionSequence;
188class TemplateArgument;
189class TemplateArgumentLoc;
190class TemplateInstantiationCallback;
191class TemplatePartialOrderingContext;
192class TemplateSpecCandidateSet;
193class Token;
194class TypeConstraint;
195class TypoCorrectionConsumer;
196class UnresolvedSetImpl;
197class UnresolvedSetIterator;
198class VisibleDeclConsumer;
199
200namespace sema {
201class BlockScopeInfo;
202class Capture;
203class CapturedRegionScopeInfo;
204class CapturingScopeInfo;
205class CompoundScopeInfo;
206class DelayedDiagnostic;
207class DelayedDiagnosticPool;
208class FunctionScopeInfo;
209class LambdaScopeInfo;
210class SemaPPCallbacks;
211class TemplateDeductionInfo;
212} // namespace sema
213
214// AssignmentAction - This is used by all the assignment diagnostic functions
215// to represent what is actually causing the operation
216enum class AssignmentAction {
217 Assigning,
218 Passing,
219 Returning,
220 Converting,
221 Initializing,
222 Sending,
223 Casting,
224 Passing_CFAudited
225};
226
227namespace threadSafety {
228class BeforeSet;
229void threadSafetyCleanup(BeforeSet *Cache);
230} // namespace threadSafety
231
232// FIXME: No way to easily map from TemplateTypeParmTypes to
233// TemplateTypeParmDecls, so we have this horrible PointerUnion.
234typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *,
235 const TemplateSpecializationType *,
236 const SubstBuiltinTemplatePackType *>,
237 SourceLocation>
238 UnexpandedParameterPack;
239
240/// Describes whether we've seen any nullability information for the given
241/// file.
242struct FileNullability {
243 /// The first pointer declarator (of any pointer kind) in the file that does
244 /// not have a corresponding nullability annotation.
245 SourceLocation PointerLoc;
246
247 /// The end location for the first pointer declarator in the file. Used for
248 /// placing fix-its.
249 SourceLocation PointerEndLoc;
250
251 /// Which kind of pointer declarator we saw.
252 uint8_t PointerKind;
253
254 /// Whether we saw any type nullability annotations in the given file.
255 bool SawTypeNullability = false;
256};
257
258/// A mapping from file IDs to a record of whether we've seen nullability
259/// information in that file.
260class FileNullabilityMap {
261 /// A mapping from file IDs to the nullability information for each file ID.
262 llvm::DenseMap<FileID, FileNullability> Map;
263
264 /// A single-element cache based on the file ID.
265 struct {
266 FileID File;
267 FileNullability Nullability;
268 } Cache;
269
270public:
271 FileNullability &operator[](FileID file) {
272 // Check the single-element cache.
273 if (file == Cache.File)
274 return Cache.Nullability;
275
276 // It's not in the single-element cache; flush the cache if we have one.
277 if (!Cache.File.isInvalid()) {
278 Map[Cache.File] = Cache.Nullability;
279 }
280
281 // Pull this entry into the cache.
282 Cache.File = file;
283 Cache.Nullability = Map[file];
284 return Cache.Nullability;
285 }
286};
287
288/// Tracks expected type during expression parsing, for use in code completion.
289/// The type is tied to a particular token, all functions that update or consume
290/// the type take a start location of the token they are looking at as a
291/// parameter. This avoids updating the type on hot paths in the parser.
292class PreferredTypeBuilder {
293public:
294 PreferredTypeBuilder(ASTContext *Ctx, bool Enabled)
295 : Ctx(Ctx), Enabled(Enabled) {}
296
297 void enterCondition(Sema &S, SourceLocation Tok);
298 void enterReturn(Sema &S, SourceLocation Tok);
299 void enterVariableInit(SourceLocation Tok, Decl *D);
300 /// Handles e.g. BaseType{ .D = Tok...
301 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
302 const Designation &D);
303 /// Computing a type for the function argument may require running
304 /// overloading, so we postpone its computation until it is actually needed.
305 ///
306 /// Clients should be very careful when using this function, as it stores a
307 /// function_ref, clients should make sure all calls to get() with the same
308 /// location happen while function_ref is alive.
309 ///
310 /// The callback should also emit signature help as a side-effect, but only
311 /// if the completion point has been reached.
312 void enterFunctionArgument(SourceLocation Tok,
313 llvm::function_ref<QualType()> ComputeType);
314
315 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
316 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
317 SourceLocation OpLoc);
318 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
319 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
320 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
321 /// Handles all type casts, including C-style cast, C++ casts, etc.
322 void enterTypeCast(SourceLocation Tok, QualType CastType);
323
324 /// Get the expected type associated with this location, if any.
325 ///
326 /// If the location is a function argument, determining the expected type
327 /// involves considering all function overloads and the arguments so far.
328 /// In this case, signature help for these function overloads will be reported
329 /// as a side-effect (only if the completion point has been reached).
330 QualType get(SourceLocation Tok) const {
331 if (!Enabled || Tok != ExpectedLoc)
332 return QualType();
333 if (!Type.isNull())
334 return Type;
335 if (ComputeType)
336 return ComputeType();
337 return QualType();
338 }
339
340private:
341 ASTContext *Ctx;
342 bool Enabled;
343 /// Start position of a token for which we store expected type.
344 SourceLocation ExpectedLoc;
345 /// Expected type for a token starting at ExpectedLoc.
346 QualType Type;
347 /// A function to compute expected type at ExpectedLoc. It is only considered
348 /// if Type is null.
349 llvm::function_ref<QualType()> ComputeType;
350};
351
352struct SkipBodyInfo {
353 SkipBodyInfo() = default;
354 bool ShouldSkip = false;
355 bool CheckSameAsPrevious = false;
356 NamedDecl *Previous = nullptr;
357 NamedDecl *New = nullptr;
358};
359
360/// Describes the result of template argument deduction.
361///
362/// The TemplateDeductionResult enumeration describes the result of
363/// template argument deduction, as returned from
364/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
365/// structure provides additional information about the results of
366/// template argument deduction, e.g., the deduced template argument
367/// list (if successful) or the specific template parameters or
368/// deduced arguments that were involved in the failure.
369enum class TemplateDeductionResult {
370 /// Template argument deduction was successful.
371 Success = 0,
372 /// The declaration was invalid; do nothing.
373 Invalid,
374 /// Template argument deduction exceeded the maximum template
375 /// instantiation depth (which has already been diagnosed).
376 InstantiationDepth,
377 /// Template argument deduction did not deduce a value
378 /// for every template parameter.
379 Incomplete,
380 /// Template argument deduction did not deduce a value for every
381 /// expansion of an expanded template parameter pack.
382 IncompletePack,
383 /// Template argument deduction produced inconsistent
384 /// deduced values for the given template parameter.
385 Inconsistent,
386 /// Template argument deduction failed due to inconsistent
387 /// cv-qualifiers on a template parameter type that would
388 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
389 /// but were given a non-const "X".
390 Underqualified,
391 /// Substitution of the deduced template argument values
392 /// resulted in an error.
393 SubstitutionFailure,
394 /// After substituting deduced template arguments, a dependent
395 /// parameter type did not match the corresponding argument.
396 DeducedMismatch,
397 /// After substituting deduced template arguments, an element of
398 /// a dependent parameter type did not match the corresponding element
399 /// of the corresponding argument (when deducing from an initializer list).
400 DeducedMismatchNested,
401 /// A non-depnedent component of the parameter did not match the
402 /// corresponding component of the argument.
403 NonDeducedMismatch,
404 /// When performing template argument deduction for a function
405 /// template, there were too many call arguments.
406 TooManyArguments,
407 /// When performing template argument deduction for a function
408 /// template, there were too few call arguments.
409 TooFewArguments,
410 /// The explicitly-specified template arguments were not valid
411 /// template arguments for the given template.
412 InvalidExplicitArguments,
413 /// Checking non-dependent argument conversions failed.
414 NonDependentConversionFailure,
415 /// The deduced arguments did not satisfy the constraints associated
416 /// with the template.
417 ConstraintsNotSatisfied,
418 /// Deduction failed; that's all we know.
419 MiscellaneousDeductionFailure,
420 /// CUDA Target attributes do not match.
421 CUDATargetMismatch,
422 /// Some error which was already diagnosed.
423 AlreadyDiagnosed
424};
425
426/// Kinds of C++ special members.
427enum class CXXSpecialMemberKind {
428 DefaultConstructor,
429 CopyConstructor,
430 MoveConstructor,
431 CopyAssignment,
432 MoveAssignment,
433 Destructor,
434 Invalid
435};
436
437/// The kind of conversion being performed.
438enum class CheckedConversionKind {
439 /// An implicit conversion.
440 Implicit,
441 /// A C-style cast.
442 CStyleCast,
443 /// A functional-style cast.
444 FunctionalCast,
445 /// A cast other than a C-style cast.
446 OtherCast,
447 /// A conversion for an operand of a builtin overloaded operator.
448 ForBuiltinOverloadedOp
449};
450
451enum class TagUseKind {
452 Reference, // Reference to a tag: 'struct foo *X;'
453 Declaration, // Fwd decl of a tag: 'struct foo;'
454 Definition, // Definition of a tag: 'struct foo { int X; } Y;'
455 Friend // Friend declaration: 'friend struct foo;'
456};
457
458/// Used with attributes/effects with a boolean condition, e.g. `nonblocking`.
459enum class FunctionEffectMode : uint8_t {
460 None, // effect is not present.
461 False, // effect(false).
462 True, // effect(true).
463 Dependent // effect(expr) where expr is dependent.
464};
465
466/// pragma clang section kind
467enum class PragmaClangSectionKind {
468 Invalid = 0,
469 BSS = 1,
470 Data = 2,
471 Rodata = 3,
472 Text = 4,
473 Relro = 5
474};
475
476enum class PragmaClangSectionAction { Set = 0, Clear = 1 };
477
478enum class PragmaOptionsAlignKind {
479 Native, // #pragma options align=native
480 Natural, // #pragma options align=natural
481 Packed, // #pragma options align=packed
482 Power, // #pragma options align=power
483 Mac68k, // #pragma options align=mac68k
484 Reset // #pragma options align=reset
485};
486
487enum class TUFragmentKind {
488 /// The global module fragment, between 'module;' and a module-declaration.
489 Global,
490 /// A normal translation unit fragment. For a non-module unit, this is the
491 /// entire translation unit. Otherwise, it runs from the module-declaration
492 /// to the private-module-fragment (if any) or the end of the TU (if not).
493 Normal,
494 /// The private module fragment, between 'module :private;' and the end of
495 /// the translation unit.
496 Private
497};
498
499enum class FormatStringType {
500 Scanf,
501 Printf,
502 NSString,
503 Strftime,
504 Strfmon,
505 Kprintf,
506 FreeBSDKPrintf,
507 OSTrace,
508 OSLog,
509 Unknown
510};
511
512// Used for emitting the right warning by DefaultVariadicArgumentPromotion
513enum class VariadicCallType {
514 Function,
515 Block,
516 Method,
517 Constructor,
518 DoesNotApply
519};
520
521enum class BuiltinCountedByRefKind {
522 Assignment,
523 Initializer,
524 FunctionArg,
525 ReturnArg,
526 ArraySubscript,
527 BinaryExpr,
528};
529
530// Contexts where using non-trivial C union types can be disallowed. This is
531// passed to err_non_trivial_c_union_in_invalid_context.
532enum class NonTrivialCUnionContext {
533 // Function parameter.
534 FunctionParam,
535 // Function return.
536 FunctionReturn,
537 // Default-initialized object.
538 DefaultInitializedObject,
539 // Variable with automatic storage duration.
540 AutoVar,
541 // Initializer expression that might copy from another object.
542 CopyInit,
543 // Assignment.
544 Assignment,
545 // Compound literal.
546 CompoundLiteral,
547 // Block capture.
548 BlockCapture,
549 // lvalue-to-rvalue conversion of volatile type.
550 LValueToRValueVolatile,
551};
552
553/// Describes the result of the name lookup and resolution performed
554/// by \c Sema::ClassifyName().
555enum class NameClassificationKind {
556 /// This name is not a type or template in this context, but might be
557 /// something else.
558 Unknown,
559 /// Classification failed; an error has been produced.
560 Error,
561 /// The name has been typo-corrected to a keyword.
562 Keyword,
563 /// The name was classified as a type.
564 Type,
565 /// The name was classified as a specific non-type, non-template
566 /// declaration. ActOnNameClassifiedAsNonType should be called to
567 /// convert the declaration to an expression.
568 NonType,
569 /// The name was classified as an ADL-only function name.
570 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
571 /// result to an expression.
572 UndeclaredNonType,
573 /// The name denotes a member of a dependent type that could not be
574 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
575 /// convert the result to an expression.
576 DependentNonType,
577 /// The name was classified as an overload set, and an expression
578 /// representing that overload set has been formed.
579 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
580 /// expression referencing the overload set.
581 OverloadSet,
582 /// The name was classified as a template whose specializations are types.
583 TypeTemplate,
584 /// The name was classified as a variable template name.
585 VarTemplate,
586 /// The name was classified as a function template name.
587 FunctionTemplate,
588 /// The name was classified as an ADL-only function template name.
589 UndeclaredTemplate,
590 /// The name was classified as a concept name.
591 Concept,
592};
593
594enum class PointerAuthDiscArgKind {
595 // Address discrimination argument of __ptrauth.
596 Addr,
597
598 // Extra discriminator argument of __ptrauth.
599 Extra,
600};
601
602/// Common ways to introduce type names without a tag for use in diagnostics.
603/// Keep in sync with err_tag_reference_non_tag.
604enum class NonTagKind {
605 NonStruct,
606 NonClass,
607 NonUnion,
608 NonEnum,
609 Typedef,
610 TypeAlias,
611 Template,
612 TypeAliasTemplate,
613 TemplateTemplateArgument,
614};
615
616enum class OffsetOfKind {
617 // Not parsing a type within __builtin_offsetof.
618 Outside,
619 // Parsing a type within __builtin_offsetof.
620 Builtin,
621 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
622 // To improve our diagnostic message.
623 Macro,
624};
625
626/// Describes the kind of merge to perform for availability
627/// attributes (including "deprecated", "unavailable", and "availability").
628enum class AvailabilityMergeKind {
629 /// Don't merge availability attributes at all.
630 None,
631 /// Merge availability attributes for a redeclaration, which requires
632 /// an exact match.
633 Redeclaration,
634 /// Merge availability attributes for an override, which requires
635 /// an exact match or a weakening of constraints.
636 Override,
637 /// Merge availability attributes for an implementation of
638 /// a protocol requirement.
639 ProtocolImplementation,
640 /// Merge availability attributes for an implementation of
641 /// an optional protocol requirement.
642 OptionalProtocolImplementation
643};
644
645enum class TrivialABIHandling {
646 /// The triviality of a method unaffected by "trivial_abi".
647 IgnoreTrivialABI,
648
649 /// The triviality of a method affected by "trivial_abi".
650 ConsiderTrivialABI
651};
652
653enum class TryCaptureKind { Implicit, ExplicitByVal, ExplicitByRef };
654
655enum class AllowFoldKind {
656 No,
657 Allow,
658};
659
660/// Context in which we're performing a usual arithmetic conversion.
661enum class ArithConvKind {
662 /// An arithmetic operation.
663 Arithmetic,
664 /// A bitwise operation.
665 BitwiseOp,
666 /// A comparison.
667 Comparison,
668 /// A conditional (?:) operator.
669 Conditional,
670 /// A compound assignment expression.
671 CompAssign,
672};
673
674// Used for determining in which context a type is allowed to be passed to a
675// vararg function.
676enum class VarArgKind {
677 Valid,
678 ValidInCXX11,
679 Undefined,
680 MSVCUndefined,
681 Invalid
682};
683
684/// AssignConvertType - All of the 'assignment' semantic checks return this
685/// enum to indicate whether the assignment was allowed. These checks are
686/// done for simple assignments, as well as initialization, return from
687/// function, argument passing, etc. The query is phrased in terms of a
688/// source and destination type.
689enum class AssignConvertType {
690 /// Compatible - the types are compatible according to the standard.
691 Compatible,
692
693 /// CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because
694 /// a void * can implicitly convert to another pointer type, which we
695 /// differentiate for better diagnostic behavior.
696 CompatibleVoidPtrToNonVoidPtr,
697
698 /// PointerToInt - The assignment converts a pointer to an int, which we
699 /// accept as an extension.
700 PointerToInt,
701
702 /// IntToPointer - The assignment converts an int to a pointer, which we
703 /// accept as an extension.
704 IntToPointer,
705
706 /// FunctionVoidPointer - The assignment is between a function pointer and
707 /// void*, which the standard doesn't allow, but we accept as an extension.
708 FunctionVoidPointer,
709
710 /// IncompatiblePointer - The assignment is between two pointers types that
711 /// are not compatible, but we accept them as an extension.
712 IncompatiblePointer,
713
714 /// IncompatibleFunctionPointer - The assignment is between two function
715 /// pointers types that are not compatible, but we accept them as an
716 /// extension.
717 IncompatibleFunctionPointer,
718
719 /// IncompatibleFunctionPointerStrict - The assignment is between two
720 /// function pointer types that are not identical, but are compatible,
721 /// unless compiled with -fsanitize=cfi, in which case the type mismatch
722 /// may trip an indirect call runtime check.
723 IncompatibleFunctionPointerStrict,
724
725 /// IncompatiblePointerSign - The assignment is between two pointers types
726 /// which point to integers which have a different sign, but are otherwise
727 /// identical. This is a subset of the above, but broken out because it's by
728 /// far the most common case of incompatible pointers.
729 IncompatiblePointerSign,
730
731 /// CompatiblePointerDiscardsQualifiers - The assignment discards
732 /// c/v/r qualifiers, which we accept as an extension.
733 CompatiblePointerDiscardsQualifiers,
734
735 /// IncompatiblePointerDiscardsQualifiers - The assignment
736 /// discards qualifiers that we don't permit to be discarded,
737 /// like address spaces.
738 IncompatiblePointerDiscardsQualifiers,
739
740 /// IncompatiblePointerDiscardsOverflowBehavior - The assignment
741 /// discards overflow behavior annotations between otherwise compatible
742 /// pointer types.
743 IncompatiblePointerDiscardsOverflowBehavior,
744
745 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
746 /// changes address spaces in nested pointer types which is not allowed.
747 /// For instance, converting __private int ** to __generic int ** is
748 /// illegal even though __private could be converted to __generic.
749 IncompatibleNestedPointerAddressSpaceMismatch,
750
751 /// IncompatibleNestedPointerQualifiers - The assignment is between two
752 /// nested pointer types, and the qualifiers other than the first two
753 /// levels differ e.g. char ** -> const char **, but we accept them as an
754 /// extension.
755 IncompatibleNestedPointerQualifiers,
756
757 /// IncompatibleVectors - The assignment is between two vector types that
758 /// have the same size, which we accept as an extension.
759 IncompatibleVectors,
760
761 /// IntToBlockPointer - The assignment converts an int to a block
762 /// pointer. We disallow this.
763 IntToBlockPointer,
764
765 /// IncompatibleBlockPointer - The assignment is between two block
766 /// pointers types that are not compatible.
767 IncompatibleBlockPointer,
768
769 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
770 /// id type and something else (that is incompatible with it). For example,
771 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
772 IncompatibleObjCQualifiedId,
773
774 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
775 /// object with __weak qualifier.
776 IncompatibleObjCWeakRef,
777
778 /// IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType
779 /// kinds, e.g., from __ob_trap to __ob_wrap or vice versa.
780 IncompatibleOBTKinds,
781
782 /// CompatibleOBTDiscards - Assignment discards overflow behavior
783 CompatibleOBTDiscards,
784
785 /// Incompatible - We reject this conversion outright, it is invalid to
786 /// represent it in the AST.
787 Incompatible
788};
789
790/// The scope in which to find allocation functions.
791enum class AllocationFunctionScope {
792 /// Only look for allocation functions in the global scope.
793 Global,
794 /// Only look for allocation functions in the scope of the
795 /// allocated class.
796 Class,
797 /// Look for allocation functions in both the global scope
798 /// and in the scope of the allocated class.
799 Both
800};
801
802/// Describes the result of an "if-exists" condition check.
803enum class IfExistsResult {
804 /// The symbol exists.
805 Exists,
806
807 /// The symbol does not exist.
808 DoesNotExist,
809
810 /// The name is a dependent name, so the results will differ
811 /// from one instantiation to the next.
812 Dependent,
813
814 /// An error occurred.
815 Error
816};
817
818enum class CorrectTypoKind {
819 NonError, // CorrectTypo used in a non error recovery situation.
820 ErrorRecovery // CorrectTypo used in normal error recovery.
821};
822
823enum class OverloadKind {
824 /// This is a legitimate overload: the existing declarations are
825 /// functions or function templates with different signatures.
826 Overload,
827
828 /// This is not an overload because the signature exactly matches
829 /// an existing declaration.
830 Match,
831
832 /// This is not an overload because the lookup results contain a
833 /// non-function.
834 NonFunction
835};
836
837/// Contexts in which a converted constant expression is required.
838enum class CCEKind {
839 CaseValue, ///< Expression in a case label.
840 Enumerator, ///< Enumerator value with fixed underlying type.
841 TemplateArg, ///< Value of a non-type template parameter.
842 TempArgStrict, ///< As above, but applies strict template checking
843 ///< rules.
844 ArrayBound, ///< Array bound in array declarator or new-expression.
845 ExplicitBool, ///< Condition in an explicit(bool) specifier.
846 Noexcept, ///< Condition in a noexcept(bool) specifier.
847 StaticAssertMessageSize, ///< Call to size() in a static assert
848 ///< message.
849 StaticAssertMessageData, ///< Call to data() in a static assert
850 ///< message.
851};
852
853/// Enums for the diagnostics of target, target_version and target_clones.
854namespace DiagAttrParams {
855enum DiagType { Unsupported, Duplicate, Unknown };
856enum Specifier { None, CPU, Tune };
857enum AttrName { Target, TargetClones, TargetVersion };
858} // end namespace DiagAttrParams
859
860void inferNoReturnAttr(Sema &S, Decl *D);
861
862#ifdef __GNUC__
863#pragma GCC diagnostic push
864#pragma GCC diagnostic ignored "-Wattributes"
865#endif
866/// Sema - This implements semantic analysis and AST building for C.
867/// \nosubgrouping
868class Sema final : public SemaBase {
869#ifdef __GNUC__
870#pragma GCC diagnostic pop
871#endif
872 // Table of Contents
873 // -----------------
874 // 1. Semantic Analysis (Sema.cpp)
875 // 2. API Notes (SemaAPINotes.cpp)
876 // 3. C++ Access Control (SemaAccess.cpp)
877 // 4. Attributes (SemaAttr.cpp)
878 // 5. Availability Attribute Handling (SemaAvailability.cpp)
879 // 6. Bounds Safety (SemaBoundsSafety.cpp)
880 // 7. Casts (SemaCast.cpp)
881 // 8. Extra Semantic Checking (SemaChecking.cpp)
882 // 9. C++ Coroutines (SemaCoroutine.cpp)
883 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
884 // 11. Declarations (SemaDecl.cpp)
885 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
886 // 13. C++ Declarations (SemaDeclCXX.cpp)
887 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
888 // 15. Expressions (SemaExpr.cpp)
889 // 16. C++ Expressions (SemaExprCXX.cpp)
890 // 17. Member Access Expressions (SemaExprMember.cpp)
891 // 18. Initializers (SemaInit.cpp)
892 // 19. C++ Lambda Expressions (SemaLambda.cpp)
893 // 20. Name Lookup (SemaLookup.cpp)
894 // 21. Modules (SemaModule.cpp)
895 // 22. C++ Overloading (SemaOverload.cpp)
896 // 23. Statements (SemaStmt.cpp)
897 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
898 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
899 // 26. C++ Templates (SemaTemplate.cpp)
900 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
901 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
902 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
903 // 30. C++ Template Declaration Instantiation
904 // (SemaTemplateInstantiateDecl.cpp)
905 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
906 // 32. Constraints and Concepts (SemaConcept.cpp)
907 // 33. Types (SemaType.cpp)
908 // 34. FixIt Helpers (SemaFixItUtils.cpp)
909 // 35. Function Effects (SemaFunctionEffects.cpp)
910
911 /// \name Semantic Analysis
912 /// Implementations are in Sema.cpp
913 ///@{
914
915public:
916 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
917 TranslationUnitKind TUKind = TU_Complete,
918 CodeCompleteConsumer *CompletionConsumer = nullptr);
919 ~Sema();
920
921 /// Perform initialization that occurs after the parser has been
922 /// initialized but before it parses anything.
923 void Initialize();
924
925 /// This virtual key function only exists to limit the emission of debug info
926 /// describing the Sema class. GCC and Clang only emit debug info for a class
927 /// with a vtable when the vtable is emitted. Sema is final and not
928 /// polymorphic, but the debug info size savings are so significant that it is
929 /// worth adding a vtable just to take advantage of this optimization.
930 LLVM_DECLARE_VIRTUAL_ANCHOR_FUNCTION();
931
932 const LangOptions &getLangOpts() const { return LangOpts; }
933 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
934 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
935
936 DiagnosticsEngine &getDiagnostics() const { return Diags; }
937 SourceManager &getSourceManager() const { return SourceMgr; }
938 Preprocessor &getPreprocessor() const { return PP; }
939 ASTContext &getASTContext() const { return Context; }
940 ASTConsumer &getASTConsumer() const { return Consumer; }
941 ASTMutationListener *getASTMutationListener() const;
942 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
943
944 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
945 StringRef Platform);
946 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
947
948 /// Registers an external source. If an external source already exists,
949 /// creates a multiplex external source and appends to it.
950 ///
951 ///\param[in] E - A non-null external sema source.
952 ///
953 void addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E);
954
955 /// Print out statistics about the semantic analysis.
956 void PrintStats() const;
957
958 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
959 /// guaranteed). Produces a warning if we're low on stack space and allocates
960 /// more in that case. Use this in code that may recurse deeply (for example,
961 /// in template instantiation) to avoid stack overflow.
962 void runWithSufficientStackSpace(SourceLocation Loc,
963 llvm::function_ref<void()> Fn);
964
965 /// Returns default addr space for method qualifiers.
966 LangAS getDefaultCXXMethodAddrSpace() const;
967
968 /// Load weak undeclared identifiers from the external source.
969 void LoadExternalWeakUndeclaredIdentifiers();
970
971 /// Load #pragma redefine_extname'd undeclared identifiers from the external
972 /// source.
973 void LoadExternalExtnameUndeclaredIdentifiers();
974
975 /// Determine if VD, which must be a variable or function, is an external
976 /// symbol that nonetheless can't be referenced from outside this translation
977 /// unit because its type has no linkage and it's not extern "C".
978 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
979
980 /// Determines whether the given source location is in the main file
981 /// and we're in a context where we should warn about unused entities.
982 bool isMainFileLoc(SourceLocation Loc) const;
983
984 /// Obtain a sorted list of functions that are undefined but ODR-used.
985 void getUndefinedButUsed(
986 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
987
988 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
989 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
990 /// Retrieves list of suspicious delete-expressions that will be checked at
991 /// the end of translation unit.
992 const llvm::MapVector<FieldDecl *, DeleteLocs> &
993 getMismatchingDeleteExpressions() const;
994
995 /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
996 /// This is closely coupled to the SemaDiagnosticBuilder class and
997 /// should not be used elsewhere.
998 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
999
1000 void addImplicitTypedef(StringRef Name, QualType T);
1001
1002 /// Whether uncompilable error has occurred. This includes error happens
1003 /// in deferred diagnostics.
1004 bool hasUncompilableErrorOccurred() const;
1005
1006 /// Looks through the macro-expansion chain for the given
1007 /// location, looking for a macro expansion with the given name.
1008 /// If one is found, returns true and sets the location to that
1009 /// expansion loc.
1010 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1011
1012 /// Calls \c Lexer::getLocForEndOfToken()
1013 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1014
1015 /// Calls \c Lexer::findNextToken() to find the next token, and if the
1016 /// locations of both ends of the token can be resolved it return that
1017 /// range; Otherwise it returns an invalid SourceRange.
1018 SourceRange getRangeForNextToken(
1019 SourceLocation Loc, bool IncludeMacros, bool IncludeComments,
1020 std::optional<tok::TokenKind> ExpectedToken = std::nullopt);
1021
1022 /// Retrieve the module loader associated with the preprocessor.
1023 ModuleLoader &getModuleLoader() const;
1024
1025 /// Invent a new identifier for parameters of abbreviated templates.
1026 IdentifierInfo *
1027 InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName,
1028 unsigned Index);
1029
1030 void emitAndClearUnusedLocalTypedefWarnings();
1031
1032 // Emit all deferred diagnostics.
1033 void emitDeferredDiags();
1034
1035 /// This is called before the very first declaration in the translation unit
1036 /// is parsed. Note that the ASTContext may have already injected some
1037 /// declarations.
1038 void ActOnStartOfTranslationUnit();
1039 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1040 /// translation unit when EOF is reached and all but the top-level scope is
1041 /// popped.
1042 void ActOnEndOfTranslationUnit();
1043 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1044
1045 /// Determines the active Scope associated with the given declaration
1046 /// context.
1047 ///
1048 /// This routine maps a declaration context to the active Scope object that
1049 /// represents that declaration context in the parser. It is typically used
1050 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1051 /// declarations) that injects a name for name-lookup purposes and, therefore,
1052 /// must update the Scope.
1053 ///
1054 /// \returns The scope corresponding to the given declaraion context, or NULL
1055 /// if no such scope is open.
1056 Scope *getScopeForContext(DeclContext *Ctx);
1057
1058 void PushFunctionScope();
1059 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1060 sema::LambdaScopeInfo *PushLambdaScope();
1061
1062 /// This is used to inform Sema what the current TemplateParameterDepth
1063 /// is during Parsing. Currently it is used to pass on the depth
1064 /// when parsing generic lambda 'auto' parameters.
1065 void RecordParsingTemplateParameterDepth(unsigned Depth);
1066
1067 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1068 RecordDecl *RD, CapturedRegionKind K,
1069 unsigned OpenMPCaptureLevel = 0);
1070
1071 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1072 /// time after they've been popped.
1073 class PoppedFunctionScopeDeleter {
1074 Sema *Self;
1075
1076 public:
1077 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1078 void operator()(sema::FunctionScopeInfo *Scope) const;
1079 };
1080
1081 using PoppedFunctionScopePtr =
1082 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1083
1084 /// Pop a function (or block or lambda or captured region) scope from the
1085 /// stack.
1086 ///
1087 /// \param WP The warning policy to use for CFG-based warnings, or null if
1088 /// such warnings should not be produced.
1089 /// \param D The declaration corresponding to this function scope, if
1090 /// producing CFG-based warnings.
1091 /// \param BlockType The type of the block expression, if D is a BlockDecl.
1092 PoppedFunctionScopePtr
1093 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1094 Decl *D = nullptr, QualType BlockType = QualType());
1095
1096 sema::FunctionScopeInfo *getEnclosingFunction() const;
1097
1098 void setFunctionHasBranchIntoScope();
1099 void setFunctionHasBranchProtectedScope();
1100 void setFunctionHasIndirectGoto();
1101 void setFunctionHasMustTail();
1102
1103 void PushCompoundScope(bool IsStmtExpr);
1104 void PopCompoundScope();
1105
1106 /// Determine whether any errors occurred within this function/method/
1107 /// block.
1108 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1109
1110 /// Retrieve the current block, if any.
1111 sema::BlockScopeInfo *getCurBlock();
1112
1113 /// Get the innermost lambda or block enclosing the current location, if any.
1114 /// This looks through intervening non-lambda, non-block scopes such as local
1115 /// functions.
1116 sema::CapturingScopeInfo *getEnclosingLambdaOrBlock() const;
1117
1118 /// Retrieve the current lambda scope info, if any.
1119 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1120 /// lambda scope info ignoring all inner capturing scopes that are not
1121 /// lambda scopes.
1122 sema::LambdaScopeInfo *
1123 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1124
1125 /// Retrieve the current generic lambda info, if any.
1126 sema::LambdaScopeInfo *getCurGenericLambda();
1127
1128 /// Retrieve the current captured region, if any.
1129 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1130
1131 void ActOnComment(SourceRange Comment);
1132
1133 /// Retrieve the parser's current scope.
1134 ///
1135 /// This routine must only be used when it is certain that semantic analysis
1136 /// and the parser are in precisely the same context, which is not the case
1137 /// when, e.g., we are performing any kind of template instantiation.
1138 /// Therefore, the only safe places to use this scope are in the parser
1139 /// itself and in routines directly invoked from the parser and *never* from
1140 /// template substitution or instantiation.
1141 Scope *getCurScope() const { return CurScope; }
1142
1143 IdentifierInfo *getSuperIdentifier() const;
1144
1145 DeclContext *getCurLexicalContext() const {
1146 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
1147 }
1148
1149 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1150 const FunctionDecl *FD = nullptr);
1151 SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
1152 const PartialDiagnostic &PD,
1153 const FunctionDecl *FD = nullptr) {
1154 return targetDiag(Loc, DiagID: PD.getDiagID(), FD) << PD;
1155 }
1156
1157 /// Check if the type is allowed to be used for the current target.
1158 void checkTypeSupport(QualType Ty, SourceLocation Loc,
1159 ValueDecl *D = nullptr);
1160
1161 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1162 /// cast. If there is already an implicit cast, merge into the existing one.
1163 /// If isLvalue, the result of the cast is an lvalue.
1164 ExprResult ImpCastExprToType(
1165 Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue,
1166 const CXXCastPath *BasePath = nullptr,
1167 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
1168
1169 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1170 /// to the conversion from scalar type ScalarTy to the Boolean type.
1171 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
1172
1173 /// If \p AllowLambda is true, treat lambda as function.
1174 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1175
1176 /// Returns a pointer to the innermost enclosing function, or nullptr if the
1177 /// current context is not inside a function. If \p AllowLambda is true,
1178 /// this can return the call operator of an enclosing lambda, otherwise
1179 /// lambdas are skipped when looking for an enclosing function.
1180 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1181
1182 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1183 /// the method decl for the method being parsed. If we're currently
1184 /// in a 'block', this returns the containing context.
1185 ObjCMethodDecl *getCurMethodDecl();
1186
1187 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1188 /// or C function we're in, otherwise return null. If we're currently
1189 /// in a 'block', this returns the containing context.
1190 NamedDecl *getCurFunctionOrMethodDecl() const;
1191
1192 /// Warn if we're implicitly casting from a _Nullable pointer type to a
1193 /// _Nonnull one.
1194 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
1195 SourceLocation Loc);
1196
1197 /// Warn when implicitly casting 0 to nullptr.
1198 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1199
1200 /// Warn when implicitly changing function effects.
1201 void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType,
1202 SourceLocation Loc);
1203
1204 /// makeUnavailableInSystemHeader - There is an error in the current
1205 /// context. If we're still in a system header, and we can plausibly
1206 /// make the relevant declaration unavailable instead of erroring, do
1207 /// so and return true.
1208 bool makeUnavailableInSystemHeader(SourceLocation loc,
1209 UnavailableAttr::ImplicitReason reason);
1210
1211 /// Retrieve a suitable printing policy for diagnostics.
1212 PrintingPolicy getPrintingPolicy() const {
1213 return getPrintingPolicy(Ctx: Context, PP);
1214 }
1215
1216 /// Retrieve a suitable printing policy for diagnostics.
1217 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1218 const Preprocessor &PP);
1219
1220 /// Scope actions.
1221 void ActOnTranslationUnitScope(Scope *S);
1222
1223 /// Determine whether \param D is function like (function or function
1224 /// template) for parsing.
1225 bool isDeclaratorFunctionLike(Declarator &D);
1226
1227 /// The maximum alignment, same as in llvm::Value. We duplicate them here
1228 /// because that allows us not to duplicate the constants in clang code,
1229 /// which we must to since we can't directly use the llvm constants.
1230 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1231 ///
1232 /// This is the greatest alignment value supported by load, store, and alloca
1233 /// instructions, and global values.
1234 static const unsigned MaxAlignmentExponent = 32;
1235 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1236
1237 /// Flag indicating whether or not to collect detailed statistics.
1238 bool CollectStats;
1239
1240 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1241
1242 /// Stack containing information about each of the nested
1243 /// function, block, and method scopes that are currently active.
1244 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
1245
1246 /// The index of the first FunctionScope that corresponds to the current
1247 /// context.
1248 unsigned FunctionScopesStart = 0;
1249
1250 /// Track the number of currently active capturing scopes.
1251 unsigned CapturingFunctionScopes = 0;
1252
1253 llvm::BumpPtrAllocator BumpAlloc;
1254
1255 /// The kind of translation unit we are processing.
1256 ///
1257 /// When we're processing a complete translation unit, Sema will perform
1258 /// end-of-translation-unit semantic tasks (such as creating
1259 /// initializers for tentative definitions in C) once parsing has
1260 /// completed. Modules and precompiled headers perform different kinds of
1261 /// checks.
1262 const TranslationUnitKind TUKind;
1263
1264 /// Translation Unit Scope - useful to Objective-C actions that need
1265 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1266 /// For example, user-defined classes, built-in "id" type, etc.
1267 Scope *TUScope;
1268
1269 void incrementMSManglingNumber() const {
1270 return CurScope->incrementMSManglingNumber();
1271 }
1272
1273 /// Try to recover by turning the given expression into a
1274 /// call. Returns true if recovery was attempted or an error was
1275 /// emitted; this may also leave the ExprResult invalid.
1276 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1277 bool ForceComplain = false,
1278 bool (*IsPlausibleResult)(QualType) = nullptr);
1279
1280 // Adds implicit lifetime bound attribute for implicit this to its
1281 // TypeSourceInfo.
1282 void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD);
1283
1284 /// Figure out if an expression could be turned into a call.
1285 ///
1286 /// Use this when trying to recover from an error where the programmer may
1287 /// have written just the name of a function instead of actually calling it.
1288 ///
1289 /// \param E - The expression to examine.
1290 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1291 /// with no arguments, this parameter is set to the type returned by such a
1292 /// call; otherwise, it is set to an empty QualType.
1293 /// \param OverloadSet - If the expression is an overloaded function
1294 /// name, this parameter is populated with the decls of the various
1295 /// overloads.
1296 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1297 UnresolvedSetImpl &NonTemplateOverloads);
1298
1299 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
1300 typedef OpaquePtr<TemplateName> TemplateTy;
1301 typedef OpaquePtr<QualType> TypeTy;
1302
1303 OpenCLOptions OpenCLFeatures;
1304 FPOptions CurFPFeatures;
1305
1306 const LangOptions &LangOpts;
1307 Preprocessor &PP;
1308 ASTContext &Context;
1309 ASTConsumer &Consumer;
1310 DiagnosticsEngine &Diags;
1311 SourceManager &SourceMgr;
1312 api_notes::APINotesManager APINotes;
1313
1314 /// A RAII object to enter scope of a compound statement.
1315 class CompoundScopeRAII {
1316 public:
1317 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1318 S.ActOnStartOfCompoundStmt(IsStmtExpr);
1319 }
1320
1321 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1322 CompoundScopeRAII(const CompoundScopeRAII &) = delete;
1323 CompoundScopeRAII &operator=(const CompoundScopeRAII &) = delete;
1324
1325 private:
1326 Sema &S;
1327 };
1328
1329 /// An RAII helper that pops function a function scope on exit.
1330 struct FunctionScopeRAII {
1331 Sema &S;
1332 bool Active;
1333 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
1334 ~FunctionScopeRAII() {
1335 if (Active)
1336 S.PopFunctionScopeInfo();
1337 }
1338 void disable() { Active = false; }
1339 };
1340
1341 sema::FunctionScopeInfo *getCurFunction() const {
1342 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1343 }
1344
1345 /// Worker object for performing CFG-based warnings.
1346 sema::AnalysisBasedWarnings AnalysisWarnings;
1347 threadSafety::BeforeSet *ThreadSafetyDeclCache;
1348
1349 /// Callback to the parser to parse templated functions when needed.
1350 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1351 LateTemplateParserCB *LateTemplateParser;
1352 void *OpaqueParser;
1353
1354 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
1355 LateTemplateParser = LTP;
1356 OpaqueParser = P;
1357 }
1358
1359 /// Callback to the parser to parse a type expressed as a string.
1360 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1361 ParseTypeFromStringCallback;
1362
1363 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1364 /// This is used as part of a hack to omit that class from ADL results.
1365 DeclarationName VAListTagName;
1366
1367 /// Is the last error level diagnostic immediate. This is used to determined
1368 /// whether the next info diagnostic should be immediate.
1369 bool IsLastErrorImmediate = true;
1370
1371 /// Track if we're currently analyzing overflow behavior types in assignment
1372 /// context.
1373 bool InOverflowBehaviorAssignmentContext = false;
1374
1375 class DelayedDiagnostics;
1376
1377 class DelayedDiagnosticsState {
1378 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1379 friend class Sema::DelayedDiagnostics;
1380 };
1381 typedef DelayedDiagnosticsState ParsingDeclState;
1382 typedef DelayedDiagnosticsState ProcessingContextState;
1383
1384 /// A class which encapsulates the logic for delaying diagnostics
1385 /// during parsing and other processing.
1386 class DelayedDiagnostics {
1387 /// The current pool of diagnostics into which delayed
1388 /// diagnostics should go.
1389 sema::DelayedDiagnosticPool *CurPool = nullptr;
1390
1391 public:
1392 DelayedDiagnostics() = default;
1393
1394 /// Adds a delayed diagnostic.
1395 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1396
1397 /// Determines whether diagnostics should be delayed.
1398 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1399
1400 /// Returns the current delayed-diagnostics pool.
1401 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1402
1403 /// Enter a new scope. Access and deprecation diagnostics will be
1404 /// collected in this pool.
1405 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
1406 DelayedDiagnosticsState state;
1407 state.SavedPool = CurPool;
1408 CurPool = &pool;
1409 return state;
1410 }
1411
1412 /// Leave a delayed-diagnostic state that was previously pushed.
1413 /// Do not emit any of the diagnostics. This is performed as part
1414 /// of the bookkeeping of popping a pool "properly".
1415 void popWithoutEmitting(DelayedDiagnosticsState state) {
1416 CurPool = state.SavedPool;
1417 }
1418
1419 /// Enter a new scope where access and deprecation diagnostics are
1420 /// not delayed.
1421 DelayedDiagnosticsState pushUndelayed() {
1422 DelayedDiagnosticsState state;
1423 state.SavedPool = CurPool;
1424 CurPool = nullptr;
1425 return state;
1426 }
1427
1428 /// Undo a previous pushUndelayed().
1429 void popUndelayed(DelayedDiagnosticsState state) {
1430 assert(CurPool == nullptr);
1431 CurPool = state.SavedPool;
1432 }
1433 } DelayedDiagnostics;
1434
1435 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
1436 return DelayedDiagnostics.push(pool);
1437 }
1438
1439 /// Diagnostics that are emitted only if we discover that the given function
1440 /// must be codegen'ed. Because handling these correctly adds overhead to
1441 /// compilation, this is currently only used for offload languages like CUDA,
1442 /// OpenMP, and SYCL.
1443 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1444
1445 /// CurContext - This is the current declaration context of parsing.
1446 DeclContext *CurContext;
1447
1448 SemaAMDGPU &AMDGPU() {
1449 assert(AMDGPUPtr);
1450 return *AMDGPUPtr;
1451 }
1452
1453 SemaARM &ARM() {
1454 assert(ARMPtr);
1455 return *ARMPtr;
1456 }
1457
1458 SemaAVR &AVR() {
1459 assert(AVRPtr);
1460 return *AVRPtr;
1461 }
1462
1463 SemaBPF &BPF() {
1464 assert(BPFPtr);
1465 return *BPFPtr;
1466 }
1467
1468 SemaCodeCompletion &CodeCompletion() {
1469 assert(CodeCompletionPtr);
1470 return *CodeCompletionPtr;
1471 }
1472
1473 SemaCUDA &CUDA() {
1474 assert(CUDAPtr);
1475 return *CUDAPtr;
1476 }
1477
1478 SemaDirectX &DirectX() {
1479 assert(DirectXPtr);
1480 return *DirectXPtr;
1481 }
1482
1483 SemaHLSL &HLSL() {
1484 assert(HLSLPtr);
1485 return *HLSLPtr;
1486 }
1487
1488 SemaHexagon &Hexagon() {
1489 assert(HexagonPtr);
1490 return *HexagonPtr;
1491 }
1492
1493 SemaLoongArch &LoongArch() {
1494 assert(LoongArchPtr);
1495 return *LoongArchPtr;
1496 }
1497
1498 SemaM68k &M68k() {
1499 assert(M68kPtr);
1500 return *M68kPtr;
1501 }
1502
1503 SemaMIPS &MIPS() {
1504 assert(MIPSPtr);
1505 return *MIPSPtr;
1506 }
1507
1508 SemaMSP430 &MSP430() {
1509 assert(MSP430Ptr);
1510 return *MSP430Ptr;
1511 }
1512
1513 SemaNVPTX &NVPTX() {
1514 assert(NVPTXPtr);
1515 return *NVPTXPtr;
1516 }
1517
1518 SemaObjC &ObjC() {
1519 assert(ObjCPtr);
1520 return *ObjCPtr;
1521 }
1522
1523 SemaOpenACC &OpenACC() {
1524 assert(OpenACCPtr);
1525 return *OpenACCPtr;
1526 }
1527
1528 SemaOpenCL &OpenCL() {
1529 assert(OpenCLPtr);
1530 return *OpenCLPtr;
1531 }
1532
1533 SemaOpenMP &OpenMP() {
1534 assert(OpenMPPtr && "SemaOpenMP is dead");
1535 return *OpenMPPtr;
1536 }
1537
1538 SemaPPC &PPC() {
1539 assert(PPCPtr);
1540 return *PPCPtr;
1541 }
1542
1543 SemaPseudoObject &PseudoObject() {
1544 assert(PseudoObjectPtr);
1545 return *PseudoObjectPtr;
1546 }
1547
1548 SemaRISCV &RISCV() {
1549 assert(RISCVPtr);
1550 return *RISCVPtr;
1551 }
1552
1553 SemaSPIRV &SPIRV() {
1554 assert(SPIRVPtr);
1555 return *SPIRVPtr;
1556 }
1557
1558 SemaSYCL &SYCL() {
1559 assert(SYCLPtr);
1560 return *SYCLPtr;
1561 }
1562
1563 SemaSwift &Swift() {
1564 assert(SwiftPtr);
1565 return *SwiftPtr;
1566 }
1567
1568 SemaSystemZ &SystemZ() {
1569 assert(SystemZPtr);
1570 return *SystemZPtr;
1571 }
1572
1573 SemaWasm &Wasm() {
1574 assert(WasmPtr);
1575 return *WasmPtr;
1576 }
1577
1578 SemaX86 &X86() {
1579 assert(X86Ptr);
1580 return *X86Ptr;
1581 }
1582
1583 /// Source of additional semantic information.
1584 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
1585
1586protected:
1587 friend class Parser;
1588 friend class InitializationSequence;
1589 friend class ASTReader;
1590 friend class ASTDeclReader;
1591 friend class ASTWriter;
1592
1593private:
1594 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1595 bool WarnedDarwinSDKInfoMissing = false;
1596
1597 StackExhaustionHandler StackHandler;
1598
1599 Sema(const Sema &) = delete;
1600 void operator=(const Sema &) = delete;
1601
1602 /// The handler for the FileChanged preprocessor events.
1603 ///
1604 /// Used for diagnostics that implement custom semantic analysis for #include
1605 /// directives, like -Wpragma-pack.
1606 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1607
1608 /// The parser's current scope.
1609 ///
1610 /// The parser maintains this state here.
1611 Scope *CurScope;
1612
1613 mutable IdentifierInfo *Ident_super;
1614
1615 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1616 std::unique_ptr<SemaARM> ARMPtr;
1617 std::unique_ptr<SemaAVR> AVRPtr;
1618 std::unique_ptr<SemaBPF> BPFPtr;
1619 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1620 std::unique_ptr<SemaCUDA> CUDAPtr;
1621 std::unique_ptr<SemaDirectX> DirectXPtr;
1622 std::unique_ptr<SemaHLSL> HLSLPtr;
1623 std::unique_ptr<SemaHexagon> HexagonPtr;
1624 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1625 std::unique_ptr<SemaM68k> M68kPtr;
1626 std::unique_ptr<SemaMIPS> MIPSPtr;
1627 std::unique_ptr<SemaMSP430> MSP430Ptr;
1628 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1629 std::unique_ptr<SemaObjC> ObjCPtr;
1630 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1631 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1632 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1633 std::unique_ptr<SemaPPC> PPCPtr;
1634 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1635 std::unique_ptr<SemaRISCV> RISCVPtr;
1636 std::unique_ptr<SemaSPIRV> SPIRVPtr;
1637 std::unique_ptr<SemaSYCL> SYCLPtr;
1638 std::unique_ptr<SemaSwift> SwiftPtr;
1639 std::unique_ptr<SemaSystemZ> SystemZPtr;
1640 std::unique_ptr<SemaWasm> WasmPtr;
1641 std::unique_ptr<SemaX86> X86Ptr;
1642
1643 ///@}
1644
1645 //
1646 //
1647 // -------------------------------------------------------------------------
1648 //
1649 //
1650
1651 /// \name API Notes
1652 /// Implementations are in SemaAPINotes.cpp
1653 ///@{
1654
1655public:
1656 /// Map any API notes provided for this declaration to attributes on the
1657 /// declaration.
1658 ///
1659 /// Triggered by declaration-attribute processing.
1660 void ProcessAPINotes(Decl *D);
1661 /// Apply the 'Nullability:' annotation to the specified declaration
1662 void ApplyNullability(Decl *D, NullabilityKind Nullability);
1663 /// Apply the 'Type:' annotation to the specified declaration
1664 void ApplyAPINotesType(Decl *D, StringRef TypeString);
1665
1666 /// Whether APINotes should be gathered for all applicable Swift language
1667 /// versions, without being applied. Leaving clients of the current module
1668 /// to select and apply the correct version.
1669 bool captureSwiftVersionIndependentAPINotes() {
1670 return APINotes.captureVersionIndependentSwift();
1671 }
1672 ///@}
1673
1674 //
1675 //
1676 // -------------------------------------------------------------------------
1677 //
1678 //
1679
1680 /// \name C++ Access Control
1681 /// Implementations are in SemaAccess.cpp
1682 ///@{
1683
1684public:
1685 enum AccessResult {
1686 AR_accessible,
1687 AR_inaccessible,
1688 AR_dependent,
1689 AR_delayed
1690 };
1691
1692 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1693 /// Returns true on error (when the previous member decl access specifier
1694 /// is different from the new member decl access specifier).
1695 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1696 NamedDecl *PrevMemberDecl,
1697 AccessSpecifier LexicalAS);
1698
1699 /// Perform access-control checking on a previously-unresolved member
1700 /// access which has now been resolved to a member.
1701 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
1702 DeclAccessPair FoundDecl);
1703 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
1704 DeclAccessPair FoundDecl);
1705
1706 /// Checks access to an overloaded operator new or delete.
1707 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
1708 SourceRange PlacementRange,
1709 CXXRecordDecl *NamingClass,
1710 DeclAccessPair FoundDecl,
1711 bool Diagnose = true);
1712
1713 /// Checks access to a constructor.
1714 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1715 DeclAccessPair FoundDecl,
1716 const InitializedEntity &Entity,
1717 bool IsCopyBindingRefToTemp = false);
1718
1719 /// Checks access to a constructor.
1720 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1721 DeclAccessPair FoundDecl,
1722 const InitializedEntity &Entity,
1723 const PartialDiagnostic &PDiag);
1724 AccessResult CheckDestructorAccess(SourceLocation Loc,
1725 CXXDestructorDecl *Dtor,
1726 const PartialDiagnostic &PDiag,
1727 QualType objectType = QualType());
1728
1729 /// Checks access to the target of a friend declaration.
1730 AccessResult CheckFriendAccess(NamedDecl *D);
1731
1732 /// Checks access to a member.
1733 AccessResult CheckMemberAccess(SourceLocation UseLoc,
1734 CXXRecordDecl *NamingClass,
1735 DeclAccessPair Found);
1736
1737 /// Checks implicit access to a member in a structured binding.
1738 AccessResult
1739 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
1740 CXXRecordDecl *DecomposedClass,
1741 DeclAccessPair Field);
1742 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1743 const SourceRange &,
1744 DeclAccessPair FoundDecl);
1745
1746 /// Checks access to an overloaded member operator, including
1747 /// conversion operators.
1748 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1749 Expr *ArgExpr,
1750 DeclAccessPair FoundDecl);
1751 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1752 ArrayRef<Expr *> ArgExprs,
1753 DeclAccessPair FoundDecl);
1754 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
1755 DeclAccessPair FoundDecl);
1756
1757 /// Checks access for a hierarchy conversion.
1758 ///
1759 /// \param ForceCheck true if this check should be performed even if access
1760 /// control is disabled; some things rely on this for semantics
1761 /// \param ForceUnprivileged true if this check should proceed as if the
1762 /// context had no special privileges
1763 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base,
1764 QualType Derived, const CXXBasePath &Path,
1765 unsigned DiagID, bool ForceCheck = false,
1766 bool ForceUnprivileged = false);
1767
1768 AccessResult CheckBaseClassAccess(
1769 SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1770 const CXXBasePath &Path, unsigned DiagID,
1771 llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1772 bool ForceCheck = false, bool ForceUnprivileged = false);
1773
1774 /// Checks access to all the declarations in the given result set.
1775 void CheckLookupAccess(const LookupResult &R);
1776
1777 /// Checks access to Target from the given class. The check will take access
1778 /// specifiers into account, but no member access expressions and such.
1779 ///
1780 /// \param Target the declaration to check if it can be accessed
1781 /// \param NamingClass the class in which the lookup was started.
1782 /// \param BaseType type of the left side of member access expression.
1783 /// \p BaseType and \p NamingClass are used for C++ access control.
1784 /// Depending on the lookup case, they should be set to the following:
1785 /// - lhs.target (member access without a qualifier):
1786 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1787 /// - lhs.X::target (member access with a qualifier):
1788 /// BaseType is the type of 'lhs', NamingClass is 'X'
1789 /// - X::target (qualified lookup without member access):
1790 /// BaseType is null, NamingClass is 'X'.
1791 /// - target (unqualified lookup).
1792 /// BaseType is null, NamingClass is the parent class of 'target'.
1793 /// \return true if the Target is accessible from the Class, false otherwise.
1794 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1795 QualType BaseType);
1796
1797 /// Is the given member accessible for the purposes of deciding whether to
1798 /// define a special member function as deleted?
1799 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1800 DeclAccessPair Found, QualType ObjectType,
1801 SourceLocation Loc,
1802 const PartialDiagnostic &Diag);
1803 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1804 DeclAccessPair Found,
1805 QualType ObjectType) {
1806 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1807 Loc: SourceLocation(), Diag: PDiag());
1808 }
1809
1810 void HandleDependentAccessCheck(
1811 const DependentDiagnostic &DD,
1812 const MultiLevelTemplateArgumentList &TemplateArgs);
1813 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
1814
1815 ///@}
1816
1817 //
1818 //
1819 // -------------------------------------------------------------------------
1820 //
1821 //
1822
1823 /// \name Attributes
1824 /// Implementations are in SemaAttr.cpp
1825 ///@{
1826
1827public:
1828 /// Controls member pointer representation format under the MS ABI.
1829 LangOptions::PragmaMSPointersToMembersKind
1830 MSPointerToMemberRepresentationMethod;
1831
1832 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1833
1834 /// Source location for newly created implicit MSInheritanceAttrs
1835 SourceLocation ImplicitMSInheritanceAttrLoc;
1836
1837 struct PragmaClangSection {
1838 std::string SectionName;
1839 bool Valid = false;
1840 SourceLocation PragmaLocation;
1841 };
1842
1843 PragmaClangSection PragmaClangBSSSection;
1844 PragmaClangSection PragmaClangDataSection;
1845 PragmaClangSection PragmaClangRodataSection;
1846 PragmaClangSection PragmaClangRelroSection;
1847 PragmaClangSection PragmaClangTextSection;
1848
1849 enum PragmaMsStackAction {
1850 PSK_Reset = 0x0, // #pragma ()
1851 PSK_Set = 0x1, // #pragma (value)
1852 PSK_Push = 0x2, // #pragma (push[, id])
1853 PSK_Pop = 0x4, // #pragma (pop[, id])
1854 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1855 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1856 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1857 };
1858
1859 struct PragmaPackInfo {
1860 PragmaMsStackAction Action;
1861 StringRef SlotLabel;
1862 Token Alignment;
1863 };
1864
1865 // #pragma pack and align.
1866 class AlignPackInfo {
1867 public:
1868 // `Native` represents default align mode, which may vary based on the
1869 // platform.
1870 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1871
1872 // #pragma pack info constructor
1873 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1874 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1875 assert(Num == PackNumber && "The pack number has been truncated.");
1876 }
1877
1878 // #pragma align info constructor
1879 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
1880 : PackAttr(false), AlignMode(M),
1881 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1882
1883 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1884
1885 AlignPackInfo() : AlignPackInfo(Native, false) {}
1886
1887 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1888 // integer encoding for it. This should only be passed to
1889 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1890 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
1891 std::uint32_t Encoding{};
1892 if (Info.IsXLStack())
1893 Encoding |= IsXLMask;
1894
1895 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1896
1897 if (Info.IsPackAttr())
1898 Encoding |= PackAttrMask;
1899
1900 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1901
1902 return Encoding;
1903 }
1904
1905 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1906 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1907 AlignPackInfo::Mode M =
1908 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1909 int PackNumber = (Encoding & PackNumMask) >> 4;
1910
1911 if (Encoding & PackAttrMask)
1912 return AlignPackInfo(M, PackNumber, IsXL);
1913
1914 return AlignPackInfo(M, IsXL);
1915 }
1916
1917 bool IsPackAttr() const { return PackAttr; }
1918
1919 bool IsAlignAttr() const { return !PackAttr; }
1920
1921 Mode getAlignMode() const { return AlignMode; }
1922
1923 unsigned getPackNumber() const { return PackNumber; }
1924
1925 bool IsPackSet() const {
1926 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1927 // attriute on a decl.
1928 return PackNumber != UninitPackVal && PackNumber != 0;
1929 }
1930
1931 bool IsXLStack() const { return XLStack; }
1932
1933 bool operator==(const AlignPackInfo &Info) const {
1934 return std::tie(args: AlignMode, args: PackNumber, args: PackAttr, args: XLStack) ==
1935 std::tie(args: Info.AlignMode, args: Info.PackNumber, args: Info.PackAttr,
1936 args: Info.XLStack);
1937 }
1938
1939 bool operator!=(const AlignPackInfo &Info) const {
1940 return !(*this == Info);
1941 }
1942
1943 private:
1944 /// \brief True if this is a pragma pack attribute,
1945 /// not a pragma align attribute.
1946 bool PackAttr;
1947
1948 /// \brief The alignment mode that is in effect.
1949 Mode AlignMode;
1950
1951 /// \brief The pack number of the stack.
1952 unsigned char PackNumber;
1953
1954 /// \brief True if it is a XL #pragma align/pack stack.
1955 bool XLStack;
1956
1957 /// \brief Uninitialized pack value.
1958 static constexpr unsigned char UninitPackVal = -1;
1959
1960 // Masks to encode and decode an AlignPackInfo.
1961 static constexpr uint32_t IsXLMask{0x0000'0001};
1962 static constexpr uint32_t AlignModeMask{0x0000'0006};
1963 static constexpr uint32_t PackAttrMask{0x00000'0008};
1964 static constexpr uint32_t PackNumMask{0x0000'01F0};
1965 };
1966
1967 template <typename ValueType> struct PragmaStack {
1968 struct Slot {
1969 llvm::StringRef StackSlotLabel;
1970 ValueType Value;
1971 SourceLocation PragmaLocation;
1972 SourceLocation PragmaPushLocation;
1973 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
1974 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
1975 : StackSlotLabel(StackSlotLabel), Value(Value),
1976 PragmaLocation(PragmaLocation),
1977 PragmaPushLocation(PragmaPushLocation) {}
1978 };
1979
1980 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
1981 llvm::StringRef StackSlotLabel, ValueType Value) {
1982 if (Action == PSK_Reset) {
1983 CurrentValue = DefaultValue;
1984 CurrentPragmaLocation = PragmaLocation;
1985 return;
1986 }
1987 if (Action & PSK_Push)
1988 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
1989 PragmaLocation);
1990 else if (Action & PSK_Pop) {
1991 if (!StackSlotLabel.empty()) {
1992 // If we've got a label, try to find it and jump there.
1993 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
1994 return x.StackSlotLabel == StackSlotLabel;
1995 });
1996 // If we found the label so pop from there.
1997 if (I != Stack.rend()) {
1998 CurrentValue = I->Value;
1999 CurrentPragmaLocation = I->PragmaLocation;
2000 Stack.erase(std::prev(I.base()), Stack.end());
2001 }
2002 } else if (!Stack.empty()) {
2003 // We do not have a label, just pop the last entry.
2004 CurrentValue = Stack.back().Value;
2005 CurrentPragmaLocation = Stack.back().PragmaLocation;
2006 Stack.pop_back();
2007 }
2008 }
2009 if (Action & PSK_Set) {
2010 CurrentValue = Value;
2011 CurrentPragmaLocation = PragmaLocation;
2012 }
2013 }
2014
2015 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
2016 // method body to restore the stacks on exit, so it works like this:
2017 //
2018 // struct S {
2019 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
2020 // void Method {}
2021 // #pragma <name>(pop, InternalPragmaSlot)
2022 // };
2023 //
2024 // It works even with #pragma vtordisp, although MSVC doesn't support
2025 // #pragma vtordisp(push [, id], n)
2026 // syntax.
2027 //
2028 // Push / pop a named sentinel slot.
2029 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
2030 assert((Action == PSK_Push || Action == PSK_Pop) &&
2031 "Can only push / pop #pragma stack sentinels!");
2032 Act(PragmaLocation: CurrentPragmaLocation, Action, StackSlotLabel: Label, Value: CurrentValue);
2033 }
2034
2035 // Constructors.
2036 explicit PragmaStack(const ValueType &Default)
2037 : DefaultValue(Default), CurrentValue(Default) {}
2038
2039 bool hasValue() const { return CurrentValue != DefaultValue; }
2040
2041 SmallVector<Slot, 2> Stack;
2042 ValueType DefaultValue; // Value used for PSK_Reset action.
2043 ValueType CurrentValue;
2044 SourceLocation CurrentPragmaLocation;
2045 };
2046 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2047 // we shouldn't do so if they're in a module).
2048
2049 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2050 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
2051 ///
2052 /// 0: Suppress all vtordisps
2053 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2054 /// structors
2055 /// 2: Always insert vtordisps to support RTTI on partially constructed
2056 /// objects
2057 PragmaStack<MSVtorDispMode> VtorDispStack;
2058 PragmaStack<AlignPackInfo> AlignPackStack;
2059 // The current #pragma align/pack values and locations at each #include.
2060 struct AlignPackIncludeState {
2061 AlignPackInfo CurrentValue;
2062 SourceLocation CurrentPragmaLocation;
2063 bool HasNonDefaultValue, ShouldWarnOnInclude;
2064 };
2065 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
2066 // Segment #pragmas.
2067 PragmaStack<StringLiteral *> DataSegStack;
2068 PragmaStack<StringLiteral *> BSSSegStack;
2069 PragmaStack<StringLiteral *> ConstSegStack;
2070 PragmaStack<StringLiteral *> CodeSegStack;
2071
2072 // #pragma strict_gs_check.
2073 PragmaStack<bool> StrictGuardStackCheckStack;
2074
2075 // This stack tracks the current state of Sema.CurFPFeatures.
2076 PragmaStack<FPOptionsOverride> FpPragmaStack;
2077 FPOptionsOverride CurFPFeatureOverrides() {
2078 FPOptionsOverride result;
2079 if (!FpPragmaStack.hasValue()) {
2080 result = FPOptionsOverride();
2081 } else {
2082 result = FpPragmaStack.CurrentValue;
2083 }
2084 return result;
2085 }
2086
2087 enum PragmaSectionKind {
2088 PSK_DataSeg,
2089 PSK_BSSSeg,
2090 PSK_ConstSeg,
2091 PSK_CodeSeg,
2092 };
2093
2094 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2095 // Actions should be performed only if we enter / exit a C++ method body.
2096 class PragmaStackSentinelRAII {
2097 public:
2098 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2099 ~PragmaStackSentinelRAII();
2100 PragmaStackSentinelRAII(const PragmaStackSentinelRAII &) = delete;
2101 PragmaStackSentinelRAII &
2102 operator=(const PragmaStackSentinelRAII &) = delete;
2103
2104 private:
2105 Sema &S;
2106 StringRef SlotLabel;
2107 bool ShouldAct;
2108 };
2109
2110 /// Last section used with #pragma init_seg.
2111 StringLiteral *CurInitSeg;
2112 SourceLocation CurInitSegLoc;
2113
2114 /// Sections used with #pragma alloc_text.
2115 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2116
2117 /// VisContext - Manages the stack for \#pragma GCC visibility.
2118 void *VisContext; // Really a "PragmaVisStack*"
2119
2120 /// This an attribute introduced by \#pragma clang attribute.
2121 struct PragmaAttributeEntry {
2122 SourceLocation Loc;
2123 ParsedAttr *Attribute;
2124 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
2125 bool IsUsed;
2126 };
2127
2128 /// A push'd group of PragmaAttributeEntries.
2129 struct PragmaAttributeGroup {
2130 /// The location of the push attribute.
2131 SourceLocation Loc;
2132 /// The namespace of this push group.
2133 const IdentifierInfo *Namespace;
2134 SmallVector<PragmaAttributeEntry, 2> Entries;
2135 };
2136
2137 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
2138
2139 /// The declaration that is currently receiving an attribute from the
2140 /// #pragma attribute stack.
2141 const Decl *PragmaAttributeCurrentTargetDecl;
2142
2143 /// This represents the last location of a "#pragma clang optimize off"
2144 /// directive if such a directive has not been closed by an "on" yet. If
2145 /// optimizations are currently "on", this is set to an invalid location.
2146 SourceLocation OptimizeOffPragmaLocation;
2147
2148 /// Get the location for the currently active "\#pragma clang optimize
2149 /// off". If this location is invalid, then the state of the pragma is "on".
2150 SourceLocation getOptimizeOffPragmaLocation() const {
2151 return OptimizeOffPragmaLocation;
2152 }
2153
2154 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2155 /// whether the optimizations in the list passed to the pragma should be
2156 /// turned off or on. This boolean is true by default because command line
2157 /// options are honored when `#pragma optimize("", on)`.
2158 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2159 bool MSPragmaOptimizeIsOn = true;
2160
2161 /// Set of no-builtin functions listed by \#pragma function.
2162 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
2163
2164 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2165 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2166 void AddAlignmentAttributesForRecord(RecordDecl *RD);
2167
2168 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2169 void AddMsStructLayoutForRecord(RecordDecl *RD);
2170
2171 /// Add gsl::Pointer attribute to std::container::iterator
2172 /// \param ND The declaration that introduces the name
2173 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2174 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2175
2176 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2177 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
2178
2179 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2180 void inferLifetimeBoundAttribute(FunctionDecl *FD);
2181
2182 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2183 void inferLifetimeCaptureByAttribute(FunctionDecl *FD);
2184
2185 /// Add [[gsl::Pointer]] attributes for std:: types.
2186 void inferGslPointerAttribute(TypedefNameDecl *TD);
2187
2188 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2189 StringRef ParamName);
2190 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2191 // can be the name of a function parameter, we need to parse the function
2192 // declaration and rest of the parameters before processesing 'X'. Therefore
2193 // do this lazily instead of processing while parsing the annotation itself.
2194 void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD);
2195
2196 /// Add _Nullable attributes for std:: types.
2197 void inferNullableClassAttribute(CXXRecordDecl *CRD);
2198
2199 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2200 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
2201 PragmaClangSectionAction Action,
2202 PragmaClangSectionKind SecKind,
2203 StringRef SecName);
2204
2205 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2206 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
2207 SourceLocation PragmaLoc);
2208
2209 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2210 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2211 StringRef SlotLabel, Expr *Alignment);
2212
2213 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2214 /// (unless they are value dependent or type dependent). Returns false
2215 /// and emits a diagnostic if one or more of the arguments could not be
2216 /// folded into a constant.
2217 bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
2218 MutableArrayRef<Expr *> Args);
2219
2220 enum class PragmaAlignPackDiagnoseKind {
2221 NonDefaultStateAtInclude,
2222 ChangedStateAtExit
2223 };
2224
2225 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
2226 SourceLocation IncludeLoc);
2227 void DiagnoseUnterminatedPragmaAlignPack();
2228
2229 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2230 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
2231
2232 /// ActOnPragmaMSComment - Called on well formed
2233 /// \#pragma comment(kind, "arg").
2234 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
2235 StringRef Arg);
2236
2237 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2238 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2239 StringRef Value);
2240
2241 /// Are precise floating point semantics currently enabled?
2242 bool isPreciseFPEnabled() {
2243 return !CurFPFeatures.getAllowFPReassociate() &&
2244 !CurFPFeatures.getNoSignedZero() &&
2245 !CurFPFeatures.getAllowReciprocal() &&
2246 !CurFPFeatures.getAllowApproxFunc();
2247 }
2248
2249 void ActOnPragmaFPEvalMethod(SourceLocation Loc,
2250 LangOptions::FPEvalMethodKind Value);
2251
2252 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2253 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2254 PragmaFloatControlKind Value);
2255
2256 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2257 /// pointers_to_members(representation method[, general purpose
2258 /// representation]).
2259 void ActOnPragmaMSPointersToMembers(
2260 LangOptions::PragmaMSPointersToMembersKind Kind,
2261 SourceLocation PragmaLoc);
2262
2263 /// Called on well formed \#pragma vtordisp().
2264 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2265 SourceLocation PragmaLoc, MSVtorDispMode Value);
2266
2267 bool UnifySection(StringRef SectionName, int SectionFlags,
2268 NamedDecl *TheDecl);
2269 bool UnifySection(StringRef SectionName, int SectionFlags,
2270 SourceLocation PragmaSectionLocation);
2271
2272 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2273 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2274 PragmaMsStackAction Action,
2275 llvm::StringRef StackSlotLabel,
2276 StringLiteral *SegmentName, llvm::StringRef PragmaName);
2277
2278 /// Called on well formed \#pragma section().
2279 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2280 StringLiteral *SegmentName);
2281
2282 /// Called on well-formed \#pragma init_seg().
2283 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2284 StringLiteral *SegmentName);
2285
2286 /// Called on well-formed \#pragma alloc_text().
2287 void ActOnPragmaMSAllocText(
2288 SourceLocation PragmaLocation, StringRef Section,
2289 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2290 &Functions);
2291
2292 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2293 /// strict_gs_check.
2294 void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
2295 PragmaMsStackAction Action,
2296 bool Value);
2297
2298 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2299 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2300 SourceLocation PragmaLoc);
2301
2302 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
2303 SourceLocation PragmaLoc,
2304 attr::ParsedSubjectMatchRuleSet Rules);
2305 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
2306 const IdentifierInfo *Namespace);
2307
2308 /// Called on well-formed '\#pragma clang attribute pop'.
2309 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
2310 const IdentifierInfo *Namespace);
2311
2312 /// Adds the attributes that have been specified using the
2313 /// '\#pragma clang attribute push' directives to the given declaration.
2314 void AddPragmaAttributes(Scope *S, Decl *D);
2315
2316 using InstantiationContextDiagFuncRef =
2317 llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
2318 auto getDefaultDiagFunc() {
2319 return [this](SourceLocation Loc, PartialDiagnostic PD) {
2320 // This bypasses a lot of the filters in the diag engine, as it's
2321 // to be used to attach notes to diagnostics which have already
2322 // been filtered through.
2323 DiagnosticBuilder Builder(Diags.Report(Loc, DiagID: PD.getDiagID()));
2324 PD.Emit(DB: Builder);
2325 };
2326 }
2327
2328 void PrintPragmaAttributeInstantiationPoint(
2329 InstantiationContextDiagFuncRef DiagFunc);
2330 void PrintPragmaAttributeInstantiationPoint() {
2331 PrintPragmaAttributeInstantiationPoint(DiagFunc: getDefaultDiagFunc());
2332 }
2333
2334 void DiagnoseUnterminatedPragmaAttribute();
2335
2336 /// Called on well formed \#pragma clang optimize.
2337 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2338
2339 /// #pragma optimize("[optimization-list]", on | off).
2340 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2341
2342 /// Call on well formed \#pragma function.
2343 void
2344 ActOnPragmaMSFunction(SourceLocation Loc,
2345 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2346
2347 NamedDecl *lookupExternCFunctionOrVariable(IdentifierInfo *IdentId,
2348 SourceLocation NameLoc,
2349 Scope *curScope);
2350
2351 /// Information from a C++ #pragma export, for a symbol that we
2352 /// haven't seen the declaration for yet.
2353 struct PendingPragmaInfo {
2354 SourceLocation NameLoc;
2355 bool Used;
2356 };
2357
2358 llvm::DenseMap<IdentifierInfo *, PendingPragmaInfo> PendingExportedNames;
2359
2360 /// ActonPragmaExport - called on well-formed '\#pragma export'.
2361 void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc,
2362 Scope *curScope);
2363
2364 /// Only called on function definitions; if there is a pragma in scope
2365 /// with the effect of a range-based optnone, consider marking the function
2366 /// with attribute optnone.
2367 void AddRangeBasedOptnone(FunctionDecl *FD);
2368
2369 /// Only called on function definitions; if there is a `#pragma alloc_text`
2370 /// that decides which code section the function should be in, add
2371 /// attribute section to the function.
2372 void AddSectionMSAllocText(FunctionDecl *FD);
2373
2374 /// Adds the 'optnone' attribute to the function declaration if there
2375 /// are no conflicts; Loc represents the location causing the 'optnone'
2376 /// attribute to be added (usually because of a pragma).
2377 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
2378
2379 /// Only called on function definitions; if there is a MSVC #pragma optimize
2380 /// in scope, consider changing the function's attributes based on the
2381 /// optimization list passed to the pragma.
2382 void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
2383
2384 /// Only called on function definitions; if there is a pragma in scope
2385 /// with the effect of a range-based no_builtin, consider marking the function
2386 /// with attribute no_builtin.
2387 void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
2388
2389 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2390 /// add an appropriate visibility attribute.
2391 void AddPushedVisibilityAttribute(Decl *RD);
2392
2393 /// FreeVisContext - Deallocate and null out VisContext.
2394 void FreeVisContext();
2395
2396 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2397 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2398 SourceLocation PragmaLoc);
2399
2400 /// ActOnPragmaFPContract - Called on well formed
2401 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2402 /// \#pragma clang fp contract
2403 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
2404
2405 /// Called on well formed
2406 /// \#pragma clang fp reassociate
2407 /// or
2408 /// \#pragma clang fp reciprocal
2409 void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind,
2410 bool IsEnabled);
2411
2412 /// ActOnPragmaFenvAccess - Called on well formed
2413 /// \#pragma STDC FENV_ACCESS
2414 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2415
2416 /// ActOnPragmaCXLimitedRange - Called on well formed
2417 /// \#pragma STDC CX_LIMITED_RANGE
2418 void ActOnPragmaCXLimitedRange(SourceLocation Loc,
2419 LangOptions::ComplexRangeKind Range);
2420
2421 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2422 void ActOnPragmaFPExceptions(SourceLocation Loc,
2423 LangOptions::FPExceptionModeKind);
2424
2425 /// Called to set constant rounding mode for floating point operations.
2426 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2427
2428 /// Called to set exception behavior for floating point operations.
2429 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
2430
2431 /// PushNamespaceVisibilityAttr - Note that we've entered a
2432 /// namespace with a visibility attribute.
2433 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2434 SourceLocation Loc);
2435
2436 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2437 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2438 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2439
2440 /// Handles semantic checking for features that are common to all attributes,
2441 /// such as checking whether a parameter was properly specified, or the
2442 /// correct number of arguments were passed, etc. Returns true if the
2443 /// attribute has been diagnosed.
2444 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2445 bool SkipArgCountCheck = false);
2446 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2447 bool SkipArgCountCheck = false);
2448
2449 ///@}
2450
2451 //
2452 //
2453 // -------------------------------------------------------------------------
2454 //
2455 //
2456
2457 /// \name Availability Attribute Handling
2458 /// Implementations are in SemaAvailability.cpp
2459 ///@{
2460
2461public:
2462 /// Issue any -Wunguarded-availability warnings in \c FD
2463 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
2464
2465 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2466
2467 /// Retrieve the current function, if any, that should be analyzed for
2468 /// potential availability violations.
2469 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2470
2471 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
2472 const ObjCInterfaceDecl *UnknownObjCClass,
2473 bool ObjCPropertyAccess,
2474 bool AvoidPartialAvailabilityChecks,
2475 ObjCInterfaceDecl *ClassReceiver);
2476
2477 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs);
2478
2479 std::pair<AvailabilityResult, const NamedDecl *>
2480 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2481 ObjCInterfaceDecl *ClassReceiver);
2482 ///@}
2483
2484 //
2485 //
2486 // -------------------------------------------------------------------------
2487 //
2488 //
2489
2490 /// \name Bounds Safety
2491 /// Implementations are in SemaBoundsSafety.cpp
2492 ///@{
2493public:
2494 /// Check if applying the specified attribute variant from the "counted by"
2495 /// family of attributes to FieldDecl \p FD is semantically valid. If
2496 /// semantically invalid diagnostics will be emitted explaining the problems.
2497 ///
2498 /// \param FD The FieldDecl to apply the attribute to
2499 /// \param E The count expression on the attribute
2500 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2501 /// attributes. If the false the attribute is from
2502 /// "counted_by" family of attributes.
2503 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2504 /// of attributes. If false the attribute does not have the
2505 /// suffix.
2506 ///
2507 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2508 /// \p CountInBytes and \p OrNull both being true indicates the
2509 /// `counted_by_or_null` attribute.
2510 ///
2511 /// \returns false iff semantically valid.
2512 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2513 bool OrNull);
2514
2515 /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2516 /// `__counted_by_or_null` pointer type \param LHSTy.
2517 ///
2518 /// \param LHSTy The type being assigned to. Checks will only be performed if
2519 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2520 /// \param RHSExpr The expression being assigned from.
2521 /// \param Action The type assignment being performed
2522 /// \param Loc The SourceLocation to use for error diagnostics
2523 /// \param Assignee The ValueDecl being assigned. This is used to compute
2524 /// the name of the assignee. If the assignee isn't known this can
2525 /// be set to nullptr.
2526 /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2527 /// Assignee to compute the name of the assignee use the fully
2528 /// qualified name, otherwise use the unqualified name.
2529 ///
2530 /// \returns True iff no diagnostic where emitted, false otherwise.
2531 bool BoundsSafetyCheckAssignmentToCountAttrPtr(
2532 QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2533 SourceLocation Loc, const ValueDecl *Assignee,
2534 bool ShowFullyQualifiedAssigneeName);
2535
2536 /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2537 /// pointer.
2538 ///
2539 /// \param Entity The entity being initialized
2540 /// \param Kind The kind of initialization being performed
2541 /// \param Action The type assignment being performed
2542 /// \param LHSTy The type being assigned to. Checks will only be performed if
2543 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2544 /// \param RHSExpr The expression being used for initialization.
2545 ///
2546 /// \returns True iff no diagnostic where emitted, false otherwise.
2547 bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity,
2548 const InitializationKind &Kind,
2549 AssignmentAction Action,
2550 QualType LHSType, Expr *RHSExpr);
2551
2552 /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2553 /// or counted_by_or_null pointers in \param E.
2554 ///
2555 /// \param E the expression to check
2556 ///
2557 /// \returns True iff no diagnostic where emitted, false otherwise.
2558 bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E);
2559 ///@}
2560
2561 //
2562 //
2563 // -------------------------------------------------------------------------
2564 //
2565 //
2566
2567 /// \name Casts
2568 /// Implementations are in SemaCast.cpp
2569 ///@{
2570
2571public:
2572 static bool isCast(CheckedConversionKind CCK) {
2573 return CCK == CheckedConversionKind::CStyleCast ||
2574 CCK == CheckedConversionKind::FunctionalCast ||
2575 CCK == CheckedConversionKind::OtherCast;
2576 }
2577
2578 /// ActOnCXXNamedCast - Parse
2579 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2580 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2581 SourceLocation LAngleBracketLoc, Declarator &D,
2582 SourceLocation RAngleBracketLoc,
2583 SourceLocation LParenLoc, Expr *E,
2584 SourceLocation RParenLoc);
2585
2586 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2587 TypeSourceInfo *Ty, Expr *E,
2588 SourceRange AngleBrackets, SourceRange Parens);
2589
2590 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
2591 ExprResult Operand,
2592 SourceLocation RParenLoc);
2593
2594 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
2595 Expr *Operand, SourceLocation RParenLoc);
2596
2597 // Checks that reinterpret casts don't have undefined behavior.
2598 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2599 bool IsDereference, SourceRange Range);
2600
2601 // Checks that the vector type should be initialized from a scalar
2602 // by splatting the value rather than populating a single element.
2603 // This is the case for AltiVecVector types as well as with
2604 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2605 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2606
2607 // Checks if the -faltivec-src-compat=gcc option is specified.
2608 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2609 // treated the same way as they are when trying to initialize
2610 // these vectors on gcc (an error is emitted).
2611 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
2612 QualType SrcTy);
2613
2614 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
2615 SourceLocation RParenLoc, Expr *Op);
2616
2617 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
2618 SourceLocation LParenLoc,
2619 Expr *CastExpr,
2620 SourceLocation RParenLoc);
2621
2622 ///@}
2623
2624 //
2625 //
2626 // -------------------------------------------------------------------------
2627 //
2628 //
2629
2630 /// \name Extra Semantic Checking
2631 /// Implementations are in SemaChecking.cpp
2632 ///@{
2633
2634public:
2635 /// Used to change context to isConstantEvaluated without pushing a heavy
2636 /// ExpressionEvaluationContextRecord object.
2637 bool isConstantEvaluatedOverride = false;
2638
2639 bool isConstantEvaluatedContext() const {
2640 return currentEvaluationContext().isConstantEvaluated() ||
2641 isConstantEvaluatedOverride;
2642 }
2643
2644 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
2645 unsigned ByteNo) const;
2646
2647 enum FormatArgumentPassingKind {
2648 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2649 FAPK_Variadic, // values to format are passed as variadic arguments
2650 FAPK_VAList, // values to format are passed in a va_list
2651 FAPK_Elsewhere, // values to format are not passed to this function
2652 };
2653
2654 // Used to grab the relevant information from a FormatAttr and a
2655 // FunctionDeclaration.
2656 struct FormatStringInfo {
2657 unsigned FormatIdx;
2658 unsigned FirstDataArg;
2659 FormatArgumentPassingKind ArgPassingKind;
2660 };
2661
2662 /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2663 /// populate the FormatStringInfo parameter with the attribute's correct
2664 /// format_idx and firstDataArg. Returns true when the format fits the
2665 /// function and the FormatStringInfo has been populated.
2666 static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2667 unsigned FirstArg, FormatStringInfo *FSI);
2668 static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2669 bool HasImplicitThisParam, bool IsVariadic,
2670 FormatStringInfo *FSI);
2671
2672 // Used by C++ template instantiation.
2673 ExprResult BuiltinShuffleVector(CallExpr *TheCall);
2674
2675 /// ConvertVectorExpr - Handle __builtin_convertvector
2676 ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2677 SourceLocation BuiltinLoc,
2678 SourceLocation RParenLoc);
2679
2680 static StringRef GetFormatStringTypeName(FormatStringType FST);
2681 static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2682 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2683 static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2684
2685 bool FormatStringHasSArg(const StringLiteral *FExpr);
2686
2687 /// Check for comparisons of floating-point values using == and !=. Issue a
2688 /// warning if the comparison is not likely to do what the programmer
2689 /// intended.
2690 void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2691 const Expr *RHS, BinaryOperatorKind Opcode);
2692
2693 /// Register a magic integral constant to be used as a type tag.
2694 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2695 uint64_t MagicValue, QualType Type,
2696 bool LayoutCompatible, bool MustBeNull);
2697
2698 struct TypeTagData {
2699 TypeTagData() {}
2700
2701 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
2702 : Type(Type), LayoutCompatible(LayoutCompatible),
2703 MustBeNull(MustBeNull) {}
2704
2705 QualType Type;
2706
2707 /// If true, \c Type should be compared with other expression's types for
2708 /// layout-compatibility.
2709 LLVM_PREFERRED_TYPE(bool)
2710 unsigned LayoutCompatible : 1;
2711 LLVM_PREFERRED_TYPE(bool)
2712 unsigned MustBeNull : 1;
2713 };
2714
2715 /// A pair of ArgumentKind identifier and magic value. This uniquely
2716 /// identifies the magic value.
2717 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2718
2719 /// Diagnoses the current set of gathered accesses. This happens at the end of
2720 /// each expression evaluation context. Diagnostics are emitted only for
2721 /// accesses gathered in the current evaluation context.
2722 void DiagnoseMisalignedMembers();
2723
2724 /// This function checks if the expression is in the sef of potentially
2725 /// misaligned members and it is converted to some pointer type T with lower
2726 /// or equal alignment requirements. If so it removes it. This is used when
2727 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2728 /// void*).
2729 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2730
2731 /// Returns true if `From` is a function or pointer to a function with the
2732 /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2733 /// function without this attribute.
2734 bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2735
2736 /// This function calls Action when it determines that E designates a
2737 /// misaligned member due to the packed attribute. This is used to emit
2738 /// local diagnostics like in reference binding.
2739 void RefersToMemberWithReducedAlignment(
2740 Expr *E,
2741 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2742 Action);
2743
2744 enum class AtomicArgumentOrder { API, AST };
2745 ExprResult
2746 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2747 SourceLocation RParenLoc, MultiExprArg Args,
2748 AtomicExpr::AtomicOp Op,
2749 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
2750
2751 /// Check to see if a given expression could have '.c_str()' called on it.
2752 bool hasCStrMethod(const Expr *E);
2753
2754 /// Diagnose pointers that are always non-null.
2755 /// \param E the expression containing the pointer
2756 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2757 /// compared to a null pointer
2758 /// \param IsEqual True when the comparison is equal to a null pointer
2759 /// \param Range Extra SourceRange to highlight in the diagnostic
2760 void DiagnoseAlwaysNonNullPointer(Expr *E,
2761 Expr::NullPointerConstantKind NullType,
2762 bool IsEqual, SourceRange Range);
2763
2764 /// CheckParmsForFunctionDef - Check that the parameters of the given
2765 /// function are appropriate for the definition of a function. This
2766 /// takes care of any checks that cannot be performed on the
2767 /// declaration itself, e.g., that the types of each of the function
2768 /// parameters are complete.
2769 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2770 bool CheckParameterNames);
2771
2772 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2773 /// pointer cast increases the alignment requirements.
2774 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2775
2776 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2777 /// to weak/__unsafe_unretained type.
2778 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2779
2780 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2781 /// to weak/__unsafe_unretained expression.
2782 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2783
2784 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2785 /// statement as a \p Body, and it is located on the same line.
2786 ///
2787 /// This helps prevent bugs due to typos, such as:
2788 /// if (condition);
2789 /// do_stuff();
2790 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2791 unsigned DiagID);
2792
2793 /// Warn if a for/while loop statement \p S, which is followed by
2794 /// \p PossibleBody, has a suspicious null statement as a body.
2795 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2796
2797 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2798 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2799 SourceLocation OpLoc);
2800
2801 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2802 bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
2803 const TypeSourceInfo *Derived);
2804
2805 /// CheckFunctionCall - Check a direct function call for various correctness
2806 /// and safety properties not strictly enforced by the C type system.
2807 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2808 const FunctionProtoType *Proto);
2809
2810 enum class EltwiseBuiltinArgTyRestriction {
2811 None,
2812 FloatTy,
2813 IntegerTy,
2814 SignedIntOrFloatTy,
2815 };
2816
2817 /// \param FPOnly restricts the arguments to floating-point types.
2818 std::optional<QualType>
2819 BuiltinVectorMath(CallExpr *TheCall,
2820 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2821 EltwiseBuiltinArgTyRestriction::None);
2822 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2823
2824 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2825 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2826
2827 /// Handles the checks for format strings, non-POD arguments to vararg
2828 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2829 /// attributes and AArch64 SME attributes.
2830 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2831 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2832 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2833 VariadicCallType CallType);
2834
2835 /// Verify that two format strings (as understood by attribute(format) and
2836 /// attribute(format_matches) are compatible. If they are incompatible,
2837 /// diagnostics are emitted with the assumption that \c
2838 /// AuthoritativeFormatString is correct and
2839 /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2840 /// diagnostics will point to it and a note will refer to \c
2841 /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2842 bool
2843 CheckFormatStringsCompatible(FormatStringType FST,
2844 const StringLiteral *AuthoritativeFormatString,
2845 const StringLiteral *TestedFormatString,
2846 const Expr *FunctionCallArg = nullptr);
2847
2848 /// Verify that one format string (as understood by attribute(format)) is
2849 /// self-consistent; for instance, that it doesn't have multiple positional
2850 /// arguments referring to the same argument in incompatible ways. Diagnose
2851 /// if it isn't.
2852 bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str);
2853
2854 /// \brief Enforce the bounds of a TCB
2855 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2856 /// directly calls other functions in the same TCB as marked by the
2857 /// enforce_tcb and enforce_tcb_leaf attributes.
2858 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2859 const NamedDecl *Callee);
2860
2861 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2862
2863 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2864 /// TheCall is a constant expression.
2865 bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
2866 llvm::APSInt &Result);
2867
2868 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2869 /// TheCall is a constant expression in the range [Low, High].
2870 bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
2871 int High, bool RangeIsError = true);
2872
2873 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2874 /// TheCall is a constant expression is a multiple of Num..
2875 bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
2876 unsigned Multiple);
2877
2878 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2879 /// constant expression representing a power of 2.
2880 bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum);
2881
2882 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2883 /// a constant expression representing an arbitrary byte value shifted left by
2884 /// a multiple of 8 bits.
2885 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
2886 unsigned ArgBits);
2887
2888 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2889 /// TheCall is a constant expression representing either a shifted byte value,
2890 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2891 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2892 /// Arm MVE intrinsics.
2893 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum,
2894 unsigned ArgBits);
2895
2896 /// Checks that a call expression's argument count is at least the desired
2897 /// number. This is useful when doing custom type-checking on a variadic
2898 /// function. Returns true on error.
2899 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2900
2901 /// Checks that a call expression's argument count is at most the desired
2902 /// number. This is useful when doing custom type-checking on a variadic
2903 /// function. Returns true on error.
2904 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
2905
2906 /// Checks that a call expression's argument count is in the desired range.
2907 /// This is useful when doing custom type-checking on a variadic function.
2908 /// Returns true on error.
2909 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
2910 unsigned MaxArgCount);
2911
2912 /// Checks that a call expression's argument count is the desired number.
2913 /// This is useful when doing custom type-checking. Returns true on error.
2914 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
2915
2916 /// Returns true if the argument consists of one contiguous run of 1s with any
2917 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
2918 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
2919 /// since all 1s are not contiguous.
2920 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2921
2922 void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
2923 bool *ICContext = nullptr,
2924 bool IsListInit = false);
2925
2926 /// Check for overflow behavior type related implicit conversion diagnostics.
2927 /// Returns true if OBT-related diagnostic was issued, false otherwise.
2928 bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
2929 SourceLocation CC);
2930
2931 bool
2932 BuiltinElementwiseTernaryMath(CallExpr *TheCall,
2933 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2934 EltwiseBuiltinArgTyRestriction::FloatTy);
2935 bool PrepareBuiltinElementwiseMathOneArgCall(
2936 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
2937 EltwiseBuiltinArgTyRestriction::None);
2938
2939private:
2940 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2941 const ArraySubscriptExpr *ASE = nullptr,
2942 bool AllowOnePastEnd = true, bool IndexNegated = false);
2943 void CheckArrayAccess(const Expr *E);
2944
2945 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2946 const FunctionProtoType *Proto);
2947
2948 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2949 /// such as function pointers returned from functions.
2950 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
2951
2952 /// CheckConstructorCall - Check a constructor call for correctness and safety
2953 /// properties not enforced by the C type system.
2954 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
2955 ArrayRef<const Expr *> Args,
2956 const FunctionProtoType *Proto, SourceLocation Loc);
2957
2958 /// Warn if a pointer or reference argument passed to a function points to an
2959 /// object that is less aligned than the parameter. This can happen when
2960 /// creating a typedef with a lower alignment than the original type and then
2961 /// calling functions defined in terms of the original type.
2962 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
2963 StringRef ParamName, QualType ArgTy, QualType ParamTy);
2964
2965 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
2966
2967 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2968 CallExpr *TheCall);
2969
2970 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2971 CallExpr *TheCall);
2972
2973 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
2974
2975 /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
2976 /// or '__builtin_c23_va_start' for validity. Emit an error and return true
2977 /// on failure; return false on success.
2978 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
2979 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
2980
2981 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2982 /// friends. This is declared to take (...), so we have to check everything.
2983 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
2984
2985 /// BuiltinSemaBuiltinFPClassification - Handle functions like
2986 /// __builtin_isnan and friends. This is declared to take (...), so we have
2987 /// to check everything.
2988 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
2989 unsigned BuiltinID);
2990
2991 /// Perform semantic analysis for a call to __builtin_complex.
2992 bool BuiltinComplex(CallExpr *TheCall);
2993 bool BuiltinOSLogFormat(CallExpr *TheCall);
2994
2995 /// BuiltinPrefetch - Handle __builtin_prefetch.
2996 /// This is declared to take (const void*, ...) and can take two
2997 /// optional constant int args.
2998 bool BuiltinPrefetch(CallExpr *TheCall);
2999
3000 /// Handle __builtin_alloca_with_align. This is declared
3001 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3002 /// than 8.
3003 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
3004
3005 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
3006 bool BuiltinArithmeticFence(CallExpr *TheCall);
3007
3008 /// BuiltinAssume - Handle __assume (MS Extension).
3009 /// __assume does not evaluate its arguments, and should warn if its argument
3010 /// has side effects.
3011 bool BuiltinAssume(CallExpr *TheCall);
3012
3013 /// Handle __builtin_assume_aligned. This is declared
3014 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3015 bool BuiltinAssumeAligned(CallExpr *TheCall);
3016
3017 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3018 /// This checks that the target supports __builtin_longjmp and
3019 /// that val is a constant 1.
3020 bool BuiltinLongjmp(CallExpr *TheCall);
3021
3022 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3023 /// This checks that the target supports __builtin_setjmp.
3024 bool BuiltinSetjmp(CallExpr *TheCall);
3025
3026 /// We have a call to a function like __sync_fetch_and_add, which is an
3027 /// overloaded function based on the pointer type of its first argument.
3028 /// The main BuildCallExpr routines have already promoted the types of
3029 /// arguments because all of these calls are prototyped as void(...).
3030 ///
3031 /// This function goes through and does final semantic checking for these
3032 /// builtins, as well as generating any warnings.
3033 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
3034
3035 /// BuiltinNontemporalOverloaded - We have a call to
3036 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3037 /// overloaded function based on the pointer type of its last argument.
3038 ///
3039 /// This function goes through and does final semantic checking for these
3040 /// builtins.
3041 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
3042 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
3043 AtomicExpr::AtomicOp Op);
3044
3045 /// \param FPOnly restricts the arguments to floating-point types.
3046 bool BuiltinElementwiseMath(CallExpr *TheCall,
3047 EltwiseBuiltinArgTyRestriction ArgTyRestr =
3048 EltwiseBuiltinArgTyRestriction::None);
3049 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
3050
3051 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
3052
3053 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
3054 BuiltinCountedByRefKind K);
3055 bool BuiltinCountedByRef(CallExpr *TheCall);
3056
3057 // Matrix builtin handling.
3058 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
3059 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
3060 ExprResult CallResult);
3061 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
3062 ExprResult CallResult);
3063
3064 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3065 /// functions) for correct use of format strings.
3066 /// Returns true if a format string has been fully checked.
3067 bool CheckFormatArguments(const FormatAttr *Format,
3068 ArrayRef<const Expr *> Args, bool IsCXXMember,
3069 VariadicCallType CallType, SourceLocation Loc,
3070 SourceRange Range,
3071 llvm::SmallBitVector &CheckedVarArgs);
3072 bool CheckFormatString(const FormatMatchesAttr *Format,
3073 ArrayRef<const Expr *> Args, bool IsCXXMember,
3074 VariadicCallType CallType, SourceLocation Loc,
3075 SourceRange Range,
3076 llvm::SmallBitVector &CheckedVarArgs);
3077 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3078 FormatArgumentPassingKind FAPK,
3079 StringLiteral *ReferenceFormatString,
3080 unsigned format_idx, unsigned firstDataArg,
3081 FormatStringType Type, VariadicCallType CallType,
3082 SourceLocation Loc, SourceRange range,
3083 llvm::SmallBitVector &CheckedVarArgs);
3084
3085 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3086
3087 /// Warn when using the wrong abs() function.
3088 void CheckAbsoluteValueFunction(const CallExpr *Call,
3089 const FunctionDecl *FDecl);
3090
3091 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3092
3093 /// Check for dangerous or invalid arguments to memset().
3094 ///
3095 /// This issues warnings on known problematic, dangerous or unspecified
3096 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3097 /// function calls.
3098 ///
3099 /// \param Call The call expression to diagnose.
3100 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3101 IdentifierInfo *FnName);
3102
3103 bool CheckSizeofMemaccessArgument(const Expr *SizeOfArg, const Expr *Dest,
3104 IdentifierInfo *FnName);
3105 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3106 // be the size of the source, instead of the destination.
3107 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3108
3109 // Warn on anti-patterns as the 'size' argument to strncat.
3110 // The correct size argument should look like following:
3111 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3112 void CheckStrncatArguments(const CallExpr *Call,
3113 const IdentifierInfo *FnName);
3114
3115 /// Alerts the user that they are attempting to free a non-malloc'd object.
3116 void CheckFreeArguments(const CallExpr *E);
3117
3118 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3119 SourceLocation ReturnLoc, bool isObjCMethod = false,
3120 const AttrVec *Attrs = nullptr,
3121 const FunctionDecl *FD = nullptr);
3122
3123 /// Diagnoses "dangerous" implicit conversions within the given
3124 /// expression (which is a full expression). Implements -Wconversion
3125 /// and -Wsign-compare.
3126 ///
3127 /// \param CC the "context" location of the implicit conversion, i.e.
3128 /// the most location of the syntactic entity requiring the implicit
3129 /// conversion
3130 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3131
3132 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3133 /// Input argument E is a logical expression.
3134 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
3135
3136 /// Diagnose when expression is an integer constant expression and its
3137 /// evaluation results in integer overflow
3138 void CheckForIntOverflow(const Expr *E);
3139 void CheckUnsequencedOperations(const Expr *E);
3140
3141 /// Perform semantic checks on a completed expression. This will either
3142 /// be a full-expression or a default argument expression.
3143 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3144 bool IsConstexpr = false);
3145
3146 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3147 Expr *Init);
3148
3149 /// A map from magic value to type information.
3150 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3151 TypeTagForDatatypeMagicValues;
3152
3153 /// Peform checks on a call of a function with argument_with_type_tag
3154 /// or pointer_with_type_tag attributes.
3155 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3156 const ArrayRef<const Expr *> ExprArgs,
3157 SourceLocation CallSiteLoc);
3158
3159 /// Check if we are taking the address of a packed field
3160 /// as this may be a problem if the pointer value is dereferenced.
3161 void CheckAddressOfPackedMember(Expr *rhs);
3162
3163 /// Helper class that collects misaligned member designations and
3164 /// their location info for delayed diagnostics.
3165 struct MisalignedMember {
3166 Expr *E;
3167 RecordDecl *RD;
3168 ValueDecl *MD;
3169 CharUnits Alignment;
3170
3171 MisalignedMember() : E(), RD(), MD() {}
3172 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3173 CharUnits Alignment)
3174 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
3175 explicit MisalignedMember(Expr *E)
3176 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3177
3178 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3179 };
3180
3181 /// Adds an expression to the set of gathered misaligned members.
3182 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3183 CharUnits Alignment);
3184 ///@}
3185
3186 //
3187 //
3188 // -------------------------------------------------------------------------
3189 //
3190 //
3191
3192 /// \name C++ Coroutines
3193 /// Implementations are in SemaCoroutine.cpp
3194 ///@{
3195
3196public:
3197 /// The C++ "std::coroutine_traits" template, which is defined in
3198 /// \<coroutine_traits>
3199 ClassTemplateDecl *StdCoroutineTraitsCache;
3200
3201 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
3202 StringRef Keyword);
3203 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3204 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3205 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
3206
3207 ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
3208 ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
3209 UnresolvedLookupExpr *Lookup);
3210 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3211 Expr *Awaiter, bool IsImplicit = false);
3212 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3213 UnresolvedLookupExpr *Lookup);
3214 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
3215 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
3216 bool IsImplicit = false);
3217 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
3218 bool buildCoroutineParameterMoves(SourceLocation Loc);
3219 VarDecl *buildCoroutinePromise(SourceLocation Loc);
3220 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
3221
3222 // As a clang extension, enforces that a non-coroutine function must be marked
3223 // with [[clang::coro_wrapper]] if it returns a type marked with
3224 // [[clang::coro_return_type]].
3225 // Expects that FD is not a coroutine.
3226 void CheckCoroutineWrapper(FunctionDecl *FD);
3227 /// Lookup 'coroutine_traits' in std namespace and std::experimental
3228 /// namespace. The namespace found is recorded in Namespace.
3229 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
3230 SourceLocation FuncLoc);
3231 /// Check that the expression co_await promise.final_suspend() shall not be
3232 /// potentially-throwing.
3233 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3234
3235 ///@}
3236
3237 //
3238 //
3239 // -------------------------------------------------------------------------
3240 //
3241 //
3242
3243 /// \name C++ Scope Specifiers
3244 /// Implementations are in SemaCXXScopeSpec.cpp
3245 ///@{
3246
3247public:
3248 // Marks SS invalid if it represents an incomplete type.
3249 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
3250 // Complete an enum decl, maybe without a scope spec.
3251 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
3252 CXXScopeSpec *SS = nullptr);
3253
3254 /// Compute the DeclContext that is associated with the given type.
3255 ///
3256 /// \param T the type for which we are attempting to find a DeclContext.
3257 ///
3258 /// \returns the declaration context represented by the type T,
3259 /// or NULL if the declaration context cannot be computed (e.g., because it is
3260 /// dependent and not the current instantiation).
3261 DeclContext *computeDeclContext(QualType T);
3262
3263 /// Compute the DeclContext that is associated with the given
3264 /// scope specifier.
3265 ///
3266 /// \param SS the C++ scope specifier as it appears in the source
3267 ///
3268 /// \param EnteringContext when true, we will be entering the context of
3269 /// this scope specifier, so we can retrieve the declaration context of a
3270 /// class template or class template partial specialization even if it is
3271 /// not the current instantiation.
3272 ///
3273 /// \returns the declaration context represented by the scope specifier @p SS,
3274 /// or NULL if the declaration context cannot be computed (e.g., because it is
3275 /// dependent and not the current instantiation).
3276 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
3277 bool EnteringContext = false);
3278 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
3279
3280 /// If the given nested name specifier refers to the current
3281 /// instantiation, return the declaration that corresponds to that
3282 /// current instantiation (C++0x [temp.dep.type]p1).
3283 ///
3284 /// \param NNS a dependent nested name specifier.
3285 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier NNS);
3286
3287 /// The parser has parsed a global nested-name-specifier '::'.
3288 ///
3289 /// \param CCLoc The location of the '::'.
3290 ///
3291 /// \param SS The nested-name-specifier, which will be updated in-place
3292 /// to reflect the parsed nested-name-specifier.
3293 ///
3294 /// \returns true if an error occurred, false otherwise.
3295 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
3296
3297 /// The parser has parsed a '__super' nested-name-specifier.
3298 ///
3299 /// \param SuperLoc The location of the '__super' keyword.
3300 ///
3301 /// \param ColonColonLoc The location of the '::'.
3302 ///
3303 /// \param SS The nested-name-specifier, which will be updated in-place
3304 /// to reflect the parsed nested-name-specifier.
3305 ///
3306 /// \returns true if an error occurred, false otherwise.
3307 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
3308 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3309
3310 /// Determines whether the given declaration is an valid acceptable
3311 /// result for name lookup of a nested-name-specifier.
3312 /// \param SD Declaration checked for nested-name-specifier.
3313 /// \param IsExtension If not null and the declaration is accepted as an
3314 /// extension, the pointed variable is assigned true.
3315 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
3316 bool *CanCorrect = nullptr);
3317
3318 /// If the given nested-name-specifier begins with a bare identifier
3319 /// (e.g., Base::), perform name lookup for that identifier as a
3320 /// nested-name-specifier within the given scope, and return the result of
3321 /// that name lookup.
3322 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier NNS);
3323
3324 /// Keeps information about an identifier in a nested-name-spec.
3325 ///
3326 struct NestedNameSpecInfo {
3327 /// The type of the object, if we're parsing nested-name-specifier in
3328 /// a member access expression.
3329 ParsedType ObjectType;
3330
3331 /// The identifier preceding the '::'.
3332 IdentifierInfo *Identifier;
3333
3334 /// The location of the identifier.
3335 SourceLocation IdentifierLoc;
3336
3337 /// The location of the '::'.
3338 SourceLocation CCLoc;
3339
3340 /// Creates info object for the most typical case.
3341 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3342 SourceLocation ColonColonLoc,
3343 ParsedType ObjectType = ParsedType())
3344 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
3345 CCLoc(ColonColonLoc) {}
3346
3347 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3348 SourceLocation ColonColonLoc, QualType ObjectType)
3349 : ObjectType(ParsedType::make(P: ObjectType)), Identifier(II),
3350 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3351 };
3352
3353 /// Build a new nested-name-specifier for "identifier::", as described
3354 /// by ActOnCXXNestedNameSpecifier.
3355 ///
3356 /// \param S Scope in which the nested-name-specifier occurs.
3357 /// \param IdInfo Parser information about an identifier in the
3358 /// nested-name-spec.
3359 /// \param EnteringContext If true, enter the context specified by the
3360 /// nested-name-specifier.
3361 /// \param SS Optional nested name specifier preceding the identifier.
3362 /// \param ScopeLookupResult Provides the result of name lookup within the
3363 /// scope of the nested-name-specifier that was computed at template
3364 /// definition time.
3365 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3366 /// error recovery and what kind of recovery is performed.
3367 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3368 /// are allowed. The bool value pointed by this parameter is set to
3369 /// 'true' if the identifier is treated as if it was followed by ':',
3370 /// not '::'.
3371 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3372 ///
3373 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3374 /// that it contains an extra parameter \p ScopeLookupResult, which provides
3375 /// the result of name lookup within the scope of the nested-name-specifier
3376 /// that was computed at template definition time.
3377 ///
3378 /// If ErrorRecoveryLookup is true, then this call is used to improve error
3379 /// recovery. This means that it should not emit diagnostics, it should
3380 /// just return true on failure. It also means it should only return a valid
3381 /// scope if it *knows* that the result is correct. It should not return in a
3382 /// dependent context, for example. Nor will it extend \p SS with the scope
3383 /// specifier.
3384 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3385 bool EnteringContext, CXXScopeSpec &SS,
3386 NamedDecl *ScopeLookupResult,
3387 bool ErrorRecoveryLookup,
3388 bool *IsCorrectedToColon = nullptr,
3389 bool OnlyNamespace = false);
3390
3391 /// The parser has parsed a nested-name-specifier 'identifier::'.
3392 ///
3393 /// \param S The scope in which this nested-name-specifier occurs.
3394 ///
3395 /// \param IdInfo Parser information about an identifier in the
3396 /// nested-name-spec.
3397 ///
3398 /// \param EnteringContext Whether we're entering the context nominated by
3399 /// this nested-name-specifier.
3400 ///
3401 /// \param SS The nested-name-specifier, which is both an input
3402 /// parameter (the nested-name-specifier before this type) and an
3403 /// output parameter (containing the full nested-name-specifier,
3404 /// including this new type).
3405 ///
3406 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3407 /// are allowed. The bool value pointed by this parameter is set to 'true'
3408 /// if the identifier is treated as if it was followed by ':', not '::'.
3409 ///
3410 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3411 ///
3412 /// \returns true if an error occurred, false otherwise.
3413 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3414 bool EnteringContext, CXXScopeSpec &SS,
3415 bool *IsCorrectedToColon = nullptr,
3416 bool OnlyNamespace = false);
3417
3418 /// The parser has parsed a nested-name-specifier
3419 /// 'template[opt] template-name < template-args >::'.
3420 ///
3421 /// \param S The scope in which this nested-name-specifier occurs.
3422 ///
3423 /// \param SS The nested-name-specifier, which is both an input
3424 /// parameter (the nested-name-specifier before this type) and an
3425 /// output parameter (containing the full nested-name-specifier,
3426 /// including this new type).
3427 ///
3428 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3429 /// \param TemplateName the template name.
3430 /// \param TemplateNameLoc The location of the template name.
3431 /// \param LAngleLoc The location of the opening angle bracket ('<').
3432 /// \param TemplateArgs The template arguments.
3433 /// \param RAngleLoc The location of the closing angle bracket ('>').
3434 /// \param CCLoc The location of the '::'.
3435 ///
3436 /// \param EnteringContext Whether we're entering the context of the
3437 /// nested-name-specifier.
3438 ///
3439 ///
3440 /// \returns true if an error occurred, false otherwise.
3441 bool ActOnCXXNestedNameSpecifier(
3442 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3443 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3444 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3445 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3446
3447 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS,
3448 SourceLocation ColonColonLoc);
3449
3450 bool ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS,
3451 const DeclSpec &DS,
3452 SourceLocation ColonColonLoc,
3453 QualType Type);
3454
3455 /// IsInvalidUnlessNestedName - This method is used for error recovery
3456 /// purposes to determine whether the specified identifier is only valid as
3457 /// a nested name specifier, for example a namespace name. It is
3458 /// conservatively correct to always return false from this method.
3459 ///
3460 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3461 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3462 NestedNameSpecInfo &IdInfo,
3463 bool EnteringContext);
3464
3465 /// Given a C++ nested-name-specifier, produce an annotation value
3466 /// that the parser can use later to reconstruct the given
3467 /// nested-name-specifier.
3468 ///
3469 /// \param SS A nested-name-specifier.
3470 ///
3471 /// \returns A pointer containing all of the information in the
3472 /// nested-name-specifier \p SS.
3473 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3474
3475 /// Given an annotation pointer for a nested-name-specifier, restore
3476 /// the nested-name-specifier structure.
3477 ///
3478 /// \param Annotation The annotation pointer, produced by
3479 /// \c SaveNestedNameSpecifierAnnotation().
3480 ///
3481 /// \param AnnotationRange The source range corresponding to the annotation.
3482 ///
3483 /// \param SS The nested-name-specifier that will be updated with the contents
3484 /// of the annotation pointer.
3485 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3486 SourceRange AnnotationRange,
3487 CXXScopeSpec &SS);
3488
3489 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3490
3491 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3492 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3493 /// After this method is called, according to [C++ 3.4.3p3], names should be
3494 /// looked up in the declarator-id's scope, until the declarator is parsed and
3495 /// ActOnCXXExitDeclaratorScope is called.
3496 /// The 'SS' should be a non-empty valid CXXScopeSpec.
3497 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
3498
3499 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3500 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3501 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3502 /// Used to indicate that names should revert to being looked up in the
3503 /// defining scope.
3504 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3505
3506 ///@}
3507
3508 //
3509 //
3510 // -------------------------------------------------------------------------
3511 //
3512 //
3513
3514 /// \name Declarations
3515 /// Implementations are in SemaDecl.cpp
3516 ///@{
3517
3518public:
3519 IdentifierResolver IdResolver;
3520
3521 /// The index of the first InventedParameterInfo that refers to the current
3522 /// context.
3523 unsigned InventedParameterInfosStart = 0;
3524
3525 /// A RAII object to temporarily push a declaration context.
3526 class ContextRAII {
3527 private:
3528 Sema &S;
3529 DeclContext *SavedContext;
3530 ProcessingContextState SavedContextState;
3531 QualType SavedCXXThisTypeOverride;
3532 unsigned SavedFunctionScopesStart;
3533 unsigned SavedInventedParameterInfosStart;
3534
3535 public:
3536 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3537 : S(S), SavedContext(S.CurContext),
3538 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3539 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3540 SavedFunctionScopesStart(S.FunctionScopesStart),
3541 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3542 assert(ContextToPush && "pushing null context");
3543 S.CurContext = ContextToPush;
3544 if (NewThisContext)
3545 S.CXXThisTypeOverride = QualType();
3546 // Any saved FunctionScopes do not refer to this context.
3547 S.FunctionScopesStart = S.FunctionScopes.size();
3548 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3549 }
3550
3551 void pop() {
3552 if (!SavedContext)
3553 return;
3554 S.CurContext = SavedContext;
3555 S.DelayedDiagnostics.popUndelayed(state: SavedContextState);
3556 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3557 S.FunctionScopesStart = SavedFunctionScopesStart;
3558 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3559 SavedContext = nullptr;
3560 }
3561
3562 ~ContextRAII() { pop(); }
3563 ContextRAII(const ContextRAII &) = delete;
3564 ContextRAII &operator=(const ContextRAII &) = delete;
3565 };
3566
3567 void DiagnoseInvalidJumps(Stmt *Body);
3568
3569 /// The function definitions which were renamed as part of typo-correction
3570 /// to match their respective declarations. We want to keep track of them
3571 /// to ensure that we don't emit a "redefinition" error if we encounter a
3572 /// correctly named definition after the renamed definition.
3573 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
3574
3575 /// A cache of the flags available in enumerations with the flag_bits
3576 /// attribute.
3577 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3578
3579 /// A cache of enumerator values for enums checked by -Wassign-enum.
3580 llvm::DenseMap<const EnumDecl *, llvm::SmallVector<llvm::APSInt>>
3581 AssignEnumCache;
3582
3583 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3584 /// declared. Rare. May alias another identifier, declared or undeclared.
3585 ///
3586 /// For aliases, the target identifier is used as a key for eventual
3587 /// processing when the target is declared. For the single-identifier form,
3588 /// the sole identifier is used as the key. Each entry is a `SetVector`
3589 /// (ordered by parse order) of aliases (identified by the alias name) in case
3590 /// of multiple aliases to the same undeclared identifier.
3591 llvm::MapVector<
3592 IdentifierInfo *,
3593 llvm::SetVector<
3594 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
3595 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3596 WeakUndeclaredIdentifiers;
3597
3598 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3599 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3600 /// to define functions that occur in multiple standards to call the version
3601 /// in the currently selected standard.
3602 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *> ExtnameUndeclaredIdentifiers;
3603
3604 /// Set containing all typedefs that are likely unused.
3605 llvm::SmallSetVector<const TypedefNameDecl *, 4>
3606 UnusedLocalTypedefNameCandidates;
3607
3608 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
3609 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
3610 UnusedFileScopedDeclsType;
3611
3612 /// The set of file scoped decls seen so far that have not been used
3613 /// and must warn if not used. Only contains the first declaration.
3614 UnusedFileScopedDeclsType UnusedFileScopedDecls;
3615
3616 typedef LazyVector<VarDecl *, ExternalSemaSource,
3617 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
3618 TentativeDefinitionsType;
3619
3620 /// All the tentative definitions encountered in the TU.
3621 TentativeDefinitionsType TentativeDefinitions;
3622
3623 /// All the external declarations encoutered and used in the TU.
3624 SmallVector<DeclaratorDecl *, 4> ExternalDeclarations;
3625
3626 /// Generally null except when we temporarily switch decl contexts,
3627 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3628 DeclContext *OriginalLexicalContext;
3629
3630 /// Is the module scope we are in a C++ Header Unit?
3631 bool currentModuleIsHeaderUnit() const {
3632 return ModuleScopes.empty() ? false
3633 : ModuleScopes.back().Module->isHeaderUnit();
3634 }
3635
3636 /// Get the module owning an entity.
3637 Module *getOwningModule(const Decl *Entity) {
3638 return Entity->getOwningModule();
3639 }
3640
3641 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3642
3643 enum class DiagCtorKind { None, Implicit, Typename };
3644 /// Returns the TypeDeclType for the given type declaration,
3645 /// as ASTContext::getTypeDeclType would, but
3646 /// performs the required semantic checks for name lookup of said entity.
3647 void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD,
3648 SourceLocation NameLoc);
3649
3650 /// If the identifier refers to a type name within this scope,
3651 /// return the declaration of that type.
3652 ///
3653 /// This routine performs ordinary name lookup of the identifier II
3654 /// within the given scope, with optional C++ scope specifier SS, to
3655 /// determine whether the name refers to a type. If so, returns an
3656 /// opaque pointer (actually a QualType) corresponding to that
3657 /// type. Otherwise, returns NULL.
3658 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
3659 Scope *S, CXXScopeSpec *SS = nullptr,
3660 bool isClassName = false, bool HasTrailingDot = false,
3661 ParsedType ObjectType = nullptr,
3662 bool IsCtorOrDtorName = false,
3663 bool WantNontrivialTypeSourceInfo = false,
3664 bool IsClassTemplateDeductionContext = true,
3665 ImplicitTypenameContext AllowImplicitTypename =
3666 ImplicitTypenameContext::No,
3667 IdentifierInfo **CorrectedII = nullptr);
3668
3669 /// isTagName() - This method is called *for error recovery purposes only*
3670 /// to determine if the specified name is a valid tag name ("struct foo"). If
3671 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3672 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3673 /// diagnose cases in C where the user forgot to specify the tag.
3674 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
3675
3676 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3677 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3678 /// then downgrade the missing typename error to a warning.
3679 /// This is needed for MSVC compatibility; Example:
3680 /// @code
3681 /// template<class T> class A {
3682 /// public:
3683 /// typedef int TYPE;
3684 /// };
3685 /// template<class T> class B : public A<T> {
3686 /// public:
3687 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3688 /// };
3689 /// @endcode
3690 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3691 void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc,
3692 Scope *S, CXXScopeSpec *SS,
3693 ParsedType &SuggestedType,
3694 bool IsTemplateName = false);
3695
3696 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3697 /// type name has failed in a dependent context. In these situations, we
3698 /// automatically form a DependentTypeName that will retry lookup in a related
3699 /// scope during instantiation.
3700 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
3701 SourceLocation NameLoc,
3702 bool IsTemplateTypeArg);
3703
3704 class NameClassification {
3705 NameClassificationKind Kind;
3706 union {
3707 ExprResult Expr;
3708 NamedDecl *NonTypeDecl;
3709 TemplateName Template;
3710 ParsedType Type;
3711 };
3712
3713 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3714
3715 public:
3716 NameClassification(ParsedType Type)
3717 : Kind(NameClassificationKind::Type), Type(Type) {}
3718
3719 NameClassification(const IdentifierInfo *Keyword)
3720 : Kind(NameClassificationKind::Keyword) {}
3721
3722 static NameClassification Error() {
3723 return NameClassification(NameClassificationKind::Error);
3724 }
3725
3726 static NameClassification Unknown() {
3727 return NameClassification(NameClassificationKind::Unknown);
3728 }
3729
3730 static NameClassification OverloadSet(ExprResult E) {
3731 NameClassification Result(NameClassificationKind::OverloadSet);
3732 Result.Expr = E;
3733 return Result;
3734 }
3735
3736 static NameClassification NonType(NamedDecl *D) {
3737 NameClassification Result(NameClassificationKind::NonType);
3738 Result.NonTypeDecl = D;
3739 return Result;
3740 }
3741
3742 static NameClassification UndeclaredNonType() {
3743 return NameClassification(NameClassificationKind::UndeclaredNonType);
3744 }
3745
3746 static NameClassification DependentNonType() {
3747 return NameClassification(NameClassificationKind::DependentNonType);
3748 }
3749
3750 static NameClassification TypeTemplate(TemplateName Name) {
3751 NameClassification Result(NameClassificationKind::TypeTemplate);
3752 Result.Template = Name;
3753 return Result;
3754 }
3755
3756 static NameClassification VarTemplate(TemplateName Name) {
3757 NameClassification Result(NameClassificationKind::VarTemplate);
3758 Result.Template = Name;
3759 return Result;
3760 }
3761
3762 static NameClassification FunctionTemplate(TemplateName Name) {
3763 NameClassification Result(NameClassificationKind::FunctionTemplate);
3764 Result.Template = Name;
3765 return Result;
3766 }
3767
3768 static NameClassification Concept(TemplateName Name) {
3769 NameClassification Result(NameClassificationKind::Concept);
3770 Result.Template = Name;
3771 return Result;
3772 }
3773
3774 static NameClassification UndeclaredTemplate(TemplateName Name) {
3775 NameClassification Result(NameClassificationKind::UndeclaredTemplate);
3776 Result.Template = Name;
3777 return Result;
3778 }
3779
3780 NameClassificationKind getKind() const { return Kind; }
3781
3782 ExprResult getExpression() const {
3783 assert(Kind == NameClassificationKind::OverloadSet);
3784 return Expr;
3785 }
3786
3787 ParsedType getType() const {
3788 assert(Kind == NameClassificationKind::Type);
3789 return Type;
3790 }
3791
3792 NamedDecl *getNonTypeDecl() const {
3793 assert(Kind == NameClassificationKind::NonType);
3794 return NonTypeDecl;
3795 }
3796
3797 TemplateName getTemplateName() const {
3798 assert(Kind == NameClassificationKind::TypeTemplate ||
3799 Kind == NameClassificationKind::FunctionTemplate ||
3800 Kind == NameClassificationKind::VarTemplate ||
3801 Kind == NameClassificationKind::Concept ||
3802 Kind == NameClassificationKind::UndeclaredTemplate);
3803 return Template;
3804 }
3805
3806 TemplateNameKind getTemplateNameKind() const {
3807 switch (Kind) {
3808 case NameClassificationKind::TypeTemplate:
3809 return TNK_Type_template;
3810 case NameClassificationKind::FunctionTemplate:
3811 return TNK_Function_template;
3812 case NameClassificationKind::VarTemplate:
3813 return TNK_Var_template;
3814 case NameClassificationKind::Concept:
3815 return TNK_Concept_template;
3816 case NameClassificationKind::UndeclaredTemplate:
3817 return TNK_Undeclared_template;
3818 default:
3819 llvm_unreachable("unsupported name classification.");
3820 }
3821 }
3822 };
3823
3824 /// Perform name lookup on the given name, classifying it based on
3825 /// the results of name lookup and the following token.
3826 ///
3827 /// This routine is used by the parser to resolve identifiers and help direct
3828 /// parsing. When the identifier cannot be found, this routine will attempt
3829 /// to correct the typo and classify based on the resulting name.
3830 ///
3831 /// \param S The scope in which we're performing name lookup.
3832 ///
3833 /// \param SS The nested-name-specifier that precedes the name.
3834 ///
3835 /// \param Name The identifier. If typo correction finds an alternative name,
3836 /// this pointer parameter will be updated accordingly.
3837 ///
3838 /// \param NameLoc The location of the identifier.
3839 ///
3840 /// \param NextToken The token following the identifier. Used to help
3841 /// disambiguate the name.
3842 ///
3843 /// \param CCC The correction callback, if typo correction is desired.
3844 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3845 IdentifierInfo *&Name, SourceLocation NameLoc,
3846 const Token &NextToken,
3847 CorrectionCandidateCallback *CCC = nullptr);
3848
3849 /// Act on the result of classifying a name as an undeclared (ADL-only)
3850 /// non-type declaration.
3851 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
3852 SourceLocation NameLoc);
3853 /// Act on the result of classifying a name as an undeclared member of a
3854 /// dependent base class.
3855 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
3856 IdentifierInfo *Name,
3857 SourceLocation NameLoc,
3858 bool IsAddressOfOperand);
3859 /// Act on the result of classifying a name as a specific non-type
3860 /// declaration.
3861 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
3862 NamedDecl *Found,
3863 SourceLocation NameLoc,
3864 const Token &NextToken);
3865 /// Act on the result of classifying a name as an overload set.
3866 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
3867
3868 /// Describes the detailed kind of a template name. Used in diagnostics.
3869 enum class TemplateNameKindForDiagnostics {
3870 ClassTemplate,
3871 FunctionTemplate,
3872 VarTemplate,
3873 AliasTemplate,
3874 TemplateTemplateParam,
3875 Concept,
3876 DependentTemplate
3877 };
3878 TemplateNameKindForDiagnostics
3879 getTemplateNameKindForDiagnostics(TemplateName Name);
3880
3881 /// Determine whether it's plausible that E was intended to be a
3882 /// template-name.
3883 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
3884 if (!getLangOpts().CPlusPlus || E.isInvalid())
3885 return false;
3886 Dependent = false;
3887 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E.get()))
3888 return !DRE->hasExplicitTemplateArgs();
3889 if (auto *ME = dyn_cast<MemberExpr>(Val: E.get()))
3890 return !ME->hasExplicitTemplateArgs();
3891 Dependent = true;
3892 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(Val: E.get()))
3893 return !DSDRE->hasExplicitTemplateArgs();
3894 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(Val: E.get()))
3895 return !DSME->hasExplicitTemplateArgs();
3896 // Any additional cases recognized here should also be handled by
3897 // diagnoseExprIntendedAsTemplateName.
3898 return false;
3899 }
3900
3901 void warnOnReservedIdentifier(const NamedDecl *D);
3902 void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D);
3903
3904 void ProcessPragmaExport(DeclaratorDecl *newDecl);
3905
3906 Decl *ActOnDeclarator(Scope *S, Declarator &D);
3907
3908 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
3909 MultiTemplateParamsArg TemplateParameterLists);
3910
3911 /// Attempt to fold a variable-sized type to a constant-sized type, returning
3912 /// true if we were successful.
3913 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T,
3914 SourceLocation Loc,
3915 unsigned FailedFoldDiagID);
3916
3917 /// Register the given locally-scoped extern "C" declaration so
3918 /// that it can be found later for redeclarations. We include any extern "C"
3919 /// declaration that is not visible in the translation unit here, not just
3920 /// function-scope declarations.
3921 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
3922
3923 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3924 /// If T is the name of a class, then each of the following shall have a
3925 /// name different from T:
3926 /// - every static data member of class T;
3927 /// - every member function of class T
3928 /// - every member of class T that is itself a type;
3929 /// \returns true if the declaration name violates these rules.
3930 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
3931
3932 /// Diagnose a declaration whose declarator-id has the given
3933 /// nested-name-specifier.
3934 ///
3935 /// \param SS The nested-name-specifier of the declarator-id.
3936 ///
3937 /// \param DC The declaration context to which the nested-name-specifier
3938 /// resolves.
3939 ///
3940 /// \param Name The name of the entity being declared.
3941 ///
3942 /// \param Loc The location of the name of the entity being declared.
3943 ///
3944 /// \param IsMemberSpecialization Whether we are declaring a member
3945 /// specialization.
3946 ///
3947 /// \param TemplateId The template-id, if any.
3948 ///
3949 /// \returns true if we cannot safely recover from this error, false
3950 /// otherwise.
3951 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3952 DeclarationName Name, SourceLocation Loc,
3953 TemplateIdAnnotation *TemplateId,
3954 bool IsMemberSpecialization);
3955
3956 bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range);
3957
3958 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
3959
3960 bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind,
3961 unsigned &IntVal);
3962
3963 /// Diagnose function specifiers on a declaration of an identifier that
3964 /// does not identify a function.
3965 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
3966
3967 /// Return the declaration shadowed by the given typedef \p D, or null
3968 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3969 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
3970 const LookupResult &R);
3971
3972 /// Return the declaration shadowed by the given variable \p D, or null
3973 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3974 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
3975
3976 /// Return the declaration shadowed by the given variable \p D, or null
3977 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3978 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
3979 const LookupResult &R);
3980 /// Diagnose variable or built-in function shadowing. Implements
3981 /// -Wshadow.
3982 ///
3983 /// This method is called whenever a VarDecl is added to a "useful"
3984 /// scope.
3985 ///
3986 /// \param ShadowedDecl the declaration that is shadowed by the given variable
3987 /// \param R the lookup of the name
3988 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
3989 const LookupResult &R);
3990
3991 /// Check -Wshadow without the advantage of a previous lookup.
3992 void CheckShadow(Scope *S, VarDecl *D);
3993
3994 /// Warn if 'E', which is an expression that is about to be modified, refers
3995 /// to a shadowing declaration.
3996 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
3997
3998 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
3999 /// when these variables are captured by the lambda.
4000 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
4001
4002 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
4003 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4004 TypedefNameDecl *NewTD);
4005 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
4006 NamedDecl *ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4007 TypeSourceInfo *TInfo,
4008 LookupResult &Previous);
4009
4010 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4011 /// declares a typedef-name, either using the 'typedef' type specifier or via
4012 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4013 NamedDecl *ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D,
4014 LookupResult &Previous, bool &Redeclaration);
4015 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4016 TypeSourceInfo *TInfo,
4017 LookupResult &Previous,
4018 MultiTemplateParamsArg TemplateParamLists,
4019 bool &AddToScope,
4020 ArrayRef<BindingDecl *> Bindings = {});
4021
4022private:
4023 // Perform a check on an AsmLabel to verify its consistency and emit
4024 // diagnostics in case of an error.
4025 void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
4026 TypeSourceInfo *TInfo, VarDecl *);
4027
4028public:
4029 /// Perform semantic checking on a newly-created variable
4030 /// declaration.
4031 ///
4032 /// This routine performs all of the type-checking required for a
4033 /// variable declaration once it has been built. It is used both to
4034 /// check variables after they have been parsed and their declarators
4035 /// have been translated into a declaration, and to check variables
4036 /// that have been instantiated from a template.
4037 ///
4038 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4039 ///
4040 /// Returns true if the variable declaration is a redeclaration.
4041 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
4042 void CheckVariableDeclarationType(VarDecl *NewVD);
4043 void CheckCompleteVariableDeclaration(VarDecl *VD);
4044
4045 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4046 TypeSourceInfo *TInfo,
4047 LookupResult &Previous,
4048 MultiTemplateParamsArg TemplateParamLists,
4049 bool &AddToScope);
4050
4051 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4052 /// and if so, check that it's a valid override and remember it.
4053 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
4054
4055 /// Perform semantic checking of a new function declaration.
4056 ///
4057 /// Performs semantic analysis of the new function declaration
4058 /// NewFD. This routine performs all semantic checking that does not
4059 /// require the actual declarator involved in the declaration, and is
4060 /// used both for the declaration of functions as they are parsed
4061 /// (called via ActOnDeclarator) and for the declaration of functions
4062 /// that have been instantiated via C++ template instantiation (called
4063 /// via InstantiateDecl).
4064 ///
4065 /// \param IsMemberSpecialization whether this new function declaration is
4066 /// a member specialization (that replaces any definition provided by the
4067 /// previous declaration).
4068 ///
4069 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4070 ///
4071 /// \returns true if the function declaration is a redeclaration.
4072 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4073 LookupResult &Previous,
4074 bool IsMemberSpecialization, bool DeclIsDefn);
4075
4076 /// Checks if the new declaration declared in dependent context must be
4077 /// put in the same redeclaration chain as the specified declaration.
4078 ///
4079 /// \param D Declaration that is checked.
4080 /// \param PrevDecl Previous declaration found with proper lookup method for
4081 /// the same declaration name.
4082 /// \returns True if D must be added to the redeclaration chain which PrevDecl
4083 /// belongs to.
4084 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4085
4086 /// Determines if we can perform a correct type check for \p D as a
4087 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4088 /// best-effort check.
4089 ///
4090 /// \param NewD The new declaration.
4091 /// \param OldD The old declaration.
4092 /// \param NewT The portion of the type of the new declaration to check.
4093 /// \param OldT The portion of the type of the old declaration to check.
4094 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4095 QualType NewT, QualType OldT);
4096 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4097 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4098
4099 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4100 /// containing class. Otherwise it will return implicit SectionAttr if the
4101 /// function is a definition and there is an active value on CodeSegStack
4102 /// (from the current #pragma code-seg value).
4103 ///
4104 /// \param FD Function being declared.
4105 /// \param IsDefinition Whether it is a definition or just a declaration.
4106 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4107 /// nullptr if no attribute should be added.
4108 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4109 bool IsDefinition);
4110
4111 /// Common checks for a parameter-declaration that should apply to both
4112 /// function parameters and non-type template parameters.
4113 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4114
4115 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4116 /// to introduce parameters into function prototype scope.
4117 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4118 SourceLocation ExplicitThisLoc = {});
4119
4120 /// Synthesizes a variable for a parameter arising from a
4121 /// typedef.
4122 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4123 QualType T);
4124 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4125 SourceLocation NameLoc,
4126 const IdentifierInfo *Name, QualType T,
4127 TypeSourceInfo *TSInfo, StorageClass SC);
4128
4129 /// Emit diagnostics if the initializer or any of its explicit or
4130 /// implicitly-generated subexpressions require copying or
4131 /// default-initializing a type that is or contains a C union type that is
4132 /// non-trivial to copy or default-initialize.
4133 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4134
4135 // These flags are passed to checkNonTrivialCUnion.
4136 enum NonTrivialCUnionKind {
4137 NTCUK_Init = 0x1,
4138 NTCUK_Destruct = 0x2,
4139 NTCUK_Copy = 0x4,
4140 };
4141
4142 /// Emit diagnostics if a non-trivial C union type or a struct that contains
4143 /// a non-trivial C union is used in an invalid context.
4144 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
4145 NonTrivialCUnionContext UseContext,
4146 unsigned NonTrivialKind);
4147
4148 /// Certain globally-unique variables might be accidentally duplicated if
4149 /// built into multiple shared libraries with hidden visibility. This can
4150 /// cause problems if the variable is mutable, its initialization is
4151 /// effectful, or its address is taken.
4152 bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl);
4153 void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl);
4154
4155 /// AddInitializerToDecl - Adds the initializer Init to the
4156 /// declaration dcl. If DirectInit is true, this is C++ direct
4157 /// initialization rather than copy initialization.
4158 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4159 void ActOnUninitializedDecl(Decl *dcl);
4160
4161 /// ActOnInitializerError - Given that there was an error parsing an
4162 /// initializer for the given declaration, try to at least re-establish
4163 /// invariants such as whether a variable's type is either dependent or
4164 /// complete.
4165 void ActOnInitializerError(Decl *Dcl);
4166
4167 void ActOnCXXForRangeDecl(Decl *D);
4168 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
4169 IdentifierInfo *Ident,
4170 ParsedAttributes &Attrs);
4171
4172 /// Check if VD needs to be dllexport/dllimport due to being in a
4173 /// dllexport/import function.
4174 void CheckStaticLocalForDllExport(VarDecl *VD);
4175 void CheckThreadLocalForLargeAlignment(VarDecl *VD);
4176
4177 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4178 /// any semantic actions necessary after any initializer has been attached.
4179 void FinalizeDeclaration(Decl *D);
4180 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4181 ArrayRef<Decl *> Group);
4182
4183 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4184 /// group, performing any necessary semantic checking.
4185 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
4186
4187 /// Should be called on all declarations that might have attached
4188 /// documentation comments.
4189 void ActOnDocumentableDecl(Decl *D);
4190 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
4191
4192 enum class FnBodyKind {
4193 /// C++26 [dcl.fct.def.general]p1
4194 /// function-body:
4195 /// ctor-initializer[opt] compound-statement
4196 /// function-try-block
4197 Other,
4198 /// = default ;
4199 Default,
4200 /// deleted-function-body
4201 ///
4202 /// deleted-function-body:
4203 /// = delete ;
4204 /// = delete ( unevaluated-string ) ;
4205 Delete
4206 };
4207
4208 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4209 SourceLocation LocAfterDecls);
4210 void CheckForFunctionRedefinition(
4211 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4212 SkipBodyInfo *SkipBody = nullptr);
4213 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
4214 MultiTemplateParamsArg TemplateParamLists,
4215 SkipBodyInfo *SkipBody = nullptr,
4216 FnBodyKind BodyKind = FnBodyKind::Other);
4217 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
4218 SkipBodyInfo *SkipBody = nullptr,
4219 FnBodyKind BodyKind = FnBodyKind::Other);
4220 void applyFunctionAttributesBeforeParsingBody(Decl *FD);
4221
4222 /// Determine whether we can delay parsing the body of a function or
4223 /// function template until it is used, assuming we don't care about emitting
4224 /// code for that function.
4225 ///
4226 /// This will be \c false if we may need the body of the function in the
4227 /// middle of parsing an expression (where it's impractical to switch to
4228 /// parsing a different function), for instance, if it's constexpr in C++11
4229 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4230 bool canDelayFunctionBody(const Declarator &D);
4231
4232 /// Determine whether we can skip parsing the body of a function
4233 /// definition, assuming we don't care about analyzing its body or emitting
4234 /// code for that function.
4235 ///
4236 /// This will be \c false only if we may need the body of the function in
4237 /// order to parse the rest of the program (for instance, if it is
4238 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4239 bool canSkipFunctionBody(Decl *D);
4240
4241 /// Given the set of return statements within a function body,
4242 /// compute the variables that are subject to the named return value
4243 /// optimization.
4244 ///
4245 /// Each of the variables that is subject to the named return value
4246 /// optimization will be marked as NRVO variables in the AST, and any
4247 /// return statement that has a marked NRVO variable as its NRVO candidate can
4248 /// use the named return value optimization.
4249 ///
4250 /// This function applies a very simplistic algorithm for NRVO: if every
4251 /// return statement in the scope of a variable has the same NRVO candidate,
4252 /// that candidate is an NRVO variable.
4253 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
4254
4255 /// Performs semantic analysis at the end of a function body.
4256 ///
4257 /// \param RetainFunctionScopeInfo If \c true, the client is responsible for
4258 /// releasing the associated \p FunctionScopeInfo. This is useful when
4259 /// building e.g. LambdaExprs.
4260 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body,
4261 bool IsInstantiation = false,
4262 bool RetainFunctionScopeInfo = false);
4263 Decl *ActOnSkippedFunctionBody(Decl *Decl);
4264 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
4265
4266 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4267 /// attribute for which parsing is delayed.
4268 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
4269
4270 /// Diagnose any unused parameters in the given sequence of
4271 /// ParmVarDecl pointers.
4272 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
4273
4274 /// Diagnose whether the size of parameters or return value of a
4275 /// function or obj-c method definition is pass-by-value and larger than a
4276 /// specified threshold.
4277 void
4278 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
4279 QualType ReturnTy, NamedDecl *D);
4280
4281 Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc,
4282 SourceLocation RParenLoc);
4283
4284 TopLevelStmtDecl *ActOnStartTopLevelStmtDecl(Scope *S);
4285 void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement);
4286
4287 void ActOnPopScope(SourceLocation Loc, Scope *S);
4288
4289 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4290 /// no declarator (e.g. "struct foo;") is parsed.
4291 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4292 const ParsedAttributesView &DeclAttrs,
4293 RecordDecl *&AnonRecord);
4294
4295 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4296 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4297 /// parameters to cope with template friend declarations.
4298 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4299 const ParsedAttributesView &DeclAttrs,
4300 MultiTemplateParamsArg TemplateParams,
4301 bool IsExplicitInstantiation,
4302 RecordDecl *&AnonRecord,
4303 SourceLocation EllipsisLoc = {});
4304
4305 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4306 /// anonymous structure or union. Anonymous unions are a C++ feature
4307 /// (C++ [class.union]) and a C11 feature; anonymous structures
4308 /// are a C11 feature and GNU C++ extension.
4309 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4310 RecordDecl *Record,
4311 const PrintingPolicy &Policy);
4312
4313 /// Called once it is known whether
4314 /// a tag declaration is an anonymous union or struct.
4315 void ActOnDefinedDeclarationSpecifier(Decl *D);
4316
4317 /// Emit diagnostic warnings for placeholder members.
4318 /// We can only do that after the class is fully constructed,
4319 /// as anonymous union/structs can insert placeholders
4320 /// in their parent scope (which might be a Record).
4321 void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record);
4322
4323 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4324 /// Microsoft C anonymous structure.
4325 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4326 /// Example:
4327 ///
4328 /// struct A { int a; };
4329 /// struct B { struct A; int b; };
4330 ///
4331 /// void foo() {
4332 /// B var;
4333 /// var.a = 3;
4334 /// }
4335 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4336 RecordDecl *Record);
4337
4338 /// Given a non-tag type declaration, returns an enum useful for indicating
4339 /// what kind of non-tag type this is.
4340 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4341
4342 /// Determine whether a tag with a given kind is acceptable
4343 /// as a redeclaration of the given tag declaration.
4344 ///
4345 /// \returns true if the new tag kind is acceptable, false otherwise.
4346 bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag,
4347 bool isDefinition, SourceLocation NewTagLoc,
4348 const IdentifierInfo *Name);
4349
4350 /// This is invoked when we see 'struct foo' or 'struct {'. In the
4351 /// former case, Name will be non-null. In the later case, Name will be null.
4352 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4353 /// a reference/declaration/definition of a tag.
4354 ///
4355 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4356 /// trailing-type-specifier) other than one in an alias-declaration.
4357 ///
4358 /// \param SkipBody If non-null, will be set to indicate if the caller should
4359 /// skip the definition of this tag and treat it as if it were a declaration.
4360 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4361 SourceLocation KWLoc, CXXScopeSpec &SS,
4362 IdentifierInfo *Name, SourceLocation NameLoc,
4363 const ParsedAttributesView &Attr, AccessSpecifier AS,
4364 SourceLocation ModulePrivateLoc,
4365 MultiTemplateParamsArg TemplateParameterLists,
4366 bool &OwnedDecl, bool &IsDependent,
4367 SourceLocation ScopedEnumKWLoc,
4368 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4369 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4370 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4371
4372 /// ActOnField - Each field of a C struct/union is passed into this in order
4373 /// to create a FieldDecl object for it.
4374 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4375 Declarator &D, Expr *BitfieldWidth);
4376
4377 /// HandleField - Analyze a field of a C struct or a C++ data member.
4378 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4379 Declarator &D, Expr *BitfieldWidth,
4380 InClassInitStyle InitStyle, AccessSpecifier AS);
4381
4382 /// Build a new FieldDecl and check its well-formedness.
4383 ///
4384 /// This routine builds a new FieldDecl given the fields name, type,
4385 /// record, etc. \p PrevDecl should refer to any previous declaration
4386 /// with the same name and in the same scope as the field to be
4387 /// created.
4388 ///
4389 /// \returns a new FieldDecl.
4390 ///
4391 /// \todo The Declarator argument is a hack. It will be removed once
4392 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4393 TypeSourceInfo *TInfo, RecordDecl *Record,
4394 SourceLocation Loc, bool Mutable,
4395 Expr *BitfieldWidth, InClassInitStyle InitStyle,
4396 SourceLocation TSSL, AccessSpecifier AS,
4397 NamedDecl *PrevDecl, Declarator *D = nullptr);
4398
4399 bool CheckNontrivialField(FieldDecl *FD);
4400
4401 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4402 /// class and class extensions. For every class \@interface and class
4403 /// extension \@interface, if the last ivar is a bitfield of any type,
4404 /// then add an implicit `char :0` ivar to the end of that interface.
4405 void ActOnLastBitfield(SourceLocation DeclStart,
4406 SmallVectorImpl<Decl *> &AllIvarDecls);
4407
4408 // This is used for both record definitions and ObjC interface declarations.
4409 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4410 ArrayRef<Decl *> Fields, SourceLocation LBrac,
4411 SourceLocation RBrac, const ParsedAttributesView &AttrList);
4412
4413 /// ActOnTagStartDefinition - Invoked when we have entered the
4414 /// scope of a tag's definition (e.g., for an enumeration, class,
4415 /// struct, or union).
4416 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4417
4418 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4419 /// Differently from C++, actually parse the body and reject / error out
4420 /// in case of a structural mismatch.
4421 bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4422
4423 typedef void *SkippedDefinitionContext;
4424
4425 /// Invoked when we enter a tag definition that we're skipping.
4426 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
4427
4428 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4429 /// C++ record definition's base-specifiers clause and are starting its
4430 /// member declarations.
4431 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
4432 SourceLocation FinalLoc,
4433 bool IsFinalSpelledSealed,
4434 bool IsAbstract,
4435 SourceLocation LBraceLoc);
4436
4437 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4438 /// the definition of a tag (enumeration, class, struct, or union).
4439 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
4440 SourceRange BraceRange);
4441
4442 ASTContext::CXXRecordDeclRelocationInfo
4443 CheckCXX2CRelocatable(const clang::CXXRecordDecl *D);
4444
4445 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
4446
4447 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4448 /// error parsing the definition of a tag.
4449 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
4450
4451 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
4452 EnumConstantDecl *LastEnumConst,
4453 SourceLocation IdLoc, IdentifierInfo *Id,
4454 Expr *val);
4455
4456 /// Check that this is a valid underlying type for an enum declaration.
4457 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
4458
4459 /// Check whether this is a valid redeclaration of a previous enumeration.
4460 /// \return true if the redeclaration was invalid.
4461 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4462 QualType EnumUnderlyingTy, bool IsFixed,
4463 const EnumDecl *Prev);
4464
4465 /// Determine whether the body of an anonymous enumeration should be skipped.
4466 /// \param II The name of the first enumerator.
4467 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
4468 SourceLocation IILoc);
4469
4470 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4471 SourceLocation IdLoc, IdentifierInfo *Id,
4472 const ParsedAttributesView &Attrs,
4473 SourceLocation EqualLoc, Expr *Val,
4474 SkipBodyInfo *SkipBody = nullptr);
4475 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4476 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4477 const ParsedAttributesView &Attr);
4478
4479 /// Set the current declaration context until it gets popped.
4480 void PushDeclContext(Scope *S, DeclContext *DC);
4481 void PopDeclContext();
4482
4483 /// EnterDeclaratorContext - Used when we must lookup names in the context
4484 /// of a declarator's nested name specifier.
4485 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
4486 void ExitDeclaratorContext(Scope *S);
4487
4488 /// Enter a template parameter scope, after it's been associated with a
4489 /// particular DeclContext. Causes lookup within the scope to chain through
4490 /// enclosing contexts in the correct order.
4491 void EnterTemplatedContext(Scope *S, DeclContext *DC);
4492
4493 /// Push the parameters of D, which must be a function, into scope.
4494 void ActOnReenterFunctionContext(Scope *S, Decl *D);
4495 void ActOnExitFunctionContext();
4496
4497 /// Add this decl to the scope shadowed decl chains.
4498 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4499
4500 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4501 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4502 /// true if 'D' belongs to the given declaration context.
4503 ///
4504 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4505 /// enclosing namespace set of the context, rather than contained
4506 /// directly within it.
4507 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4508 bool AllowInlineNamespace = false) const;
4509
4510 /// Finds the scope corresponding to the given decl context, if it
4511 /// happens to be an enclosing scope. Otherwise return NULL.
4512 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
4513
4514 /// Subroutines of ActOnDeclarator().
4515 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4516 TypeSourceInfo *TInfo);
4517 bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New);
4518
4519 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4520 void mergeDeclAttributes(
4521 NamedDecl *New, Decl *Old,
4522 AvailabilityMergeKind AMK = AvailabilityMergeKind::Redeclaration);
4523
4524 /// CheckAttributesOnDeducedType - Calls Sema functions for attributes that
4525 /// requires the type to be deduced.
4526 void CheckAttributesOnDeducedType(Decl *D);
4527
4528 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4529 /// same name and scope as a previous declaration 'Old'. Figure out
4530 /// how to resolve this situation, merging decls or emitting
4531 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4532 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
4533 LookupResult &OldDecls);
4534
4535 /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4536 /// definition visible.
4537 /// This method performs any necessary cleanup on the parser state to discard
4538 /// child nodes from newly parsed decl we are retiring.
4539 void CleanupMergedEnum(Scope *S, Decl *New);
4540
4541 /// MergeFunctionDecl - We just parsed a function 'New' from
4542 /// declarator D which has the same name and scope as a previous
4543 /// declaration 'Old'. Figure out how to resolve this situation,
4544 /// merging decls or emitting diagnostics as appropriate.
4545 ///
4546 /// In C++, New and Old must be declarations that are not
4547 /// overloaded. Use IsOverload to determine whether New and Old are
4548 /// overloaded, and to select the Old declaration that New should be
4549 /// merged with.
4550 ///
4551 /// Returns true if there was an error, false otherwise.
4552 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
4553 bool MergeTypeWithOld, bool NewDeclIsDefn);
4554
4555 /// Completes the merge of two function declarations that are
4556 /// known to be compatible.
4557 ///
4558 /// This routine handles the merging of attributes and other
4559 /// properties of function declarations from the old declaration to
4560 /// the new declaration, once we know that New is in fact a
4561 /// redeclaration of Old.
4562 ///
4563 /// \returns false
4564 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4565 Scope *S, bool MergeTypeWithOld);
4566 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
4567
4568 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4569 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4570 /// situation, merging decls or emitting diagnostics as appropriate.
4571 ///
4572 /// Tentative definition rules (C99 6.9.2p2) are checked by
4573 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4574 /// definitions here, since the initializer hasn't been attached.
4575 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
4576
4577 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4578 /// scope as a previous declaration 'Old'. Figure out how to merge their
4579 /// types, emitting diagnostics as appropriate.
4580 ///
4581 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4582 /// back to here in AddInitializerToDecl. We can't check them before the
4583 /// initializer is attached.
4584 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4585
4586 /// We've just determined that \p Old and \p New both appear to be definitions
4587 /// of the same variable. Either diagnose or fix the problem.
4588 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4589 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
4590
4591 /// Filters out lookup results that don't fall within the given scope
4592 /// as determined by isDeclInScope.
4593 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4594 bool ConsiderLinkage, bool AllowInlineNamespace);
4595
4596 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4597 /// have compatible owning modules.
4598 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4599
4600 /// [module.interface]p6:
4601 /// A redeclaration of an entity X is implicitly exported if X was introduced
4602 /// by an exported declaration; otherwise it shall not be exported.
4603 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4604
4605 /// A wrapper function for checking the semantic restrictions of
4606 /// a redeclaration within a module.
4607 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4608
4609 /// Check the redefinition in C++20 Modules.
4610 ///
4611 /// [basic.def.odr]p14:
4612 /// For any definable item D with definitions in multiple translation units,
4613 /// - if D is a non-inline non-templated function or variable, or
4614 /// - if the definitions in different translation units do not satisfy the
4615 /// following requirements,
4616 /// the program is ill-formed; a diagnostic is required only if the
4617 /// definable item is attached to a named module and a prior definition is
4618 /// reachable at the point where a later definition occurs.
4619 /// - Each such definition shall not be attached to a named module
4620 /// ([module.unit]).
4621 /// - Each such definition shall consist of the same sequence of tokens, ...
4622 /// ...
4623 ///
4624 /// Return true if the redefinition is not allowed. Return false otherwise.
4625 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4626
4627 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4628
4629 /// If it's a file scoped decl that must warn if not used, keep track
4630 /// of it.
4631 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4632
4633 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4634 DiagReceiverTy;
4635
4636 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4637 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
4638 DiagReceiverTy DiagReceiver);
4639 void DiagnoseUnusedDecl(const NamedDecl *ND);
4640
4641 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4642 /// unless they are marked attr(unused).
4643 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4644
4645 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4646 /// variable.
4647 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4648
4649 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4650 /// from S, where a non-field would be declared. This routine copes
4651 /// with the difference between C and C++ scoping rules in structs and
4652 /// unions. For example, the following code is well-formed in C but
4653 /// ill-formed in C++:
4654 /// @code
4655 /// struct S6 {
4656 /// enum { BAR } e;
4657 /// };
4658 ///
4659 /// void test_S6() {
4660 /// struct S6 a;
4661 /// a.e = BAR;
4662 /// }
4663 /// @endcode
4664 /// For the declaration of BAR, this routine will return a different
4665 /// scope. The scope S will be the scope of the unnamed enumeration
4666 /// within S6. In C++, this routine will return the scope associated
4667 /// with S6, because the enumeration's scope is a transparent
4668 /// context but structures can contain non-field names. In C, this
4669 /// routine will return the translation unit scope, since the
4670 /// enumeration's scope is a transparent context and structures cannot
4671 /// contain non-field names.
4672 Scope *getNonFieldDeclScope(Scope *S);
4673
4674 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4675 SourceLocation Loc);
4676
4677 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4678 /// file scope. lazily create a decl for it. ForRedeclaration is true
4679 /// if we're creating this built-in in anticipation of redeclaring the
4680 /// built-in.
4681 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4682 bool ForRedeclaration, SourceLocation Loc);
4683
4684 /// Get the outermost AttributedType node that sets a calling convention.
4685 /// Valid types should not have multiple attributes with different CCs.
4686 const AttributedType *getCallingConvAttributedType(QualType T) const;
4687
4688 /// GetNameForDeclarator - Determine the full declaration name for the
4689 /// given Declarator.
4690 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
4691
4692 /// Retrieves the declaration name from a parsed unqualified-id.
4693 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
4694
4695 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4696 /// we are currently parsing the initializer.
4697 llvm::SmallPtrSet<const Decl *, 4> ParsingInitForAutoVars;
4698
4699 /// Look for a locally scoped extern "C" declaration by the given name.
4700 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
4701
4702 void deduceOpenCLAddressSpace(VarDecl *decl);
4703 void deduceHLSLAddressSpace(VarDecl *decl);
4704
4705 /// Adjust the \c DeclContext for a function or variable that might be a
4706 /// function-local external declaration.
4707 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
4708
4709 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4710
4711 /// Checks if the variant/multiversion functions are compatible.
4712 bool areMultiversionVariantFunctionsCompatible(
4713 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4714 const PartialDiagnostic &NoProtoDiagID,
4715 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4716 const PartialDiagnosticAt &NoSupportDiagIDAt,
4717 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4718 bool ConstexprSupported, bool CLinkageMayDiffer);
4719
4720 /// type checking declaration initializers (C99 6.7.8)
4721 bool CheckForConstantInitializer(
4722 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4723
4724 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
4725 QualType Type, TypeSourceInfo *TSI,
4726 SourceRange Range, bool DirectInit,
4727 Expr *Init);
4728
4729 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
4730 Expr *Init);
4731
4732 sema::LambdaScopeInfo *RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator);
4733
4734 // Heuristically tells if the function is `get_return_object` member of a
4735 // coroutine promise_type by matching the function name.
4736 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4737 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4738
4739 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4740 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4741 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4742 Scope *S);
4743
4744 /// If this function is a C++ replaceable global allocation function
4745 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4746 /// adds any function attributes that we know a priori based on the standard.
4747 ///
4748 /// We need to check for duplicate attributes both here and where user-written
4749 /// attributes are applied to declarations.
4750 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4751 FunctionDecl *FD);
4752
4753 /// Adds any function attributes that we know a priori based on
4754 /// the declaration of this function.
4755 ///
4756 /// These attributes can apply both to implicitly-declared builtins
4757 /// (like __builtin___printf_chk) or to library-declared functions
4758 /// like NSLog or printf.
4759 ///
4760 /// We need to check for duplicate attributes both here and where user-written
4761 /// attributes are applied to declarations.
4762 void AddKnownFunctionAttributes(FunctionDecl *FD);
4763
4764 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4765 /// the correct width, and that the field type is valid.
4766 /// Returns false on success.
4767 ExprResult VerifyBitField(SourceLocation FieldLoc,
4768 const IdentifierInfo *FieldName, QualType FieldTy,
4769 bool IsMsStruct, Expr *BitWidth);
4770
4771 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4772 /// enum. If AllowMask is true, then we also allow the complement of a valid
4773 /// value, to be used as a mask.
4774 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4775 bool AllowMask) const;
4776
4777 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4778 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4779 SourceLocation WeakNameLoc);
4780
4781 /// ActOnPragmaRedefineExtname - Called on well formed
4782 /// \#pragma redefine_extname oldname newname.
4783 void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName,
4784 IdentifierInfo *AliasName,
4785 SourceLocation PragmaLoc,
4786 SourceLocation WeakNameLoc,
4787 SourceLocation AliasNameLoc);
4788
4789 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4790 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4791 SourceLocation PragmaLoc,
4792 SourceLocation WeakNameLoc,
4793 SourceLocation AliasNameLoc);
4794
4795 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4796 enum class FunctionEmissionStatus {
4797 Emitted,
4798 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4799 OMPDiscarded, // Discarded due to OpenMP hostness
4800 TemplateDiscarded, // Discarded due to uninstantiated templates
4801 Unknown,
4802 };
4803 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4804 bool Final = false);
4805
4806 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4807 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4808
4809 /// Function or variable declarations to be checked for whether the deferred
4810 /// diagnostics should be emitted.
4811 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
4812
4813private:
4814 /// Map of current shadowing declarations to shadowed declarations. Warn if
4815 /// it looks like the user is trying to modify the shadowing declaration.
4816 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4817
4818 // We need this to handle
4819 //
4820 // typedef struct {
4821 // void *foo() { return 0; }
4822 // } A;
4823 //
4824 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4825 // for example. If 'A', foo will have external linkage. If we have '*A',
4826 // foo will have no linkage. Since we can't know until we get to the end
4827 // of the typedef, this function finds out if D might have non-external
4828 // linkage. Callers should verify at the end of the TU if it D has external
4829 // linkage or not.
4830 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4831
4832#include "clang/Sema/AttrIsTypeDependent.inc"
4833
4834 ///@}
4835
4836 //
4837 //
4838 // -------------------------------------------------------------------------
4839 //
4840 //
4841
4842 /// \name Declaration Attribute Handling
4843 /// Implementations are in SemaDeclAttr.cpp
4844 ///@{
4845
4846public:
4847 /// Describes the kind of priority given to an availability attribute.
4848 ///
4849 /// The sum of priorities deteremines the final priority of the attribute.
4850 /// The final priority determines how the attribute will be merged.
4851 /// An attribute with a lower priority will always remove higher priority
4852 /// attributes for the specified platform when it is being applied. An
4853 /// attribute with a higher priority will not be applied if the declaration
4854 /// already has an availability attribute with a lower priority for the
4855 /// specified platform. The final prirority values are not expected to match
4856 /// the values in this enumeration, but instead should be treated as a plain
4857 /// integer value. This enumeration just names the priority weights that are
4858 /// used to calculate that final vaue.
4859 enum AvailabilityPriority : int {
4860 /// The availability attribute was specified explicitly next to the
4861 /// declaration.
4862 AP_Explicit = 0,
4863
4864 /// The availability attribute was applied using '#pragma clang attribute'.
4865 AP_PragmaClangAttribute = 1,
4866
4867 /// The availability attribute for a specific platform was inferred from
4868 /// an availability attribute for another platform.
4869 AP_InferredFromOtherPlatform = 2,
4870
4871 /// The availability attribute was inferred from an 'anyAppleOS'
4872 /// availability attribute.
4873 AP_InferredFromAnyAppleOS = 3,
4874
4875 /// The availability attribute was inferred from an 'anyAppleOS'
4876 /// availability attribute that was applied using '#pragma clang attribute'.
4877 /// This has the lowest priority.
4878 AP_PragmaClangAttribute_InferredFromAnyAppleOS = 4
4879 };
4880
4881 /// Describes the reason a calling convention specification was ignored, used
4882 /// for diagnostics.
4883 enum class CallingConventionIgnoredReason {
4884 ForThisTarget = 0,
4885 VariadicFunction,
4886 ConstructorDestructor,
4887 BuiltinFunction
4888 };
4889
4890 /// A helper function to provide Attribute Location for the Attr types
4891 /// AND the ParsedAttr.
4892 template <typename AttrInfo>
4893 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
4894 getAttrLoc(const AttrInfo &AL) {
4895 return AL.getLocation();
4896 }
4897 SourceLocation getAttrLoc(const AttributeCommonInfo &CI);
4898
4899 /// If Expr is a valid integer constant, get the value of the integer
4900 /// expression and return success or failure. May output an error.
4901 ///
4902 /// Negative argument is implicitly converted to unsigned, unless
4903 /// \p StrictlyUnsigned is true.
4904 template <typename AttrInfo>
4905 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
4906 unsigned Idx = UINT_MAX,
4907 bool StrictlyUnsigned = false) {
4908 std::optional<llvm::APSInt> I = llvm::APSInt(32);
4909 if (Expr->isTypeDependent() ||
4910 !(I = Expr->getIntegerConstantExpr(Ctx: Context))) {
4911 if (Idx != UINT_MAX)
4912 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
4913 << &AI << Idx << AANT_ArgumentIntegerConstant
4914 << Expr->getSourceRange();
4915 else
4916 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
4917 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
4918 return false;
4919 }
4920
4921 if (!I->isIntN(N: 32)) {
4922 Diag(Loc: Expr->getExprLoc(), DiagID: diag::err_ice_too_large)
4923 << toString(I: *I, Radix: 10, Signed: false) << 32 << /* Unsigned */ 1;
4924 return false;
4925 }
4926
4927 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
4928 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
4929 << &AI << /*non-negative*/ 1;
4930 return false;
4931 }
4932
4933 Val = (uint32_t)I->getZExtValue();
4934 return true;
4935 }
4936
4937 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
4938 /// \#pragma weak during processing of other Decls.
4939 /// I couldn't figure out a clean way to generate these in-line, so
4940 /// we store them here and handle separately -- which is a hack.
4941 /// It would be best to refactor this.
4942 SmallVector<Decl *, 2> WeakTopLevelDecl;
4943
4944 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
4945 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
4946
4947 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
4948 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
4949 ExtVectorDeclsType;
4950
4951 /// ExtVectorDecls - This is a list all the extended vector types. This allows
4952 /// us to associate a raw vector type with one of the ext_vector type names.
4953 /// This is only necessary for issuing pretty diagnostics.
4954 ExtVectorDeclsType ExtVectorDecls;
4955
4956 /// Check if the argument \p E is a ASCII string literal. If not emit an error
4957 /// and return false, otherwise set \p Str to the value of the string literal
4958 /// and return true.
4959 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
4960 const Expr *E, StringRef &Str,
4961 SourceLocation *ArgLocation = nullptr);
4962
4963 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
4964 /// If not emit an error and return false. If the argument is an identifier it
4965 /// will emit an error with a fixit hint and treat it as if it was a string
4966 /// literal.
4967 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4968 StringRef &Str,
4969 SourceLocation *ArgLocation = nullptr);
4970
4971 /// Determine if type T is a valid subject for a nonnull and similar
4972 /// attributes. Dependent types are considered valid so they can be checked
4973 /// during instantiation time. By default, we look through references (the
4974 /// behavior used by nonnull), but if the second parameter is true, then we
4975 /// treat a reference type as valid.
4976 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4977
4978 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
4979 /// declaration.
4980 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4981 Expr *OE);
4982
4983 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
4984 /// declaration.
4985 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
4986 Expr *ParamExpr);
4987
4988 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4989 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4990
4991 AvailabilityAttr *
4992 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
4993 const IdentifierInfo *Platform, bool Implicit,
4994 VersionTuple Introduced, VersionTuple Deprecated,
4995 VersionTuple Obsoleted, bool IsUnavailable,
4996 StringRef Message, bool IsStrict, StringRef Replacement,
4997 AvailabilityMergeKind AMK, int Priority,
4998 const IdentifierInfo *IIEnvironment,
4999 VersionTuple OrigAnyAppleOSVersion = {});
5000
5001 TypeVisibilityAttr *
5002 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5003 TypeVisibilityAttr::VisibilityType Vis);
5004 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5005 VisibilityAttr::VisibilityType Vis);
5006 void mergeVisibilityType(Decl *D, SourceLocation Loc,
5007 VisibilityAttr::VisibilityType Type);
5008 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
5009 StringRef Name);
5010
5011 /// Used to implement to perform semantic checking on
5012 /// attribute((section("foo"))) specifiers.
5013 ///
5014 /// In this case, "foo" is passed in to be checked. If the section
5015 /// specifier is invalid, return an Error that indicates the problem.
5016 ///
5017 /// This is a simple quality of implementation feature to catch errors
5018 /// and give good diagnostics in cases when the assembler or code generator
5019 /// would otherwise reject the section specifier.
5020 llvm::Error isValidSectionSpecifier(StringRef Str);
5021 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
5022 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
5023 StringRef Name);
5024
5025 // Check for things we'd like to warn about. Multiversioning issues are
5026 // handled later in the process, once we know how many exist.
5027 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
5028
5029 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
5030 StringRef NewUserDiagnostic);
5031 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
5032 const IdentifierInfo *Format, int FormatIdx,
5033 int FirstArg);
5034 FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
5035 const AttributeCommonInfo &CI,
5036 const IdentifierInfo *Format,
5037 int FormatIdx,
5038 StringLiteral *FormatStr);
5039 ModularFormatAttr *mergeModularFormatAttr(Decl *D,
5040 const AttributeCommonInfo &CI,
5041 const IdentifierInfo *ModularImplFn,
5042 StringRef ImplName,
5043 MutableArrayRef<StringRef> Aspects);
5044
5045 PersonalityAttr *mergePersonalityAttr(Decl *D, FunctionDecl *Routine,
5046 const AttributeCommonInfo &CI);
5047
5048 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5049 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5050 bool IsPackExpansion);
5051 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
5052 bool IsPackExpansion);
5053
5054 /// AddAlignValueAttr - Adds an align_value attribute to a particular
5055 /// declaration.
5056 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
5057
5058 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
5059 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
5060 MutableArrayRef<Expr *> Args);
5061 Attr *CreateAnnotationAttr(const ParsedAttr &AL);
5062
5063 bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range,
5064 bool BestCase,
5065 MSInheritanceModel SemanticSpelling);
5066
5067 void CheckAlignasUnderalignment(Decl *D);
5068
5069 /// AddModeAttr - Adds a mode attribute to a particular declaration.
5070 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
5071 const IdentifierInfo *Name, bool InInstantiation = false);
5072 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
5073 const AttributeCommonInfo &CI,
5074 const IdentifierInfo *Ident);
5075 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
5076 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
5077 const AttributeCommonInfo &CI);
5078 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
5079 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
5080 const InternalLinkageAttr &AL);
5081
5082 /// Check validaty of calling convention attribute \p attr. If \p FD
5083 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
5084 /// target. Otherwise, it is specified by \p CFT.
5085 bool CheckCallingConvAttr(
5086 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
5087 CUDAFunctionTarget CFT = CUDAFunctionTarget::InvalidTarget);
5088
5089 /// Checks a regparm attribute, returning true if it is ill-formed and
5090 /// otherwise setting numParams to the appropriate value.
5091 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
5092
5093 /// Create an CUDALaunchBoundsAttr attribute.
5094 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
5095 Expr *MaxThreads,
5096 Expr *MinBlocks,
5097 Expr *MaxBlocks);
5098
5099 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
5100 /// declaration.
5101 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5102 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
5103
5104 /// Add a cluster_dims attribute to a particular declaration.
5105 CUDAClusterDimsAttr *createClusterDimsAttr(const AttributeCommonInfo &CI,
5106 Expr *X, Expr *Y, Expr *Z);
5107 void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
5108 Expr *Y, Expr *Z);
5109 /// Add a no_cluster attribute to a particular declaration.
5110 void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI);
5111
5112 enum class RetainOwnershipKind { NS, CF, OS };
5113
5114 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5115 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5116
5117 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5118
5119 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5120 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5121 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5122 const AttributeCommonInfo &CI,
5123 bool BestCase,
5124 MSInheritanceModel Model);
5125
5126 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5127 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5128 const EnforceTCBLeafAttr &AL);
5129
5130 /// Helper for delayed processing TransparentUnion or
5131 /// BPFPreserveAccessIndexAttr attribute.
5132 void ProcessDeclAttributeDelayed(Decl *D,
5133 const ParsedAttributesView &AttrList);
5134
5135 // Options for ProcessDeclAttributeList().
5136 struct ProcessDeclAttributeOptions {
5137 ProcessDeclAttributeOptions()
5138 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
5139
5140 ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
5141 ProcessDeclAttributeOptions Result = *this;
5142 Result.IncludeCXX11Attributes = Val;
5143 return Result;
5144 }
5145
5146 ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
5147 ProcessDeclAttributeOptions Result = *this;
5148 Result.IgnoreTypeAttributes = Val;
5149 return Result;
5150 }
5151
5152 // Should C++11 attributes be processed?
5153 bool IncludeCXX11Attributes;
5154
5155 // Should any type attributes encountered be ignored?
5156 // If this option is false, a diagnostic will be emitted for any type
5157 // attributes of a kind that does not "slide" from the declaration to
5158 // the decl-specifier-seq.
5159 bool IgnoreTypeAttributes;
5160 };
5161
5162 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5163 /// attribute list to the specified decl, ignoring any type attributes.
5164 void ProcessDeclAttributeList(Scope *S, Decl *D,
5165 const ParsedAttributesView &AttrList,
5166 const ProcessDeclAttributeOptions &Options =
5167 ProcessDeclAttributeOptions());
5168
5169 /// Annotation attributes are the only attributes allowed after an access
5170 /// specifier.
5171 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5172 const ParsedAttributesView &AttrList);
5173
5174 /// checkUnusedDeclAttributes - Given a declarator which is not being
5175 /// used to build a declaration, complain about any decl attributes
5176 /// which might be lying around on it.
5177 void checkUnusedDeclAttributes(Declarator &D);
5178
5179 void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5180
5181 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5182 /// \#pragma weak needs a non-definition decl and source may not have one.
5183 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
5184 SourceLocation Loc);
5185
5186 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5187 /// applied to it, possibly with an alias.
5188 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5189
5190 void ProcessPragmaWeak(Scope *S, Decl *D);
5191 // Decl attributes - this routine is the top level dispatcher.
5192 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5193
5194 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5195
5196 /// Given a set of delayed diagnostics, re-emit them as if they had
5197 /// been delayed in the current context instead of in the given pool.
5198 /// Essentially, this just moves them to the current pool.
5199 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5200
5201 /// Check that the type is a plain record with one field being a pointer
5202 /// type and the other field being an integer. This matches the common
5203 /// implementation of std::span or sized_allocation_t in P0901R11.
5204 bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty);
5205
5206 /// Check if IdxExpr is a valid parameter index for a function or
5207 /// instance method D. May output an error.
5208 ///
5209 /// \returns true if IdxExpr is a valid index.
5210 template <typename AttrInfo>
5211 bool checkFunctionOrMethodParameterIndex(
5212 const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5213 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5214 bool CanIndexVariadicArguments = false) {
5215 assert(isFunctionOrMethodOrBlockForAttrSubject(D));
5216
5217 // In C++ the implicit 'this' function parameter also counts.
5218 // Parameters are counted from one.
5219 bool HP = hasFunctionProto(D);
5220 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
5221 bool IV = HP && isFunctionOrMethodVariadic(D);
5222 unsigned NumParams =
5223 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
5224
5225 std::optional<llvm::APSInt> IdxInt;
5226 if (IdxExpr->isTypeDependent() ||
5227 !(IdxInt = IdxExpr->getIntegerConstantExpr(Ctx: Context))) {
5228 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5229 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5230 << IdxExpr->getSourceRange();
5231 return false;
5232 }
5233
5234 constexpr unsigned Limit = 1 << ParamIdx::IdxBitWidth;
5235 unsigned IdxSource = IdxInt->getLimitedValue(Limit);
5236 if (IdxSource < 1 || IdxSource == Limit ||
5237 ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5238 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5239 << &AI << AttrArgNum << IdxExpr->getSourceRange();
5240 return false;
5241 }
5242 if (HasImplicitThisParam && !CanIndexImplicitThis) {
5243 if (IdxSource == 1) {
5244 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5245 << &AI << IdxExpr->getSourceRange();
5246 return false;
5247 }
5248 }
5249
5250 Idx = ParamIdx(IdxSource, D);
5251 return true;
5252 }
5253
5254 ///@}
5255
5256 //
5257 //
5258 // -------------------------------------------------------------------------
5259 //
5260 //
5261
5262 /// \name C++ Declarations
5263 /// Implementations are in SemaDeclCXX.cpp
5264 ///@{
5265
5266public:
5267 void CheckDelegatingCtorCycles();
5268
5269 /// Called before parsing a function declarator belonging to a function
5270 /// declaration.
5271 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
5272 unsigned TemplateParameterDepth);
5273
5274 /// Called after parsing a function declarator belonging to a function
5275 /// declaration.
5276 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
5277
5278 // Act on C++ namespaces
5279 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5280 SourceLocation NamespaceLoc,
5281 SourceLocation IdentLoc, IdentifierInfo *Ident,
5282 SourceLocation LBrace,
5283 const ParsedAttributesView &AttrList,
5284 UsingDirectiveDecl *&UsingDecl, bool IsNested);
5285
5286 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5287 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5288 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5289
5290 NamespaceDecl *getStdNamespace() const;
5291
5292 /// Retrieve the special "std" namespace, which may require us to
5293 /// implicitly define the namespace.
5294 NamespaceDecl *getOrCreateStdNamespace();
5295
5296 CXXRecordDecl *getStdBadAlloc() const;
5297 EnumDecl *getStdAlignValT() const;
5298
5299 TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const;
5300 FunctionDecl *BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl,
5301 QualType AllocType, SourceLocation);
5302
5303 ValueDecl *tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
5304 const IdentifierInfo *MemberOrBase);
5305
5306 enum class ComparisonCategoryUsage {
5307 /// The '<=>' operator was used in an expression and a builtin operator
5308 /// was selected.
5309 OperatorInExpression,
5310 /// A defaulted 'operator<=>' needed the comparison category. This
5311 /// typically only applies to 'std::strong_ordering', due to the implicit
5312 /// fallback return value.
5313 DefaultedOperator,
5314 };
5315
5316 /// Lookup the specified comparison category types in the standard
5317 /// library, an check the VarDecls possibly returned by the operator<=>
5318 /// builtins for that type.
5319 ///
5320 /// \return The type of the comparison category type corresponding to the
5321 /// specified Kind, or a null type if an error occurs
5322 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5323 SourceLocation Loc,
5324 ComparisonCategoryUsage Usage);
5325
5326 /// Tests whether Ty is an instance of std::initializer_list and, if
5327 /// it is and Element is not NULL, assigns the element type to Element.
5328 bool isStdInitializerList(QualType Ty, QualType *Element);
5329
5330 /// Tests whether Ty is an instance of std::type_identity and, if
5331 /// it is and TypeArgument is not NULL, assigns the element type to Element.
5332 /// If MalformedDecl is not null, and type_identity was ruled out due to being
5333 /// incorrectly structured despite having the correct name, the faulty Decl
5334 /// will be assigned to MalformedDecl.
5335 bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5336 const Decl **MalformedDecl = nullptr);
5337
5338 /// Looks for the std::initializer_list template and instantiates it
5339 /// with Element, or emits an error if it's not found.
5340 ///
5341 /// \returns The instantiated template, or null on error.
5342 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5343
5344 /// Looks for the std::type_identity template and instantiates it
5345 /// with Type, or returns a null type if type_identity has not been declared
5346 ///
5347 /// \returns The instantiated template, or null if std::type_identity is not
5348 /// declared
5349 QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc);
5350
5351 /// Determine whether Ctor is an initializer-list constructor, as
5352 /// defined in [dcl.init.list]p2.
5353 bool isInitListConstructor(const FunctionDecl *Ctor);
5354
5355 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5356 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5357 SourceLocation IdentLoc,
5358 IdentifierInfo *NamespcName,
5359 const ParsedAttributesView &AttrList);
5360
5361 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5362
5363 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5364 SourceLocation AliasLoc, IdentifierInfo *Alias,
5365 CXXScopeSpec &SS, SourceLocation IdentLoc,
5366 IdentifierInfo *Ident);
5367
5368 /// Remove decls we can't actually see from a lookup being used to declare
5369 /// shadow using decls.
5370 ///
5371 /// \param S - The scope of the potential shadow decl
5372 /// \param Previous - The lookup of a potential shadow decl's name.
5373 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5374
5375 /// Hides a using shadow declaration. This is required by the current
5376 /// using-decl implementation when a resolvable using declaration in a
5377 /// class is followed by a declaration which would hide or override
5378 /// one or more of the using decl's targets; for example:
5379 ///
5380 /// struct Base { void foo(int); };
5381 /// struct Derived : Base {
5382 /// using Base::foo;
5383 /// void foo(int);
5384 /// };
5385 ///
5386 /// The governing language is C++03 [namespace.udecl]p12:
5387 ///
5388 /// When a using-declaration brings names from a base class into a
5389 /// derived class scope, member functions in the derived class
5390 /// override and/or hide member functions with the same name and
5391 /// parameter types in a base class (rather than conflicting).
5392 ///
5393 /// There are two ways to implement this:
5394 /// (1) optimistically create shadow decls when they're not hidden
5395 /// by existing declarations, or
5396 /// (2) don't create any shadow decls (or at least don't make them
5397 /// visible) until we've fully parsed/instantiated the class.
5398 /// The problem with (1) is that we might have to retroactively remove
5399 /// a shadow decl, which requires several O(n) operations because the
5400 /// decl structures are (very reasonably) not designed for removal.
5401 /// (2) avoids this but is very fiddly and phase-dependent.
5402 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5403
5404 /// Determines whether to create a using shadow decl for a particular
5405 /// decl, given the set of decls existing prior to this using lookup.
5406 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5407 const LookupResult &PreviousDecls,
5408 UsingShadowDecl *&PrevShadow);
5409
5410 /// Builds a shadow declaration corresponding to a 'using' declaration.
5411 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5412 NamedDecl *Target,
5413 UsingShadowDecl *PrevDecl);
5414
5415 /// Checks that the given using declaration is not an invalid
5416 /// redeclaration. Note that this is checking only for the using decl
5417 /// itself, not for any ill-formedness among the UsingShadowDecls.
5418 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5419 bool HasTypenameKeyword,
5420 const CXXScopeSpec &SS,
5421 SourceLocation NameLoc,
5422 const LookupResult &Previous);
5423
5424 /// Checks that the given nested-name qualifier used in a using decl
5425 /// in the current context is appropriately related to the current
5426 /// scope. If an error is found, diagnoses it and returns true.
5427 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5428 /// the result of that lookup. UD is likewise nullptr, except when we have an
5429 /// already-populated UsingDecl whose shadow decls contain the same
5430 /// information (i.e. we're instantiating a UsingDecl with non-dependent
5431 /// scope).
5432 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5433 const CXXScopeSpec &SS,
5434 const DeclarationNameInfo &NameInfo,
5435 SourceLocation NameLoc,
5436 const LookupResult *R = nullptr,
5437 const UsingDecl *UD = nullptr);
5438
5439 /// Builds a using declaration.
5440 ///
5441 /// \param IsInstantiation - Whether this call arises from an
5442 /// instantiation of an unresolved using declaration. We treat
5443 /// the lookup differently for these declarations.
5444 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5445 SourceLocation UsingLoc,
5446 bool HasTypenameKeyword,
5447 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5448 DeclarationNameInfo NameInfo,
5449 SourceLocation EllipsisLoc,
5450 const ParsedAttributesView &AttrList,
5451 bool IsInstantiation, bool IsUsingIfExists);
5452 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
5453 SourceLocation UsingLoc,
5454 SourceLocation EnumLoc,
5455 SourceLocation NameLoc,
5456 TypeSourceInfo *EnumType, EnumDecl *ED);
5457 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5458 ArrayRef<NamedDecl *> Expansions);
5459
5460 /// Additional checks for a using declaration referring to a constructor name.
5461 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5462
5463 /// Given a derived-class using shadow declaration for a constructor and the
5464 /// correspnding base class constructor, find or create the implicit
5465 /// synthesized derived class constructor to use for this initialization.
5466 CXXConstructorDecl *
5467 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5468 ConstructorUsingShadowDecl *DerivedShadow);
5469
5470 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5471 SourceLocation UsingLoc,
5472 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5473 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5474 const ParsedAttributesView &AttrList);
5475 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
5476 SourceLocation UsingLoc,
5477 SourceLocation EnumLoc, SourceRange TyLoc,
5478 const IdentifierInfo &II, ParsedType Ty,
5479 const CXXScopeSpec &SS);
5480 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5481 MultiTemplateParamsArg TemplateParams,
5482 SourceLocation UsingLoc, UnqualifiedId &Name,
5483 const ParsedAttributesView &AttrList,
5484 TypeResult Type, Decl *DeclFromDeclSpec);
5485
5486 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5487 /// including handling of its default argument expressions.
5488 ///
5489 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5490 ExprResult BuildCXXConstructExpr(
5491 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5492 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5493 bool HadMultipleCandidates, bool IsListInitialization,
5494 bool IsStdInitListInitialization, bool RequiresZeroInit,
5495 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5496
5497 /// Build a CXXConstructExpr whose constructor has already been resolved if
5498 /// it denotes an inherited constructor.
5499 ExprResult BuildCXXConstructExpr(
5500 SourceLocation ConstructLoc, QualType DeclInitType,
5501 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5502 bool HadMultipleCandidates, bool IsListInitialization,
5503 bool IsStdInitListInitialization, bool RequiresZeroInit,
5504 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5505
5506 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5507 // the constructor can be elidable?
5508 ExprResult BuildCXXConstructExpr(
5509 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5510 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5511 bool HadMultipleCandidates, bool IsListInitialization,
5512 bool IsStdInitListInitialization, bool RequiresZeroInit,
5513 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5514
5515 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr,
5516 SourceLocation InitLoc);
5517
5518 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5519 /// constructed variable.
5520 void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit);
5521
5522 /// Helper class that collects exception specifications for
5523 /// implicitly-declared special member functions.
5524 class ImplicitExceptionSpecification {
5525 // Pointer to allow copying
5526 Sema *Self;
5527 // We order exception specifications thus:
5528 // noexcept is the most restrictive, but is only used in C++11.
5529 // throw() comes next.
5530 // Then a throw(collected exceptions)
5531 // Finally no specification, which is expressed as noexcept(false).
5532 // throw(...) is used instead if any called function uses it.
5533 ExceptionSpecificationType ComputedEST;
5534 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5535 SmallVector<QualType, 4> Exceptions;
5536
5537 void ClearExceptions() {
5538 ExceptionsSeen.clear();
5539 Exceptions.clear();
5540 }
5541
5542 public:
5543 explicit ImplicitExceptionSpecification(Sema &Self)
5544 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5545 if (!Self.getLangOpts().CPlusPlus11)
5546 ComputedEST = EST_DynamicNone;
5547 }
5548
5549 /// Get the computed exception specification type.
5550 ExceptionSpecificationType getExceptionSpecType() const {
5551 assert(!isComputedNoexcept(ComputedEST) &&
5552 "noexcept(expr) should not be a possible result");
5553 return ComputedEST;
5554 }
5555
5556 /// The number of exceptions in the exception specification.
5557 unsigned size() const { return Exceptions.size(); }
5558
5559 /// The set of exceptions in the exception specification.
5560 const QualType *data() const { return Exceptions.data(); }
5561
5562 /// Integrate another called method into the collected data.
5563 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5564
5565 /// Integrate an invoked expression into the collected data.
5566 void CalledExpr(Expr *E) { CalledStmt(S: E); }
5567
5568 /// Integrate an invoked statement into the collected data.
5569 void CalledStmt(Stmt *S);
5570
5571 /// Overwrite an EPI's exception specification with this
5572 /// computed exception specification.
5573 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5574 FunctionProtoType::ExceptionSpecInfo ESI;
5575 ESI.Type = getExceptionSpecType();
5576 if (ESI.Type == EST_Dynamic) {
5577 ESI.Exceptions = Exceptions;
5578 } else if (ESI.Type == EST_None) {
5579 /// C++11 [except.spec]p14:
5580 /// The exception-specification is noexcept(false) if the set of
5581 /// potential exceptions of the special member function contains "any"
5582 ESI.Type = EST_NoexceptFalse;
5583 ESI.NoexceptExpr =
5584 Self->ActOnCXXBoolLiteral(OpLoc: SourceLocation(), Kind: tok::kw_false).get();
5585 }
5586 return ESI;
5587 }
5588 };
5589
5590 /// Evaluate the implicit exception specification for a defaulted
5591 /// special member function.
5592 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5593
5594 /// Check the given exception-specification and update the
5595 /// exception specification information with the results.
5596 void checkExceptionSpecification(bool IsTopLevel,
5597 ExceptionSpecificationType EST,
5598 ArrayRef<ParsedType> DynamicExceptions,
5599 ArrayRef<SourceRange> DynamicExceptionRanges,
5600 Expr *NoexceptExpr,
5601 SmallVectorImpl<QualType> &Exceptions,
5602 FunctionProtoType::ExceptionSpecInfo &ESI);
5603
5604 /// Add an exception-specification to the given member or friend function
5605 /// (or function template). The exception-specification was parsed
5606 /// after the function itself was declared.
5607 void actOnDelayedExceptionSpecification(
5608 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5609 ArrayRef<ParsedType> DynamicExceptions,
5610 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5611
5612 class InheritedConstructorInfo;
5613
5614 /// Determine if a special member function should have a deleted
5615 /// definition when it is defaulted.
5616 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
5617 InheritedConstructorInfo *ICI = nullptr,
5618 bool Diagnose = false);
5619
5620 /// Produce notes explaining why a defaulted function was defined as deleted.
5621 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5622
5623 /// Declare the implicit default constructor for the given class.
5624 ///
5625 /// \param ClassDecl The class declaration into which the implicit
5626 /// default constructor will be added.
5627 ///
5628 /// \returns The implicitly-declared default constructor.
5629 CXXConstructorDecl *
5630 DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl);
5631
5632 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5633 /// defining this constructor as the default constructor.
5634 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5635 CXXConstructorDecl *Constructor);
5636
5637 /// Declare the implicit destructor for the given class.
5638 ///
5639 /// \param ClassDecl The class declaration into which the implicit
5640 /// destructor will be added.
5641 ///
5642 /// \returns The implicitly-declared destructor.
5643 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5644
5645 /// DefineImplicitDestructor - Checks for feasibility of
5646 /// defining this destructor as the default destructor.
5647 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5648 CXXDestructorDecl *Destructor);
5649
5650 /// Build an exception spec for destructors that don't have one.
5651 ///
5652 /// C++11 says that user-defined destructors with no exception spec get one
5653 /// that looks as if the destructor was implicitly declared.
5654 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5655
5656 /// Define the specified inheriting constructor.
5657 void DefineInheritingConstructor(SourceLocation UseLoc,
5658 CXXConstructorDecl *Constructor);
5659
5660 /// Declare the implicit copy constructor for the given class.
5661 ///
5662 /// \param ClassDecl The class declaration into which the implicit
5663 /// copy constructor will be added.
5664 ///
5665 /// \returns The implicitly-declared copy constructor.
5666 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5667
5668 /// DefineImplicitCopyConstructor - Checks for feasibility of
5669 /// defining this constructor as the copy constructor.
5670 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5671 CXXConstructorDecl *Constructor);
5672
5673 /// Declare the implicit move constructor for the given class.
5674 ///
5675 /// \param ClassDecl The Class declaration into which the implicit
5676 /// move constructor will be added.
5677 ///
5678 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5679 /// declared.
5680 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5681
5682 /// DefineImplicitMoveConstructor - Checks for feasibility of
5683 /// defining this constructor as the move constructor.
5684 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5685 CXXConstructorDecl *Constructor);
5686
5687 /// Declare the implicit copy assignment operator for the given class.
5688 ///
5689 /// \param ClassDecl The class declaration into which the implicit
5690 /// copy assignment operator will be added.
5691 ///
5692 /// \returns The implicitly-declared copy assignment operator.
5693 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5694
5695 /// Defines an implicitly-declared copy assignment operator.
5696 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5697 CXXMethodDecl *MethodDecl);
5698
5699 /// Declare the implicit move assignment operator for the given class.
5700 ///
5701 /// \param ClassDecl The Class declaration into which the implicit
5702 /// move assignment operator will be added.
5703 ///
5704 /// \returns The implicitly-declared move assignment operator, or NULL if it
5705 /// wasn't declared.
5706 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5707
5708 /// Defines an implicitly-declared move assignment operator.
5709 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5710 CXXMethodDecl *MethodDecl);
5711
5712 /// Check a completed declaration of an implicit special member.
5713 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5714
5715 /// Determine whether the given function is an implicitly-deleted
5716 /// special member function.
5717 bool isImplicitlyDeleted(FunctionDecl *FD);
5718
5719 /// Check whether 'this' shows up in the type of a static member
5720 /// function after the (naturally empty) cv-qualifier-seq would be.
5721 ///
5722 /// \returns true if an error occurred.
5723 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5724
5725 /// Whether this' shows up in the exception specification of a static
5726 /// member function.
5727 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5728
5729 /// Check whether 'this' shows up in the attributes of the given
5730 /// static member function.
5731 ///
5732 /// \returns true if an error occurred.
5733 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5734
5735 bool CheckImmediateEscalatingFunctionDefinition(
5736 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5737
5738 void DiagnoseImmediateEscalatingReason(FunctionDecl *FD);
5739
5740 /// Given a constructor and the set of arguments provided for the
5741 /// constructor, convert the arguments and add any required default arguments
5742 /// to form a proper call to this constructor.
5743 ///
5744 /// \returns true if an error occurred, false otherwise.
5745 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5746 QualType DeclInitType, MultiExprArg ArgsPtr,
5747 SourceLocation Loc,
5748 SmallVectorImpl<Expr *> &ConvertedArgs,
5749 bool AllowExplicit = false,
5750 bool IsListInitialization = false);
5751
5752 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5753 /// initializer for the declaration 'Dcl'.
5754 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5755 /// static data member of class X, names should be looked up in the scope of
5756 /// class X.
5757 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5758
5759 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5760 /// initializer for the declaration 'Dcl'.
5761 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5762
5763 /// Define the "body" of the conversion from a lambda object to a
5764 /// function pointer.
5765 ///
5766 /// This routine doesn't actually define a sensible body; rather, it fills
5767 /// in the initialization expression needed to copy the lambda object into
5768 /// the block, and IR generation actually generates the real body of the
5769 /// block pointer conversion.
5770 void
5771 DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc,
5772 CXXConversionDecl *Conv);
5773
5774 /// Define the "body" of the conversion from a lambda object to a
5775 /// block pointer.
5776 ///
5777 /// This routine doesn't actually define a sensible body; rather, it fills
5778 /// in the initialization expression needed to copy the lambda object into
5779 /// the block, and IR generation actually generates the real body of the
5780 /// block pointer conversion.
5781 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5782 CXXConversionDecl *Conv);
5783
5784 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5785 /// linkage specification, including the language and (if present)
5786 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5787 /// language string literal. LBraceLoc, if valid, provides the location of
5788 /// the '{' brace. Otherwise, this linkage specification does not
5789 /// have any braces.
5790 Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5791 Expr *LangStr, SourceLocation LBraceLoc);
5792
5793 /// ActOnFinishLinkageSpecification - Complete the definition of
5794 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5795 /// valid, it's the position of the closing '}' brace in a linkage
5796 /// specification that uses braces.
5797 Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec,
5798 SourceLocation RBraceLoc);
5799
5800 //===--------------------------------------------------------------------===//
5801 // C++ Classes
5802 //
5803
5804 /// Get the class that is directly named by the current context. This is the
5805 /// class for which an unqualified-id in this scope could name a constructor
5806 /// or destructor.
5807 ///
5808 /// If the scope specifier denotes a class, this will be that class.
5809 /// If the scope specifier is empty, this will be the class whose
5810 /// member-specification we are currently within. Otherwise, there
5811 /// is no such class.
5812 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
5813
5814 /// isCurrentClassName - Determine whether the identifier II is the
5815 /// name of the class type currently being defined. In the case of
5816 /// nested classes, this will only return true if II is the name of
5817 /// the innermost class.
5818 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5819 const CXXScopeSpec *SS = nullptr);
5820
5821 /// Determine whether the identifier II is a typo for the name of
5822 /// the class type currently being defined. If so, update it to the identifier
5823 /// that should have been used.
5824 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5825
5826 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5827 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
5828 SourceLocation ColonLoc,
5829 const ParsedAttributesView &Attrs);
5830
5831 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5832 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5833 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
5834 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
5835 /// present (but parsing it has been deferred).
5836 NamedDecl *
5837 ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
5838 MultiTemplateParamsArg TemplateParameterLists,
5839 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5840 InClassInitStyle InitStyle);
5841
5842 /// Enter a new C++ default initializer scope. After calling this, the
5843 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
5844 /// parsing or instantiating the initializer failed.
5845 void ActOnStartCXXInClassMemberInitializer();
5846
5847 /// This is invoked after parsing an in-class initializer for a
5848 /// non-static C++ class member, and after instantiating an in-class
5849 /// initializer in a class template. Such actions are deferred until the class
5850 /// is complete.
5851 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5852 SourceLocation EqualLoc,
5853 ExprResult Init);
5854
5855 /// Handle a C++ member initializer using parentheses syntax.
5856 MemInitResult
5857 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
5858 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
5859 const DeclSpec &DS, SourceLocation IdLoc,
5860 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
5861 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
5862
5863 /// Handle a C++ member initializer using braced-init-list syntax.
5864 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
5865 CXXScopeSpec &SS,
5866 IdentifierInfo *MemberOrBase,
5867 ParsedType TemplateTypeTy,
5868 const DeclSpec &DS, SourceLocation IdLoc,
5869 Expr *InitList, SourceLocation EllipsisLoc);
5870
5871 /// Handle a C++ member initializer.
5872 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
5873 CXXScopeSpec &SS,
5874 IdentifierInfo *MemberOrBase,
5875 ParsedType TemplateTypeTy,
5876 const DeclSpec &DS, SourceLocation IdLoc,
5877 Expr *Init, SourceLocation EllipsisLoc);
5878
5879 MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init,
5880 SourceLocation IdLoc);
5881
5882 MemInitResult BuildBaseInitializer(QualType BaseType,
5883 TypeSourceInfo *BaseTInfo, Expr *Init,
5884 CXXRecordDecl *ClassDecl,
5885 SourceLocation EllipsisLoc);
5886
5887 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
5888 CXXRecordDecl *ClassDecl);
5889
5890 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5891 CXXCtorInitializer *Initializer);
5892
5893 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5894 ArrayRef<CXXCtorInitializer *> Initializers = {});
5895
5896 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5897 /// mark all the non-trivial destructors of its members and bases as
5898 /// referenced.
5899 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5900 CXXRecordDecl *Record);
5901
5902 /// Mark destructors of virtual bases of this class referenced. In the Itanium
5903 /// C++ ABI, this is done when emitting a destructor for any non-abstract
5904 /// class. In the Microsoft C++ ABI, this is done any time a class's
5905 /// destructor is referenced.
5906 void MarkVirtualBaseDestructorsReferenced(
5907 SourceLocation Location, CXXRecordDecl *ClassDecl,
5908 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
5909 nullptr);
5910
5911 /// Do semantic checks to allow the complete destructor variant to be emitted
5912 /// when the destructor is defined in another translation unit. In the Itanium
5913 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
5914 /// can be emitted in separate TUs. To emit the complete variant, run a subset
5915 /// of the checks performed when emitting a regular destructor.
5916 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
5917 CXXDestructorDecl *Dtor);
5918
5919 /// The list of classes whose vtables have been used within
5920 /// this translation unit, and the source locations at which the
5921 /// first use occurred.
5922 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
5923
5924 /// The list of vtables that are required but have not yet been
5925 /// materialized.
5926 SmallVector<VTableUse, 16> VTableUses;
5927
5928 /// The set of classes whose vtables have been used within
5929 /// this translation unit, and a bit that will be true if the vtable is
5930 /// required to be emitted (otherwise, it should be emitted only if needed
5931 /// by code generation).
5932 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5933
5934 /// Load any externally-stored vtable uses.
5935 void LoadExternalVTableUses();
5936
5937 /// Note that the vtable for the given class was used at the
5938 /// given location.
5939 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5940 bool DefinitionRequired = false);
5941
5942 /// Mark the exception specifications of all virtual member functions
5943 /// in the given class as needed.
5944 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5945 const CXXRecordDecl *RD);
5946
5947 /// MarkVirtualMembersReferenced - Will mark all members of the given
5948 /// CXXRecordDecl referenced.
5949 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
5950 bool ConstexprOnly = false);
5951
5952 /// Define all of the vtables that have been used in this
5953 /// translation unit and reference any virtual members used by those
5954 /// vtables.
5955 ///
5956 /// \returns true if any work was done, false otherwise.
5957 bool DefineUsedVTables();
5958
5959 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5960 /// special functions, such as the default constructor, copy
5961 /// constructor, or destructor, to the given C++ class (C++
5962 /// [special]p1). This routine can only be executed just before the
5963 /// definition of the class is complete.
5964 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5965
5966 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5967 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
5968 ArrayRef<CXXCtorInitializer *> MemInits,
5969 bool AnyErrors);
5970
5971 /// Check class-level dllimport/dllexport attribute. The caller must
5972 /// ensure that referenceDLLExportedClassMethods is called some point later
5973 /// when all outer classes of Class are complete.
5974 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5975 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
5976
5977 void referenceDLLExportedClassMethods();
5978
5979 /// Perform propagation of DLL attributes from a derived class to a
5980 /// templated base class for MS compatibility.
5981 void propagateDLLAttrToBaseClassTemplate(
5982 CXXRecordDecl *Class, Attr *ClassAttr,
5983 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5984 SourceLocation BaseLoc);
5985
5986 /// Perform semantic checks on a class definition that has been
5987 /// completing, introducing implicitly-declared members, checking for
5988 /// abstract types, etc.
5989 ///
5990 /// \param S The scope in which the class was parsed. Null if we didn't just
5991 /// parse a class definition.
5992 /// \param Record The completed class.
5993 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
5994
5995 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
5996 /// conditions that are needed for the attribute to have an effect.
5997 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
5998
5999 /// Check that VTable Pointer authentication is only being set on the first
6000 /// first instantiation of the vtable
6001 void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD);
6002
6003 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6004 Decl *TagDecl, SourceLocation LBrac,
6005 SourceLocation RBrac,
6006 const ParsedAttributesView &AttrList);
6007
6008 /// Perform any semantic analysis which needs to be delayed until all
6009 /// pending class member declarations have been parsed.
6010 void ActOnFinishCXXMemberDecls();
6011 void ActOnFinishCXXNonNestedClass();
6012
6013 /// This is used to implement the constant expression evaluation part of the
6014 /// attribute enable_if extension. There is nothing in standard C++ which
6015 /// would require reentering parameters.
6016 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6017 unsigned ActOnReenterTemplateScope(Decl *Template,
6018 llvm::function_ref<Scope *()> EnterScope);
6019 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6020
6021 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6022 /// parsing a top-level (non-nested) C++ class, and we are now
6023 /// parsing those parts of the given Method declaration that could
6024 /// not be parsed earlier (C++ [class.mem]p2), such as default
6025 /// arguments. This action should enter the scope of the given
6026 /// Method declaration as if we had just parsed the qualified method
6027 /// name. However, it should not bring the parameters into scope;
6028 /// that will be performed by ActOnDelayedCXXMethodParameter.
6029 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6030 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6031 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6032
6033 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6034 /// processing the delayed method declaration for Method. The method
6035 /// declaration is now considered finished. There may be a separate
6036 /// ActOnStartOfFunctionDef action later (not necessarily
6037 /// immediately!) for this method, if it was also defined inside the
6038 /// class body.
6039 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6040 void ActOnFinishDelayedMemberInitializers(Decl *Record);
6041
6042 enum class StringEvaluationContext { StaticAssert = 0, Asm = 1 };
6043
6044 bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
6045 StringEvaluationContext EvalContext,
6046 bool ErrorOnInvalidMessage);
6047 bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
6048 StringEvaluationContext EvalContext,
6049 bool ErrorOnInvalidMessage);
6050
6051 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6052 Expr *AssertExpr, Expr *AssertMessageExpr,
6053 SourceLocation RParenLoc);
6054 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6055 Expr *AssertExpr, Expr *AssertMessageExpr,
6056 SourceLocation RParenLoc, bool Failed);
6057
6058 /// Try to print more useful information about a failed static_assert
6059 /// with expression \E
6060 void DiagnoseStaticAssertDetails(const Expr *E);
6061
6062 /// If E represents a built-in type trait, or a known standard type trait,
6063 /// try to print more information about why the type type-trait failed.
6064 /// This assumes we already evaluated the expression to a false boolean value.
6065 void DiagnoseTypeTraitDetails(const Expr *E);
6066
6067 /// Handle a friend type declaration. This works in tandem with
6068 /// ActOnTag.
6069 ///
6070 /// Notes on friend class templates:
6071 ///
6072 /// We generally treat friend class declarations as if they were
6073 /// declaring a class. So, for example, the elaborated type specifier
6074 /// in a friend declaration is required to obey the restrictions of a
6075 /// class-head (i.e. no typedefs in the scope chain), template
6076 /// parameters are required to match up with simple template-ids, &c.
6077 /// However, unlike when declaring a template specialization, it's
6078 /// okay to refer to a template specialization without an empty
6079 /// template parameter declaration, e.g.
6080 /// friend class A<T>::B<unsigned>;
6081 /// We permit this as a special case; if there are any template
6082 /// parameters present at all, require proper matching, i.e.
6083 /// template <> template \<class T> friend class A<int>::B;
6084 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6085 MultiTemplateParamsArg TemplateParams,
6086 SourceLocation EllipsisLoc);
6087 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6088 MultiTemplateParamsArg TemplateParams);
6089
6090 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6091 /// the well-formedness of the constructor declarator @p D with type @p
6092 /// R. If there are any errors in the declarator, this routine will
6093 /// emit diagnostics and set the invalid bit to true. In any case, the type
6094 /// will be updated to reflect a well-formed type for the constructor and
6095 /// returned.
6096 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6097 StorageClass &SC);
6098
6099 /// CheckConstructor - Checks a fully-formed constructor for
6100 /// well-formedness, issuing any diagnostics required. Returns true if
6101 /// the constructor declarator is invalid.
6102 void CheckConstructor(CXXConstructorDecl *Constructor);
6103
6104 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6105 /// the well-formednes of the destructor declarator @p D with type @p
6106 /// R. If there are any errors in the declarator, this routine will
6107 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6108 /// will be updated to reflect a well-formed type for the destructor and
6109 /// returned.
6110 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6111 StorageClass &SC);
6112
6113 /// CheckDestructor - Checks a fully-formed destructor definition for
6114 /// well-formedness, issuing any diagnostics required. Returns true
6115 /// on error.
6116 bool CheckDestructor(CXXDestructorDecl *Destructor);
6117
6118 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6119 /// well-formednes of the conversion function declarator @p D with
6120 /// type @p R. If there are any errors in the declarator, this routine
6121 /// will emit diagnostics and return true. Otherwise, it will return
6122 /// false. Either way, the type @p R will be updated to reflect a
6123 /// well-formed type for the conversion operator.
6124 void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC);
6125
6126 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6127 /// the declaration of the given C++ conversion function. This routine
6128 /// is responsible for recording the conversion function in the C++
6129 /// class, if possible.
6130 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6131
6132 /// Check the validity of a declarator that we parsed for a deduction-guide.
6133 /// These aren't actually declarators in the grammar, so we need to check that
6134 /// the user didn't specify any pieces that are not part of the
6135 /// deduction-guide grammar. Return true on invalid deduction-guide.
6136 bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6137 StorageClass &SC);
6138
6139 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6140
6141 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6142 CXXSpecialMemberKind CSM,
6143 SourceLocation DefaultLoc);
6144 void CheckDelayedMemberExceptionSpecs();
6145
6146 /// Kinds of defaulted comparison operator functions.
6147 enum class DefaultedComparisonKind : unsigned char {
6148 /// This is not a defaultable comparison operator.
6149 None,
6150 /// This is an operator== that should be implemented as a series of
6151 /// subobject comparisons.
6152 Equal,
6153 /// This is an operator<=> that should be implemented as a series of
6154 /// subobject comparisons.
6155 ThreeWay,
6156 /// This is an operator!= that should be implemented as a rewrite in terms
6157 /// of a == comparison.
6158 NotEqual,
6159 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
6160 /// terms of a <=> comparison.
6161 Relational,
6162 };
6163
6164 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6165 DefaultedComparisonKind DCK);
6166 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6167 FunctionDecl *Spaceship);
6168 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6169 DefaultedComparisonKind DCK);
6170
6171 void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name,
6172 QualType R, bool IsLambda,
6173 DeclContext *DC = nullptr);
6174 void CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
6175 DeclarationName Name, QualType R);
6176 void CheckExplicitObjectLambda(Declarator &D);
6177
6178 //===--------------------------------------------------------------------===//
6179 // C++ Derived Classes
6180 //
6181
6182 /// Check the validity of a C++ base class specifier.
6183 ///
6184 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6185 /// and returns NULL otherwise.
6186 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6187 SourceRange SpecifierRange, bool Virtual,
6188 AccessSpecifier Access,
6189 TypeSourceInfo *TInfo,
6190 SourceLocation EllipsisLoc);
6191
6192 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6193 /// one entry in the base class list of a class specifier, for
6194 /// example:
6195 /// class foo : public bar, virtual private baz {
6196 /// 'public bar' and 'virtual private baz' are each base-specifiers.
6197 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6198 const ParsedAttributesView &Attrs, bool Virtual,
6199 AccessSpecifier Access, ParsedType basetype,
6200 SourceLocation BaseLoc,
6201 SourceLocation EllipsisLoc);
6202
6203 /// Performs the actual work of attaching the given base class
6204 /// specifiers to a C++ class.
6205 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6206 MutableArrayRef<CXXBaseSpecifier *> Bases);
6207
6208 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6209 /// class, after checking whether there are any duplicate base
6210 /// classes.
6211 void ActOnBaseSpecifiers(Decl *ClassDecl,
6212 MutableArrayRef<CXXBaseSpecifier *> Bases);
6213
6214 /// Determine whether the type \p Derived is a C++ class that is
6215 /// derived from the type \p Base.
6216 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6217 CXXRecordDecl *Base, CXXBasePaths &Paths);
6218 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6219 CXXRecordDecl *Base);
6220 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6221 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6222 CXXBasePaths &Paths);
6223
6224 // FIXME: I don't like this name.
6225 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6226
6227 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6228 SourceLocation Loc, SourceRange Range,
6229 CXXCastPath *BasePath = nullptr,
6230 bool IgnoreAccess = false);
6231
6232 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6233 /// conversion (where Derived and Base are class types) is
6234 /// well-formed, meaning that the conversion is unambiguous (and
6235 /// that all of the base classes are accessible). Returns true
6236 /// and emits a diagnostic if the code is ill-formed, returns false
6237 /// otherwise. Loc is the location where this routine should point to
6238 /// if there is an error, and Range is the source range to highlight
6239 /// if there is an error.
6240 ///
6241 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6242 /// diagnostic for the respective type of error will be suppressed, but the
6243 /// check for ill-formed code will still be performed.
6244 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6245 unsigned InaccessibleBaseID,
6246 unsigned AmbiguousBaseConvID,
6247 SourceLocation Loc, SourceRange Range,
6248 DeclarationName Name, CXXCastPath *BasePath,
6249 bool IgnoreAccess = false);
6250
6251 /// Builds a string representing ambiguous paths from a
6252 /// specific derived class to different subobjects of the same base
6253 /// class.
6254 ///
6255 /// This function builds a string that can be used in error messages
6256 /// to show the different paths that one can take through the
6257 /// inheritance hierarchy to go from the derived class to different
6258 /// subobjects of a base class. The result looks something like this:
6259 /// @code
6260 /// struct D -> struct B -> struct A
6261 /// struct D -> struct C -> struct A
6262 /// @endcode
6263 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6264
6265 bool CheckOverridingFunctionAttributes(CXXMethodDecl *New,
6266 const CXXMethodDecl *Old);
6267
6268 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6269 /// covariant, according to C++ [class.virtual]p5.
6270 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6271 const CXXMethodDecl *Old);
6272
6273 // Check that the overriding method has no explicit object parameter.
6274 bool CheckExplicitObjectOverride(CXXMethodDecl *New,
6275 const CXXMethodDecl *Old);
6276
6277 /// Mark the given method pure.
6278 ///
6279 /// \param Method the method to be marked pure.
6280 ///
6281 /// \param InitRange the source range that covers the "0" initializer.
6282 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6283
6284 /// CheckOverrideControl - Check C++11 override control semantics.
6285 void CheckOverrideControl(NamedDecl *D);
6286
6287 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6288 /// not used in the declaration of an overriding method.
6289 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
6290
6291 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6292 /// function overrides a virtual member function marked 'final', according to
6293 /// C++11 [class.virtual]p4.
6294 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6295 const CXXMethodDecl *Old);
6296
6297 enum AbstractDiagSelID {
6298 AbstractNone = -1,
6299 AbstractReturnType,
6300 AbstractParamType,
6301 AbstractVariableType,
6302 AbstractFieldType,
6303 AbstractIvarType,
6304 AbstractSynthesizedIvarType,
6305 AbstractArrayType
6306 };
6307
6308 struct TypeDiagnoser;
6309
6310 bool isAbstractType(SourceLocation Loc, QualType T);
6311 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6312 TypeDiagnoser &Diagnoser);
6313 template <typename... Ts>
6314 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6315 const Ts &...Args) {
6316 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6317 return RequireNonAbstractType(Loc, T, Diagnoser);
6318 }
6319
6320 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6321
6322 //===--------------------------------------------------------------------===//
6323 // C++ Overloaded Operators [C++ 13.5]
6324 //
6325
6326 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6327 /// of this overloaded operator is well-formed. If so, returns false;
6328 /// otherwise, emits appropriate diagnostics and returns true.
6329 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6330
6331 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6332 /// of this literal operator function is well-formed. If so, returns
6333 /// false; otherwise, emits appropriate diagnostics and returns true.
6334 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6335
6336 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6337 /// found in an explicit(bool) specifier.
6338 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
6339
6340 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6341 /// Returns true if the explicit specifier is now resolved.
6342 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
6343
6344 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6345 /// C++ if/switch/while/for statement.
6346 /// e.g: "if (int x = f()) {...}"
6347 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
6348
6349 // Emitting members of dllexported classes is delayed until the class
6350 // (including field initializers) is fully parsed.
6351 SmallVector<CXXRecordDecl *, 4> DelayedDllExportClasses;
6352 SmallVector<CXXMethodDecl *, 4> DelayedDllExportMemberFunctions;
6353
6354 /// Merge the exception specifications of two variable declarations.
6355 ///
6356 /// This is called when there's a redeclaration of a VarDecl. The function
6357 /// checks if the redeclaration might have an exception specification and
6358 /// validates compatibility and merges the specs if necessary.
6359 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
6360
6361 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6362 /// function, once we already know that they have the same
6363 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6364 /// error, false otherwise.
6365 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
6366
6367 /// Helpers for dealing with blocks and functions.
6368 void CheckCXXDefaultArguments(FunctionDecl *FD);
6369
6370 /// CheckExtraCXXDefaultArguments - Check for any extra default
6371 /// arguments in the declarator, which is not a function declaration
6372 /// or definition and therefore is not permitted to have default
6373 /// arguments. This routine should be invoked for every declarator
6374 /// that is not a function declaration or definition.
6375 void CheckExtraCXXDefaultArguments(Declarator &D);
6376
6377 CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD) {
6378 return getDefaultedFunctionKind(FD: MD).asSpecialMember();
6379 }
6380
6381 /// Perform semantic analysis for the variable declaration that
6382 /// occurs within a C++ catch clause, returning the newly-created
6383 /// variable.
6384 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
6385 SourceLocation StartLoc,
6386 SourceLocation IdLoc,
6387 const IdentifierInfo *Id);
6388
6389 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6390 /// handler.
6391 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
6392
6393 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
6394
6395 /// Handle a friend tag declaration where the scope specifier was
6396 /// templated.
6397 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6398 unsigned TagSpec, SourceLocation TagLoc,
6399 CXXScopeSpec &SS, IdentifierInfo *Name,
6400 SourceLocation NameLoc,
6401 SourceLocation EllipsisLoc,
6402 const ParsedAttributesView &Attr,
6403 MultiTemplateParamsArg TempParamLists);
6404
6405 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
6406 SourceLocation DeclStart, Declarator &D,
6407 Expr *BitfieldWidth,
6408 InClassInitStyle InitStyle,
6409 AccessSpecifier AS,
6410 const ParsedAttr &MSPropertyAttr);
6411
6412 /// Diagnose why the specified class does not have a trivial special member of
6413 /// the given kind.
6414 void DiagnoseNontrivial(const CXXRecordDecl *Record,
6415 CXXSpecialMemberKind CSM);
6416
6417 /// Determine whether a defaulted or deleted special member function is
6418 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6419 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6420 bool SpecialMemberIsTrivial(
6421 CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
6422 TrivialABIHandling TAH = TrivialABIHandling::IgnoreTrivialABI,
6423 bool Diagnose = false);
6424
6425 /// For a defaulted function, the kind of defaulted function that it is.
6426 class DefaultedFunctionKind {
6427 LLVM_PREFERRED_TYPE(CXXSpecialMemberKind)
6428 unsigned SpecialMember : 8;
6429 unsigned Comparison : 8;
6430
6431 public:
6432 DefaultedFunctionKind()
6433 : SpecialMember(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid)),
6434 Comparison(llvm::to_underlying(E: DefaultedComparisonKind::None)) {}
6435 DefaultedFunctionKind(CXXSpecialMemberKind CSM)
6436 : SpecialMember(llvm::to_underlying(E: CSM)),
6437 Comparison(llvm::to_underlying(E: DefaultedComparisonKind::None)) {}
6438 DefaultedFunctionKind(DefaultedComparisonKind Comp)
6439 : SpecialMember(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid)),
6440 Comparison(llvm::to_underlying(E: Comp)) {}
6441
6442 bool isSpecialMember() const {
6443 return static_cast<CXXSpecialMemberKind>(SpecialMember) !=
6444 CXXSpecialMemberKind::Invalid;
6445 }
6446 bool isComparison() const {
6447 return static_cast<DefaultedComparisonKind>(Comparison) !=
6448 DefaultedComparisonKind::None;
6449 }
6450
6451 explicit operator bool() const {
6452 return isSpecialMember() || isComparison();
6453 }
6454
6455 CXXSpecialMemberKind asSpecialMember() const {
6456 return static_cast<CXXSpecialMemberKind>(SpecialMember);
6457 }
6458 DefaultedComparisonKind asComparison() const {
6459 return static_cast<DefaultedComparisonKind>(Comparison);
6460 }
6461
6462 /// Get the index of this function kind for use in diagnostics.
6463 unsigned getDiagnosticIndex() const {
6464 static_assert(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid) >
6465 llvm::to_underlying(E: CXXSpecialMemberKind::Destructor),
6466 "invalid should have highest index");
6467 static_assert((unsigned)DefaultedComparisonKind::None == 0,
6468 "none should be equal to zero");
6469 return SpecialMember + Comparison;
6470 }
6471 };
6472
6473 /// Determine the kind of defaulting that would be done for a given function.
6474 ///
6475 /// If the function is both a default constructor and a copy / move
6476 /// constructor (due to having a default argument for the first parameter),
6477 /// this picks CXXSpecialMemberKind::DefaultConstructor.
6478 ///
6479 /// FIXME: Check that case is properly handled by all callers.
6480 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
6481
6482 /// Handle a C++11 empty-declaration and attribute-declaration.
6483 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
6484 SourceLocation SemiLoc);
6485
6486 enum class CheckConstexprKind {
6487 /// Diagnose issues that are non-constant or that are extensions.
6488 Diagnose,
6489 /// Identify whether this function satisfies the formal rules for constexpr
6490 /// functions in the current lanugage mode (with no extensions).
6491 CheckValid
6492 };
6493
6494 // Check whether a function declaration satisfies the requirements of a
6495 // constexpr function definition or a constexpr constructor definition. If so,
6496 // return true. If not, produce appropriate diagnostics (unless asked not to
6497 // by Kind) and return false.
6498 //
6499 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6500 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
6501 CheckConstexprKind Kind);
6502
6503 /// Diagnose methods which overload virtual methods in a base class
6504 /// without overriding any.
6505 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
6506
6507 /// Check if a method overloads virtual methods in a base class without
6508 /// overriding any.
6509 void
6510 FindHiddenVirtualMethods(CXXMethodDecl *MD,
6511 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6512 void
6513 NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6514 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6515
6516 /// ActOnParamDefaultArgument - Check whether the default argument
6517 /// provided for a function parameter is well-formed. If so, attach it
6518 /// to the parameter declaration.
6519 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6520 Expr *defarg);
6521
6522 /// ActOnParamUnparsedDefaultArgument - We've seen a default
6523 /// argument for a function parameter, but we can't parse it yet
6524 /// because we're inside a class definition. Note that this default
6525 /// argument will be parsed later.
6526 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
6527 SourceLocation ArgLoc);
6528
6529 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6530 /// the default argument for the parameter param failed.
6531 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
6532 Expr *DefaultArg);
6533 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6534 SourceLocation EqualLoc);
6535 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6536 SourceLocation EqualLoc);
6537
6538 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6539 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6540 StringLiteral *Message = nullptr);
6541 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
6542
6543 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6544 StringLiteral *DeletedMessage = nullptr);
6545 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
6546 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
6547 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
6548
6549 NamedDecl *
6550 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
6551 MultiTemplateParamsArg TemplateParamLists);
6552 void DiagPlaceholderVariableDefinition(SourceLocation Loc);
6553 bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
6554 RecordDecl *ClassDecl,
6555 const IdentifierInfo *Name);
6556
6557 UnsignedOrNone GetDecompositionElementCount(QualType DecompType,
6558 SourceLocation Loc);
6559 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
6560
6561 /// Stack containing information needed when in C++2a an 'auto' is encountered
6562 /// in a function declaration parameter type specifier in order to invent a
6563 /// corresponding template parameter in the enclosing abbreviated function
6564 /// template. This information is also present in LambdaScopeInfo, stored in
6565 /// the FunctionScopes stack.
6566 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
6567
6568 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6569 std::unique_ptr<CXXFieldCollector> FieldCollector;
6570
6571 typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType;
6572 /// Set containing all declared private fields that are not used.
6573 NamedDeclSetType UnusedPrivateFields;
6574
6575 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 8> RecordDeclSetTy;
6576
6577 /// PureVirtualClassDiagSet - a set of class declarations which we have
6578 /// emitted a list of pure virtual functions. Used to prevent emitting the
6579 /// same list more than once.
6580 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6581
6582 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
6583 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
6584 DelegatingCtorDeclsType;
6585
6586 /// All the delegating constructors seen so far in the file, used for
6587 /// cycle detection at the end of the TU.
6588 DelegatingCtorDeclsType DelegatingCtorDecls;
6589
6590 /// The C++ "std" namespace, where the standard library resides.
6591 LazyDeclPtr StdNamespace;
6592
6593 /// The C++ "std::initializer_list" template, which is defined in
6594 /// \<initializer_list>.
6595 ClassTemplateDecl *StdInitializerList;
6596
6597 /// The C++ "std::type_identity" template, which is defined in
6598 /// \<type_traits>.
6599 ClassTemplateDecl *StdTypeIdentity;
6600
6601 // Contains the locations of the beginning of unparsed default
6602 // argument locations.
6603 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6604
6605 /// UndefinedInternals - all the used, undefined objects which require a
6606 /// definition in this translation unit.
6607 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6608
6609 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6610 SpecialMemberDecl;
6611
6612 /// The C++ special members which we are currently in the process of
6613 /// declaring. If this process recursively triggers the declaration of the
6614 /// same special member, we should act as if it is not yet declared.
6615 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
6616
6617 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
6618
6619 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6620
6621 typedef ProcessingContextState ParsingClassState;
6622 ParsingClassState PushParsingClass() {
6623 ParsingClassDepth++;
6624 return DelayedDiagnostics.pushUndelayed();
6625 }
6626 void PopParsingClass(ParsingClassState state) {
6627 ParsingClassDepth--;
6628 DelayedDiagnostics.popUndelayed(state);
6629 }
6630
6631 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
6632 CXXScopeSpec &SS,
6633 ParsedType TemplateTypeTy,
6634 IdentifierInfo *MemberOrBase);
6635
6636private:
6637 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6638 QualType ResultTy,
6639 ArrayRef<QualType> Args);
6640 // Helper for ActOnFields to check for all function pointer members.
6641 bool EntirelyFunctionPointers(const RecordDecl *Record);
6642
6643 // A cache representing if we've fully checked the various comparison category
6644 // types stored in ASTContext. The bit-index corresponds to the integer value
6645 // of a ComparisonCategoryType enumerator.
6646 llvm::SmallBitVector FullyCheckedComparisonCategories;
6647
6648 /// Check if there is a field shadowing.
6649 void CheckShadowInheritedFields(const SourceLocation &Loc,
6650 DeclarationName FieldName,
6651 const CXXRecordDecl *RD,
6652 bool DeclIsField = true);
6653
6654 ///@}
6655
6656 //
6657 //
6658 // -------------------------------------------------------------------------
6659 //
6660 //
6661
6662 /// \name C++ Exception Specifications
6663 /// Implementations are in SemaExceptionSpec.cpp
6664 ///@{
6665
6666public:
6667 /// All the overriding functions seen during a class definition
6668 /// that had their exception spec checks delayed, plus the overridden
6669 /// function.
6670 SmallVector<std::pair<const CXXMethodDecl *, const CXXMethodDecl *>, 2>
6671 DelayedOverridingExceptionSpecChecks;
6672
6673 /// All the function redeclarations seen during a class definition that had
6674 /// their exception spec checks delayed, plus the prior declaration they
6675 /// should be checked against. Except during error recovery, the new decl
6676 /// should always be a friend declaration, as that's the only valid way to
6677 /// redeclare a special member before its class is complete.
6678 SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 2>
6679 DelayedEquivalentExceptionSpecChecks;
6680
6681 /// Determine if we're in a case where we need to (incorrectly) eagerly
6682 /// parse an exception specification to work around a libstdc++ bug.
6683 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6684
6685 /// Check the given noexcept-specifier, convert its expression, and compute
6686 /// the appropriate ExceptionSpecificationType.
6687 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6688 ExceptionSpecificationType &EST);
6689
6690 CanThrowResult canThrow(const Stmt *E);
6691 /// Determine whether the callee of a particular function call can throw.
6692 /// E, D and Loc are all optional.
6693 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6694 SourceLocation Loc = SourceLocation());
6695 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
6696 const FunctionProtoType *FPT);
6697 void UpdateExceptionSpec(FunctionDecl *FD,
6698 const FunctionProtoType::ExceptionSpecInfo &ESI);
6699
6700 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6701 /// exception specification. Incomplete types, or pointers to incomplete types
6702 /// other than void are not allowed.
6703 ///
6704 /// \param[in,out] T The exception type. This will be decayed to a pointer
6705 /// type
6706 /// when the input is an array or a function type.
6707 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
6708
6709 /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6710 /// pointer to member to a function with an exception specification. This
6711 /// means that it is invalid to add another level of indirection.
6712 bool CheckDistantExceptionSpec(QualType T);
6713 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
6714
6715 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6716 /// exception specifications. Exception specifications are equivalent if
6717 /// they allow exactly the same set of exception types. It does not matter how
6718 /// that is achieved. See C++ [except.spec]p2.
6719 bool CheckEquivalentExceptionSpec(const FunctionProtoType *Old,
6720 SourceLocation OldLoc,
6721 const FunctionProtoType *New,
6722 SourceLocation NewLoc);
6723 bool CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
6724 const PartialDiagnostic &NoteID,
6725 const FunctionProtoType *Old,
6726 SourceLocation OldLoc,
6727 const FunctionProtoType *New,
6728 SourceLocation NewLoc);
6729 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6730
6731 /// CheckExceptionSpecSubset - Check whether the second function type's
6732 /// exception specification is a subset (or equivalent) of the first function
6733 /// type. This is used by override and pointer assignment checks.
6734 bool CheckExceptionSpecSubset(
6735 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6736 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6737 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6738 SourceLocation SuperLoc, const FunctionProtoType *Subset,
6739 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6740
6741 /// CheckParamExceptionSpec - Check if the parameter and return types of the
6742 /// two functions have equivalent exception specs. This is part of the
6743 /// assignment and override compatibility check. We do not check the
6744 /// parameters of parameter function pointers recursively, as no sane
6745 /// programmer would even be able to write such a function type.
6746 bool CheckParamExceptionSpec(
6747 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6748 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6749 SourceLocation TargetLoc, const FunctionProtoType *Source,
6750 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6751
6752 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6753
6754 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6755 /// spec is a subset of base spec.
6756 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6757 const CXXMethodDecl *Old);
6758
6759 ///@}
6760
6761 //
6762 //
6763 // -------------------------------------------------------------------------
6764 //
6765 //
6766
6767 /// \name Expressions
6768 /// Implementations are in SemaExpr.cpp
6769 ///@{
6770
6771public:
6772 /// Describes how the expressions currently being parsed are
6773 /// evaluated at run-time, if at all.
6774 enum class ExpressionEvaluationContext {
6775 /// The current expression and its subexpressions occur within an
6776 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6777 /// \c sizeof, where the type of the expression may be significant but
6778 /// no code will be generated to evaluate the value of the expression at
6779 /// run time.
6780 Unevaluated,
6781
6782 /// The current expression occurs within a braced-init-list within
6783 /// an unevaluated operand. This is mostly like a regular unevaluated
6784 /// context, except that we still instantiate constexpr functions that are
6785 /// referenced here so that we can perform narrowing checks correctly.
6786 UnevaluatedList,
6787
6788 /// The current expression occurs within a discarded statement.
6789 /// This behaves largely similarly to an unevaluated operand in preventing
6790 /// definitions from being required, but not in other ways.
6791 DiscardedStatement,
6792
6793 /// The current expression occurs within an unevaluated
6794 /// operand that unconditionally permits abstract references to
6795 /// fields, such as a SIZE operator in MS-style inline assembly.
6796 UnevaluatedAbstract,
6797
6798 /// The current context is "potentially evaluated" in C++11 terms,
6799 /// but the expression is evaluated at compile-time (like the values of
6800 /// cases in a switch statement).
6801 ConstantEvaluated,
6802
6803 /// In addition of being constant evaluated, the current expression
6804 /// occurs in an immediate function context - either a consteval function
6805 /// or a consteval if statement.
6806 ImmediateFunctionContext,
6807
6808 /// The current expression is potentially evaluated at run time,
6809 /// which means that code may be generated to evaluate the value of the
6810 /// expression at run time.
6811 PotentiallyEvaluated,
6812
6813 /// The current expression is potentially evaluated, but any
6814 /// declarations referenced inside that expression are only used if
6815 /// in fact the current expression is used.
6816 ///
6817 /// This value is used when parsing default function arguments, for which
6818 /// we would like to provide diagnostics (e.g., passing non-POD arguments
6819 /// through varargs) but do not want to mark declarations as "referenced"
6820 /// until the default argument is used.
6821 PotentiallyEvaluatedIfUsed
6822 };
6823
6824 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6825 /// to a variable (constant) that may or may not be odr-used in this Expr, and
6826 /// we won't know until all lvalue-to-rvalue and discarded value conversions
6827 /// have been applied to all subexpressions of the enclosing full expression.
6828 /// This is cleared at the end of each full expression.
6829 using MaybeODRUseExprSet = llvm::SmallSetVector<Expr *, 4>;
6830 MaybeODRUseExprSet MaybeODRUseExprs;
6831
6832 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6833
6834 /// Data structure used to record current or nested
6835 /// expression evaluation contexts.
6836 struct ExpressionEvaluationContextRecord {
6837 /// The expression evaluation context.
6838 ExpressionEvaluationContext Context;
6839
6840 /// Whether the enclosing context needed a cleanup.
6841 CleanupInfo ParentCleanup;
6842
6843 /// The number of active cleanup objects when we entered
6844 /// this expression evaluation context.
6845 unsigned NumCleanupObjects;
6846
6847 MaybeODRUseExprSet SavedMaybeODRUseExprs;
6848
6849 /// The lambdas that are present within this context, if it
6850 /// is indeed an unevaluated context.
6851 SmallVector<LambdaExpr *, 2> Lambdas;
6852
6853 /// The declaration that provides context for lambda expressions
6854 /// and block literals if the normal declaration context does not
6855 /// suffice, e.g., in a default function argument.
6856 Decl *ManglingContextDecl;
6857
6858 /// Declaration for initializer if one is currently being
6859 /// parsed. Used when an expression has a possibly unreachable
6860 /// diagnostic to reference the declaration as a whole.
6861 VarDecl *DeclForInitializer = nullptr;
6862
6863 /// If we are processing a decltype type, a set of call expressions
6864 /// for which we have deferred checking the completeness of the return type.
6865 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
6866
6867 /// If we are processing a decltype type, a set of temporary binding
6868 /// expressions for which we have deferred checking the destructor.
6869 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
6870
6871 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
6872
6873 /// Expressions appearing as the LHS of a volatile assignment in this
6874 /// context. We produce a warning for these when popping the context if
6875 /// they are not discarded-value expressions nor unevaluated operands.
6876 SmallVector<Expr *, 2> VolatileAssignmentLHSs;
6877
6878 /// Set of candidates for starting an immediate invocation.
6879 llvm::SmallVector<ImmediateInvocationCandidate, 4>
6880 ImmediateInvocationCandidates;
6881
6882 /// Set of DeclRefExprs referencing a consteval function when used in a
6883 /// context not already known to be immediately invoked.
6884 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
6885
6886 /// P2718R0 - Lifetime extension in range-based for loops.
6887 /// MaterializeTemporaryExprs in for-range-init expressions which need to
6888 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
6889 /// InLifetimeExtendingContext is true.
6890 SmallVector<MaterializeTemporaryExpr *, 8> ForRangeLifetimeExtendTemps;
6891
6892 /// Small set of gathered accesses to potentially misaligned members
6893 /// due to the packed attribute.
6894 SmallVector<MisalignedMember, 4> MisalignedMembers;
6895
6896 /// \brief Describes whether we are in an expression constext which we have
6897 /// to handle differently.
6898 enum ExpressionKind {
6899 EK_Decltype,
6900 EK_TemplateArgument,
6901 EK_AttrArgument,
6902 EK_VariableInit,
6903 EK_Other
6904 } ExprContext;
6905
6906 // A context can be nested in both a discarded statement context and
6907 // an immediate function context, so they need to be tracked independently.
6908 bool InDiscardedStatement;
6909 bool InImmediateFunctionContext;
6910 bool InImmediateEscalatingFunctionContext;
6911
6912 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
6913
6914 // We are in a constant context, but we also allow
6915 // non constant expressions, for example for array bounds (which may be
6916 // VLAs).
6917 bool InConditionallyConstantEvaluateContext = false;
6918
6919 /// Whether we are currently in a context in which all temporaries must be
6920 /// lifetime-extended, even if they're not bound to a reference (for
6921 /// example, in a for-range initializer).
6922 bool InLifetimeExtendingContext = false;
6923
6924 /// Whether evaluating an expression for a switch case label.
6925 bool IsCaseExpr = false;
6926
6927 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
6928 bool RebuildDefaultArgOrDefaultInit = false;
6929
6930 // When evaluating immediate functions in the initializer of a default
6931 // argument or default member initializer, this is the declaration whose
6932 // default initializer is being evaluated and the location of the call
6933 // or constructor definition.
6934 struct InitializationContext {
6935 InitializationContext(SourceLocation Loc, ValueDecl *Decl,
6936 DeclContext *Context)
6937 : Loc(Loc), Decl(Decl), Context(Context) {
6938 assert(Decl && Context && "invalid initialization context");
6939 }
6940
6941 SourceLocation Loc;
6942 ValueDecl *Decl = nullptr;
6943 DeclContext *Context = nullptr;
6944 };
6945 std::optional<InitializationContext> DelayedDefaultInitializationContext;
6946
6947 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
6948 unsigned NumCleanupObjects,
6949 CleanupInfo ParentCleanup,
6950 Decl *ManglingContextDecl,
6951 ExpressionKind ExprContext)
6952 : Context(Context), ParentCleanup(ParentCleanup),
6953 NumCleanupObjects(NumCleanupObjects),
6954 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
6955 InDiscardedStatement(false), InImmediateFunctionContext(false),
6956 InImmediateEscalatingFunctionContext(false) {}
6957
6958 bool isUnevaluated() const {
6959 return Context == ExpressionEvaluationContext::Unevaluated ||
6960 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
6961 Context == ExpressionEvaluationContext::UnevaluatedList;
6962 }
6963
6964 bool isPotentiallyEvaluated() const {
6965 return Context == ExpressionEvaluationContext::PotentiallyEvaluated ||
6966 Context ==
6967 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed ||
6968 Context == ExpressionEvaluationContext::ConstantEvaluated;
6969 }
6970
6971 bool isConstantEvaluated() const {
6972 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
6973 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
6974 }
6975
6976 bool isImmediateFunctionContext() const {
6977 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
6978 (Context == ExpressionEvaluationContext::DiscardedStatement &&
6979 InImmediateFunctionContext) ||
6980 // C++23 [expr.const]p14:
6981 // An expression or conversion is in an immediate function
6982 // context if it is potentially evaluated and either:
6983 // * its innermost enclosing non-block scope is a function
6984 // parameter scope of an immediate function, or
6985 // * its enclosing statement is enclosed by the compound-
6986 // statement of a consteval if statement.
6987 (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
6988 InImmediateFunctionContext);
6989 }
6990
6991 bool isDiscardedStatementContext() const {
6992 return Context == ExpressionEvaluationContext::DiscardedStatement ||
6993 ((Context ==
6994 ExpressionEvaluationContext::ImmediateFunctionContext ||
6995 isPotentiallyEvaluated()) &&
6996 InDiscardedStatement);
6997 }
6998 };
6999
7000 const ExpressionEvaluationContextRecord &currentEvaluationContext() const {
7001 assert(!ExprEvalContexts.empty() &&
7002 "Must be in an expression evaluation context");
7003 return ExprEvalContexts.back();
7004 }
7005
7006 ExpressionEvaluationContextRecord &currentEvaluationContext() {
7007 assert(!ExprEvalContexts.empty() &&
7008 "Must be in an expression evaluation context");
7009 return ExprEvalContexts.back();
7010 }
7011
7012 ExpressionEvaluationContextRecord &parentEvaluationContext() {
7013 assert(ExprEvalContexts.size() >= 2 &&
7014 "Must be in an expression evaluation context");
7015 return ExprEvalContexts[ExprEvalContexts.size() - 2];
7016 }
7017
7018 const ExpressionEvaluationContextRecord &parentEvaluationContext() const {
7019 return const_cast<Sema *>(this)->parentEvaluationContext();
7020 }
7021
7022 bool isAttrContext() const {
7023 return ExprEvalContexts.back().ExprContext ==
7024 ExpressionEvaluationContextRecord::ExpressionKind::EK_AttrArgument;
7025 }
7026
7027 /// Increment when we find a reference; decrement when we find an ignored
7028 /// assignment. Ultimately the value is 0 if every reference is an ignored
7029 /// assignment.
7030 ///
7031 /// Uses canonical VarDecl as key so in-class decls and out-of-class defs of
7032 /// static data members get tracked as a single entry.
7033 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
7034
7035 /// Used to control the generation of ExprWithCleanups.
7036 CleanupInfo Cleanup;
7037
7038 /// ExprCleanupObjects - This is the stack of objects requiring
7039 /// cleanup that are created by the current full expression.
7040 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
7041
7042 /// Determine whether the use of this declaration is valid, without
7043 /// emitting diagnostics.
7044 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
7045 // A version of DiagnoseUseOfDecl that should be used if overload resolution
7046 // has been used to find this declaration, which means we don't have to bother
7047 // checking the trailing requires clause.
7048 bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) {
7049 return DiagnoseUseOfDecl(
7050 D, Locs: Loc, /*UnknownObjCClass=*/UnknownObjCClass: nullptr, /*ObjCPropertyAccess=*/ObjCPropertyAccess: false,
7051 /*AvoidPartialAvailabilityChecks=*/AvoidPartialAvailabilityChecks: false, /*ClassReceiver=*/ClassReceiver: nullptr,
7052 /*SkipTrailingRequiresClause=*/SkipTrailingRequiresClause: true);
7053 }
7054
7055 /// Determine whether the use of this declaration is valid, and
7056 /// emit any corresponding diagnostics.
7057 ///
7058 /// This routine diagnoses various problems with referencing
7059 /// declarations that can occur when using a declaration. For example,
7060 /// it might warn if a deprecated or unavailable declaration is being
7061 /// used, or produce an error (and return true) if a C++0x deleted
7062 /// function is being used.
7063 ///
7064 /// \returns true if there was an error (this declaration cannot be
7065 /// referenced), false otherwise.
7066 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
7067 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
7068 bool ObjCPropertyAccess = false,
7069 bool AvoidPartialAvailabilityChecks = false,
7070 ObjCInterfaceDecl *ClassReceiver = nullptr,
7071 bool SkipTrailingRequiresClause = false);
7072
7073 /// Emit a note explaining that this function is deleted.
7074 void NoteDeletedFunction(FunctionDecl *FD);
7075
7076 /// DiagnoseSentinelCalls - This routine checks whether a call or
7077 /// message-send is to a declaration with the sentinel attribute, and
7078 /// if so, it checks that the requirements of the sentinel are
7079 /// satisfied.
7080 void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
7081 ArrayRef<Expr *> Args);
7082
7083 void PushExpressionEvaluationContext(
7084 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
7085 ExpressionEvaluationContextRecord::ExpressionKind Type =
7086 ExpressionEvaluationContextRecord::EK_Other);
7087
7088 void PushExpressionEvaluationContextForFunction(
7089 ExpressionEvaluationContext NewContext, FunctionDecl *FD);
7090
7091 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
7092 void PushExpressionEvaluationContext(
7093 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
7094 ExpressionEvaluationContextRecord::ExpressionKind Type =
7095 ExpressionEvaluationContextRecord::EK_Other);
7096 void PopExpressionEvaluationContext();
7097
7098 void DiscardCleanupsInEvaluationContext();
7099
7100 ExprResult TransformToPotentiallyEvaluated(Expr *E);
7101 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
7102 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
7103
7104 /// Check whether E, which is either a discarded-value expression or an
7105 /// unevaluated operand, is a simple-assignment to a volatlie-qualified
7106 /// lvalue, and if so, remove it from the list of volatile-qualified
7107 /// assignments that we are going to warn are deprecated.
7108 void CheckUnusedVolatileAssignment(Expr *E);
7109
7110 ExprResult ActOnConstantExpression(ExprResult Res);
7111
7112 // Functions for marking a declaration referenced. These functions also
7113 // contain the relevant logic for marking if a reference to a function or
7114 // variable is an odr-use (in the C++11 sense). There are separate variants
7115 // for expressions referring to a decl; these exist because odr-use marking
7116 // needs to be delayed for some constant variables when we build one of the
7117 // named expressions.
7118 //
7119 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
7120 // should usually be true. This only needs to be set to false if the lack of
7121 // odr-use cannot be determined from the current context (for instance,
7122 // because the name denotes a virtual function and was written without an
7123 // explicit nested-name-specifier).
7124 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
7125
7126 /// Mark a function referenced, and check whether it is odr-used
7127 /// (C++ [basic.def.odr]p2, C99 6.9p3)
7128 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
7129 bool MightBeOdrUse = true);
7130
7131 /// Mark a variable referenced, and check whether it is odr-used
7132 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
7133 /// used directly for normal expressions referring to VarDecl.
7134 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
7135
7136 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7137 ///
7138 /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7139 /// be handled with care if the DeclRefExpr is not newly-created.
7140 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7141
7142 /// Perform reference-marking and odr-use handling for a MemberExpr.
7143 void MarkMemberReferenced(MemberExpr *E);
7144
7145 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7146 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
7147 void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc,
7148 unsigned CapturingScopeIndex);
7149
7150 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
7151 void CleanupVarDeclMarking();
7152
7153 /// Try to capture the given variable.
7154 ///
7155 /// \param Var The variable to capture.
7156 ///
7157 /// \param Loc The location at which the capture occurs.
7158 ///
7159 /// \param Kind The kind of capture, which may be implicit (for either a
7160 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7161 ///
7162 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7163 /// an explicit lambda capture.
7164 ///
7165 /// \param BuildAndDiagnose Whether we are actually supposed to add the
7166 /// captures or diagnose errors. If false, this routine merely check whether
7167 /// the capture can occur without performing the capture itself or complaining
7168 /// if the variable cannot be captured.
7169 ///
7170 /// \param CaptureType Will be set to the type of the field used to capture
7171 /// this variable in the innermost block or lambda. Only valid when the
7172 /// variable can be captured.
7173 ///
7174 /// \param DeclRefType Will be set to the type of a reference to the capture
7175 /// from within the current scope. Only valid when the variable can be
7176 /// captured.
7177 ///
7178 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7179 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7180 /// This is useful when enclosing lambdas must speculatively capture
7181 /// variables that may or may not be used in certain specializations of
7182 /// a nested generic lambda.
7183 ///
7184 /// \returns true if an error occurred (i.e., the variable cannot be
7185 /// captured) and false if the capture succeeded.
7186 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7187 TryCaptureKind Kind, SourceLocation EllipsisLoc,
7188 bool BuildAndDiagnose, QualType &CaptureType,
7189 QualType &DeclRefType,
7190 const unsigned *const FunctionScopeIndexToStopAt);
7191
7192 /// Try to capture the given variable.
7193 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7194 TryCaptureKind Kind = TryCaptureKind::Implicit,
7195 SourceLocation EllipsisLoc = SourceLocation());
7196
7197 /// Checks if the variable must be captured.
7198 bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc);
7199
7200 /// Given a variable, determine the type that a reference to that
7201 /// variable will have in the given scope.
7202 QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc);
7203
7204 /// Mark all of the declarations referenced within a particular AST node as
7205 /// referenced. Used when template instantiation instantiates a non-dependent
7206 /// type -- entities referenced by the type are now referenced.
7207 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
7208
7209 /// Mark any declarations that appear within this expression or any
7210 /// potentially-evaluated subexpressions as "referenced".
7211 ///
7212 /// \param SkipLocalVariables If true, don't mark local variables as
7213 /// 'referenced'.
7214 /// \param StopAt Subexpressions that we shouldn't recurse into.
7215 void MarkDeclarationsReferencedInExpr(Expr *E,
7216 bool SkipLocalVariables = false,
7217 ArrayRef<const Expr *> StopAt = {});
7218
7219 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7220 /// conversion.
7221 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7222
7223 /// Conditionally issue a diagnostic based on the statements's reachability
7224 /// analysis.
7225 ///
7226 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7227 /// the function body is parsed, and then do a basic reachability analysis to
7228 /// determine if the statement is reachable. If it is unreachable, the
7229 /// diagnostic will not be emitted.
7230 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7231 const PartialDiagnostic &PD);
7232
7233 /// Conditionally issue a diagnostic based on the current
7234 /// evaluation context.
7235 ///
7236 /// \param Statement If Statement is non-null, delay reporting the
7237 /// diagnostic until the function body is parsed, and then do a basic
7238 /// reachability analysis to determine if the statement is reachable.
7239 /// If it is unreachable, the diagnostic will not be emitted.
7240 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7241 const PartialDiagnostic &PD);
7242 /// Similar, but diagnostic is only produced if all the specified statements
7243 /// are reachable.
7244 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7245 const PartialDiagnostic &PD);
7246
7247 // Primary Expressions.
7248 SourceRange getExprRange(Expr *E) const;
7249
7250 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7251 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7252 bool HasTrailingLParen, bool IsAddressOfOperand,
7253 CorrectionCandidateCallback *CCC = nullptr,
7254 bool IsInlineAsmIdentifier = false,
7255 Token *KeywordReplacement = nullptr);
7256
7257 /// Decomposes the given name into a DeclarationNameInfo, its location, and
7258 /// possibly a list of template arguments.
7259 ///
7260 /// If this produces template arguments, it is permitted to call
7261 /// DecomposeTemplateName.
7262 ///
7263 /// This actually loses a lot of source location information for
7264 /// non-standard name kinds; we should consider preserving that in
7265 /// some way.
7266 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7267 TemplateArgumentListInfo &Buffer,
7268 DeclarationNameInfo &NameInfo,
7269 const TemplateArgumentListInfo *&TemplateArgs);
7270
7271 /// Diagnose a lookup that found results in an enclosing class during error
7272 /// recovery. This usually indicates that the results were found in a
7273 /// dependent base class that could not be searched as part of a template
7274 /// definition. Always issues a diagnostic (though this may be only a warning
7275 /// in MS compatibility mode).
7276 ///
7277 /// Return \c true if the error is unrecoverable, or \c false if the caller
7278 /// should attempt to recover using these lookup results.
7279 bool DiagnoseDependentMemberLookup(const LookupResult &R);
7280
7281 /// Diagnose an empty lookup.
7282 ///
7283 /// \return false if new lookup candidates were found
7284 bool
7285 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7286 CorrectionCandidateCallback &CCC,
7287 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7288 ArrayRef<Expr *> Args = {},
7289 DeclContext *LookupCtx = nullptr);
7290
7291 /// If \p D cannot be odr-used in the current expression evaluation context,
7292 /// return a reason explaining why. Otherwise, return NOUR_None.
7293 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
7294
7295 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7296 SourceLocation Loc,
7297 const CXXScopeSpec *SS = nullptr);
7298 DeclRefExpr *
7299 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7300 const DeclarationNameInfo &NameInfo,
7301 const CXXScopeSpec *SS = nullptr,
7302 NamedDecl *FoundD = nullptr,
7303 SourceLocation TemplateKWLoc = SourceLocation(),
7304 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7305
7306 /// BuildDeclRefExpr - Build an expression that references a
7307 /// declaration that does not require a closure capture.
7308 DeclRefExpr *
7309 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7310 const DeclarationNameInfo &NameInfo,
7311 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7312 SourceLocation TemplateKWLoc = SourceLocation(),
7313 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7314
7315 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7316 bool HasTrailingLParen);
7317
7318 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7319 /// declaration name, generally during template instantiation.
7320 /// There's a large number of things which don't need to be done along
7321 /// this path.
7322 ExprResult BuildQualifiedDeclarationNameExpr(
7323 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7324 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7325
7326 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7327 bool NeedsADL,
7328 bool AcceptInvalidDecl = false);
7329
7330 /// Complete semantic analysis for a reference to the given declaration.
7331 ExprResult BuildDeclarationNameExpr(
7332 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7333 NamedDecl *FoundD = nullptr,
7334 const TemplateArgumentListInfo *TemplateArgs = nullptr,
7335 bool AcceptInvalidDecl = false);
7336
7337 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7338 // where Tokens representing function local predefined macros (such as
7339 // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7340 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7341
7342 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7343 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7344 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7345
7346 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7347
7348 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7349 ExprResult ActOnCharacterConstant(const Token &Tok,
7350 Scope *UDLScope = nullptr);
7351 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7352 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7353 MultiExprArg Val);
7354 ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7355 unsigned NumUserSpecifiedExprs,
7356 SourceLocation InitLoc,
7357 SourceLocation LParenLoc,
7358 SourceLocation RParenLoc);
7359
7360 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7361 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle
7362 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7363 /// from multiple tokens. However, the common case is that StringToks points
7364 /// to one string.
7365 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7366 Scope *UDLScope = nullptr);
7367
7368 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7369
7370 /// ControllingExprOrType is either an opaque pointer coming out of a
7371 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7372 /// into two so we don't take a void *, but that's awkward because one of
7373 /// the operands is either a ParsedType or an Expr *, which doesn't lend
7374 /// itself to generic code very well.
7375 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7376 SourceLocation DefaultLoc,
7377 SourceLocation RParenLoc,
7378 bool PredicateIsExpr,
7379 void *ControllingExprOrType,
7380 ArrayRef<ParsedType> ArgTypes,
7381 ArrayRef<Expr *> ArgExprs);
7382 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7383 /// it'd be better to split this interface into two so we don't take a
7384 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7385 /// isn't a trivial change.
7386 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7387 SourceLocation DefaultLoc,
7388 SourceLocation RParenLoc,
7389 bool PredicateIsExpr,
7390 void *ControllingExprOrType,
7391 ArrayRef<TypeSourceInfo *> Types,
7392 ArrayRef<Expr *> Exprs);
7393
7394 // Binary/Unary Operators. 'Tok' is the token for the operator.
7395 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7396 Expr *InputExpr, bool IsAfterAmp = false);
7397 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7398 Expr *Input, bool IsAfterAmp = false);
7399
7400 /// Unary Operators. 'Tok' is the token for the operator.
7401 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7402 Expr *Input, bool IsAfterAmp = false);
7403
7404 /// Determine whether the given expression is a qualified member
7405 /// access expression, of a form that could be turned into a pointer to member
7406 /// with the address-of operator.
7407 bool isQualifiedMemberAccess(Expr *E);
7408 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7409 const Expr *Op,
7410 const CXXMethodDecl *MD);
7411
7412 /// CheckAddressOfOperand - The operand of & must be either a function
7413 /// designator or an lvalue designating an object. If it is an lvalue, the
7414 /// object cannot be declared with storage class register or be a bit field.
7415 /// Note: The usual conversions are *not* applied to the operand of the &
7416 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7417 /// In C++, the operand might be an overloaded function name, in which case
7418 /// we allow the '&' but retain the overloaded-function type.
7419 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7420
7421 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7422 /// _Alignas(type-name) .
7423 /// [dcl.align] An alignment-specifier of the form
7424 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7425 ///
7426 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7427 /// _Alignas(_Alignof(type-name)).
7428 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7429 SourceLocation OpLoc, SourceRange R);
7430 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7431 SourceLocation OpLoc, SourceRange R);
7432
7433 /// Build a sizeof or alignof expression given a type operand.
7434 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7435 SourceLocation OpLoc,
7436 UnaryExprOrTypeTrait ExprKind,
7437 SourceRange R);
7438
7439 /// Build a sizeof or alignof expression given an expression
7440 /// operand.
7441 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7442 UnaryExprOrTypeTrait ExprKind);
7443
7444 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7445 /// expr and the same for @c alignof and @c __alignof
7446 /// Note that the ArgRange is invalid if isType is false.
7447 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7448 UnaryExprOrTypeTrait ExprKind,
7449 bool IsType, void *TyOrEx,
7450 SourceRange ArgRange);
7451
7452 /// Check for operands with placeholder types and complain if found.
7453 /// Returns ExprError() if there was an error and no recovery was possible.
7454 ExprResult CheckPlaceholderExpr(Expr *E);
7455 bool CheckVecStepExpr(Expr *E);
7456
7457 /// Check the constraints on expression operands to unary type expression
7458 /// and type traits.
7459 ///
7460 /// Completes any types necessary and validates the constraints on the operand
7461 /// expression. The logic mostly mirrors the type-based overload, but may
7462 /// modify the expression as it completes the type for that expression through
7463 /// template instantiation, etc.
7464 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
7465
7466 /// Check the constraints on operands to unary expression and type
7467 /// traits.
7468 ///
7469 /// This will complete any types necessary, and validate the various
7470 /// constraints on those operands.
7471 ///
7472 /// The UsualUnaryConversions() function is *not* called by this routine.
7473 /// C99 6.3.2.1p[2-4] all state:
7474 /// Except when it is the operand of the sizeof operator ...
7475 ///
7476 /// C++ [expr.sizeof]p4
7477 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7478 /// standard conversions are not applied to the operand of sizeof.
7479 ///
7480 /// This policy is followed for all of the unary trait expressions.
7481 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7482 SourceRange ExprRange,
7483 UnaryExprOrTypeTrait ExprKind,
7484 StringRef KWName);
7485
7486 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7487 tok::TokenKind Kind, Expr *Input);
7488
7489 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7490 MultiExprArg ArgExprs,
7491 SourceLocation RLoc);
7492 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7493 Expr *Idx, SourceLocation RLoc);
7494
7495 ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx,
7496 SourceLocation RBLoc);
7497
7498 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7499 Expr *ColumnIdx,
7500 SourceLocation RBLoc);
7501
7502 /// ConvertArgumentsForCall - Converts the arguments specified in
7503 /// Args/NumArgs to the parameter types of the function FDecl with
7504 /// function prototype Proto. Call is the call expression itself, and
7505 /// Fn is the function expression. For a C++ member function, this
7506 /// routine does not attempt to convert the object argument. Returns
7507 /// true if the call is ill-formed.
7508 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7509 const FunctionProtoType *Proto,
7510 ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7511 bool ExecConfig = false);
7512
7513 /// CheckStaticArrayArgument - If the given argument corresponds to a static
7514 /// array parameter, check that it is non-null, and that if it is formed by
7515 /// array-to-pointer decay, the underlying array is sufficiently large.
7516 ///
7517 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7518 /// the array type derivation, then for each call to the function, the value
7519 /// of the corresponding actual argument shall provide access to the first
7520 /// element of an array with at least as many elements as specified by the
7521 /// size expression.
7522 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7523 const Expr *ArgExpr);
7524
7525 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7526 /// This provides the location of the left/right parens and a list of comma
7527 /// locations.
7528 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7529 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7530 Expr *ExecConfig = nullptr);
7531
7532 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7533 /// This provides the location of the left/right parens and a list of comma
7534 /// locations.
7535 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7536 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7537 Expr *ExecConfig = nullptr,
7538 bool IsExecConfig = false,
7539 bool AllowRecovery = false);
7540
7541 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7542 // with the specified CallArgs
7543 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7544 MultiExprArg CallArgs);
7545
7546 using ADLCallKind = CallExpr::ADLCallKind;
7547
7548 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7549 /// i.e. an expression not of \p OverloadTy. The expression should
7550 /// unary-convert to an expression of function-pointer or
7551 /// block-pointer type.
7552 ///
7553 /// \param NDecl the declaration being called, if available
7554 ExprResult
7555 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7556 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7557 Expr *Config = nullptr, bool IsExecConfig = false,
7558 ADLCallKind UsesADL = ADLCallKind::NotADL);
7559
7560 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D,
7561 ParsedType &Ty, SourceLocation RParenLoc,
7562 Expr *CastExpr);
7563
7564 /// Prepares for a scalar cast, performing all the necessary stages
7565 /// except the final cast and returning the kind required.
7566 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
7567
7568 /// Build an altivec or OpenCL literal.
7569 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
7570 SourceLocation RParenLoc, Expr *E,
7571 TypeSourceInfo *TInfo);
7572
7573 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7574 /// the ParenListExpr into a sequence of comma binary operators.
7575 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
7576
7577 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7578 SourceLocation RParenLoc, Expr *InitExpr);
7579
7580 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
7581 TypeSourceInfo *TInfo,
7582 SourceLocation RParenLoc,
7583 Expr *LiteralExpr);
7584
7585 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7586 SourceLocation RBraceLoc);
7587
7588 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7589 SourceLocation RBraceLoc);
7590
7591 /// Binary Operators. 'Tok' is the token for the operator.
7592 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind,
7593 Expr *LHSExpr, Expr *RHSExpr);
7594 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7595 Expr *LHSExpr, Expr *RHSExpr,
7596 bool ForFoldExpression = false);
7597
7598 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7599 /// operator @p Opc at location @c TokLoc. This routine only supports
7600 /// built-in operations; ActOnBinOp handles overloaded operators.
7601 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
7602 Expr *LHSExpr, Expr *RHSExpr,
7603 bool ForFoldExpression = false);
7604 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7605 UnresolvedSetImpl &Functions);
7606
7607 /// Look for instances where it is likely the comma operator is confused with
7608 /// another operator. There is an explicit list of acceptable expressions for
7609 /// the left hand side of the comma operator, otherwise emit a warning.
7610 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7611
7612 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7613 /// in the case of a the GNU conditional expr extension.
7614 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
7615 SourceLocation ColonLoc, Expr *CondExpr,
7616 Expr *LHSExpr, Expr *RHSExpr);
7617
7618 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7619 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
7620 LabelDecl *TheDecl);
7621
7622 void ActOnStartStmtExpr();
7623 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7624 SourceLocation RPLoc);
7625 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
7626 SourceLocation RPLoc, unsigned TemplateDepth);
7627 // Handle the final expression in a statement expression.
7628 ExprResult ActOnStmtExprResult(ExprResult E);
7629 void ActOnStmtExprError();
7630
7631 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
7632 struct OffsetOfComponent {
7633 SourceLocation LocStart, LocEnd;
7634 bool isBrackets; // true if [expr], false if .ident
7635 union {
7636 IdentifierInfo *IdentInfo;
7637 Expr *E;
7638 } U;
7639 };
7640
7641 /// __builtin_offsetof(type, a.b[123][456].c)
7642 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
7643 TypeSourceInfo *TInfo,
7644 ArrayRef<OffsetOfComponent> Components,
7645 SourceLocation RParenLoc);
7646 ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
7647 SourceLocation TypeLoc,
7648 ParsedType ParsedArgTy,
7649 ArrayRef<OffsetOfComponent> Components,
7650 SourceLocation RParenLoc);
7651
7652 // __builtin_choose_expr(constExpr, expr1, expr2)
7653 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7654 Expr *LHSExpr, Expr *RHSExpr,
7655 SourceLocation RPLoc);
7656
7657 // __builtin_va_arg(expr, type)
7658 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
7659 SourceLocation RPLoc);
7660 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
7661 TypeSourceInfo *TInfo, SourceLocation RPLoc);
7662
7663 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7664 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7665 ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind,
7666 SourceLocation BuiltinLoc,
7667 SourceLocation RPLoc);
7668
7669 // #embed
7670 ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
7671 StringLiteral *BinaryData, StringRef FileName);
7672
7673 // Build a potentially resolved SourceLocExpr.
7674 ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
7675 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7676 DeclContext *ParentContext);
7677
7678 // __null
7679 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
7680
7681 bool CheckCaseExpression(Expr *E);
7682
7683 //===------------------------- "Block" Extension ------------------------===//
7684
7685 /// ActOnBlockStart - This callback is invoked when a block literal is
7686 /// started.
7687 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7688
7689 /// ActOnBlockArguments - This callback allows processing of block arguments.
7690 /// If there are no arguments, this is still invoked.
7691 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7692 Scope *CurScope);
7693
7694 /// ActOnBlockError - If there is an error parsing a block, this callback
7695 /// is invoked to pop the information about the block from the action impl.
7696 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7697
7698 /// ActOnBlockStmtExpr - This is called when the body of a block statement
7699 /// literal was successfully completed. ^(int x){...}
7700 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
7701 Scope *CurScope);
7702
7703 //===---------------------------- Clang Extensions ----------------------===//
7704
7705 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7706 /// provided arguments.
7707 ///
7708 /// __builtin_convertvector( value, dst type )
7709 ///
7710 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7711 SourceLocation BuiltinLoc,
7712 SourceLocation RParenLoc);
7713
7714 //===---------------------------- OpenCL Features -----------------------===//
7715
7716 /// Parse a __builtin_astype expression.
7717 ///
7718 /// __builtin_astype( value, dst type )
7719 ///
7720 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7721 SourceLocation BuiltinLoc,
7722 SourceLocation RParenLoc);
7723
7724 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7725 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
7726 SourceLocation BuiltinLoc,
7727 SourceLocation RParenLoc);
7728
7729 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7730 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
7731 ArrayRef<Expr *> SubExprs,
7732 QualType T = QualType());
7733
7734 /// Cast a base object to a member's actual type.
7735 ///
7736 /// There are two relevant checks:
7737 ///
7738 /// C++ [class.access.base]p7:
7739 ///
7740 /// If a class member access operator [...] is used to access a non-static
7741 /// data member or non-static member function, the reference is ill-formed
7742 /// if the left operand [...] cannot be implicitly converted to a pointer to
7743 /// the naming class of the right operand.
7744 ///
7745 /// C++ [expr.ref]p7:
7746 ///
7747 /// If E2 is a non-static data member or a non-static member function, the
7748 /// program is ill-formed if the class of which E2 is directly a member is
7749 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7750 ///
7751 /// Note that the latter check does not consider access; the access of the
7752 /// "real" base class is checked as appropriate when checking the access of
7753 /// the member name.
7754 ExprResult PerformObjectMemberConversion(Expr *From,
7755 NestedNameSpecifier Qualifier,
7756 NamedDecl *FoundDecl,
7757 NamedDecl *Member);
7758
7759 /// CheckCallReturnType - Checks that a call expression's return type is
7760 /// complete. Returns true on failure. The location passed in is the location
7761 /// that best represents the call.
7762 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7763 CallExpr *CE, FunctionDecl *FD);
7764
7765 /// Emit a warning for all pending noderef expressions that we recorded.
7766 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
7767
7768 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
7769
7770 /// Instantiate or parse a C++ default argument expression as necessary.
7771 /// Return true on error.
7772 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7773 ParmVarDecl *Param, Expr *Init = nullptr,
7774 bool SkipImmediateInvocations = true);
7775
7776 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7777 /// the default expr if needed.
7778 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7779 ParmVarDecl *Param, Expr *Init = nullptr);
7780
7781 /// Wrap the expression in a ConstantExpr if it is a potential immediate
7782 /// invocation.
7783 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
7784
7785 void MarkExpressionAsImmediateEscalating(Expr *E);
7786
7787 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7788 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7789
7790 /// Abstract base class used for diagnosing integer constant
7791 /// expression violations.
7792 class VerifyICEDiagnoser {
7793 public:
7794 bool Suppress;
7795
7796 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) {}
7797
7798 virtual SemaDiagnosticBuilder
7799 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7800 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7801 SourceLocation Loc) = 0;
7802 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
7803 virtual ~VerifyICEDiagnoser() {}
7804 };
7805
7806 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7807 /// and reports the appropriate diagnostics. Returns false on success.
7808 /// Can optionally return the value of the expression.
7809 ExprResult
7810 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7811 VerifyICEDiagnoser &Diagnoser,
7812 AllowFoldKind CanFold = AllowFoldKind::No);
7813 ExprResult
7814 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7815 unsigned DiagID,
7816 AllowFoldKind CanFold = AllowFoldKind::No);
7817 ExprResult
7818 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7819 AllowFoldKind CanFold = AllowFoldKind::No);
7820 ExprResult
7821 VerifyIntegerConstantExpression(Expr *E,
7822 AllowFoldKind CanFold = AllowFoldKind::No) {
7823 return VerifyIntegerConstantExpression(E, Result: nullptr, CanFold);
7824 }
7825
7826 /// DiagnoseAssignmentAsCondition - Given that an expression is
7827 /// being used as a boolean condition, warn if it's an assignment.
7828 void DiagnoseAssignmentAsCondition(Expr *E);
7829
7830 /// Redundant parentheses over an equality comparison can indicate
7831 /// that the user intended an assignment used as condition.
7832 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7833
7834 class FullExprArg {
7835 public:
7836 FullExprArg() : E(nullptr) {}
7837 FullExprArg(Sema &actions) : E(nullptr) {}
7838
7839 ExprResult release() { return E; }
7840
7841 Expr *get() const { return E; }
7842
7843 Expr *operator->() { return E; }
7844
7845 private:
7846 // FIXME: No need to make the entire Sema class a friend when it's just
7847 // Sema::MakeFullExpr that needs access to the constructor below.
7848 friend class Sema;
7849
7850 explicit FullExprArg(Expr *expr) : E(expr) {}
7851
7852 Expr *E;
7853 };
7854
7855 FullExprArg MakeFullExpr(Expr *Arg) {
7856 return MakeFullExpr(Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation());
7857 }
7858 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
7859 return FullExprArg(
7860 ActOnFinishFullExpr(Expr: Arg, CC, /*DiscardedValue*/ DiscardedValue: false).get());
7861 }
7862 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
7863 ExprResult FE =
7864 ActOnFinishFullExpr(Expr: Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation(),
7865 /*DiscardedValue*/ DiscardedValue: true);
7866 return FullExprArg(FE.get());
7867 }
7868
7869 class ConditionResult {
7870 Decl *ConditionVar;
7871 ExprResult Condition;
7872 bool Invalid;
7873 std::optional<bool> KnownValue;
7874
7875 friend class Sema;
7876 ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
7877 bool IsConstexpr)
7878 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
7879 if (IsConstexpr && Condition.get()) {
7880 if (std::optional<llvm::APSInt> Val =
7881 Condition.get()->getIntegerConstantExpr(Ctx: S.Context)) {
7882 KnownValue = !!(*Val);
7883 }
7884 }
7885 }
7886 explicit ConditionResult(bool Invalid)
7887 : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
7888 KnownValue(std::nullopt) {}
7889
7890 public:
7891 ConditionResult() : ConditionResult(false) {}
7892 bool isInvalid() const { return Invalid; }
7893 std::pair<VarDecl *, Expr *> get() const {
7894 return std::make_pair(x: cast_or_null<VarDecl>(Val: ConditionVar),
7895 y: Condition.get());
7896 }
7897 std::optional<bool> getKnownValue() const { return KnownValue; }
7898 };
7899 static ConditionResult ConditionError() { return ConditionResult(true); }
7900
7901 /// CheckBooleanCondition - Diagnose problems involving the use of
7902 /// the given expression as a boolean condition (e.g. in an if
7903 /// statement). Also performs the standard function and array
7904 /// decays, possibly changing the input variable.
7905 ///
7906 /// \param Loc - A location associated with the condition, e.g. the
7907 /// 'if' keyword.
7908 /// \return true iff there were any errors
7909 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
7910 bool IsConstexpr = false);
7911
7912 enum class ConditionKind {
7913 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
7914 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
7915 Switch ///< An integral condition for a 'switch' statement.
7916 };
7917
7918 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
7919 ConditionKind CK, bool MissingOK = false);
7920
7921 QualType CheckConditionalOperands( // C99 6.5.15
7922 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
7923 ExprObjectKind &OK, SourceLocation QuestionLoc);
7924
7925 /// Emit a specialized diagnostic when one expression is a null pointer
7926 /// constant and the other is not a pointer. Returns true if a diagnostic is
7927 /// emitted.
7928 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7929 SourceLocation QuestionLoc);
7930
7931 /// type checking for vector binary operators.
7932 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7933 SourceLocation Loc, bool IsCompAssign,
7934 bool AllowBothBool, bool AllowBoolConversion,
7935 bool AllowBoolOperation, bool ReportInvalid);
7936
7937 /// Return a signed ext_vector_type that is of identical size and number of
7938 /// elements. For floating point vectors, return an integer type of identical
7939 /// size and number of elements. In the non ext_vector_type case, search from
7940 /// the largest type to the smallest type to avoid cases where long long ==
7941 /// long, where long gets picked over long long.
7942 QualType GetSignedVectorType(QualType V);
7943 QualType GetSignedSizelessVectorType(QualType V);
7944
7945 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7946 /// operates on extended vector types. Instead of producing an IntTy result,
7947 /// like a scalar comparison, a vector comparison produces a vector of integer
7948 /// types.
7949 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7950 SourceLocation Loc,
7951 BinaryOperatorKind Opc);
7952 QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7953 SourceLocation Loc,
7954 BinaryOperatorKind Opc);
7955 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7956 SourceLocation Loc,
7957 BinaryOperatorKind Opc);
7958 QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7959 SourceLocation Loc,
7960 BinaryOperatorKind Opc);
7961 // type checking for sizeless vector binary operators.
7962 QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
7963 SourceLocation Loc, bool IsCompAssign,
7964 ArithConvKind OperationKind);
7965
7966 /// Type checking for matrix binary operators.
7967 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
7968 SourceLocation Loc,
7969 bool IsCompAssign);
7970 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
7971 SourceLocation Loc, bool IsCompAssign);
7972
7973 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
7974 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
7975 /// VLST) allowed?
7976 ///
7977 /// This will also return false if the two given types do not make sense from
7978 /// the perspective of SVE bitcasts.
7979 bool isValidSveBitcast(QualType srcType, QualType destType);
7980
7981 /// Are the two types matrix types and do they have the same dimensions i.e.
7982 /// do they have the same number of rows and the same number of columns?
7983 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
7984
7985 bool areVectorTypesSameSize(QualType srcType, QualType destType);
7986
7987 /// Are the two types lax-compatible vector types? That is, given
7988 /// that one of them is a vector, do they have equal storage sizes,
7989 /// where the storage size is the number of elements times the element
7990 /// size?
7991 ///
7992 /// This will also return false if either of the types is neither a
7993 /// vector nor a real type.
7994 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
7995
7996 /// Is this a legal conversion between two types, one of which is
7997 /// known to be a vector type?
7998 bool isLaxVectorConversion(QualType srcType, QualType destType);
7999
8000 // This returns true if at least one of the types is an altivec vector.
8001 bool anyAltivecTypes(QualType srcType, QualType destType);
8002
8003 // type checking C++ declaration initializers (C++ [dcl.init]).
8004
8005 /// Check a cast of an unknown-any type. We intentionally only
8006 /// trigger this for C-style casts.
8007 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8008 Expr *CastExpr, CastKind &CastKind,
8009 ExprValueKind &VK, CXXCastPath &Path);
8010
8011 /// Force an expression with unknown-type to an expression of the
8012 /// given type.
8013 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8014
8015 /// Type-check an expression that's being passed to an
8016 /// __unknown_anytype parameter.
8017 ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result,
8018 QualType &paramType);
8019
8020 // CheckMatrixCast - Check type constraints for matrix casts.
8021 // We allow casting between matrixes of the same dimensions i.e. when they
8022 // have the same number of rows and column. Returns true if the cast is
8023 // invalid.
8024 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8025 CastKind &Kind);
8026
8027 // CheckVectorCast - check type constraints for vectors.
8028 // Since vectors are an extension, there are no C standard reference for this.
8029 // We allow casting between vectors and integer datatypes of the same size.
8030 // returns true if the cast is invalid
8031 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8032 CastKind &Kind);
8033
8034 /// Prepare `SplattedExpr` for a vector splat operation, adding
8035 /// implicit casts if necessary.
8036 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8037
8038 /// Prepare `SplattedExpr` for a matrix splat operation, adding
8039 /// implicit casts if necessary.
8040 ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr);
8041
8042 // CheckExtVectorCast - check type constraints for extended vectors.
8043 // Since vectors are an extension, there are no C standard reference for this.
8044 // We allow casting between vectors and integer datatypes of the same size,
8045 // or vectors and the element type of that vector.
8046 // returns the cast expr
8047 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8048 CastKind &Kind);
8049
8050 QualType PreferredConditionType(ConditionKind K) const {
8051 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
8052 }
8053
8054 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
8055 // functions and arrays to their respective pointers (C99 6.3.2.1), and
8056 // promotes floating-piont types according to the language semantics.
8057 ExprResult UsualUnaryConversions(Expr *E);
8058
8059 // UsualUnaryFPConversions - promotes floating-point types according to the
8060 // current language semantics.
8061 ExprResult UsualUnaryFPConversions(Expr *E);
8062
8063 /// CallExprUnaryConversions - a special case of an unary conversion
8064 /// performed on a function designator of a call expression.
8065 ExprResult CallExprUnaryConversions(Expr *E);
8066
8067 // DefaultFunctionArrayConversion - converts functions and arrays
8068 // to their respective pointers (C99 6.3.2.1).
8069 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8070
8071 // DefaultFunctionArrayLvalueConversion - converts functions and
8072 // arrays to their respective pointers and performs the
8073 // lvalue-to-rvalue conversion.
8074 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8075 bool Diagnose = true);
8076
8077 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8078 // the operand. This function is a no-op if the operand has a function type
8079 // or an array type.
8080 ExprResult DefaultLvalueConversion(Expr *E);
8081
8082 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8083 // do not have a prototype. Integer promotions are performed on each
8084 // argument, and arguments that have type float are promoted to double.
8085 ExprResult DefaultArgumentPromotion(Expr *E);
8086
8087 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8088 const FunctionProtoType *Proto,
8089 Expr *Fn);
8090
8091 /// Determine the degree of POD-ness for an expression.
8092 /// Incomplete types are considered POD, since this check can be performed
8093 /// when we're in an unevaluated context.
8094 VarArgKind isValidVarArgType(const QualType &Ty);
8095
8096 /// Check to see if the given expression is a valid argument to a variadic
8097 /// function, issuing a diagnostic if not.
8098 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8099
8100 /// GatherArgumentsForCall - Collector argument expressions for various
8101 /// form of call prototypes.
8102 bool GatherArgumentsForCall(
8103 SourceLocation CallLoc, FunctionDecl *FDecl,
8104 const FunctionProtoType *Proto, unsigned FirstParam,
8105 ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs,
8106 VariadicCallType CallType = VariadicCallType::DoesNotApply,
8107 bool AllowExplicit = false, bool IsListInitialization = false);
8108
8109 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8110 // will create a runtime trap if the resulting type is not a POD type.
8111 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8112 FunctionDecl *FDecl);
8113
8114 // Check that the usual arithmetic conversions can be performed on this pair
8115 // of expressions that might be of enumeration type.
8116 void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc,
8117 ArithConvKind ACK);
8118
8119 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8120 // operands and then handles various conversions that are common to binary
8121 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8122 // routine returns the first non-arithmetic type found. The client is
8123 // responsible for emitting appropriate error diagnostics.
8124 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8125 SourceLocation Loc, ArithConvKind ACK);
8126
8127 bool IsAssignConvertCompatible(AssignConvertType ConvTy) {
8128 switch (ConvTy) {
8129 default:
8130 return false;
8131 case AssignConvertType::Compatible:
8132 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
8133 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
8134 return true;
8135 }
8136 llvm_unreachable("impossible");
8137 }
8138
8139 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8140 /// assignment conversion type specified by ConvTy. This returns true if the
8141 /// conversion was invalid or false if the conversion was accepted.
8142 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc,
8143 QualType DstType, QualType SrcType,
8144 Expr *SrcExpr, AssignmentAction Action,
8145 bool *Complained = nullptr);
8146
8147 /// CheckAssignmentConstraints - Perform type checking for assignment,
8148 /// argument passing, variable initialization, and function return values.
8149 /// C99 6.5.16.
8150 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8151 QualType LHSType,
8152 QualType RHSType);
8153
8154 /// Check assignment constraints and optionally prepare for a conversion of
8155 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8156 /// is true.
8157 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8158 ExprResult &RHS, CastKind &Kind,
8159 bool ConvertRHS = true);
8160
8161 /// Check assignment constraints for an assignment of RHS to LHSType.
8162 ///
8163 /// \param LHSType The destination type for the assignment.
8164 /// \param RHS The source expression for the assignment.
8165 /// \param Diagnose If \c true, diagnostics may be produced when checking
8166 /// for assignability. If a diagnostic is produced, \p RHS will be
8167 /// set to ExprError(). Note that this function may still return
8168 /// without producing a diagnostic, even for an invalid assignment.
8169 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8170 /// in an audited Core Foundation API and does not need to be checked
8171 /// for ARC retain issues.
8172 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8173 /// conversions necessary to perform the assignment. If \c false,
8174 /// \p Diagnose must also be \c false.
8175 AssignConvertType CheckSingleAssignmentConstraints(
8176 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8177 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8178
8179 // If the lhs type is a transparent union, check whether we
8180 // can initialize the transparent union with the given expression.
8181 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8182 ExprResult &RHS);
8183
8184 /// the following "Check" methods will return a valid/converted QualType
8185 /// or a null QualType (indicating an error diagnostic was issued).
8186
8187 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8188 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8189 ExprResult &RHS);
8190
8191 /// Diagnose cases where a scalar was implicitly converted to a vector and
8192 /// diagnose the underlying types. Otherwise, diagnose the error
8193 /// as invalid vector logical operands for non-C++ cases.
8194 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8195 ExprResult &RHS);
8196
8197 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8198 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8199 BinaryOperatorKind Opc);
8200 QualType CheckRemainderOperands( // C99 6.5.5
8201 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8202 bool IsCompAssign = false);
8203 QualType CheckAdditionOperands( // C99 6.5.6
8204 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8205 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8206 QualType CheckSubtractionOperands( // C99 6.5.6
8207 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8208 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8209 QualType CheckShiftOperands( // C99 6.5.7
8210 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8211 BinaryOperatorKind Opc, bool IsCompAssign = false);
8212 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
8213 QualType CheckCompareOperands( // C99 6.5.8/9
8214 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8215 BinaryOperatorKind Opc);
8216 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8217 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8218 BinaryOperatorKind Opc);
8219 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8220 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8221 BinaryOperatorKind Opc);
8222 // CheckAssignmentOperands is used for both simple and compound assignment.
8223 // For simple assignment, pass both expressions and a null converted type.
8224 // For compound assignment, pass both expressions and the converted type.
8225 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8226 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8227 BinaryOperatorKind Opc);
8228
8229 /// To be used for checking whether the arguments being passed to
8230 /// function exceeds the number of parameters expected for it.
8231 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8232 bool PartialOverloading = false) {
8233 // We check whether we're just after a comma in code-completion.
8234 if (NumArgs > 0 && PartialOverloading)
8235 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8236 return NumArgs > NumParams;
8237 }
8238
8239 /// Whether the AST is currently being rebuilt to correct immediate
8240 /// invocations. Immediate invocation candidates and references to consteval
8241 /// functions aren't tracked when this is set.
8242 bool RebuildingImmediateInvocation = false;
8243
8244 bool isAlwaysConstantEvaluatedContext() const {
8245 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8246 return (Ctx.isConstantEvaluated() || isConstantEvaluatedOverride) &&
8247 !Ctx.InConditionallyConstantEvaluateContext;
8248 }
8249
8250 /// Determines whether we are currently in a context that
8251 /// is not evaluated as per C++ [expr] p5.
8252 bool isUnevaluatedContext() const {
8253 return currentEvaluationContext().isUnevaluated();
8254 }
8255
8256 bool isImmediateFunctionContext() const {
8257 return currentEvaluationContext().isImmediateFunctionContext();
8258 }
8259
8260 bool isInLifetimeExtendingContext() const {
8261 return currentEvaluationContext().InLifetimeExtendingContext;
8262 }
8263
8264 bool needsRebuildOfDefaultArgOrInit() const {
8265 return currentEvaluationContext().RebuildDefaultArgOrDefaultInit;
8266 }
8267
8268 bool isCheckingDefaultArgumentOrInitializer() const {
8269 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8270 return (Ctx.Context ==
8271 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) ||
8272 Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer;
8273 }
8274
8275 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8276 InnermostDeclarationWithDelayedImmediateInvocations() const {
8277 assert(!ExprEvalContexts.empty() &&
8278 "Must be in an expression evaluation context");
8279 for (const auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8280 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8281 Ctx.DelayedDefaultInitializationContext)
8282 return Ctx.DelayedDefaultInitializationContext;
8283 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8284 Ctx.isUnevaluated())
8285 break;
8286 }
8287 return std::nullopt;
8288 }
8289
8290 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8291 OutermostDeclarationWithDelayedImmediateInvocations() const {
8292 assert(!ExprEvalContexts.empty() &&
8293 "Must be in an expression evaluation context");
8294 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8295 for (auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8296 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8297 !Ctx.DelayedDefaultInitializationContext && Res)
8298 break;
8299 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8300 Ctx.isUnevaluated())
8301 break;
8302 Res = Ctx.DelayedDefaultInitializationContext;
8303 }
8304 return Res;
8305 }
8306
8307 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
8308 return getDefaultedFunctionKind(FD).asComparison();
8309 }
8310
8311 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8312 /// SelfAssigned when inside a CXXMethodDecl.
8313 const FieldDecl *
8314 getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
8315
8316 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
8317
8318 template <typename... Ts>
8319 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
8320 const Ts &...Args) {
8321 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8322 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8323 }
8324
8325 template <typename... Ts>
8326 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8327 const Ts &...Args) {
8328 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8329 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
8330 }
8331
8332 /// Abstract class used to diagnose incomplete types.
8333 struct TypeDiagnoser {
8334 TypeDiagnoser() {}
8335
8336 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
8337 virtual ~TypeDiagnoser() {}
8338 };
8339
8340 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8341 protected:
8342 unsigned DiagID;
8343 std::tuple<const Ts &...> Args;
8344
8345 template <std::size_t... Is>
8346 void emit(const SemaDiagnosticBuilder &DB,
8347 std::index_sequence<Is...>) const {
8348 // Apply all tuple elements to the builder in order.
8349 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8350 (void)Dummy;
8351 }
8352
8353 public:
8354 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8355 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8356 assert(DiagID != 0 && "no diagnostic for type diagnoser");
8357 }
8358
8359 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8360 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8361 emit(DB, std::index_sequence_for<Ts...>());
8362 DB << T;
8363 }
8364 };
8365
8366 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8367 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8368 /// For example, a diagnostic with no other parameters would generally have
8369 /// the form "...%select{incomplete|sizeless}0 type %1...".
8370 template <typename... Ts>
8371 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
8372 public:
8373 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8374 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8375
8376 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8377 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8378 this->emit(DB, std::index_sequence_for<Ts...>());
8379 DB << T->isSizelessType() << T;
8380 }
8381 };
8382
8383 /// Check an argument list for placeholders that we won't try to
8384 /// handle later.
8385 bool CheckArgsForPlaceholders(MultiExprArg args);
8386
8387 /// The C++ "std::source_location::__impl" struct, defined in
8388 /// \<source_location>.
8389 RecordDecl *StdSourceLocationImplDecl;
8390
8391 /// A stack of expression evaluation contexts.
8392 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
8393
8394 // Set of failed immediate invocations to avoid double diagnosing.
8395 llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
8396
8397 /// List of SourceLocations where 'self' is implicitly retained inside a
8398 /// block.
8399 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
8400 ImplicitlyRetainedSelfLocs;
8401
8402 /// Do an explicit extend of the given block pointer if we're in ARC.
8403 void maybeExtendBlockObject(ExprResult &E);
8404
8405 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8406 SourceLocation LocationOfExcessPrecisionNotSatisfied;
8407 void DiagnosePrecisionLossInComplexDivision();
8408
8409private:
8410 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8411
8412 /// Methods for marking which expressions involve dereferencing a pointer
8413 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8414 /// they are parsed, meaning that a noderef pointer may not be accessed. For
8415 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8416 /// `*p`, but need to check that `address of` is called on it. This requires
8417 /// keeping a container of all pending expressions and checking if the address
8418 /// of them are eventually taken.
8419 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8420 void CheckAddressOfNoDeref(const Expr *E);
8421
8422 ///@}
8423
8424 //
8425 //
8426 // -------------------------------------------------------------------------
8427 //
8428 //
8429
8430 /// \name C++ Expressions
8431 /// Implementations are in SemaExprCXX.cpp
8432 ///@{
8433
8434public:
8435 /// The C++ "std::bad_alloc" class, which is defined by the C++
8436 /// standard library.
8437 LazyDeclPtr StdBadAlloc;
8438
8439 /// The C++ "std::align_val_t" enum class, which is defined by the C++
8440 /// standard library.
8441 LazyDeclPtr StdAlignValT;
8442
8443 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
8444 RecordDecl *CXXTypeInfoDecl;
8445
8446 /// A flag to remember whether the implicit forms of operator new and delete
8447 /// have been declared.
8448 bool GlobalNewDeleteDeclared;
8449
8450 /// Delete-expressions to be analyzed at the end of translation unit
8451 ///
8452 /// This list contains class members, and locations of delete-expressions
8453 /// that could not be proven as to whether they mismatch with new-expression
8454 /// used in initializer of the field.
8455 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8456
8457 /// Handle the result of the special case name lookup for inheriting
8458 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8459 /// constructor names in member using declarations, even if 'X' is not the
8460 /// name of the corresponding type.
8461 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
8462 SourceLocation NameLoc,
8463 const IdentifierInfo &Name);
8464
8465 ParsedType getConstructorName(const IdentifierInfo &II,
8466 SourceLocation NameLoc, Scope *S,
8467 CXXScopeSpec &SS, bool EnteringContext);
8468 ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc,
8469 Scope *S, CXXScopeSpec &SS,
8470 ParsedType ObjectType, bool EnteringContext);
8471
8472 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
8473 ParsedType ObjectType);
8474
8475 /// Build a C++ typeid expression with a type operand.
8476 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8477 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8478
8479 /// Build a C++ typeid expression with an expression operand.
8480 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8481 Expr *Operand, SourceLocation RParenLoc);
8482
8483 /// ActOnCXXTypeid - Parse typeid( something ).
8484 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
8485 bool isType, void *TyOrExpr,
8486 SourceLocation RParenLoc);
8487
8488 /// Build a Microsoft __uuidof expression with a type operand.
8489 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8490 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8491
8492 /// Build a Microsoft __uuidof expression with an expression operand.
8493 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8494 Expr *Operand, SourceLocation RParenLoc);
8495
8496 /// ActOnCXXUuidof - Parse __uuidof( something ).
8497 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
8498 bool isType, void *TyOrExpr,
8499 SourceLocation RParenLoc);
8500
8501 //// ActOnCXXThis - Parse 'this' pointer.
8502 ExprResult ActOnCXXThis(SourceLocation Loc);
8503
8504 /// Check whether the type of 'this' is valid in the current context.
8505 bool CheckCXXThisType(SourceLocation Loc, QualType Type);
8506
8507 /// Build a CXXThisExpr and mark it referenced in the current context.
8508 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8509 void MarkThisReferenced(CXXThisExpr *This);
8510
8511 /// Try to retrieve the type of the 'this' pointer.
8512 ///
8513 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8514 QualType getCurrentThisType();
8515
8516 /// When non-NULL, the C++ 'this' expression is allowed despite the
8517 /// current context not being a non-static member function. In such cases,
8518 /// this provides the type used for 'this'.
8519 QualType CXXThisTypeOverride;
8520
8521 /// RAII object used to temporarily allow the C++ 'this' expression
8522 /// to be used, with the given qualifiers on the current class type.
8523 class CXXThisScopeRAII {
8524 Sema &S;
8525 QualType OldCXXThisTypeOverride;
8526 bool Enabled;
8527
8528 public:
8529 /// Introduce a new scope where 'this' may be allowed (when enabled),
8530 /// using the given declaration (which is either a class template or a
8531 /// class) along with the given qualifiers.
8532 /// along with the qualifiers placed on '*this'.
8533 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8534 bool Enabled = true);
8535
8536 ~CXXThisScopeRAII();
8537 CXXThisScopeRAII(const CXXThisScopeRAII &) = delete;
8538 CXXThisScopeRAII &operator=(const CXXThisScopeRAII &) = delete;
8539 };
8540
8541 /// Make sure the value of 'this' is actually available in the current
8542 /// context, if it is a potentially evaluated context.
8543 ///
8544 /// \param Loc The location at which the capture of 'this' occurs.
8545 ///
8546 /// \param Explicit Whether 'this' is explicitly captured in a lambda
8547 /// capture list.
8548 ///
8549 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8550 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8551 /// This is useful when enclosing lambdas must speculatively capture
8552 /// 'this' that may or may not be used in certain specializations of
8553 /// a nested generic lambda (depending on whether the name resolves to
8554 /// a non-static member function or a static function).
8555 /// \return returns 'true' if failed, 'false' if success.
8556 bool CheckCXXThisCapture(
8557 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8558 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8559 bool ByCopy = false);
8560
8561 /// Determine whether the given type is the type of *this that is used
8562 /// outside of the body of a member function for a type that is currently
8563 /// being defined.
8564 bool isThisOutsideMemberFunctionBody(QualType BaseType);
8565
8566 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8567 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
8568
8569 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8570 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
8571
8572 //// ActOnCXXThrow - Parse throw expressions.
8573 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
8574 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
8575 bool IsThrownVarInScope);
8576
8577 /// CheckCXXThrowOperand - Validate the operand of a throw.
8578 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8579
8580 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8581 /// Can be interpreted either as function-style casting ("int(x)")
8582 /// or class type construction ("ClassType(x,y,z)")
8583 /// or creation of a value-initialized type ("int()").
8584 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
8585 SourceLocation LParenOrBraceLoc,
8586 MultiExprArg Exprs,
8587 SourceLocation RParenOrBraceLoc,
8588 bool ListInitialization);
8589
8590 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
8591 SourceLocation LParenLoc,
8592 MultiExprArg Exprs,
8593 SourceLocation RParenLoc,
8594 bool ListInitialization);
8595
8596 /// Parsed a C++ 'new' expression (C++ 5.3.4).
8597 ///
8598 /// E.g.:
8599 /// @code new (memory) int[size][4] @endcode
8600 /// or
8601 /// @code ::new Foo(23, "hello") @endcode
8602 ///
8603 /// \param StartLoc The first location of the expression.
8604 /// \param UseGlobal True if 'new' was prefixed with '::'.
8605 /// \param PlacementLParen Opening paren of the placement arguments.
8606 /// \param PlacementArgs Placement new arguments.
8607 /// \param PlacementRParen Closing paren of the placement arguments.
8608 /// \param TypeIdParens If the type is in parens, the source range.
8609 /// \param D The type to be allocated, as well as array dimensions.
8610 /// \param Initializer The initializing expression or initializer-list, or
8611 /// null if there is none.
8612 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8613 SourceLocation PlacementLParen,
8614 MultiExprArg PlacementArgs,
8615 SourceLocation PlacementRParen,
8616 SourceRange TypeIdParens, Declarator &D,
8617 Expr *Initializer);
8618 ExprResult
8619 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8620 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8621 SourceRange TypeIdParens, QualType AllocType,
8622 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8623 SourceRange DirectInitRange, Expr *Initializer);
8624
8625 /// Determine whether \p FD is an aligned allocation or deallocation
8626 /// function that is unavailable.
8627 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
8628
8629 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8630 /// function that is unavailable.
8631 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
8632 SourceLocation Loc);
8633
8634 /// Checks that a type is suitable as the allocated type
8635 /// in a new-expression.
8636 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8637 SourceRange R);
8638
8639 /// Finds the overloads of operator new and delete that are appropriate
8640 /// for the allocation.
8641 bool FindAllocationFunctions(
8642 SourceLocation StartLoc, SourceRange Range,
8643 AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope,
8644 QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP,
8645 MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew,
8646 FunctionDecl *&OperatorDelete, bool Diagnose = true);
8647
8648 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8649 /// delete. These are:
8650 /// @code
8651 /// // C++03:
8652 /// void* operator new(std::size_t) throw(std::bad_alloc);
8653 /// void* operator new[](std::size_t) throw(std::bad_alloc);
8654 /// void operator delete(void *) throw();
8655 /// void operator delete[](void *) throw();
8656 /// // C++11:
8657 /// void* operator new(std::size_t);
8658 /// void* operator new[](std::size_t);
8659 /// void operator delete(void *) noexcept;
8660 /// void operator delete[](void *) noexcept;
8661 /// // C++1y:
8662 /// void* operator new(std::size_t);
8663 /// void* operator new[](std::size_t);
8664 /// void operator delete(void *) noexcept;
8665 /// void operator delete[](void *) noexcept;
8666 /// void operator delete(void *, std::size_t) noexcept;
8667 /// void operator delete[](void *, std::size_t) noexcept;
8668 /// @endcode
8669 /// Note that the placement and nothrow forms of new are *not* implicitly
8670 /// declared. Their use requires including \<new\>.
8671 void DeclareGlobalNewDelete();
8672 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
8673 ArrayRef<QualType> Params);
8674
8675 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
8676 DeclarationName Name, FunctionDecl *&Operator,
8677 ImplicitDeallocationParameters,
8678 bool Diagnose = true);
8679 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
8680 ImplicitDeallocationParameters,
8681 DeclarationName Name,
8682 bool Diagnose = true);
8683 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
8684 CXXRecordDecl *RD,
8685 bool Diagnose,
8686 bool LookForGlobal,
8687 DeclarationName Name);
8688
8689 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8690 /// @code ::delete ptr; @endcode
8691 /// or
8692 /// @code delete [] ptr; @endcode
8693 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8694 bool ArrayForm, Expr *Operand);
8695 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
8696 bool IsDelete, bool CallCanBeVirtual,
8697 bool WarnOnNonAbstractTypes,
8698 SourceLocation DtorLoc);
8699
8700 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
8701 Expr *Operand, SourceLocation RParen);
8702 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8703 SourceLocation RParen);
8704
8705 ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base,
8706 SourceLocation OpLoc,
8707 tok::TokenKind OpKind,
8708 ParsedType &ObjectType,
8709 bool &MayBePseudoDestructor);
8710
8711 ExprResult BuildPseudoDestructorExpr(
8712 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8713 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8714 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8715
8716 ExprResult ActOnPseudoDestructorExpr(
8717 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8718 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8719 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8720
8721 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
8722 SourceLocation OpLoc,
8723 tok::TokenKind OpKind,
8724 SourceLocation TildeLoc,
8725 const DeclSpec &DS);
8726
8727 /// MaybeCreateExprWithCleanups - If the current full-expression
8728 /// requires any cleanups, surround it with a ExprWithCleanups node.
8729 /// Otherwise, just returns the passed-in expression.
8730 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
8731 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
8732 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
8733
8734 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8735 return ActOnFinishFullExpr(
8736 Expr, CC: Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8737 }
8738 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
8739 bool DiscardedValue, bool IsConstexpr = false,
8740 bool IsTemplateArgument = false);
8741 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
8742
8743 /// Process the expression contained within a decltype. For such expressions,
8744 /// certain semantic checks on temporaries are delayed until this point, and
8745 /// are omitted for the 'topmost' call in the decltype expression. If the
8746 /// topmost call bound a temporary, strip that temporary off the expression.
8747 ExprResult ActOnDecltypeExpression(Expr *E);
8748
8749 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8750 bool IsUDSuffix);
8751
8752 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
8753
8754 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8755 SourceLocation StmtLoc,
8756 ConditionKind CK);
8757
8758 /// Check the use of the given variable as a C++ condition in an if,
8759 /// while, do-while, or switch statement.
8760 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
8761 SourceLocation StmtLoc, ConditionKind CK);
8762
8763 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8764 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8765
8766 /// Helper function to determine whether this is the (deprecated) C++
8767 /// conversion from a string literal to a pointer to non-const char or
8768 /// non-const wchar_t (for narrow and wide string literals,
8769 /// respectively).
8770 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8771
8772 /// PerformImplicitConversion - Perform an implicit conversion of the
8773 /// expression From to the type ToType using the pre-computed implicit
8774 /// conversion sequence ICS. Returns the converted
8775 /// expression. Action is the kind of conversion we're performing,
8776 /// used in the error message.
8777 ExprResult PerformImplicitConversion(
8778 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8779 AssignmentAction Action,
8780 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
8781
8782 /// PerformImplicitConversion - Perform an implicit conversion of the
8783 /// expression From to the type ToType by following the standard
8784 /// conversion sequence SCS. Returns the converted
8785 /// expression. Flavor is the context in which we're performing this
8786 /// conversion, for use in error messages.
8787 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8788 const StandardConversionSequence &SCS,
8789 AssignmentAction Action,
8790 CheckedConversionKind CCK);
8791
8792 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8793
8794 /// Parsed one of the type trait support pseudo-functions.
8795 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8796 ArrayRef<ParsedType> Args,
8797 SourceLocation RParenLoc);
8798 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8799 ArrayRef<TypeSourceInfo *> Args,
8800 SourceLocation RParenLoc);
8801
8802 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8803 /// pseudo-functions.
8804 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8805 ParsedType LhsTy, Expr *DimExpr,
8806 SourceLocation RParen);
8807
8808 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8809 TypeSourceInfo *TSInfo, Expr *DimExpr,
8810 SourceLocation RParen);
8811
8812 /// ActOnExpressionTrait - Parsed one of the unary type trait support
8813 /// pseudo-functions.
8814 ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8815 Expr *Queried, SourceLocation RParen);
8816
8817 ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8818 Expr *Queried, SourceLocation RParen);
8819
8820 QualType CheckPointerToMemberOperands( // C++ 5.5
8821 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc,
8822 bool isIndirect);
8823 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
8824 ExprResult &RHS,
8825 SourceLocation QuestionLoc);
8826
8827 //// Determines if a type is trivially relocatable
8828 /// according to the C++26 rules.
8829 // FIXME: This is in Sema because it requires
8830 // overload resolution, can we move to ASTContext?
8831 bool IsCXXTriviallyRelocatableType(QualType T);
8832 bool IsCXXTriviallyRelocatableType(const CXXRecordDecl &RD);
8833
8834 /// Check the operands of ?: under C++ semantics.
8835 ///
8836 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8837 /// extension. In this case, LHS == Cond. (But they're not aliases.)
8838 ///
8839 /// This function also implements GCC's vector extension and the
8840 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8841 /// permit the use of a?b:c where the type of a is that of a integer vector
8842 /// with the same number of elements and size as the vectors of b and c. If
8843 /// one of either b or c is a scalar it is implicitly converted to match the
8844 /// type of the vector. Otherwise the expression is ill-formed. If both b and
8845 /// c are scalars, then b and c are checked and converted to the type of a if
8846 /// possible.
8847 ///
8848 /// The expressions are evaluated differently for GCC's and OpenCL's
8849 /// extensions. For the GCC extension, the ?: operator is evaluated as
8850 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8851 /// For the OpenCL extensions, the ?: operator is evaluated as
8852 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
8853 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
8854 QualType CXXCheckConditionalOperands( // C++ 5.16
8855 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8856 ExprObjectKind &OK, SourceLocation questionLoc);
8857
8858 /// Find a merged pointer type and convert the two expressions to it.
8859 ///
8860 /// This finds the composite pointer type for \p E1 and \p E2 according to
8861 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8862 /// it. It does not emit diagnostics (FIXME: that's not true if \p
8863 /// ConvertArgs is \c true).
8864 ///
8865 /// \param Loc The location of the operator requiring these two expressions to
8866 /// be converted to the composite pointer type.
8867 ///
8868 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
8869 /// type.
8870 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8871 bool ConvertArgs = true);
8872 QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1,
8873 ExprResult &E2, bool ConvertArgs = true) {
8874 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8875 QualType Composite =
8876 FindCompositePointerType(Loc, E1&: E1Tmp, E2&: E2Tmp, ConvertArgs);
8877 E1 = E1Tmp;
8878 E2 = E2Tmp;
8879 return Composite;
8880 }
8881
8882 /// MaybeBindToTemporary - If the passed in expression has a record type with
8883 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
8884 /// it simply returns the passed in expression.
8885 ExprResult MaybeBindToTemporary(Expr *E);
8886
8887 /// IgnoredValueConversions - Given that an expression's result is
8888 /// syntactically ignored, perform any conversions that are
8889 /// required.
8890 ExprResult IgnoredValueConversions(Expr *E);
8891
8892 ExprResult CheckUnevaluatedOperand(Expr *E);
8893
8894 IfExistsResult
8895 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
8896 const DeclarationNameInfo &TargetNameInfo);
8897
8898 IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S,
8899 SourceLocation KeywordLoc,
8900 bool IsIfExists, CXXScopeSpec &SS,
8901 UnqualifiedId &Name);
8902
8903 RequiresExprBodyDecl *
8904 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8905 ArrayRef<ParmVarDecl *> LocalParameters,
8906 Scope *BodyScope);
8907 void ActOnFinishRequiresExpr();
8908 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8909 concepts::Requirement *ActOnTypeRequirement(SourceLocation TypenameKWLoc,
8910 CXXScopeSpec &SS,
8911 SourceLocation NameLoc,
8912 const IdentifierInfo *TypeName,
8913 TemplateIdAnnotation *TemplateId);
8914 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8915 SourceLocation NoexceptLoc);
8916 concepts::Requirement *ActOnCompoundRequirement(
8917 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8918 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8919 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8920 concepts::ExprRequirement *BuildExprRequirement(
8921 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8922 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8923 concepts::ExprRequirement *BuildExprRequirement(
8924 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8925 bool IsSatisfied, SourceLocation NoexceptLoc,
8926 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8927 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8928 concepts::TypeRequirement *BuildTypeRequirement(
8929 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8930 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8931 concepts::NestedRequirement *
8932 BuildNestedRequirement(StringRef InvalidConstraintEntity,
8933 const ASTConstraintSatisfaction &Satisfaction);
8934 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8935 RequiresExprBodyDecl *Body,
8936 SourceLocation LParenLoc,
8937 ArrayRef<ParmVarDecl *> LocalParameters,
8938 SourceLocation RParenLoc,
8939 ArrayRef<concepts::Requirement *> Requirements,
8940 SourceLocation ClosingBraceLoc);
8941
8942private:
8943 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
8944 bool IsDelete);
8945
8946 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8947 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8948 bool DeleteWasArrayForm);
8949
8950 ///@}
8951
8952 //
8953 //
8954 // -------------------------------------------------------------------------
8955 //
8956 //
8957
8958 /// \name Member Access Expressions
8959 /// Implementations are in SemaExprMember.cpp
8960 ///@{
8961
8962public:
8963 /// Check whether an expression might be an implicit class member access.
8964 bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R,
8965 bool IsAddressOfOperand);
8966
8967 /// Builds an expression which might be an implicit member expression.
8968 ExprResult BuildPossibleImplicitMemberExpr(
8969 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
8970 const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
8971
8972 /// Builds an implicit member access expression. The current context
8973 /// is known to be an instance method, and the given unqualified lookup
8974 /// set is known to contain only instance members, at least one of which
8975 /// is from an appropriate type.
8976 ExprResult
8977 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8978 LookupResult &R,
8979 const TemplateArgumentListInfo *TemplateArgs,
8980 bool IsDefiniteInstance, const Scope *S);
8981
8982 ExprResult ActOnDependentMemberExpr(
8983 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
8984 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8985 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
8986 const TemplateArgumentListInfo *TemplateArgs);
8987
8988 /// The main callback when the parser finds something like
8989 /// expression . [nested-name-specifier] identifier
8990 /// expression -> [nested-name-specifier] identifier
8991 /// where 'identifier' encompasses a fairly broad spectrum of
8992 /// possibilities, including destructor and operator references.
8993 ///
8994 /// \param OpKind either tok::arrow or tok::period
8995 /// \param ObjCImpDecl the current Objective-C \@implementation
8996 /// decl; this is an ugly hack around the fact that Objective-C
8997 /// \@implementations aren't properly put in the context chain
8998 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
8999 tok::TokenKind OpKind, CXXScopeSpec &SS,
9000 SourceLocation TemplateKWLoc,
9001 UnqualifiedId &Member, Decl *ObjCImpDecl);
9002
9003 MemberExpr *
9004 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
9005 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
9006 ValueDecl *Member, DeclAccessPair FoundDecl,
9007 bool HadMultipleCandidates,
9008 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
9009 ExprValueKind VK, ExprObjectKind OK,
9010 const TemplateArgumentListInfo *TemplateArgs = nullptr);
9011
9012 // Check whether the declarations we found through a nested-name
9013 // specifier in a member expression are actually members of the base
9014 // type. The restriction here is:
9015 //
9016 // C++ [expr.ref]p2:
9017 // ... In these cases, the id-expression shall name a
9018 // member of the class or of one of its base classes.
9019 //
9020 // So it's perfectly legitimate for the nested-name specifier to name
9021 // an unrelated class, and for us to find an overload set including
9022 // decls from classes which are not superclasses, as long as the decl
9023 // we actually pick through overload resolution is from a superclass.
9024 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
9025 const CXXScopeSpec &SS,
9026 const LookupResult &R);
9027
9028 // This struct is for use by ActOnMemberAccess to allow
9029 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
9030 // changing the access operator from a '.' to a '->' (to see if that is the
9031 // change needed to fix an error about an unknown member, e.g. when the class
9032 // defines a custom operator->).
9033 struct ActOnMemberAccessExtraArgs {
9034 Scope *S;
9035 UnqualifiedId &Id;
9036 Decl *ObjCImpDecl;
9037 };
9038
9039 ExprResult BuildMemberReferenceExpr(
9040 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
9041 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9042 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9043 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
9044 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9045
9046 ExprResult
9047 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
9048 bool IsArrow, const CXXScopeSpec &SS,
9049 SourceLocation TemplateKWLoc,
9050 NamedDecl *FirstQualifierInScope, LookupResult &R,
9051 const TemplateArgumentListInfo *TemplateArgs,
9052 const Scope *S, bool SuppressQualifierCheck = false,
9053 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9054
9055 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
9056 SourceLocation OpLoc,
9057 const CXXScopeSpec &SS, FieldDecl *Field,
9058 DeclAccessPair FoundDecl,
9059 const DeclarationNameInfo &MemberNameInfo);
9060
9061 /// Perform conversions on the LHS of a member access expression.
9062 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
9063
9064 ExprResult BuildAnonymousStructUnionMemberReference(
9065 const CXXScopeSpec &SS, SourceLocation nameLoc,
9066 IndirectFieldDecl *indirectField,
9067 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none),
9068 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
9069
9070private:
9071 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
9072
9073 ///@}
9074
9075 //
9076 //
9077 // -------------------------------------------------------------------------
9078 //
9079 //
9080
9081 /// \name Initializers
9082 /// Implementations are in SemaInit.cpp
9083 ///@{
9084
9085public:
9086 /// Stack of types that correspond to the parameter entities that are
9087 /// currently being copy-initialized. Can be empty.
9088 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
9089
9090 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
9091 AggregateDeductionCandidates;
9092
9093 bool IsStringInit(Expr *Init, const ArrayType *AT);
9094
9095 /// Determine whether we can perform aggregate initialization for the purposes
9096 /// of overload resolution.
9097 bool CanPerformAggregateInitializationForOverloadResolution(
9098 const InitializedEntity &Entity, InitListExpr *From);
9099
9100 ExprResult ActOnDesignatedInitializer(Designation &Desig,
9101 SourceLocation EqualOrColonLoc,
9102 bool GNUSyntax, ExprResult Init);
9103
9104 /// Check that the lifetime of the initializer (and its subobjects) is
9105 /// sufficient for initializing the entity, and perform lifetime extension
9106 /// (when permitted) if not.
9107 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
9108
9109 MaterializeTemporaryExpr *
9110 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
9111 bool BoundToLvalueReference);
9112
9113 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9114 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9115 /// we don't have xvalues there.
9116 ExprResult TemporaryMaterializationConversion(Expr *E);
9117
9118 ExprResult PerformQualificationConversion(
9119 Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
9120 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
9121
9122 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
9123 ExprResult Init);
9124 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
9125 SourceLocation EqualLoc, ExprResult Init,
9126 bool TopLevelOfInitList = false,
9127 bool AllowExplicit = false);
9128
9129 QualType DeduceTemplateSpecializationFromInitializer(
9130 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9131 const InitializationKind &Kind, MultiExprArg Init);
9132
9133 ///@}
9134
9135 //
9136 //
9137 // -------------------------------------------------------------------------
9138 //
9139 //
9140
9141 /// \name C++ Lambda Expressions
9142 /// Implementations are in SemaLambda.cpp
9143 ///@{
9144
9145public:
9146 /// Create a new lambda closure type.
9147 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
9148 TypeSourceInfo *Info,
9149 unsigned LambdaDependencyKind,
9150 LambdaCaptureDefault CaptureDefault);
9151
9152 /// Number lambda for linkage purposes if necessary.
9153 void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method,
9154 std::optional<CXXRecordDecl::LambdaNumbering>
9155 NumberingOverride = std::nullopt);
9156
9157 /// Endow the lambda scope info with the relevant properties.
9158 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9159 SourceRange IntroducerRange,
9160 LambdaCaptureDefault CaptureDefault,
9161 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9162 bool Mutable);
9163
9164 CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange,
9165 CXXRecordDecl *Class);
9166
9167 void AddTemplateParametersToLambdaCallOperator(
9168 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9169 TemplateParameterList *TemplateParams);
9170
9171 void
9172 CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc,
9173 SourceLocation CallOperatorLoc,
9174 const AssociatedConstraint &TrailingRequiresClause,
9175 TypeSourceInfo *MethodTyInfo,
9176 ConstexprSpecKind ConstexprKind, StorageClass SC,
9177 ArrayRef<ParmVarDecl *> Params,
9178 bool HasExplicitResultType);
9179
9180 /// Returns true if the explicit object parameter was invalid.
9181 bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method,
9182 SourceLocation CallLoc);
9183
9184 /// Perform initialization analysis of the init-capture and perform
9185 /// any implicit conversions such as an lvalue-to-rvalue conversion if
9186 /// not being used to initialize a reference.
9187 ParsedType actOnLambdaInitCaptureInitialization(
9188 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9189 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9190 return ParsedType::make(P: buildLambdaInitCaptureInitialization(
9191 Loc, ByRef, EllipsisLoc, NumExpansions: std::nullopt, Id,
9192 DirectInit: InitKind != LambdaCaptureInitKind::CopyInit, Init));
9193 }
9194 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
9195 SourceLocation EllipsisLoc,
9196 UnsignedOrNone NumExpansions,
9197 IdentifierInfo *Id,
9198 bool DirectInit, Expr *&Init);
9199
9200 /// Create a dummy variable within the declcontext of the lambda's
9201 /// call operator, for name lookup purposes for a lambda init capture.
9202 ///
9203 /// CodeGen handles emission of lambda captures, ignoring these dummy
9204 /// variables appropriately.
9205 VarDecl *createLambdaInitCaptureVarDecl(
9206 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9207 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9208
9209 /// Add an init-capture to a lambda scope.
9210 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9211
9212 /// Note that we have finished the explicit captures for the
9213 /// given lambda.
9214 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
9215
9216 /// Deduce a block or lambda's return type based on the return
9217 /// statements present in the body.
9218 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
9219
9220 /// Once the Lambdas capture are known, we can start to create the closure,
9221 /// call operator method, and keep track of the captures.
9222 /// We do the capture lookup here, but they are not actually captured until
9223 /// after we know what the qualifiers of the call operator are.
9224 void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
9225 Scope *CurContext);
9226
9227 /// This is called after parsing the explicit template parameter list
9228 /// on a lambda (if it exists) in C++2a.
9229 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
9230 SourceLocation LAngleLoc,
9231 ArrayRef<NamedDecl *> TParams,
9232 SourceLocation RAngleLoc,
9233 ExprResult RequiresClause);
9234
9235 void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
9236 SourceLocation MutableLoc);
9237
9238 void ActOnLambdaClosureParameters(
9239 Scope *LambdaScope,
9240 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo);
9241
9242 /// ActOnStartOfLambdaDefinition - This is called just before we start
9243 /// parsing the body of a lambda; it analyzes the explicit captures and
9244 /// arguments, and sets up various data-structures for the body of the
9245 /// lambda.
9246 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
9247 Declarator &ParamInfo, const DeclSpec &DS);
9248
9249 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9250 /// is invoked to pop the information about the lambda.
9251 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9252 bool IsInstantiation = false);
9253
9254 /// ActOnLambdaExpr - This is called when the body of a lambda expression
9255 /// was successfully completed.
9256 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body);
9257
9258 /// Does copying/destroying the captured variable have side effects?
9259 bool CaptureHasSideEffects(const sema::Capture &From);
9260
9261 /// Diagnose if an explicit lambda capture is unused. Returns true if a
9262 /// diagnostic is emitted.
9263 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9264 SourceRange FixItRange,
9265 const sema::Capture &From);
9266
9267 /// Build a FieldDecl suitable to hold the given capture.
9268 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
9269
9270 /// Initialize the given capture with a suitable expression.
9271 ExprResult BuildCaptureInit(const sema::Capture &Capture,
9272 SourceLocation ImplicitCaptureLoc,
9273 bool IsOpenMPMapping = false);
9274
9275 /// Complete a lambda-expression having processed and attached the
9276 /// lambda body.
9277 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc);
9278
9279 /// Get the return type to use for a lambda's conversion function(s) to
9280 /// function pointer type, given the type of the call operator.
9281 QualType
9282 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
9283 CallingConv CC);
9284
9285 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
9286 SourceLocation ConvLocation,
9287 CXXConversionDecl *Conv, Expr *Src);
9288
9289 class LambdaScopeForCallOperatorInstantiationRAII
9290 : private FunctionScopeRAII {
9291 public:
9292 LambdaScopeForCallOperatorInstantiationRAII(
9293 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9294 LocalInstantiationScope &Scope,
9295 bool ShouldAddDeclsFromParentScope = true);
9296 };
9297
9298 /// Compute the mangling number context for a lambda expression or
9299 /// block literal. Also return the extra mangling decl if any.
9300 ///
9301 /// \param DC - The DeclContext containing the lambda expression or
9302 /// block literal.
9303 std::tuple<MangleNumberingContext *, Decl *>
9304 getCurrentMangleNumberContext(const DeclContext *DC);
9305
9306 ///@}
9307
9308 //
9309 //
9310 // -------------------------------------------------------------------------
9311 //
9312 //
9313
9314 /// \name Name Lookup
9315 ///
9316 /// These routines provide name lookup that is used during semantic
9317 /// analysis to resolve the various kinds of names (identifiers,
9318 /// overloaded operator names, constructor names, etc.) into zero or
9319 /// more declarations within a particular scope. The major entry
9320 /// points are LookupName, which performs unqualified name lookup,
9321 /// and LookupQualifiedName, which performs qualified name lookup.
9322 ///
9323 /// All name lookup is performed based on some specific criteria,
9324 /// which specify what names will be visible to name lookup and how
9325 /// far name lookup should work. These criteria are important both
9326 /// for capturing language semantics (certain lookups will ignore
9327 /// certain names, for example) and for performance, since name
9328 /// lookup is often a bottleneck in the compilation of C++. Name
9329 /// lookup criteria is specified via the LookupCriteria enumeration.
9330 ///
9331 /// The results of name lookup can vary based on the kind of name
9332 /// lookup performed, the current language, and the translation
9333 /// unit. In C, for example, name lookup will either return nothing
9334 /// (no entity found) or a single declaration. In C++, name lookup
9335 /// can additionally refer to a set of overloaded functions or
9336 /// result in an ambiguity. All of the possible results of name
9337 /// lookup are captured by the LookupResult class, which provides
9338 /// the ability to distinguish among them.
9339 ///
9340 /// Implementations are in SemaLookup.cpp
9341 ///@{
9342
9343public:
9344 /// Tracks whether we are in a context where typo correction is
9345 /// disabled.
9346 bool DisableTypoCorrection;
9347
9348 /// The number of typos corrected by CorrectTypo.
9349 unsigned TyposCorrected;
9350
9351 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9352 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9353
9354 /// A cache containing identifiers for which typo correction failed and
9355 /// their locations, so that repeated attempts to correct an identifier in a
9356 /// given location are ignored if typo correction already failed for it.
9357 IdentifierSourceLocations TypoCorrectionFailures;
9358
9359 /// SpecialMemberOverloadResult - The overloading result for a special member
9360 /// function.
9361 ///
9362 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9363 /// integer are used to determine whether overload resolution succeeded.
9364 class SpecialMemberOverloadResult {
9365 public:
9366 enum Kind { NoMemberOrDeleted, Ambiguous, Success };
9367
9368 private:
9369 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9370
9371 public:
9372 SpecialMemberOverloadResult() {}
9373 SpecialMemberOverloadResult(CXXMethodDecl *MD)
9374 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9375
9376 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
9377 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9378
9379 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
9380 void setKind(Kind K) { Pair.setInt(K); }
9381 };
9382
9383 class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode,
9384 public SpecialMemberOverloadResult {
9385 public:
9386 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
9387 : FastFoldingSetNode(ID) {}
9388 };
9389
9390 /// A cache of special member function overload resolution results
9391 /// for C++ records.
9392 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
9393
9394 enum class AcceptableKind { Visible, Reachable };
9395
9396 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9397 // TODO: make this is a typesafe union.
9398 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
9399 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
9400
9401 /// Describes the kind of name lookup to perform.
9402 enum LookupNameKind {
9403 /// Ordinary name lookup, which finds ordinary names (functions,
9404 /// variables, typedefs, etc.) in C and most kinds of names
9405 /// (functions, variables, members, types, etc.) in C++.
9406 LookupOrdinaryName = 0,
9407 /// Tag name lookup, which finds the names of enums, classes,
9408 /// structs, and unions.
9409 LookupTagName,
9410 /// Label name lookup.
9411 LookupLabel,
9412 /// Member name lookup, which finds the names of
9413 /// class/struct/union members.
9414 LookupMemberName,
9415 /// Look up of an operator name (e.g., operator+) for use with
9416 /// operator overloading. This lookup is similar to ordinary name
9417 /// lookup, but will ignore any declarations that are class members.
9418 LookupOperatorName,
9419 /// Look up a name following ~ in a destructor name. This is an ordinary
9420 /// lookup, but prefers tags to typedefs.
9421 LookupDestructorName,
9422 /// Look up of a name that precedes the '::' scope resolution
9423 /// operator in C++. This lookup completely ignores operator, object,
9424 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9425 LookupNestedNameSpecifierName,
9426 /// Look up a namespace name within a C++ using directive or
9427 /// namespace alias definition, ignoring non-namespace names (C++
9428 /// [basic.lookup.udir]p1).
9429 LookupNamespaceName,
9430 /// Look up all declarations in a scope with the given name,
9431 /// including resolved using declarations. This is appropriate
9432 /// for checking redeclarations for a using declaration.
9433 LookupUsingDeclName,
9434 /// Look up an ordinary name that is going to be redeclared as a
9435 /// name with linkage. This lookup ignores any declarations that
9436 /// are outside of the current scope unless they have linkage. See
9437 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9438 LookupRedeclarationWithLinkage,
9439 /// Look up a friend of a local class. This lookup does not look
9440 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9441 LookupLocalFriendName,
9442 /// Look up the name of an Objective-C protocol.
9443 LookupObjCProtocolName,
9444 /// Look up implicit 'self' parameter of an objective-c method.
9445 LookupObjCImplicitSelfParam,
9446 /// Look up the name of an OpenMP user-defined reduction operation.
9447 LookupOMPReductionName,
9448 /// Look up the name of an OpenMP user-defined mapper.
9449 LookupOMPMapperName,
9450 /// Look up any declaration with any name.
9451 LookupAnyName
9452 };
9453
9454 /// The possible outcomes of name lookup for a literal operator.
9455 enum LiteralOperatorLookupResult {
9456 /// The lookup resulted in an error.
9457 LOLR_Error,
9458 /// The lookup found no match but no diagnostic was issued.
9459 LOLR_ErrorNoDiagnostic,
9460 /// The lookup found a single 'cooked' literal operator, which
9461 /// expects a normal literal to be built and passed to it.
9462 LOLR_Cooked,
9463 /// The lookup found a single 'raw' literal operator, which expects
9464 /// a string literal containing the spelling of the literal token.
9465 LOLR_Raw,
9466 /// The lookup found an overload set of literal operator templates,
9467 /// which expect the characters of the spelling of the literal token to be
9468 /// passed as a non-type template argument pack.
9469 LOLR_Template,
9470 /// The lookup found an overload set of literal operator templates,
9471 /// which expect the character type and characters of the spelling of the
9472 /// string literal token to be passed as template arguments.
9473 LOLR_StringTemplatePack,
9474 };
9475
9476 SpecialMemberOverloadResult
9477 LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg,
9478 bool VolatileArg, bool RValueThis, bool ConstThis,
9479 bool VolatileThis);
9480
9481 RedeclarationKind forRedeclarationInCurContext() const;
9482
9483 /// Look up a name, looking for a single declaration. Return
9484 /// null if the results were absent, ambiguous, or overloaded.
9485 ///
9486 /// It is preferable to use the elaborated form and explicitly handle
9487 /// ambiguity and overloaded.
9488 NamedDecl *LookupSingleName(
9489 Scope *S, DeclarationName Name, SourceLocation Loc,
9490 LookupNameKind NameKind,
9491 RedeclarationKind Redecl = RedeclarationKind::NotForRedeclaration);
9492
9493 /// Lookup a builtin function, when name lookup would otherwise
9494 /// fail.
9495 bool LookupBuiltin(LookupResult &R);
9496 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9497
9498 /// Perform unqualified name lookup starting from a given
9499 /// scope.
9500 ///
9501 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9502 /// used to find names within the current scope. For example, 'x' in
9503 /// @code
9504 /// int x;
9505 /// int f() {
9506 /// return x; // unqualified name look finds 'x' in the global scope
9507 /// }
9508 /// @endcode
9509 ///
9510 /// Different lookup criteria can find different names. For example, a
9511 /// particular scope can have both a struct and a function of the same
9512 /// name, and each can be found by certain lookup criteria. For more
9513 /// information about lookup criteria, see the documentation for the
9514 /// class LookupCriteria.
9515 ///
9516 /// @param S The scope from which unqualified name lookup will
9517 /// begin. If the lookup criteria permits, name lookup may also search
9518 /// in the parent scopes.
9519 ///
9520 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9521 /// look up and the lookup kind), and is updated with the results of lookup
9522 /// including zero or more declarations and possibly additional information
9523 /// used to diagnose ambiguities.
9524 ///
9525 /// @returns \c true if lookup succeeded and false otherwise.
9526 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9527 bool ForceNoCPlusPlus = false);
9528
9529 /// Perform qualified name lookup into a given context.
9530 ///
9531 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9532 /// names when the context of those names is explicit specified, e.g.,
9533 /// "std::vector" or "x->member", or as part of unqualified name lookup.
9534 ///
9535 /// Different lookup criteria can find different names. For example, a
9536 /// particular scope can have both a struct and a function of the same
9537 /// name, and each can be found by certain lookup criteria. For more
9538 /// information about lookup criteria, see the documentation for the
9539 /// class LookupCriteria.
9540 ///
9541 /// \param R captures both the lookup criteria and any lookup results found.
9542 ///
9543 /// \param LookupCtx The context in which qualified name lookup will
9544 /// search. If the lookup criteria permits, name lookup may also search
9545 /// in the parent contexts or (for C++ classes) base classes.
9546 ///
9547 /// \param InUnqualifiedLookup true if this is qualified name lookup that
9548 /// occurs as part of unqualified name lookup.
9549 ///
9550 /// \returns true if lookup succeeded, false if it failed.
9551 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9552 bool InUnqualifiedLookup = false);
9553
9554 /// Performs qualified name lookup or special type of lookup for
9555 /// "__super::" scope specifier.
9556 ///
9557 /// This routine is a convenience overload meant to be called from contexts
9558 /// that need to perform a qualified name lookup with an optional C++ scope
9559 /// specifier that might require special kind of lookup.
9560 ///
9561 /// \param R captures both the lookup criteria and any lookup results found.
9562 ///
9563 /// \param LookupCtx The context in which qualified name lookup will
9564 /// search.
9565 ///
9566 /// \param SS An optional C++ scope-specifier.
9567 ///
9568 /// \returns true if lookup succeeded, false if it failed.
9569 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9570 CXXScopeSpec &SS);
9571
9572 /// Performs name lookup for a name that was parsed in the
9573 /// source code, and may contain a C++ scope specifier.
9574 ///
9575 /// This routine is a convenience routine meant to be called from
9576 /// contexts that receive a name and an optional C++ scope specifier
9577 /// (e.g., "N::M::x"). It will then perform either qualified or
9578 /// unqualified name lookup (with LookupQualifiedName or LookupName,
9579 /// respectively) on the given name and return those results. It will
9580 /// perform a special type of lookup for "__super::" scope specifier.
9581 ///
9582 /// @param S The scope from which unqualified name lookup will
9583 /// begin.
9584 ///
9585 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
9586 ///
9587 /// @param EnteringContext Indicates whether we are going to enter the
9588 /// context of the scope-specifier SS (if present).
9589 ///
9590 /// @returns True if any decls were found (but possibly ambiguous)
9591 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
9592 QualType ObjectType, bool AllowBuiltinCreation = false,
9593 bool EnteringContext = false);
9594
9595 /// Perform qualified name lookup into all base classes of the given
9596 /// class.
9597 ///
9598 /// \param R captures both the lookup criteria and any lookup results found.
9599 ///
9600 /// \param Class The context in which qualified name lookup will
9601 /// search. Name lookup will search in all base classes merging the results.
9602 ///
9603 /// @returns True if any decls were found (but possibly ambiguous)
9604 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
9605
9606 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
9607 UnresolvedSetImpl &Functions);
9608
9609 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9610 /// If GnuLabelLoc is a valid source location, then this is a definition
9611 /// of an __label__ label name, otherwise it is a normal label definition
9612 /// or use.
9613 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
9614 SourceLocation GnuLabelLoc = SourceLocation());
9615
9616 /// Perform a name lookup for a label with the specified name; this does not
9617 /// create a new label if the lookup fails.
9618 LabelDecl *LookupExistingLabel(IdentifierInfo *II, SourceLocation IdentLoc);
9619
9620 /// Look up the constructors for the given class.
9621 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
9622
9623 /// Look up the default constructor for the given class.
9624 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
9625
9626 /// Look up the copying constructor for the given class.
9627 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
9628 unsigned Quals);
9629
9630 /// Look up the copying assignment operator for the given class.
9631 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
9632 bool RValueThis, unsigned ThisQuals);
9633
9634 /// Look up the moving constructor for the given class.
9635 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
9636 unsigned Quals);
9637
9638 /// Look up the moving assignment operator for the given class.
9639 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
9640 bool RValueThis, unsigned ThisQuals);
9641
9642 /// Look for the destructor of the given class.
9643 ///
9644 /// During semantic analysis, this routine should be used in lieu of
9645 /// CXXRecordDecl::getDestructor().
9646 ///
9647 /// \returns The destructor for this class.
9648 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
9649
9650 /// Force the declaration of any implicitly-declared members of this
9651 /// class.
9652 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
9653
9654 /// Make a merged definition of an existing hidden definition \p ND
9655 /// visible at the specified location.
9656 void makeMergedDefinitionVisible(NamedDecl *ND);
9657
9658 /// Check ODR hashes for C/ObjC when merging types from modules.
9659 /// Differently from C++, actually parse the body and reject in case
9660 /// of a mismatch.
9661 template <typename T,
9662 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
9663 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
9664 if (Duplicate->getODRHash() != Previous->getODRHash())
9665 return false;
9666
9667 // Make the previous decl visible.
9668 makeMergedDefinitionVisible(ND: Previous);
9669 return true;
9670 }
9671
9672 /// Get the set of additional modules that should be checked during
9673 /// name lookup. A module and its imports become visible when instanting a
9674 /// template defined within it.
9675 llvm::DenseSet<Module *> &getLookupModules();
9676
9677 bool hasVisibleMergedDefinition(const NamedDecl *Def);
9678 bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
9679
9680 /// Determine if the template parameter \p D has a visible default argument.
9681 bool
9682 hasVisibleDefaultArgument(const NamedDecl *D,
9683 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9684 /// Determine if the template parameter \p D has a reachable default argument.
9685 bool hasReachableDefaultArgument(
9686 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9687 /// Determine if the template parameter \p D has a reachable default argument.
9688 bool hasAcceptableDefaultArgument(const NamedDecl *D,
9689 llvm::SmallVectorImpl<Module *> *Modules,
9690 Sema::AcceptableKind Kind);
9691
9692 /// Determine if there is a visible declaration of \p D that is an explicit
9693 /// specialization declaration for a specialization of a template. (For a
9694 /// member specialization, use hasVisibleMemberSpecialization.)
9695 bool hasVisibleExplicitSpecialization(
9696 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9697 /// Determine if there is a reachable declaration of \p D that is an explicit
9698 /// specialization declaration for a specialization of a template. (For a
9699 /// member specialization, use hasReachableMemberSpecialization.)
9700 bool hasReachableExplicitSpecialization(
9701 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9702
9703 /// Determine if there is a visible declaration of \p D that is a member
9704 /// specialization declaration (as opposed to an instantiated declaration).
9705 bool hasVisibleMemberSpecialization(
9706 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9707 /// Determine if there is a reachable declaration of \p D that is a member
9708 /// specialization declaration (as opposed to an instantiated declaration).
9709 bool hasReachableMemberSpecialization(
9710 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9711
9712 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9713
9714 /// Determine whether any declaration of an entity is visible.
9715 bool
9716 hasVisibleDeclaration(const NamedDecl *D,
9717 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9718 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9719 }
9720
9721 bool hasVisibleDeclarationSlow(const NamedDecl *D,
9722 llvm::SmallVectorImpl<Module *> *Modules);
9723 /// Determine whether any declaration of an entity is reachable.
9724 bool
9725 hasReachableDeclaration(const NamedDecl *D,
9726 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9727 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9728 }
9729 bool hasReachableDeclarationSlow(
9730 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9731
9732 void diagnoseTypo(const TypoCorrection &Correction,
9733 const PartialDiagnostic &TypoDiag,
9734 bool ErrorRecovery = true);
9735
9736 /// Diagnose a successfully-corrected typo. Separated from the correction
9737 /// itself to allow external validation of the result, etc.
9738 ///
9739 /// \param Correction The result of performing typo correction.
9740 /// \param TypoDiag The diagnostic to produce. This will have the corrected
9741 /// string added to it (and usually also a fixit).
9742 /// \param PrevNote A note to use when indicating the location of the entity
9743 /// to which we are correcting. Will have the correction string added
9744 /// to it.
9745 /// \param ErrorRecovery If \c true (the default), the caller is going to
9746 /// recover from the typo as if the corrected string had been typed.
9747 /// In this case, \c PDiag must be an error, and we will attach a fixit
9748 /// to it.
9749 void diagnoseTypo(const TypoCorrection &Correction,
9750 const PartialDiagnostic &TypoDiag,
9751 const PartialDiagnostic &PrevNote,
9752 bool ErrorRecovery = true);
9753
9754 /// Find the associated classes and namespaces for
9755 /// argument-dependent lookup for a call with the given set of
9756 /// arguments.
9757 ///
9758 /// This routine computes the sets of associated classes and associated
9759 /// namespaces searched by argument-dependent lookup
9760 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9761 void FindAssociatedClassesAndNamespaces(
9762 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9763 AssociatedNamespaceSet &AssociatedNamespaces,
9764 AssociatedClassSet &AssociatedClasses);
9765
9766 /// Produce a diagnostic describing the ambiguity that resulted
9767 /// from name lookup.
9768 ///
9769 /// \param Result The result of the ambiguous lookup to be diagnosed.
9770 void DiagnoseAmbiguousLookup(LookupResult &Result);
9771
9772 /// LookupLiteralOperator - Determine which literal operator should be used
9773 /// for a user-defined literal, per C++11 [lex.ext].
9774 ///
9775 /// Normal overload resolution is not used to select which literal operator to
9776 /// call for a user-defined literal. Look up the provided literal operator
9777 /// name, and filter the results to the appropriate set for the given argument
9778 /// types.
9779 LiteralOperatorLookupResult
9780 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
9781 bool AllowRaw, bool AllowTemplate,
9782 bool AllowStringTemplate, bool DiagnoseMissing,
9783 StringLiteral *StringLit = nullptr);
9784
9785 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
9786 ArrayRef<Expr *> Args, ADLResult &Functions);
9787
9788 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9789 VisibleDeclConsumer &Consumer,
9790 bool IncludeGlobalScope = true,
9791 bool LoadExternal = true);
9792 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9793 VisibleDeclConsumer &Consumer,
9794 bool IncludeGlobalScope = true,
9795 bool IncludeDependentBases = false,
9796 bool LoadExternal = true);
9797
9798 /// Try to "correct" a typo in the source code by finding
9799 /// visible declarations whose names are similar to the name that was
9800 /// present in the source code.
9801 ///
9802 /// \param TypoName the \c DeclarationNameInfo structure that contains
9803 /// the name that was present in the source code along with its location.
9804 ///
9805 /// \param LookupKind the name-lookup criteria used to search for the name.
9806 ///
9807 /// \param S the scope in which name lookup occurs.
9808 ///
9809 /// \param SS the nested-name-specifier that precedes the name we're
9810 /// looking for, if present.
9811 ///
9812 /// \param CCC A CorrectionCandidateCallback object that provides further
9813 /// validation of typo correction candidates. It also provides flags for
9814 /// determining the set of keywords permitted.
9815 ///
9816 /// \param MemberContext if non-NULL, the context in which to look for
9817 /// a member access expression.
9818 ///
9819 /// \param EnteringContext whether we're entering the context described by
9820 /// the nested-name-specifier SS.
9821 ///
9822 /// \param OPT when non-NULL, the search for visible declarations will
9823 /// also walk the protocols in the qualified interfaces of \p OPT.
9824 ///
9825 /// \returns a \c TypoCorrection containing the corrected name if the typo
9826 /// along with information such as the \c NamedDecl where the corrected name
9827 /// was declared, and any additional \c NestedNameSpecifier needed to access
9828 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9829 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
9830 Sema::LookupNameKind LookupKind, Scope *S,
9831 CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9832 CorrectTypoKind Mode,
9833 DeclContext *MemberContext = nullptr,
9834 bool EnteringContext = false,
9835 const ObjCObjectPointerType *OPT = nullptr,
9836 bool RecordFailure = true);
9837
9838 /// Kinds of missing import. Note, the values of these enumerators correspond
9839 /// to %select values in diagnostics.
9840 enum class MissingImportKind {
9841 Declaration,
9842 Definition,
9843 DefaultArgument,
9844 ExplicitSpecialization,
9845 PartialSpecialization
9846 };
9847
9848 /// Diagnose that the specified declaration needs to be visible but
9849 /// isn't, and suggest a module import that would resolve the problem.
9850 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9851 MissingImportKind MIK, bool Recover = true);
9852 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9853 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
9854 MissingImportKind MIK, bool Recover);
9855
9856 /// Called on #pragma clang __debug dump II
9857 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9858
9859 /// Called on #pragma clang __debug dump E
9860 void ActOnPragmaDump(Expr *E);
9861
9862private:
9863 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
9864 //
9865 // The boolean value will be true to indicate that the namespace was loaded
9866 // from an AST/PCH file, or false otherwise.
9867 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
9868
9869 /// Whether we have already loaded known namespaces from an extenal
9870 /// source.
9871 bool LoadedExternalKnownNamespaces;
9872
9873 bool CppLookupName(LookupResult &R, Scope *S);
9874
9875 /// Determine if we could use all the declarations in the module.
9876 bool isUsableModule(const Module *M);
9877
9878 /// Helper for CorrectTypo used to create and populate a new
9879 /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
9880 /// skipped entirely.
9881 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
9882 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
9883 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9884 DeclContext *MemberContext, bool EnteringContext,
9885 const ObjCObjectPointerType *OPT, bool ErrorRecovery);
9886
9887 /// Cache for module units which is usable for current module.
9888 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
9889
9890 /// Record the typo correction failure and return an empty correction.
9891 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
9892 bool RecordFailure = true) {
9893 if (RecordFailure)
9894 TypoCorrectionFailures[Typo].insert(V: TypoLoc);
9895 return TypoCorrection();
9896 }
9897
9898 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
9899
9900 /// Determine whether two declarations should be linked together, given that
9901 /// the old declaration might not be visible and the new declaration might
9902 /// not have external linkage.
9903 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
9904 const NamedDecl *New) {
9905 if (isVisible(D: Old))
9906 return true;
9907 // See comment in below overload for why it's safe to compute the linkage
9908 // of the new declaration here.
9909 if (New->isExternallyDeclarable()) {
9910 assert(Old->isExternallyDeclarable() &&
9911 "should not have found a non-externally-declarable previous decl");
9912 return true;
9913 }
9914 return false;
9915 }
9916 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
9917
9918 ///@}
9919
9920 //
9921 //
9922 // -------------------------------------------------------------------------
9923 //
9924 //
9925
9926 /// \name Modules
9927 /// Implementations are in SemaModule.cpp
9928 ///@{
9929
9930public:
9931 /// Get the module unit whose scope we are currently within.
9932 Module *getCurrentModule() const {
9933 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
9934 }
9935
9936 /// Is the module scope we are an implementation unit?
9937 bool currentModuleIsImplementation() const {
9938 if (ModuleScopes.empty())
9939 return false;
9940 const Module *M = ModuleScopes.back().Module;
9941 return M->isModuleImplementation() || M->isModulePartitionImplementation();
9942 }
9943
9944 // When loading a non-modular PCH files, this is used to restore module
9945 // visibility.
9946 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
9947 VisibleModules.setVisible(M: Mod, Loc: ImportLoc);
9948 }
9949
9950 enum class ModuleDeclKind {
9951 Interface, ///< 'export module X;'
9952 Implementation, ///< 'module X;'
9953 PartitionInterface, ///< 'export module X:Y;'
9954 PartitionImplementation, ///< 'module X:Y;'
9955 };
9956
9957 /// An enumeration to represent the transition of states in parsing module
9958 /// fragments and imports. If we are not parsing a C++20 TU, or we find
9959 /// an error in state transition, the state is set to NotACXX20Module.
9960 enum class ModuleImportState {
9961 FirstDecl, ///< Parsing the first decl in a TU.
9962 GlobalFragment, ///< after 'module;' but before 'module X;'
9963 ImportAllowed, ///< after 'module X;' but before any non-import decl.
9964 ImportFinished, ///< after any non-import decl.
9965 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
9966 ///< non-import decl.
9967 PrivateFragmentImportFinished, ///< after 'module :private;' but a
9968 ///< non-import decl has already been seen.
9969 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
9970 };
9971
9972 /// The parser has processed a module-declaration that begins the definition
9973 /// of a module interface or implementation.
9974 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
9975 SourceLocation ModuleLoc, ModuleDeclKind MDK,
9976 ModuleIdPath Path, ModuleIdPath Partition,
9977 ModuleImportState &ImportState,
9978 bool SeenNoTrivialPPDirective);
9979
9980 /// The parser has processed a global-module-fragment declaration that begins
9981 /// the definition of the global module fragment of the current module unit.
9982 /// \param ModuleLoc The location of the 'module' keyword.
9983 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
9984
9985 /// The parser has processed a private-module-fragment declaration that begins
9986 /// the definition of the private module fragment of the current module unit.
9987 /// \param ModuleLoc The location of the 'module' keyword.
9988 /// \param PrivateLoc The location of the 'private' keyword.
9989 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
9990 SourceLocation PrivateLoc);
9991
9992 /// The parser has processed a module import declaration.
9993 ///
9994 /// \param StartLoc The location of the first token in the declaration. This
9995 /// could be the location of an '@', 'export', or 'import'.
9996 /// \param ExportLoc The location of the 'export' keyword, if any.
9997 /// \param ImportLoc The location of the 'import' keyword.
9998 /// \param Path The module toplevel name as an access path.
9999 /// \param IsPartition If the name is for a partition.
10000 DeclResult ActOnModuleImport(SourceLocation StartLoc,
10001 SourceLocation ExportLoc,
10002 SourceLocation ImportLoc, ModuleIdPath Path,
10003 bool IsPartition = false);
10004 DeclResult ActOnModuleImport(SourceLocation StartLoc,
10005 SourceLocation ExportLoc,
10006 SourceLocation ImportLoc, Module *M,
10007 ModuleIdPath Path = {});
10008
10009 /// The parser has processed a module import translated from a
10010 /// #include or similar preprocessing directive.
10011 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10012 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10013
10014 /// The parsed has entered a submodule.
10015 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
10016 /// The parser has left a submodule.
10017 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
10018
10019 /// Create an implicit import of the given module at the given
10020 /// source location, for error recovery, if possible.
10021 ///
10022 /// This routine is typically used when an entity found by name lookup
10023 /// is actually hidden within a module that we know about but the user
10024 /// has forgotten to import.
10025 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
10026 Module *Mod);
10027
10028 /// We have parsed the start of an export declaration, including the '{'
10029 /// (if present).
10030 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
10031 SourceLocation LBraceLoc);
10032
10033 /// Complete the definition of an export declaration.
10034 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
10035 SourceLocation RBraceLoc);
10036
10037private:
10038 /// The parser has begun a translation unit to be compiled as a C++20
10039 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
10040 void HandleStartOfHeaderUnit();
10041
10042 struct ModuleScope {
10043 SourceLocation BeginLoc;
10044 clang::Module *Module = nullptr;
10045 VisibleModuleSet OuterVisibleModules;
10046 };
10047 /// The modules we're currently parsing.
10048 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
10049
10050 /// For an interface unit, this is the implicitly imported interface unit.
10051 clang::Module *ThePrimaryInterface = nullptr;
10052
10053 /// The explicit global module fragment of the current translation unit.
10054 /// The explicit Global Module Fragment, as specified in C++
10055 /// [module.global.frag].
10056 clang::Module *TheGlobalModuleFragment = nullptr;
10057
10058 /// The implicit global module fragments of the current translation unit.
10059 ///
10060 /// The contents in the implicit global module fragment can't be discarded.
10061 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
10062
10063 /// Namespace definitions that we will export when they finish.
10064 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
10065
10066 /// In a C++ standard module, inline declarations require a definition to be
10067 /// present at the end of a definition domain. This set holds the decls to
10068 /// be checked at the end of the TU.
10069 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
10070
10071 /// Helper function to judge if we are in module purview.
10072 /// Return false if we are not in a module.
10073 bool isCurrentModulePurview() const;
10074
10075 /// Enter the scope of the explicit global module fragment.
10076 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
10077 /// Leave the scope of the explicit global module fragment.
10078 void PopGlobalModuleFragment();
10079
10080 /// Enter the scope of an implicit global module fragment.
10081 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
10082 /// Leave the scope of an implicit global module fragment.
10083 void PopImplicitGlobalModuleFragment();
10084
10085 VisibleModuleSet VisibleModules;
10086
10087 /// Whether we had imported any named modules.
10088 bool HadImportedNamedModules = false;
10089 /// The set of instantiations we need to check if they references TU-local
10090 /// entity from TUs. This only makes sense if we imported any named modules.
10091 llvm::SmallVector<std::pair<FunctionDecl *, SourceLocation>>
10092 PendingCheckReferenceForTULocal;
10093 /// Implement [basic.link]p18, which requires that we can't use TU-local
10094 /// entities from other TUs (ignoring header units).
10095 void checkReferenceToTULocalFromOtherTU(FunctionDecl *FD,
10096 SourceLocation PointOfInstantiation);
10097 /// Implement [basic.link]p17, which diagnose for non TU local exposure in
10098 /// module interface or module partition.
10099 void checkExposure(const TranslationUnitDecl *TU);
10100
10101 ///@}
10102
10103 //
10104 //
10105 // -------------------------------------------------------------------------
10106 //
10107 //
10108
10109 /// \name C++ Overloading
10110 /// Implementations are in SemaOverload.cpp
10111 ///@{
10112
10113public:
10114 /// Whether deferrable diagnostics should be deferred.
10115 bool DeferDiags = false;
10116
10117 /// RAII class to control scope of DeferDiags.
10118 class DeferDiagsRAII {
10119 Sema &S;
10120 bool SavedDeferDiags = false;
10121
10122 public:
10123 DeferDiagsRAII(Sema &S, bool DeferDiags)
10124 : S(S), SavedDeferDiags(S.DeferDiags) {
10125 S.DeferDiags = SavedDeferDiags || DeferDiags;
10126 }
10127 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
10128 DeferDiagsRAII(const DeferDiagsRAII &) = delete;
10129 DeferDiagsRAII &operator=(const DeferDiagsRAII &) = delete;
10130 };
10131
10132 /// Flag indicating if Sema is building a recovery call expression.
10133 ///
10134 /// This flag is used to avoid building recovery call expressions
10135 /// if Sema is already doing so, which would cause infinite recursions.
10136 bool IsBuildingRecoveryCallExpr;
10137
10138 /// Determine whether the given New declaration is an overload of the
10139 /// declarations in Old. This routine returns OverloadKind::Match or
10140 /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
10141 /// New has the same signature as some function in Old (C++ 1.3.10) or if the
10142 /// Old declarations aren't functions (or function templates) at all. When it
10143 /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
10144 /// will point to the decl that New cannot be overloaded with. This decl may
10145 /// be a UsingShadowDecl on top of the underlying declaration.
10146 ///
10147 /// Example: Given the following input:
10148 ///
10149 /// void f(int, float); // #1
10150 /// void f(int, int); // #2
10151 /// int f(int, int); // #3
10152 ///
10153 /// When we process #1, there is no previous declaration of "f", so IsOverload
10154 /// will not be used.
10155 ///
10156 /// When we process #2, Old contains only the FunctionDecl for #1. By
10157 /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10158 /// they have different signatures), so this routine returns
10159 /// OverloadKind::Overload; MatchedDecl is unchanged.
10160 ///
10161 /// When we process #3, Old is an overload set containing #1 and #2. We
10162 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10163 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10164 /// types of functions are not part of the signature), IsOverload returns
10165 /// OverloadKind::Match and MatchedDecl will be set to point to the
10166 /// FunctionDecl for #2.
10167 ///
10168 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10169 /// class by a using declaration. The rules for whether to hide shadow
10170 /// declarations ignore some properties which otherwise figure into a function
10171 /// template's signature.
10172 OverloadKind CheckOverload(Scope *S, FunctionDecl *New,
10173 const LookupResult &OldDecls, NamedDecl *&OldDecl,
10174 bool UseMemberUsingDeclRules);
10175 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
10176 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10177
10178 // Checks whether MD constitutes an override the base class method BaseMD.
10179 // When checking for overrides, the object object members are ignored.
10180 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10181 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10182
10183 enum class AllowedExplicit {
10184 /// Allow no explicit functions to be used.
10185 None,
10186 /// Allow explicit conversion functions but not explicit constructors.
10187 Conversions,
10188 /// Allow both explicit conversion functions and explicit constructors.
10189 All
10190 };
10191
10192 ImplicitConversionSequence TryImplicitConversion(
10193 Expr *From, QualType ToType, bool SuppressUserConversions,
10194 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10195 bool AllowObjCWritebackConversion);
10196
10197 /// PerformImplicitConversion - Perform an implicit conversion of the
10198 /// expression From to the type ToType. Returns the
10199 /// converted expression. Flavor is the kind of conversion we're
10200 /// performing, used in the error message. If @p AllowExplicit,
10201 /// explicit user-defined conversions are permitted.
10202 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10203 AssignmentAction Action,
10204 bool AllowExplicit = false);
10205
10206 /// IsIntegralPromotion - Determines whether the conversion from the
10207 /// expression From (whose potentially-adjusted type is FromType) to
10208 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10209 /// sets PromotedType to the promoted type.
10210 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10211
10212 /// IsFloatingPointPromotion - Determines whether the conversion from
10213 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10214 /// returns true and sets PromotedType to the promoted type.
10215 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10216
10217 /// Determine if a conversion is a complex promotion.
10218 ///
10219 /// A complex promotion is defined as a complex -> complex conversion
10220 /// where the conversion between the underlying real types is a
10221 /// floating-point or integral promotion.
10222 bool IsComplexPromotion(QualType FromType, QualType ToType);
10223
10224 /// IsOverflowBehaviorTypePromotion - Determines whether the conversion from
10225 /// FromType to ToType involves an OverflowBehaviorType FromType being
10226 /// promoted to an OverflowBehaviorType ToType which has a larger bitwidth.
10227 /// If so, returns true and sets FromType to ToType.
10228 bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType);
10229
10230 /// IsOverflowBehaviorTypeConversion - Determines whether the conversion from
10231 /// FromType to ToType necessarily involves both an OverflowBehaviorType and
10232 /// a non-OverflowBehaviorType. If so, returns true and sets FromType to
10233 /// ToType.
10234 bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType);
10235
10236 /// IsPointerConversion - Determines whether the conversion of the
10237 /// expression From, which has the (possibly adjusted) type FromType,
10238 /// can be converted to the type ToType via a pointer conversion (C++
10239 /// 4.10). If so, returns true and places the converted type (that
10240 /// might differ from ToType in its cv-qualifiers at some level) into
10241 /// ConvertedType.
10242 ///
10243 /// This routine also supports conversions to and from block pointers
10244 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10245 /// pointers to interfaces. FIXME: Once we've determined the
10246 /// appropriate overloading rules for Objective-C, we may want to
10247 /// split the Objective-C checks into a different routine; however,
10248 /// GCC seems to consider all of these conversions to be pointer
10249 /// conversions, so for now they live here. IncompatibleObjC will be
10250 /// set if the conversion is an allowed Objective-C conversion that
10251 /// should result in a warning.
10252 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10253 bool InOverloadResolution, QualType &ConvertedType,
10254 bool &IncompatibleObjC);
10255
10256 /// isObjCPointerConversion - Determines whether this is an
10257 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10258 /// with the same arguments and return values.
10259 bool isObjCPointerConversion(QualType FromType, QualType ToType,
10260 QualType &ConvertedType, bool &IncompatibleObjC);
10261 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10262 QualType &ConvertedType);
10263
10264 /// FunctionParamTypesAreEqual - This routine checks two function proto types
10265 /// for equality of their parameter types. Caller has already checked that
10266 /// they have same number of parameters. If the parameters are different,
10267 /// ArgPos will have the parameter index of the first different parameter.
10268 /// If `Reversed` is true, the parameters of `NewType` will be compared in
10269 /// reverse order. That's useful if one of the functions is being used as a
10270 /// C++20 synthesized operator overload with a reversed parameter order.
10271 bool FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
10272 ArrayRef<QualType> New,
10273 unsigned *ArgPos = nullptr,
10274 bool Reversed = false);
10275
10276 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
10277 const FunctionProtoType *NewType,
10278 unsigned *ArgPos = nullptr,
10279 bool Reversed = false);
10280
10281 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10282 const FunctionDecl *NewFunction,
10283 unsigned *ArgPos = nullptr,
10284 bool Reversed = false);
10285
10286 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10287 /// function types. Catches different number of parameter, mismatch in
10288 /// parameter types, and different return types.
10289 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType,
10290 QualType ToType);
10291
10292 /// CheckPointerConversion - Check the pointer conversion from the
10293 /// expression From to the type ToType. This routine checks for
10294 /// ambiguous or inaccessible derived-to-base pointer
10295 /// conversions for which IsPointerConversion has already returned
10296 /// true. It returns true and produces a diagnostic if there was an
10297 /// error, or returns false otherwise.
10298 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10299 CXXCastPath &BasePath, bool IgnoreBaseAccess,
10300 bool Diagnose = true);
10301
10302 /// IsMemberPointerConversion - Determines whether the conversion of the
10303 /// expression From, which has the (possibly adjusted) type FromType, can be
10304 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10305 /// If so, returns true and places the converted type (that might differ from
10306 /// ToType in its cv-qualifiers at some level) into ConvertedType.
10307 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10308 bool InOverloadResolution,
10309 QualType &ConvertedType);
10310
10311 enum class MemberPointerConversionResult {
10312 Success,
10313 DifferentPointee,
10314 NotDerived,
10315 Ambiguous,
10316 Virtual,
10317 Inaccessible
10318 };
10319 enum class MemberPointerConversionDirection : bool { Downcast, Upcast };
10320 /// CheckMemberPointerConversion - Check the member pointer conversion from
10321 /// the expression From to the type ToType. This routine checks for ambiguous
10322 /// or virtual or inaccessible base-to-derived member pointer conversions for
10323 /// which IsMemberPointerConversion has already returned true. It produces a
10324 // diagnostic if there was an error.
10325 MemberPointerConversionResult CheckMemberPointerConversion(
10326 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10327 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10328 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10329
10330 /// IsQualificationConversion - Determines whether the conversion from
10331 /// an rvalue of type FromType to ToType is a qualification conversion
10332 /// (C++ 4.4).
10333 ///
10334 /// \param ObjCLifetimeConversion Output parameter that will be set to
10335 /// indicate when the qualification conversion involves a change in the
10336 /// Objective-C object lifetime.
10337 bool IsQualificationConversion(QualType FromType, QualType ToType,
10338 bool CStyle, bool &ObjCLifetimeConversion);
10339
10340 /// Determine whether the conversion from FromType to ToType is a valid
10341 /// conversion of ExtInfo/ExtProtoInfo on the nested function type.
10342 /// More precisely, this method checks whether FromType can be transformed
10343 /// into an exact match for ToType, by transforming its extended function
10344 /// type information in legal manner (e.g. by strictly stripping "noreturn"
10345 /// or "noexcept", or by stripping "noescape" for arguments).
10346 bool IsFunctionConversion(QualType FromType, QualType ToType) const;
10347
10348 /// Same as `IsFunctionConversion`, but if this would return true, it sets
10349 /// `ResultTy` to `ToType`.
10350 bool TryFunctionConversion(QualType FromType, QualType ToType,
10351 QualType &ResultTy) const;
10352
10353 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
10354 void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
10355 DeclarationName Name,
10356 OverloadCandidateSet &CandidateSet,
10357 FunctionDecl *Fn, MultiExprArg Args,
10358 bool IsMember = false);
10359
10360 ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
10361 FunctionDecl *Fun);
10362 ExprResult PerformImplicitObjectArgumentInitialization(
10363 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
10364 CXXMethodDecl *Method);
10365
10366 /// PerformContextuallyConvertToBool - Perform a contextual conversion
10367 /// of the expression From to bool (C++0x [conv]p3).
10368 ExprResult PerformContextuallyConvertToBool(Expr *From);
10369
10370 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10371 /// conversion of the expression From to an Objective-C pointer type.
10372 /// Returns a valid but null ExprResult if no conversion sequence exists.
10373 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
10374
10375 ExprResult BuildConvertedConstantExpression(Expr *From, QualType T,
10376 CCEKind CCE,
10377 NamedDecl *Dest = nullptr);
10378
10379 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10380 llvm::APSInt &Value, CCEKind CCE);
10381 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10382 APValue &Value, CCEKind CCE,
10383 NamedDecl *Dest = nullptr);
10384
10385 /// EvaluateConvertedConstantExpression - Evaluate an Expression
10386 /// That is a converted constant expression
10387 /// (which was built with BuildConvertedConstantExpression)
10388 ExprResult
10389 EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
10390 CCEKind CCE, bool RequireInt,
10391 const APValue &PreNarrowingValue);
10392
10393 /// Abstract base class used to perform a contextual implicit
10394 /// conversion from an expression to any type passing a filter.
10395 class ContextualImplicitConverter {
10396 public:
10397 bool Suppress;
10398 bool SuppressConversion;
10399
10400 ContextualImplicitConverter(bool Suppress = false,
10401 bool SuppressConversion = false)
10402 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
10403
10404 /// Determine whether the specified type is a valid destination type
10405 /// for this conversion.
10406 virtual bool match(QualType T) = 0;
10407
10408 /// Emits a diagnostic complaining that the expression does not have
10409 /// integral or enumeration type.
10410 virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10411 QualType T) = 0;
10412
10413 /// Emits a diagnostic when the expression has incomplete class type.
10414 virtual SemaDiagnosticBuilder
10415 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
10416
10417 /// Emits a diagnostic when the only matching conversion function
10418 /// is explicit.
10419 virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S,
10420 SourceLocation Loc,
10421 QualType T,
10422 QualType ConvTy) = 0;
10423
10424 /// Emits a note for the explicit conversion function.
10425 virtual SemaDiagnosticBuilder
10426 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10427
10428 /// Emits a diagnostic when there are multiple possible conversion
10429 /// functions.
10430 virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10431 QualType T) = 0;
10432
10433 /// Emits a note for one of the candidate conversions.
10434 virtual SemaDiagnosticBuilder
10435 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10436
10437 /// Emits a diagnostic when we picked a conversion function
10438 /// (for cases when we are not allowed to pick a conversion function).
10439 virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S,
10440 SourceLocation Loc,
10441 QualType T,
10442 QualType ConvTy) = 0;
10443
10444 virtual ~ContextualImplicitConverter() {}
10445 };
10446
10447 class ICEConvertDiagnoser : public ContextualImplicitConverter {
10448 bool AllowScopedEnumerations;
10449
10450 public:
10451 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10452 bool SuppressConversion)
10453 : ContextualImplicitConverter(Suppress, SuppressConversion),
10454 AllowScopedEnumerations(AllowScopedEnumerations) {}
10455
10456 /// Match an integral or (possibly scoped) enumeration type.
10457 bool match(QualType T) override;
10458
10459 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10460 QualType T) override {
10461 return diagnoseNotInt(S, Loc, T);
10462 }
10463
10464 /// Emits a diagnostic complaining that the expression does not have
10465 /// integral or enumeration type.
10466 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10467 QualType T) = 0;
10468 };
10469
10470 /// Perform a contextual implicit conversion.
10471 ExprResult
10472 PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE,
10473 ContextualImplicitConverter &Converter);
10474
10475 /// ReferenceCompareResult - Expresses the result of comparing two
10476 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10477 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10478 enum ReferenceCompareResult {
10479 /// Ref_Incompatible - The two types are incompatible, so direct
10480 /// reference binding is not possible.
10481 Ref_Incompatible = 0,
10482 /// Ref_Related - The two types are reference-related, which means
10483 /// that their unqualified forms (T1 and T2) are either the same
10484 /// or T1 is a base class of T2.
10485 Ref_Related,
10486 /// Ref_Compatible - The two types are reference-compatible.
10487 Ref_Compatible
10488 };
10489
10490 // Fake up a scoped enumeration that still contextually converts to bool.
10491 struct ReferenceConversionsScope {
10492 /// The conversions that would be performed on an lvalue of type T2 when
10493 /// binding a reference of type T1 to it, as determined when evaluating
10494 /// whether T1 is reference-compatible with T2.
10495 enum ReferenceConversions {
10496 Qualification = 0x1,
10497 NestedQualification = 0x2,
10498 Function = 0x4,
10499 DerivedToBase = 0x8,
10500 ObjC = 0x10,
10501 ObjCLifetime = 0x20,
10502
10503 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
10504 };
10505 };
10506 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
10507
10508 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10509 /// determine whether they are reference-compatible,
10510 /// reference-related, or incompatible, for use in C++ initialization by
10511 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10512 /// type, and the first type (T1) is the pointee type of the reference
10513 /// type being initialized.
10514 ReferenceCompareResult
10515 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
10516 ReferenceConversions *Conv = nullptr);
10517
10518 /// AddOverloadCandidate - Adds the given function to the set of
10519 /// candidate functions, using the given function call arguments. If
10520 /// @p SuppressUserConversions, then don't allow user-defined
10521 /// conversions via constructors or conversion operators.
10522 ///
10523 /// \param PartialOverloading true if we are performing "partial" overloading
10524 /// based on an incomplete set of function arguments. This feature is used by
10525 /// code completion.
10526 void AddOverloadCandidate(
10527 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
10528 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10529 bool PartialOverloading = false, bool AllowExplicit = true,
10530 bool AllowExplicitConversion = false,
10531 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10532 ConversionSequenceList EarlyConversions = {},
10533 OverloadCandidateParamOrder PO = {},
10534 bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10535
10536 /// Add all of the function declarations in the given function set to
10537 /// the overload candidate set.
10538 void AddFunctionCandidates(
10539 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10540 OverloadCandidateSet &CandidateSet,
10541 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10542 bool SuppressUserConversions = false, bool PartialOverloading = false,
10543 bool FirstArgumentIsBase = false);
10544
10545 /// AddMethodCandidate - Adds a named decl (which is some kind of
10546 /// method) as a method candidate to the given overload set.
10547 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10548 Expr::Classification ObjectClassification,
10549 ArrayRef<Expr *> Args,
10550 OverloadCandidateSet &CandidateSet,
10551 bool SuppressUserConversion = false,
10552 OverloadCandidateParamOrder PO = {});
10553
10554 /// AddMethodCandidate - Adds the given C++ member function to the set
10555 /// of candidate functions, using the given function call arguments
10556 /// and the object argument (@c Object). For example, in a call
10557 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10558 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10559 /// allow user-defined conversions via constructors or conversion
10560 /// operators.
10561 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10562 CXXRecordDecl *ActingContext, QualType ObjectType,
10563 Expr::Classification ObjectClassification,
10564 ArrayRef<Expr *> Args,
10565 OverloadCandidateSet &CandidateSet,
10566 bool SuppressUserConversions = false,
10567 bool PartialOverloading = false,
10568 ConversionSequenceList EarlyConversions = {},
10569 OverloadCandidateParamOrder PO = {},
10570 bool StrictPackMatch = false);
10571
10572 /// Add a C++ member function template as a candidate to the candidate
10573 /// set, using template argument deduction to produce an appropriate member
10574 /// function template specialization.
10575 void AddMethodTemplateCandidate(
10576 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10577 CXXRecordDecl *ActingContext,
10578 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10579 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10580 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10581 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10582
10583 /// Add a C++ function template specialization as a candidate
10584 /// in the candidate set, using template argument deduction to produce
10585 /// an appropriate function template specialization.
10586 void AddTemplateOverloadCandidate(
10587 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10588 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10589 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10590 bool PartialOverloading = false, bool AllowExplicit = true,
10591 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10592 OverloadCandidateParamOrder PO = {},
10593 bool AggregateCandidateDeduction = false);
10594
10595 struct CheckNonDependentConversionsFlag {
10596 /// Do not consider any user-defined conversions when constructing the
10597 /// initializing sequence.
10598 bool SuppressUserConversions;
10599
10600 /// Before constructing the initializing sequence, we check whether the
10601 /// parameter type and argument type contain any user defined conversions.
10602 /// If so, do not initialize them. This effectively bypasses some undesired
10603 /// instantiation before checking constaints, which might otherwise result
10604 /// in non-SFINAE errors e.g. recursive constraints.
10605 bool OnlyInitializeNonUserDefinedConversions;
10606
10607 CheckNonDependentConversionsFlag(
10608 bool SuppressUserConversions,
10609 bool OnlyInitializeNonUserDefinedConversions)
10610 : SuppressUserConversions(SuppressUserConversions),
10611 OnlyInitializeNonUserDefinedConversions(
10612 OnlyInitializeNonUserDefinedConversions) {}
10613 };
10614
10615 /// Check that implicit conversion sequences can be formed for each argument
10616 /// whose corresponding parameter has a non-dependent type, per DR1391's
10617 /// [temp.deduct.call]p10.
10618 bool CheckNonDependentConversions(
10619 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
10620 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10621 ConversionSequenceList &Conversions,
10622 CheckNonDependentConversionsFlag UserConversionFlag,
10623 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10624 Expr::Classification ObjectClassification = {},
10625 OverloadCandidateParamOrder PO = {});
10626
10627 /// AddConversionCandidate - Add a C++ conversion function as a
10628 /// candidate in the candidate set (C++ [over.match.conv],
10629 /// C++ [over.match.copy]). From is the expression we're converting from,
10630 /// and ToType is the type that we're eventually trying to convert to
10631 /// (which may or may not be the same type as the type that the
10632 /// conversion function produces).
10633 void AddConversionCandidate(
10634 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10635 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10636 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10637 bool AllowExplicit, bool AllowResultConversion = true,
10638 bool StrictPackMatch = false);
10639
10640 /// Adds a conversion function template specialization
10641 /// candidate to the overload set, using template argument deduction
10642 /// to deduce the template arguments of the conversion function
10643 /// template from the type that we are converting to (C++
10644 /// [temp.deduct.conv]).
10645 void AddTemplateConversionCandidate(
10646 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10647 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10648 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10649 bool AllowExplicit, bool AllowResultConversion = true);
10650
10651 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10652 /// converts the given @c Object to a function pointer via the
10653 /// conversion function @c Conversion, and then attempts to call it
10654 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10655 /// the type of function that we'll eventually be calling.
10656 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10657 DeclAccessPair FoundDecl,
10658 CXXRecordDecl *ActingContext,
10659 const FunctionProtoType *Proto, Expr *Object,
10660 ArrayRef<Expr *> Args,
10661 OverloadCandidateSet &CandidateSet);
10662
10663 /// Add all of the non-member operator function declarations in the given
10664 /// function set to the overload candidate set.
10665 void AddNonMemberOperatorCandidates(
10666 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10667 OverloadCandidateSet &CandidateSet,
10668 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10669
10670 /// Add overload candidates for overloaded operators that are
10671 /// member functions.
10672 ///
10673 /// Add the overloaded operator candidates that are member functions
10674 /// for the operator Op that was used in an operator expression such
10675 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10676 /// CandidateSet will store the added overload candidates. (C++
10677 /// [over.match.oper]).
10678 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
10679 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10680 OverloadCandidateSet &CandidateSet,
10681 OverloadCandidateParamOrder PO = {});
10682
10683 /// AddBuiltinCandidate - Add a candidate for a built-in
10684 /// operator. ResultTy and ParamTys are the result and parameter types
10685 /// of the built-in candidate, respectively. Args and NumArgs are the
10686 /// arguments being passed to the candidate. IsAssignmentOperator
10687 /// should be true when this built-in candidate is an assignment
10688 /// operator. NumContextualBoolArguments is the number of arguments
10689 /// (at the beginning of the argument list) that will be contextually
10690 /// converted to bool.
10691 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10692 OverloadCandidateSet &CandidateSet,
10693 bool IsAssignmentOperator = false,
10694 unsigned NumContextualBoolArguments = 0);
10695
10696 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10697 /// operator overloads to the candidate set (C++ [over.built]), based
10698 /// on the operator @p Op and the arguments given. For example, if the
10699 /// operator is a binary '+', this routine might add "int
10700 /// operator+(int, int)" to cover integer addition.
10701 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10702 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10703 OverloadCandidateSet &CandidateSet);
10704
10705 /// Add function candidates found via argument-dependent lookup
10706 /// to the set of overloading candidates.
10707 ///
10708 /// This routine performs argument-dependent name lookup based on the
10709 /// given function name (which may also be an operator name) and adds
10710 /// all of the overload candidates found by ADL to the overload
10711 /// candidate set (C++ [basic.lookup.argdep]).
10712 void AddArgumentDependentLookupCandidates(
10713 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10714 TemplateArgumentListInfo *ExplicitTemplateArgs,
10715 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10716
10717 /// Check the enable_if expressions on the given function. Returns the first
10718 /// failing attribute, or NULL if they were all successful.
10719 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10720 ArrayRef<Expr *> Args,
10721 bool MissingImplicitThis = false);
10722
10723 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10724 /// non-ArgDependent DiagnoseIfAttrs.
10725 ///
10726 /// Argument-dependent diagnose_if attributes should be checked each time a
10727 /// function is used as a direct callee of a function call.
10728 ///
10729 /// Returns true if any errors were emitted.
10730 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10731 const Expr *ThisArg,
10732 ArrayRef<const Expr *> Args,
10733 SourceLocation Loc);
10734
10735 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10736 /// ArgDependent DiagnoseIfAttrs.
10737 ///
10738 /// Argument-independent diagnose_if attributes should be checked on every use
10739 /// of a function.
10740 ///
10741 /// Returns true if any errors were emitted.
10742 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10743 SourceLocation Loc);
10744
10745 /// Determine if \p A and \p B are equivalent internal linkage declarations
10746 /// from different modules, and thus an ambiguity error can be downgraded to
10747 /// an extension warning.
10748 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10749 const NamedDecl *B);
10750 void diagnoseEquivalentInternalLinkageDeclarations(
10751 SourceLocation Loc, const NamedDecl *D,
10752 ArrayRef<const NamedDecl *> Equiv);
10753
10754 // Emit as a 'note' the specific overload candidate
10755 void NoteOverloadCandidate(
10756 const NamedDecl *Found, const FunctionDecl *Fn,
10757 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
10758 QualType DestType = QualType(), bool TakingAddress = false);
10759
10760 // Emit as a series of 'note's all template and non-templates identified by
10761 // the expression Expr
10762 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10763 bool TakingAddress = false);
10764
10765 /// Returns whether the given function's address can be taken or not,
10766 /// optionally emitting a diagnostic if the address can't be taken.
10767 ///
10768 /// Returns false if taking the address of the function is illegal.
10769 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10770 bool Complain = false,
10771 SourceLocation Loc = SourceLocation());
10772
10773 // [PossiblyAFunctionType] --> [Return]
10774 // NonFunctionType --> NonFunctionType
10775 // R (A) --> R(A)
10776 // R (*)(A) --> R (A)
10777 // R (&)(A) --> R (A)
10778 // R (S::*)(A) --> R (A)
10779 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10780
10781 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10782 /// an overloaded function (C++ [over.over]), where @p From is an
10783 /// expression with overloaded function type and @p ToType is the type
10784 /// we're trying to resolve to. For example:
10785 ///
10786 /// @code
10787 /// int f(double);
10788 /// int f(int);
10789 ///
10790 /// int (*pfd)(double) = f; // selects f(double)
10791 /// @endcode
10792 ///
10793 /// This routine returns the resulting FunctionDecl if it could be
10794 /// resolved, and NULL otherwise. When @p Complain is true, this
10795 /// routine will emit diagnostics if there is an error.
10796 FunctionDecl *
10797 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10798 bool Complain, DeclAccessPair &Found,
10799 bool *pHadMultipleCandidates = nullptr);
10800
10801 /// Given an expression that refers to an overloaded function, try to
10802 /// resolve that function to a single function that can have its address
10803 /// taken. This will modify `Pair` iff it returns non-null.
10804 ///
10805 /// This routine can only succeed if from all of the candidates in the
10806 /// overload set for SrcExpr that can have their addresses taken, there is one
10807 /// candidate that is more constrained than the rest.
10808 FunctionDecl *
10809 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10810
10811 /// Given an overloaded function, tries to turn it into a non-overloaded
10812 /// function reference using resolveAddressOfSingleOverloadCandidate. This
10813 /// will perform access checks, diagnose the use of the resultant decl, and,
10814 /// if requested, potentially perform a function-to-pointer decay.
10815 ///
10816 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10817 /// Otherwise, returns true. This may emit diagnostics and return true.
10818 bool resolveAndFixAddressOfSingleOverloadCandidate(
10819 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10820
10821 /// Given an expression that refers to an overloaded function, try to
10822 /// resolve that overloaded function expression down to a single function.
10823 ///
10824 /// This routine can only resolve template-ids that refer to a single function
10825 /// template, where that template-id refers to a single template whose
10826 /// template arguments are either provided by the template-id or have
10827 /// defaults, as described in C++0x [temp.arg.explicit]p3.
10828 ///
10829 /// If no template-ids are found, no diagnostics are emitted and NULL is
10830 /// returned.
10831 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(
10832 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10833 TemplateSpecCandidateSet *FailedTSC = nullptr,
10834 bool ForTypeDeduction = false);
10835
10836 // Resolve and fix an overloaded expression that can be resolved
10837 // because it identifies a single function template specialization.
10838 //
10839 // Last three arguments should only be supplied if Complain = true
10840 //
10841 // Return true if it was logically possible to so resolve the
10842 // expression, regardless of whether or not it succeeded. Always
10843 // returns true if 'complain' is set.
10844 bool ResolveAndFixSingleFunctionTemplateSpecialization(
10845 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10846 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10847 QualType DestTypeForComplaining = QualType(),
10848 unsigned DiagIDForComplaining = 0);
10849
10850 /// Add the overload candidates named by callee and/or found by argument
10851 /// dependent lookup to the given overload set.
10852 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10853 ArrayRef<Expr *> Args,
10854 OverloadCandidateSet &CandidateSet,
10855 bool PartialOverloading = false);
10856
10857 /// Add the call candidates from the given set of lookup results to the given
10858 /// overload set. Non-function lookup results are ignored.
10859 void AddOverloadedCallCandidates(
10860 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
10861 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
10862
10863 // An enum used to represent the different possible results of building a
10864 // range-based for loop.
10865 enum ForRangeStatus {
10866 FRS_Success,
10867 FRS_NoViableFunction,
10868 FRS_DiagnosticIssued
10869 };
10870
10871 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
10872 /// given LookupResult is non-empty, it is assumed to describe a member which
10873 /// will be invoked. Otherwise, the function will be found via argument
10874 /// dependent lookup.
10875 /// CallExpr is set to a valid expression and FRS_Success returned on success,
10876 /// otherwise CallExpr is set to ExprError() and some non-success value
10877 /// is returned.
10878 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
10879 SourceLocation RangeLoc,
10880 const DeclarationNameInfo &NameInfo,
10881 LookupResult &MemberLookup,
10882 OverloadCandidateSet *CandidateSet,
10883 Expr *Range, ExprResult *CallExpr);
10884
10885 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10886 /// (which eventually refers to the declaration Func) and the call
10887 /// arguments Args/NumArgs, attempt to resolve the function call down
10888 /// to a specific function. If overload resolution succeeds, returns
10889 /// the call expression produced by overload resolution.
10890 /// Otherwise, emits diagnostics and returns ExprError.
10891 ExprResult BuildOverloadedCallExpr(
10892 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
10893 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
10894 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
10895
10896 /// Constructs and populates an OverloadedCandidateSet from
10897 /// the given function.
10898 /// \returns true when an the ExprResult output parameter has been set.
10899 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
10900 MultiExprArg Args, SourceLocation RParenLoc,
10901 OverloadCandidateSet *CandidateSet,
10902 ExprResult *Result);
10903
10904 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
10905 NestedNameSpecifierLoc NNSLoc,
10906 DeclarationNameInfo DNI,
10907 const UnresolvedSetImpl &Fns,
10908 bool PerformADL = true);
10909
10910 /// Create a unary operation that may resolve to an overloaded
10911 /// operator.
10912 ///
10913 /// \param OpLoc The location of the operator itself (e.g., '*').
10914 ///
10915 /// \param Opc The UnaryOperatorKind that describes this operator.
10916 ///
10917 /// \param Fns The set of non-member functions that will be
10918 /// considered by overload resolution. The caller needs to build this
10919 /// set based on the context using, e.g.,
10920 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10921 /// set should not contain any member functions; those will be added
10922 /// by CreateOverloadedUnaryOp().
10923 ///
10924 /// \param Input The input argument.
10925 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
10926 UnaryOperatorKind Opc,
10927 const UnresolvedSetImpl &Fns, Expr *input,
10928 bool RequiresADL = true);
10929
10930 /// Perform lookup for an overloaded binary operator.
10931 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
10932 OverloadedOperatorKind Op,
10933 const UnresolvedSetImpl &Fns,
10934 ArrayRef<Expr *> Args, bool RequiresADL = true);
10935
10936 /// Create a binary operation that may resolve to an overloaded
10937 /// operator.
10938 ///
10939 /// \param OpLoc The location of the operator itself (e.g., '+').
10940 ///
10941 /// \param Opc The BinaryOperatorKind that describes this operator.
10942 ///
10943 /// \param Fns The set of non-member functions that will be
10944 /// considered by overload resolution. The caller needs to build this
10945 /// set based on the context using, e.g.,
10946 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10947 /// set should not contain any member functions; those will be added
10948 /// by CreateOverloadedBinOp().
10949 ///
10950 /// \param LHS Left-hand argument.
10951 /// \param RHS Right-hand argument.
10952 /// \param PerformADL Whether to consider operator candidates found by ADL.
10953 /// \param AllowRewrittenCandidates Whether to consider candidates found by
10954 /// C++20 operator rewrites.
10955 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
10956 /// the function in question. Such a function is never a candidate in
10957 /// our overload resolution. This also enables synthesizing a three-way
10958 /// comparison from < and == as described in C++20 [class.spaceship]p1.
10959 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
10960 const UnresolvedSetImpl &Fns, Expr *LHS,
10961 Expr *RHS, bool RequiresADL = true,
10962 bool AllowRewrittenCandidates = true,
10963 FunctionDecl *DefaultedFn = nullptr);
10964 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
10965 const UnresolvedSetImpl &Fns,
10966 Expr *LHS, Expr *RHS,
10967 FunctionDecl *DefaultedFn);
10968
10969 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10970 SourceLocation RLoc, Expr *Base,
10971 MultiExprArg Args);
10972
10973 /// BuildCallToMemberFunction - Build a call to a member
10974 /// function. MemExpr is the expression that refers to the member
10975 /// function (and includes the object parameter), Args/NumArgs are the
10976 /// arguments to the function call (not including the object
10977 /// parameter). The caller needs to validate that the member
10978 /// expression refers to a non-static member function or an overloaded
10979 /// member function.
10980 ExprResult BuildCallToMemberFunction(
10981 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
10982 SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
10983 bool IsExecConfig = false, bool AllowRecovery = false);
10984
10985 /// BuildCallToObjectOfClassType - Build a call to an object of class
10986 /// type (C++ [over.call.object]), which can end up invoking an
10987 /// overloaded function call operator (@c operator()) or performing a
10988 /// user-defined conversion on the object argument.
10989 ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object,
10990 SourceLocation LParenLoc,
10991 MultiExprArg Args,
10992 SourceLocation RParenLoc);
10993
10994 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
10995 /// (if one exists), where @c Base is an expression of class type and
10996 /// @c Member is the name of the member we're trying to find.
10997 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
10998 SourceLocation OpLoc,
10999 bool *NoArrowOperatorFound = nullptr);
11000
11001 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
11002 CXXConversionDecl *Method,
11003 bool HadMultipleCandidates);
11004
11005 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
11006 /// to a literal operator described by the provided lookup results.
11007 ExprResult BuildLiteralOperatorCall(
11008 LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args,
11009 SourceLocation LitEndLoc,
11010 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
11011
11012 /// FixOverloadedFunctionReference - E is an expression that refers to
11013 /// a C++ overloaded function (possibly with some parentheses and
11014 /// perhaps a '&' around it). We have resolved the overloaded function
11015 /// to the function declaration Fn, so patch up the expression E to
11016 /// refer (possibly indirectly) to Fn. Returns the new expr.
11017 ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl,
11018 FunctionDecl *Fn);
11019 ExprResult FixOverloadedFunctionReference(ExprResult,
11020 DeclAccessPair FoundDecl,
11021 FunctionDecl *Fn);
11022
11023 /// - Returns a selector which best matches given argument list or
11024 /// nullptr if none could be found
11025 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
11026 bool IsInstance,
11027 SmallVectorImpl<ObjCMethodDecl *> &Methods);
11028
11029 ///@}
11030
11031 //
11032 //
11033 // -------------------------------------------------------------------------
11034 //
11035 //
11036
11037 /// \name Statements
11038 /// Implementations are in SemaStmt.cpp
11039 ///@{
11040
11041public:
11042 /// Stack of active SEH __finally scopes. Can be empty.
11043 SmallVector<Scope *, 2> CurrentSEHFinally;
11044
11045 /// Stack of '_Defer' statements that are currently being parsed, as well
11046 /// as the locations of their '_Defer' keywords. Can be empty.
11047 SmallVector<std::pair<Scope *, SourceLocation>, 2> CurrentDefer;
11048
11049 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
11050 StmtResult ActOnExprStmtError();
11051
11052 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
11053 bool HasLeadingEmptyMacro = false);
11054
11055 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc,
11056 SourceLocation EndLoc);
11057 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
11058
11059 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
11060 /// whose result is unused, warn.
11061 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
11062
11063 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
11064 void ActOnAfterCompoundStatementLeadingPragmas();
11065 void ActOnFinishOfCompoundStmt();
11066 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
11067 ArrayRef<Stmt *> Elts, bool isStmtExpr);
11068
11069 sema::CompoundScopeInfo &getCurCompoundScope() const;
11070
11071 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
11072 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
11073 SourceLocation DotDotDotLoc, ExprResult RHS,
11074 SourceLocation ColonLoc);
11075
11076 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
11077 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
11078
11079 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
11080 SourceLocation ColonLoc, Stmt *SubStmt,
11081 Scope *CurScope);
11082 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
11083 SourceLocation ColonLoc, Stmt *SubStmt);
11084
11085 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
11086 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
11087 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
11088 Stmt *SubStmt);
11089
11090 /// Check whether the given statement can have musttail applied to it,
11091 /// issuing a diagnostic and returning false if not. In the success case,
11092 /// the statement is rewritten to remove implicit nodes from the return
11093 /// value.
11094 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11095
11096 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11097 SourceLocation LParenLoc, Stmt *InitStmt,
11098 ConditionResult Cond, SourceLocation RParenLoc,
11099 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11100 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11101 SourceLocation LParenLoc, Stmt *InitStmt,
11102 ConditionResult Cond, SourceLocation RParenLoc,
11103 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11104
11105 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11106
11107 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
11108 SourceLocation LParenLoc, Stmt *InitStmt,
11109 ConditionResult Cond,
11110 SourceLocation RParenLoc);
11111 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
11112 Stmt *Body);
11113
11114 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11115 /// integer not in the range of enum values.
11116 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11117 Expr *SrcExpr);
11118
11119 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
11120 ConditionResult Cond, SourceLocation RParenLoc,
11121 Stmt *Body);
11122 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
11123 SourceLocation WhileLoc, SourceLocation CondLParen,
11124 Expr *Cond, SourceLocation CondRParen);
11125
11126 StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
11127 Stmt *First, ConditionResult Second,
11128 FullExprArg Third, SourceLocation RParenLoc,
11129 Stmt *Body);
11130
11131 /// In an Objective C collection iteration statement:
11132 /// for (x in y)
11133 /// x can be an arbitrary l-value expression. Bind it up as a
11134 /// full-expression.
11135 StmtResult ActOnForEachLValueExpr(Expr *E);
11136
11137 enum BuildForRangeKind {
11138 /// Initial building of a for-range statement.
11139 BFRK_Build,
11140 /// Instantiation or recovery rebuild of a for-range statement. Don't
11141 /// attempt any typo-correction.
11142 BFRK_Rebuild,
11143 /// Determining whether a for-range statement could be built. Avoid any
11144 /// unnecessary or irreversible actions.
11145 BFRK_Check
11146 };
11147
11148 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
11149 ///
11150 /// C++11 [stmt.ranged]:
11151 /// A range-based for statement is equivalent to
11152 ///
11153 /// {
11154 /// auto && __range = range-init;
11155 /// for ( auto __begin = begin-expr,
11156 /// __end = end-expr;
11157 /// __begin != __end;
11158 /// ++__begin ) {
11159 /// for-range-declaration = *__begin;
11160 /// statement
11161 /// }
11162 /// }
11163 ///
11164 /// The body of the loop is not available yet, since it cannot be analysed
11165 /// until we have determined the type of the for-range-declaration.
11166 StmtResult ActOnCXXForRangeStmt(
11167 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11168 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11169 SourceLocation RParenLoc, BuildForRangeKind Kind,
11170 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11171
11172 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11173 StmtResult BuildCXXForRangeStmt(
11174 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11175 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11176 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11177 BuildForRangeKind Kind,
11178 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11179
11180 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11181 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11182 /// body cannot be performed until after the type of the range variable is
11183 /// determined.
11184 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11185
11186 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11187 LabelDecl *TheDecl);
11188 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11189 SourceLocation StarLoc, Expr *DestExp);
11190 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
11191 LabelDecl *Label, SourceLocation LabelLoc);
11192 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
11193 LabelDecl *Label, SourceLocation LabelLoc);
11194
11195 void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope);
11196 void ActOnDeferStmtError(Scope *CurScope);
11197 StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope);
11198
11199 struct NamedReturnInfo {
11200 const VarDecl *Candidate;
11201
11202 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
11203 Status S;
11204
11205 bool isMoveEligible() const { return S != None; };
11206 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
11207 };
11208 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
11209
11210 /// Determine whether the given expression might be move-eligible or
11211 /// copy-elidable in either a (co_)return statement or throw expression,
11212 /// without considering function return type, if applicable.
11213 ///
11214 /// \param E The expression being returned from the function or block,
11215 /// being thrown, or being co_returned from a coroutine. This expression
11216 /// might be modified by the implementation.
11217 ///
11218 /// \param Mode Overrides detection of current language mode
11219 /// and uses the rules for C++23.
11220 ///
11221 /// \returns An aggregate which contains the Candidate and isMoveEligible
11222 /// and isCopyElidable methods. If Candidate is non-null, it means
11223 /// isMoveEligible() would be true under the most permissive language
11224 /// standard.
11225 NamedReturnInfo getNamedReturnInfo(
11226 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
11227
11228 /// Determine whether the given NRVO candidate variable is move-eligible or
11229 /// copy-elidable, without considering function return type.
11230 ///
11231 /// \param VD The NRVO candidate variable.
11232 ///
11233 /// \returns An aggregate which contains the Candidate and isMoveEligible
11234 /// and isCopyElidable methods. If Candidate is non-null, it means
11235 /// isMoveEligible() would be true under the most permissive language
11236 /// standard.
11237 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11238
11239 /// Updates given NamedReturnInfo's move-eligible and
11240 /// copy-elidable statuses, considering the function
11241 /// return type criteria as applicable to return statements.
11242 ///
11243 /// \param Info The NamedReturnInfo object to update.
11244 ///
11245 /// \param ReturnType This is the return type of the function.
11246 /// \returns The copy elision candidate, in case the initial return expression
11247 /// was copy elidable, or nullptr otherwise.
11248 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11249 QualType ReturnType);
11250
11251 /// Perform the initialization of a potentially-movable value, which
11252 /// is the result of return value.
11253 ///
11254 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11255 /// treat returned lvalues as rvalues in certain cases (to prefer move
11256 /// construction), then falls back to treating them as lvalues if that failed.
11257 ExprResult
11258 PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
11259 const NamedReturnInfo &NRInfo, Expr *Value,
11260 bool SupressSimplerImplicitMoves = false);
11261
11262 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
11263
11264 /// Deduce the return type for a function from a returned expression, per
11265 /// C++1y [dcl.spec.auto]p6.
11266 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
11267 SourceLocation ReturnLoc, Expr *RetExpr,
11268 const AutoType *AT);
11269
11270 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11271 Scope *CurScope);
11272 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11273 bool AllowRecovery = false);
11274
11275 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11276 /// for capturing scopes.
11277 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11278 NamedReturnInfo &NRInfo,
11279 bool SupressSimplerImplicitMoves);
11280
11281 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11282 /// and creates a proper catch handler from them.
11283 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
11284 Stmt *HandlerBlock);
11285
11286 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11287 /// handlers and creates a try statement from them.
11288 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
11289 ArrayRef<Stmt *> Handlers);
11290
11291 void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11292
11293 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11294 SourceLocation TryLoc, Stmt *TryBlock,
11295 Stmt *Handler);
11296 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
11297 Stmt *Block);
11298 void ActOnStartSEHFinallyBlock();
11299 void ActOnAbortSEHFinallyBlock();
11300 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
11301 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
11302
11303 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
11304 bool IsIfExists,
11305 NestedNameSpecifierLoc QualifierLoc,
11306 DeclarationNameInfo NameInfo,
11307 Stmt *Nested);
11308 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
11309 bool IsIfExists, CXXScopeSpec &SS,
11310 UnqualifiedId &Name, Stmt *Nested);
11311
11312 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11313 CapturedRegionKind Kind, unsigned NumParams);
11314 typedef std::pair<StringRef, QualType> CapturedParamNameType;
11315 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11316 CapturedRegionKind Kind,
11317 ArrayRef<CapturedParamNameType> Params,
11318 unsigned OpenMPCaptureLevel = 0);
11319 StmtResult ActOnCapturedRegionEnd(Stmt *S);
11320 void ActOnCapturedRegionError();
11321 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
11322 SourceLocation Loc,
11323 unsigned NumParams);
11324
11325private:
11326 /// Check whether the given statement can have musttail applied to it,
11327 /// issuing a diagnostic and returning false if not.
11328 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11329
11330 /// Check if the given expression contains 'break' or 'continue'
11331 /// statement that produces control flow different from GCC.
11332 void CheckBreakContinueBinding(Expr *E);
11333
11334 ///@}
11335
11336 //
11337 //
11338 // -------------------------------------------------------------------------
11339 //
11340 //
11341
11342 /// \name `inline asm` Statement
11343 /// Implementations are in SemaStmtAsm.cpp
11344 ///@{
11345
11346public:
11347 ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel);
11348 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11349 bool IsVolatile, unsigned NumOutputs,
11350 unsigned NumInputs, IdentifierInfo **Names,
11351 MultiExprArg Constraints, MultiExprArg Exprs,
11352 Expr *AsmString, MultiExprArg Clobbers,
11353 unsigned NumLabels, SourceLocation RParenLoc);
11354
11355 void FillInlineAsmIdentifierInfo(Expr *Res,
11356 llvm::InlineAsmIdentifierInfo &Info);
11357 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
11358 SourceLocation TemplateKWLoc,
11359 UnqualifiedId &Id,
11360 bool IsUnevaluatedContext);
11361 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11362 SourceLocation AsmLoc);
11363 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
11364 SourceLocation AsmLoc);
11365 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
11366 ArrayRef<Token> AsmToks, StringRef AsmString,
11367 unsigned NumOutputs, unsigned NumInputs,
11368 ArrayRef<StringRef> Constraints,
11369 ArrayRef<StringRef> Clobbers,
11370 ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11371 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11372 SourceLocation Location, bool AlwaysCreate);
11373
11374 ///@}
11375
11376 //
11377 //
11378 // -------------------------------------------------------------------------
11379 //
11380 //
11381
11382 /// \name Statement Attribute Handling
11383 /// Implementations are in SemaStmtAttr.cpp
11384 ///@{
11385
11386public:
11387 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11388 const AttributeCommonInfo &A);
11389 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11390 const AttributeCommonInfo &A);
11391
11392 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11393 bool CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs);
11394
11395 /// Process the attributes before creating an attributed statement. Returns
11396 /// the semantic attributes that have been processed.
11397 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11398 SmallVectorImpl<const Attr *> &OutAttrs);
11399
11400 ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A,
11401 SourceRange Range);
11402 ExprResult BuildCXXAssumeExpr(Expr *Assumption,
11403 const IdentifierInfo *AttrName,
11404 SourceRange Range);
11405
11406 ///@}
11407
11408 //
11409 //
11410 // -------------------------------------------------------------------------
11411 //
11412 //
11413
11414 /// \name C++ Templates
11415 /// Implementations are in SemaTemplate.cpp
11416 ///@{
11417
11418public:
11419 // Saves the current floating-point pragma stack and clear it in this Sema.
11420 class FpPragmaStackSaveRAII {
11421 public:
11422 FpPragmaStackSaveRAII(Sema &S)
11423 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11424 S.FpPragmaStack.Stack.clear();
11425 }
11426 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11427 FpPragmaStackSaveRAII(const FpPragmaStackSaveRAII &) = delete;
11428 FpPragmaStackSaveRAII &operator=(const FpPragmaStackSaveRAII &) = delete;
11429
11430 private:
11431 Sema &S;
11432 PragmaStack<FPOptionsOverride> SavedStack;
11433 };
11434
11435 void resetFPOptions(FPOptions FPO) {
11436 CurFPFeatures = FPO;
11437 FpPragmaStack.CurrentValue = FPO.getChangesFrom(Base: FPOptions(LangOpts));
11438 }
11439
11440 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
11441 return llvm::ArrayRef(InventedParameterInfos.begin() +
11442 InventedParameterInfosStart,
11443 InventedParameterInfos.end());
11444 }
11445
11446 ArrayRef<sema::FunctionScopeInfo *> getFunctionScopes() const {
11447 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
11448 FunctionScopes.end());
11449 }
11450
11451 typedef llvm::MapVector<const FunctionDecl *,
11452 std::unique_ptr<LateParsedTemplate>>
11453 LateParsedTemplateMapT;
11454 LateParsedTemplateMapT LateParsedTemplateMap;
11455
11456 /// Determine the number of levels of enclosing template parameters. This is
11457 /// only usable while parsing. Note that this does not include dependent
11458 /// contexts in which no template parameters have yet been declared, such as
11459 /// in a terse function template or generic lambda before the first 'auto' is
11460 /// encountered.
11461 unsigned getTemplateDepth(Scope *S) const;
11462
11463 void FilterAcceptableTemplateNames(LookupResult &R,
11464 bool AllowFunctionTemplates = true,
11465 bool AllowDependent = true);
11466 bool hasAnyAcceptableTemplateNames(LookupResult &R,
11467 bool AllowFunctionTemplates = true,
11468 bool AllowDependent = true,
11469 bool AllowNonTemplateFunctions = false);
11470 /// Try to interpret the lookup result D as a template-name.
11471 ///
11472 /// \param D A declaration found by name lookup.
11473 /// \param AllowFunctionTemplates Whether function templates should be
11474 /// considered valid results.
11475 /// \param AllowDependent Whether unresolved using declarations (that might
11476 /// name templates) should be considered valid results.
11477 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
11478 bool AllowFunctionTemplates = true,
11479 bool AllowDependent = true);
11480
11481 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
11482 /// Whether and why a template name is required in this lookup.
11483 class RequiredTemplateKind {
11484 public:
11485 /// Template name is required if TemplateKWLoc is valid.
11486 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
11487 : TemplateKW(TemplateKWLoc) {}
11488 /// Template name is unconditionally required.
11489 RequiredTemplateKind(TemplateNameIsRequiredTag) {}
11490
11491 SourceLocation getTemplateKeywordLoc() const {
11492 return TemplateKW.value_or(u: SourceLocation());
11493 }
11494 bool hasTemplateKeyword() const {
11495 return getTemplateKeywordLoc().isValid();
11496 }
11497 bool isRequired() const { return TemplateKW != SourceLocation(); }
11498 explicit operator bool() const { return isRequired(); }
11499
11500 private:
11501 std::optional<SourceLocation> TemplateKW;
11502 };
11503
11504 enum class AssumedTemplateKind {
11505 /// This is not assumed to be a template name.
11506 None,
11507 /// This is assumed to be a template name because lookup found nothing.
11508 FoundNothing,
11509 /// This is assumed to be a template name because lookup found one or more
11510 /// functions (but no function templates).
11511 FoundFunctions,
11512 };
11513
11514 bool
11515 LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
11516 QualType ObjectType, bool EnteringContext,
11517 RequiredTemplateKind RequiredTemplate = SourceLocation(),
11518 AssumedTemplateKind *ATK = nullptr,
11519 bool AllowTypoCorrection = true);
11520
11521 TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS,
11522 bool hasTemplateKeyword,
11523 const UnqualifiedId &Name,
11524 ParsedType ObjectType, bool EnteringContext,
11525 TemplateTy &Template,
11526 bool &MemberOfUnknownSpecialization,
11527 bool Disambiguation = false);
11528
11529 /// Try to resolve an undeclared template name as a type template.
11530 ///
11531 /// Sets II to the identifier corresponding to the template name, and updates
11532 /// Name to a corresponding (typo-corrected) type template name and TNK to
11533 /// the corresponding kind, if possible.
11534 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
11535 TemplateNameKind &TNK,
11536 SourceLocation NameLoc,
11537 IdentifierInfo *&II);
11538
11539 /// Determine whether a particular identifier might be the name in a C++1z
11540 /// deduction-guide declaration.
11541 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11542 SourceLocation NameLoc, CXXScopeSpec &SS,
11543 ParsedTemplateTy *Template = nullptr);
11544
11545 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
11546 SourceLocation IILoc, Scope *S,
11547 const CXXScopeSpec *SS,
11548 TemplateTy &SuggestedTemplate,
11549 TemplateNameKind &SuggestedKind);
11550
11551 /// Determine whether we would be unable to instantiate this template (because
11552 /// it either has no definition, or is in the process of being instantiated).
11553 bool DiagnoseUninstantiableTemplate(
11554 SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11555 bool InstantiatedFromMember, const NamedDecl *Pattern,
11556 const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11557 bool Complain = true, bool *Unreachable = nullptr);
11558
11559 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11560 /// that the template parameter 'PrevDecl' is being shadowed by a new
11561 /// declaration at location Loc. Returns true to indicate that this is
11562 /// an error, and false otherwise.
11563 ///
11564 /// \param Loc The location of the declaration that shadows a template
11565 /// parameter.
11566 ///
11567 /// \param PrevDecl The template parameter that the declaration shadows.
11568 ///
11569 /// \param SupportedForCompatibility Whether to issue the diagnostic as
11570 /// a warning for compatibility with older versions of clang.
11571 /// Ignored when MSVC compatibility is enabled.
11572 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
11573 bool SupportedForCompatibility = false);
11574
11575 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11576 /// the parameter D to reference the templated declaration and return a
11577 /// pointer to the template declaration. Otherwise, do nothing to D and return
11578 /// null.
11579 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
11580
11581 /// ActOnTypeParameter - Called when a C++ template type parameter
11582 /// (e.g., "typename T") has been parsed. Typename specifies whether
11583 /// the keyword "typename" was used to declare the type parameter
11584 /// (otherwise, "class" was used), and KeyLoc is the location of the
11585 /// "class" or "typename" keyword. ParamName is the name of the
11586 /// parameter (NULL indicates an unnamed template parameter) and
11587 /// ParamNameLoc is the location of the parameter name (if any).
11588 /// If the type parameter has a default argument, it will be added
11589 /// later via ActOnTypeParameterDefault.
11590 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
11591 SourceLocation EllipsisLoc,
11592 SourceLocation KeyLoc,
11593 IdentifierInfo *ParamName,
11594 SourceLocation ParamNameLoc, unsigned Depth,
11595 unsigned Position, SourceLocation EqualLoc,
11596 ParsedType DefaultArg, bool HasTypeConstraint);
11597
11598 bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint);
11599
11600 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11601 TemplateIdAnnotation *TypeConstraint,
11602 TemplateTypeParmDecl *ConstrainedParameter,
11603 SourceLocation EllipsisLoc);
11604 bool BuildTypeConstraint(const CXXScopeSpec &SS,
11605 TemplateIdAnnotation *TypeConstraint,
11606 TemplateTypeParmDecl *ConstrainedParameter,
11607 SourceLocation EllipsisLoc,
11608 bool AllowUnexpandedPack);
11609
11610 /// Attach a type-constraint to a template parameter.
11611 /// \returns true if an error occurred. This can happen if the
11612 /// immediately-declared constraint could not be formed (e.g. incorrect number
11613 /// of arguments for the named concept).
11614 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
11615 DeclarationNameInfo NameInfo,
11616 TemplateDecl *NamedConcept, NamedDecl *FoundDecl,
11617 const TemplateArgumentListInfo *TemplateArgs,
11618 TemplateTypeParmDecl *ConstrainedParameter,
11619 SourceLocation EllipsisLoc);
11620
11621 bool AttachTypeConstraint(AutoTypeLoc TL,
11622 NonTypeTemplateParmDecl *NewConstrainedParm,
11623 NonTypeTemplateParmDecl *OrigConstrainedParm,
11624 SourceLocation EllipsisLoc);
11625
11626 /// Require the given type to be a structural type, and diagnose if it is not.
11627 ///
11628 /// \return \c true if an error was produced.
11629 bool RequireStructuralType(QualType T, SourceLocation Loc);
11630
11631 /// Check that the type of a non-type template parameter is
11632 /// well-formed.
11633 ///
11634 /// \returns the (possibly-promoted) parameter type if valid;
11635 /// otherwise, produces a diagnostic and returns a NULL type.
11636 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
11637 SourceLocation Loc);
11638 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
11639
11640 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
11641 unsigned Depth, unsigned Position,
11642 SourceLocation EqualLoc,
11643 Expr *DefaultArg);
11644
11645 /// ActOnTemplateTemplateParameter - Called when a C++ template template
11646 /// parameter (e.g. T in template <template \<typename> class T> class array)
11647 /// has been parsed. S is the current scope.
11648 NamedDecl *ActOnTemplateTemplateParameter(
11649 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind,
11650 bool TypenameKeyword, TemplateParameterList *Params,
11651 SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11652 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11653 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11654
11655 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11656 /// constrained by RequiresClause, that contains the template parameters in
11657 /// Params.
11658 TemplateParameterList *ActOnTemplateParameterList(
11659 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11660 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11661 SourceLocation RAngleLoc, Expr *RequiresClause);
11662
11663 /// The context in which we are checking a template parameter list.
11664 enum TemplateParamListContext {
11665 // For this context, Class, Variable, TypeAlias, and non-pack Template
11666 // Template Parameters are treated uniformly.
11667 TPC_Other,
11668
11669 TPC_FunctionTemplate,
11670 TPC_ClassTemplateMember,
11671 TPC_FriendClassTemplate,
11672 TPC_FriendFunctionTemplate,
11673 TPC_FriendFunctionTemplateDefinition,
11674 TPC_TemplateTemplateParameterPack,
11675 };
11676
11677 /// Checks the validity of a template parameter list, possibly
11678 /// considering the template parameter list from a previous
11679 /// declaration.
11680 ///
11681 /// If an "old" template parameter list is provided, it must be
11682 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11683 /// template parameter list.
11684 ///
11685 /// \param NewParams Template parameter list for a new template
11686 /// declaration. This template parameter list will be updated with any
11687 /// default arguments that are carried through from the previous
11688 /// template parameter list.
11689 ///
11690 /// \param OldParams If provided, template parameter list from a
11691 /// previous declaration of the same template. Default template
11692 /// arguments will be merged from the old template parameter list to
11693 /// the new template parameter list.
11694 ///
11695 /// \param TPC Describes the context in which we are checking the given
11696 /// template parameter list.
11697 ///
11698 /// \param SkipBody If we might have already made a prior merged definition
11699 /// of this template visible, the corresponding body-skipping information.
11700 /// Default argument redefinition is not an error when skipping such a body,
11701 /// because (under the ODR) we can assume the default arguments are the same
11702 /// as the prior merged definition.
11703 ///
11704 /// \returns true if an error occurred, false otherwise.
11705 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
11706 TemplateParameterList *OldParams,
11707 TemplateParamListContext TPC,
11708 SkipBodyInfo *SkipBody = nullptr);
11709
11710 /// Match the given template parameter lists to the given scope
11711 /// specifier, returning the template parameter list that applies to the
11712 /// name.
11713 ///
11714 /// \param DeclStartLoc the start of the declaration that has a scope
11715 /// specifier or a template parameter list.
11716 ///
11717 /// \param DeclLoc The location of the declaration itself.
11718 ///
11719 /// \param SS the scope specifier that will be matched to the given template
11720 /// parameter lists. This scope specifier precedes a qualified name that is
11721 /// being declared.
11722 ///
11723 /// \param TemplateId The template-id following the scope specifier, if there
11724 /// is one. Used to check for a missing 'template<>'.
11725 ///
11726 /// \param ParamLists the template parameter lists, from the outermost to the
11727 /// innermost template parameter lists.
11728 ///
11729 /// \param IsFriend Whether to apply the slightly different rules for
11730 /// matching template parameters to scope specifiers in friend
11731 /// declarations.
11732 ///
11733 /// \param IsMemberSpecialization will be set true if the scope specifier
11734 /// denotes a fully-specialized type, and therefore this is a declaration of
11735 /// a member specialization.
11736 ///
11737 /// \returns the template parameter list, if any, that corresponds to the
11738 /// name that is preceded by the scope specifier @p SS. This template
11739 /// parameter list may have template parameters (if we're declaring a
11740 /// template) or may have no template parameters (if we're declaring a
11741 /// template specialization), or may be NULL (if what we're declaring isn't
11742 /// itself a template).
11743 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
11744 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11745 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11746 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11747 bool &IsMemberSpecialization, bool &Invalid,
11748 bool SuppressDiagnostic = false);
11749
11750 /// Returns the template parameter list with all default template argument
11751 /// information.
11752 TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD);
11753
11754 DeclResult CheckClassTemplate(
11755 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11756 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11757 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11758 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11759 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11760 TemplateParameterList **OuterTemplateParamLists,
11761 SkipBodyInfo *SkipBody = nullptr);
11762
11763 /// Translates template arguments as provided by the parser
11764 /// into template arguments used by semantic analysis.
11765 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
11766 TemplateArgumentListInfo &Out);
11767
11768 /// Convert a parsed type into a parsed template argument. This is mostly
11769 /// trivial, except that we may have parsed a C++17 deduced class template
11770 /// specialization type, in which case we should form a template template
11771 /// argument instead of a type template argument.
11772 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
11773
11774 void NoteAllFoundTemplates(TemplateName Name);
11775
11776 QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
11777 TemplateName Template,
11778 SourceLocation TemplateLoc,
11779 TemplateArgumentListInfo &TemplateArgs,
11780 Scope *Scope, bool ForNestedNameSpecifier);
11781
11782 TypeResult
11783 ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
11784 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
11785 SourceLocation TemplateKWLoc, TemplateTy Template,
11786 const IdentifierInfo *TemplateII,
11787 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11788 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11789 bool IsCtorOrDtorName = false, bool IsClassName = false,
11790 ImplicitTypenameContext AllowImplicitTypename =
11791 ImplicitTypenameContext::No);
11792
11793 /// Parsed an elaborated-type-specifier that refers to a template-id,
11794 /// such as \c class T::template apply<U>.
11795 TypeResult ActOnTagTemplateIdType(
11796 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11797 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11798 SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11799 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11800
11801 DeclResult ActOnVarTemplateSpecialization(
11802 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
11803 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11804 StorageClass SC, bool IsPartialSpecialization);
11805
11806 /// Get the specialization of the given variable template corresponding to
11807 /// the specified argument list, or a null-but-valid result if the arguments
11808 /// are dependent.
11809 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
11810 SourceLocation TemplateLoc,
11811 SourceLocation TemplateNameLoc,
11812 const TemplateArgumentListInfo &TemplateArgs,
11813 bool SetWrittenArgs);
11814
11815 /// Form a reference to the specialization of the given variable template
11816 /// corresponding to the specified argument list, or a null-but-valid result
11817 /// if the arguments are dependent.
11818 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
11819 const DeclarationNameInfo &NameInfo,
11820 VarTemplateDecl *Template, NamedDecl *FoundD,
11821 SourceLocation TemplateLoc,
11822 const TemplateArgumentListInfo *TemplateArgs);
11823
11824 ExprResult CheckVarOrConceptTemplateTemplateId(
11825 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
11826 TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc,
11827 const TemplateArgumentListInfo *TemplateArgs);
11828
11829 ExprResult
11830 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11831 const DeclarationNameInfo &ConceptNameInfo,
11832 NamedDecl *FoundDecl, TemplateDecl *NamedConcept,
11833 const TemplateArgumentListInfo *TemplateArgs,
11834 bool DoCheckConstraintSatisfaction = true);
11835
11836 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
11837 void diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
11838 bool TemplateKeyword, TemplateDecl *TD,
11839 SourceLocation Loc);
11840
11841 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
11842 SourceLocation TemplateKWLoc, LookupResult &R,
11843 bool RequiresADL,
11844 const TemplateArgumentListInfo *TemplateArgs);
11845
11846 // We actually only call this from template instantiation.
11847 ExprResult
11848 BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11849 const DeclarationNameInfo &NameInfo,
11850 const TemplateArgumentListInfo *TemplateArgs,
11851 bool IsAddressOfOperand);
11852
11853 UnsignedOrNone getPackIndex(TemplateArgument Pack) const {
11854 return Pack.pack_size() - 1 - *ArgPackSubstIndex;
11855 }
11856
11857 TemplateArgument
11858 getPackSubstitutedTemplateArgument(TemplateArgument Arg) const {
11859 Arg = Arg.pack_elements()[*ArgPackSubstIndex];
11860 if (Arg.isPackExpansion())
11861 Arg = Arg.getPackExpansionPattern();
11862 return Arg;
11863 }
11864
11865 ExprResult BuildSubstNonTypeTemplateParmExpr(
11866 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP,
11867 SourceLocation loc, TemplateArgument Replacement,
11868 UnsignedOrNone PackIndex, bool Final);
11869
11870 /// Form a template name from a name that is syntactically required to name a
11871 /// template, either due to use of the 'template' keyword or because a name in
11872 /// this syntactic context is assumed to name a template (C++
11873 /// [temp.names]p2-4).
11874 ///
11875 /// This action forms a template name given the name of the template and its
11876 /// optional scope specifier. This is used when the 'template' keyword is used
11877 /// or when the parsing context unambiguously treats a following '<' as
11878 /// introducing a template argument list. Note that this may produce a
11879 /// non-dependent template name if we can perform the lookup now and identify
11880 /// the named template.
11881 ///
11882 /// For example, given "x.MetaFun::template apply", the scope specifier
11883 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
11884 /// of the "template" keyword, and "apply" is the \p Name.
11885 TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS,
11886 SourceLocation TemplateKWLoc,
11887 const UnqualifiedId &Name,
11888 ParsedType ObjectType,
11889 bool EnteringContext, TemplateTy &Template,
11890 bool AllowInjectedClassName = false);
11891
11892 DeclResult ActOnClassTemplateSpecialization(
11893 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11894 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
11895 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
11896 MultiTemplateParamsArg TemplateParameterLists,
11897 SkipBodyInfo *SkipBody = nullptr);
11898
11899 /// Check the non-type template arguments of a class template
11900 /// partial specialization according to C++ [temp.class.spec]p9.
11901 ///
11902 /// \param TemplateNameLoc the location of the template name.
11903 /// \param PrimaryTemplate the template parameters of the primary class
11904 /// template.
11905 /// \param NumExplicit the number of explicitly-specified template arguments.
11906 /// \param TemplateArgs the template arguments of the class template
11907 /// partial specialization.
11908 ///
11909 /// \returns \c true if there was an error, \c false otherwise.
11910 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
11911 TemplateDecl *PrimaryTemplate,
11912 unsigned NumExplicitArgs,
11913 ArrayRef<TemplateArgument> Args);
11914 void CheckTemplatePartialSpecialization(
11915 ClassTemplatePartialSpecializationDecl *Partial);
11916 void CheckTemplatePartialSpecialization(
11917 VarTemplatePartialSpecializationDecl *Partial);
11918
11919 Decl *ActOnTemplateDeclarator(Scope *S,
11920 MultiTemplateParamsArg TemplateParameterLists,
11921 Declarator &D);
11922
11923 /// Diagnose cases where we have an explicit template specialization
11924 /// before/after an explicit template instantiation, producing diagnostics
11925 /// for those cases where they are required and determining whether the
11926 /// new specialization/instantiation will have any effect.
11927 ///
11928 /// \param NewLoc the location of the new explicit specialization or
11929 /// instantiation.
11930 ///
11931 /// \param NewTSK the kind of the new explicit specialization or
11932 /// instantiation.
11933 ///
11934 /// \param PrevDecl the previous declaration of the entity.
11935 ///
11936 /// \param PrevTSK the kind of the old explicit specialization or
11937 /// instantiatin.
11938 ///
11939 /// \param PrevPointOfInstantiation if valid, indicates where the previous
11940 /// declaration was instantiated (either implicitly or explicitly).
11941 ///
11942 /// \param HasNoEffect will be set to true to indicate that the new
11943 /// specialization or instantiation has no effect and should be ignored.
11944 ///
11945 /// \returns true if there was an error that should prevent the introduction
11946 /// of the new declaration into the AST, false otherwise.
11947 bool CheckSpecializationInstantiationRedecl(
11948 SourceLocation NewLoc,
11949 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
11950 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
11951 SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
11952
11953 /// Perform semantic analysis for the given dependent function
11954 /// template specialization.
11955 ///
11956 /// The only possible way to get a dependent function template specialization
11957 /// is with a friend declaration, like so:
11958 ///
11959 /// \code
11960 /// template \<class T> void foo(T);
11961 /// template \<class T> class A {
11962 /// friend void foo<>(T);
11963 /// };
11964 /// \endcode
11965 ///
11966 /// There really isn't any useful analysis we can do here, so we
11967 /// just store the information.
11968 bool CheckDependentFunctionTemplateSpecialization(
11969 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
11970 LookupResult &Previous);
11971
11972 /// Perform semantic analysis for the given function template
11973 /// specialization.
11974 ///
11975 /// This routine performs all of the semantic analysis required for an
11976 /// explicit function template specialization. On successful completion,
11977 /// the function declaration \p FD will become a function template
11978 /// specialization.
11979 ///
11980 /// \param FD the function declaration, which will be updated to become a
11981 /// function template specialization.
11982 ///
11983 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
11984 /// if any. Note that this may be valid info even when 0 arguments are
11985 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
11986 /// as it anyway contains info on the angle brackets locations.
11987 ///
11988 /// \param Previous the set of declarations that may be specialized by
11989 /// this function specialization.
11990 ///
11991 /// \param QualifiedFriend whether this is a lookup for a qualified friend
11992 /// declaration with no explicit template argument list that might be
11993 /// befriending a function template specialization.
11994 bool CheckFunctionTemplateSpecialization(
11995 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
11996 LookupResult &Previous, bool QualifiedFriend = false);
11997
11998 /// Perform semantic analysis for the given non-template member
11999 /// specialization.
12000 ///
12001 /// This routine performs all of the semantic analysis required for an
12002 /// explicit member function specialization. On successful completion,
12003 /// the function declaration \p FD will become a member function
12004 /// specialization.
12005 ///
12006 /// \param Member the member declaration, which will be updated to become a
12007 /// specialization.
12008 ///
12009 /// \param Previous the set of declarations, one of which may be specialized
12010 /// by this function specialization; the set will be modified to contain the
12011 /// redeclared member.
12012 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12013 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12014
12015 // Explicit instantiation of a class template specialization
12016 DeclResult ActOnExplicitInstantiation(
12017 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
12018 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
12019 TemplateTy Template, SourceLocation TemplateNameLoc,
12020 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
12021 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
12022
12023 // Explicit instantiation of a member class of a class template.
12024 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12025 SourceLocation TemplateLoc,
12026 unsigned TagSpec, SourceLocation KWLoc,
12027 CXXScopeSpec &SS, IdentifierInfo *Name,
12028 SourceLocation NameLoc,
12029 const ParsedAttributesView &Attr);
12030
12031 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12032 SourceLocation TemplateLoc,
12033 Declarator &D);
12034
12035 /// If the given template parameter has a default template
12036 /// argument, substitute into that default template argument and
12037 /// return the corresponding template argument.
12038 TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(
12039 TemplateDecl *Template, SourceLocation TemplateKWLoc,
12040 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
12041 ArrayRef<TemplateArgument> SugaredConverted,
12042 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
12043
12044 /// Returns the top most location responsible for the definition of \p N.
12045 /// If \p N is a a template specialization, this is the location
12046 /// of the top of the instantiation stack.
12047 /// Otherwise, the location of \p N is returned.
12048 SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const;
12049
12050 /// Specifies the context in which a particular template
12051 /// argument is being checked.
12052 enum CheckTemplateArgumentKind {
12053 /// The template argument was specified in the code or was
12054 /// instantiated with some deduced template arguments.
12055 CTAK_Specified,
12056
12057 /// The template argument was deduced via template argument
12058 /// deduction.
12059 CTAK_Deduced,
12060
12061 /// The template argument was deduced from an array bound
12062 /// via template argument deduction.
12063 CTAK_DeducedFromArrayBound
12064 };
12065
12066 struct CheckTemplateArgumentInfo {
12067 explicit CheckTemplateArgumentInfo(bool PartialOrdering = false,
12068 bool MatchingTTP = false)
12069 : PartialOrdering(PartialOrdering), MatchingTTP(MatchingTTP) {}
12070 CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &) = delete;
12071 CheckTemplateArgumentInfo &
12072 operator=(const CheckTemplateArgumentInfo &) = delete;
12073
12074 /// The checked, converted argument will be added to the
12075 /// end of these vectors.
12076 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
12077
12078 /// The check is being performed in the context of partial ordering.
12079 bool PartialOrdering;
12080
12081 /// If true, assume these template arguments are
12082 /// the injected template arguments for a template template parameter.
12083 /// This will relax the requirement that all its possible uses are valid:
12084 /// TTP checking is loose, and assumes that invalid uses will be diagnosed
12085 /// during instantiation.
12086 bool MatchingTTP;
12087
12088 /// Is set to true when, in the context of TTP matching, a pack parameter
12089 /// matches non-pack arguments.
12090 bool StrictPackMatch = false;
12091 };
12092
12093 /// Check that the given template argument corresponds to the given
12094 /// template parameter.
12095 ///
12096 /// \param Param The template parameter against which the argument will be
12097 /// checked.
12098 ///
12099 /// \param Arg The template argument, which may be updated due to conversions.
12100 ///
12101 /// \param Template The template in which the template argument resides.
12102 ///
12103 /// \param TemplateLoc The location of the template name for the template
12104 /// whose argument list we're matching.
12105 ///
12106 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
12107 /// the template argument list.
12108 ///
12109 /// \param ArgumentPackIndex The index into the argument pack where this
12110 /// argument will be placed. Only valid if the parameter is a parameter pack.
12111 ///
12112 /// \param CTAK Describes how we arrived at this particular template argument:
12113 /// explicitly written, deduced, etc.
12114 ///
12115 /// \returns true on error, false otherwise.
12116 bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
12117 NamedDecl *Template, SourceLocation TemplateLoc,
12118 SourceLocation RAngleLoc,
12119 unsigned ArgumentPackIndex,
12120 CheckTemplateArgumentInfo &CTAI,
12121 CheckTemplateArgumentKind CTAK);
12122
12123 /// Check that the given template arguments can be provided to
12124 /// the given template, converting the arguments along the way.
12125 ///
12126 /// \param Template The template to which the template arguments are being
12127 /// provided.
12128 ///
12129 /// \param TemplateLoc The location of the template name in the source.
12130 ///
12131 /// \param TemplateArgs The list of template arguments. If the template is
12132 /// a template template parameter, this function may extend the set of
12133 /// template arguments to also include substituted, defaulted template
12134 /// arguments.
12135 ///
12136 /// \param PartialTemplateArgs True if the list of template arguments is
12137 /// intentionally partial, e.g., because we're checking just the initial
12138 /// set of template arguments.
12139 ///
12140 /// \param Converted Will receive the converted, canonicalized template
12141 /// arguments.
12142 ///
12143 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
12144 /// contain the converted forms of the template arguments as written.
12145 /// Otherwise, \p TemplateArgs will not be modified.
12146 ///
12147 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
12148 /// receive true if the cause for the error is the associated constraints of
12149 /// the template not being satisfied by the template arguments.
12150 ///
12151 /// \param DefaultArgs any default arguments from template specialization
12152 /// deduction.
12153 ///
12154 /// \returns true if an error occurred, false otherwise.
12155 bool CheckTemplateArgumentList(TemplateDecl *Template,
12156 SourceLocation TemplateLoc,
12157 TemplateArgumentListInfo &TemplateArgs,
12158 const DefaultArguments &DefaultArgs,
12159 bool PartialTemplateArgs,
12160 CheckTemplateArgumentInfo &CTAI,
12161 bool UpdateArgsWithConversions = true,
12162 bool *ConstraintsNotSatisfied = nullptr);
12163
12164 bool CheckTemplateArgumentList(
12165 TemplateDecl *Template, TemplateParameterList *Params,
12166 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
12167 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
12168 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions = true,
12169 bool *ConstraintsNotSatisfied = nullptr);
12170
12171 bool CheckTemplateTypeArgument(
12172 TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
12173 SmallVectorImpl<TemplateArgument> &SugaredConverted,
12174 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
12175
12176 /// Check a template argument against its corresponding
12177 /// template type parameter.
12178 ///
12179 /// This routine implements the semantics of C++ [temp.arg.type]. It
12180 /// returns true if an error occurred, and false otherwise.
12181 bool CheckTemplateArgument(TypeSourceInfo *Arg);
12182
12183 /// Check a template argument against its corresponding
12184 /// non-type template parameter.
12185 ///
12186 /// This routine implements the semantics of C++ [temp.arg.nontype].
12187 /// If an error occurred, it returns ExprError(); otherwise, it
12188 /// returns the converted template argument. \p ParamType is the
12189 /// type of the non-type template parameter after it has been instantiated.
12190 ExprResult CheckTemplateArgument(NamedDecl *Param,
12191 QualType InstantiatedParamType, Expr *Arg,
12192 TemplateArgument &SugaredConverted,
12193 TemplateArgument &CanonicalConverted,
12194 bool StrictCheck,
12195 CheckTemplateArgumentKind CTAK);
12196
12197 /// Check a template argument against its corresponding
12198 /// template template parameter.
12199 ///
12200 /// This routine implements the semantics of C++ [temp.arg.template].
12201 /// It returns true if an error occurred, and false otherwise.
12202 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
12203 TemplateParameterList *Params,
12204 TemplateArgumentLoc &Arg,
12205 bool PartialOrdering,
12206 bool *StrictPackMatch);
12207
12208 bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template,
12209 TemplateTemplateParmDecl *Param,
12210 const TemplateArgumentLoc &Arg);
12211
12212 void NoteTemplateLocation(const NamedDecl &Decl,
12213 std::optional<SourceRange> ParamRange = {});
12214 void NoteTemplateParameterLocation(const NamedDecl &Decl);
12215
12216 /// Given a non-type template argument that refers to a
12217 /// declaration and the type of its corresponding non-type template
12218 /// parameter, produce an expression that properly refers to that
12219 /// declaration.
12220 /// FIXME: This is used in some contexts where the resulting expression
12221 /// doesn't need to live too long. It would be useful if this function
12222 /// could return a temporary expression.
12223 ExprResult BuildExpressionFromDeclTemplateArgument(
12224 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
12225 NamedDecl *TemplateParam = nullptr);
12226 ExprResult
12227 BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
12228 SourceLocation Loc);
12229
12230 /// Enumeration describing how template parameter lists are compared
12231 /// for equality.
12232 enum TemplateParameterListEqualKind {
12233 /// We are matching the template parameter lists of two templates
12234 /// that might be redeclarations.
12235 ///
12236 /// \code
12237 /// template<typename T> struct X;
12238 /// template<typename T> struct X;
12239 /// \endcode
12240 TPL_TemplateMatch,
12241
12242 /// We are matching the template parameter lists of two template
12243 /// template parameters as part of matching the template parameter lists
12244 /// of two templates that might be redeclarations.
12245 ///
12246 /// \code
12247 /// template<template<int I> class TT> struct X;
12248 /// template<template<int Value> class Other> struct X;
12249 /// \endcode
12250 TPL_TemplateTemplateParmMatch,
12251
12252 /// We are determining whether the template-parameters are equivalent
12253 /// according to C++ [temp.over.link]/6. This comparison does not consider
12254 /// constraints.
12255 ///
12256 /// \code
12257 /// template<C1 T> void f(T);
12258 /// template<C2 T> void f(T);
12259 /// \endcode
12260 TPL_TemplateParamsEquivalent,
12261 };
12262
12263 // A struct to represent the 'new' declaration, which is either itself just
12264 // the named decl, or the important information we need about it in order to
12265 // do constraint comparisons.
12266 class TemplateCompareNewDeclInfo {
12267 const NamedDecl *ND = nullptr;
12268 const DeclContext *DC = nullptr;
12269 const DeclContext *LexicalDC = nullptr;
12270 SourceLocation Loc;
12271
12272 public:
12273 TemplateCompareNewDeclInfo(const NamedDecl *ND) : ND(ND) {}
12274 TemplateCompareNewDeclInfo(const DeclContext *DeclCtx,
12275 const DeclContext *LexicalDeclCtx,
12276 SourceLocation Loc)
12277
12278 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12279 assert(DC && LexicalDC &&
12280 "Constructor only for cases where we have the information to put "
12281 "in here");
12282 }
12283
12284 // If this was constructed with no information, we cannot do substitution
12285 // for constraint comparison, so make sure we can check that.
12286 bool isInvalid() const { return !ND && !DC; }
12287
12288 const NamedDecl *getDecl() const { return ND; }
12289
12290 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12291
12292 const DeclContext *getLexicalDeclContext() const {
12293 return ND ? ND->getLexicalDeclContext() : LexicalDC;
12294 }
12295
12296 const DeclContext *getDeclContext() const {
12297 return ND ? ND->getDeclContext() : DC;
12298 }
12299
12300 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12301 };
12302
12303 /// Determine whether the given template parameter lists are
12304 /// equivalent.
12305 ///
12306 /// \param New The new template parameter list, typically written in the
12307 /// source code as part of a new template declaration.
12308 ///
12309 /// \param Old The old template parameter list, typically found via
12310 /// name lookup of the template declared with this template parameter
12311 /// list.
12312 ///
12313 /// \param Complain If true, this routine will produce a diagnostic if
12314 /// the template parameter lists are not equivalent.
12315 ///
12316 /// \param Kind describes how we are to match the template parameter lists.
12317 ///
12318 /// \param TemplateArgLoc If this source location is valid, then we
12319 /// are actually checking the template parameter list of a template
12320 /// argument (New) against the template parameter list of its
12321 /// corresponding template template parameter (Old). We produce
12322 /// slightly different diagnostics in this scenario.
12323 ///
12324 /// \returns True if the template parameter lists are equal, false
12325 /// otherwise.
12326 bool TemplateParameterListsAreEqual(
12327 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12328 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12329 TemplateParameterListEqualKind Kind,
12330 SourceLocation TemplateArgLoc = SourceLocation());
12331
12332 bool TemplateParameterListsAreEqual(
12333 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12334 TemplateParameterListEqualKind Kind,
12335 SourceLocation TemplateArgLoc = SourceLocation()) {
12336 return TemplateParameterListsAreEqual(NewInstFrom: nullptr, New, OldInstFrom: nullptr, Old, Complain,
12337 Kind, TemplateArgLoc);
12338 }
12339
12340 /// Check whether a template can be declared within this scope.
12341 ///
12342 /// If the template declaration is valid in this scope, returns
12343 /// false. Otherwise, issues a diagnostic and returns true.
12344 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12345
12346 /// Called when the parser has parsed a C++ typename
12347 /// specifier, e.g., "typename T::type".
12348 ///
12349 /// \param S The scope in which this typename type occurs.
12350 /// \param TypenameLoc the location of the 'typename' keyword
12351 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12352 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12353 /// \param IdLoc the location of the identifier.
12354 /// \param IsImplicitTypename context where T::type refers to a type.
12355 TypeResult ActOnTypenameType(
12356 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12357 const IdentifierInfo &II, SourceLocation IdLoc,
12358 ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No);
12359
12360 /// Called when the parser has parsed a C++ typename
12361 /// specifier that ends in a template-id, e.g.,
12362 /// "typename MetaFun::template apply<T1, T2>".
12363 ///
12364 /// \param S The scope in which this typename type occurs.
12365 /// \param TypenameLoc the location of the 'typename' keyword
12366 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12367 /// \param TemplateLoc the location of the 'template' keyword, if any.
12368 /// \param TemplateName The template name.
12369 /// \param TemplateII The identifier used to name the template.
12370 /// \param TemplateIILoc The location of the template name.
12371 /// \param LAngleLoc The location of the opening angle bracket ('<').
12372 /// \param TemplateArgs The template arguments.
12373 /// \param RAngleLoc The location of the closing angle bracket ('>').
12374 TypeResult
12375 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12376 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12377 TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12378 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12379 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12380
12381 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12382 SourceLocation KeywordLoc,
12383 NestedNameSpecifierLoc QualifierLoc,
12384 const IdentifierInfo &II, SourceLocation IILoc,
12385 TypeSourceInfo **TSI, bool DeducedTSTContext);
12386
12387 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12388 SourceLocation KeywordLoc,
12389 NestedNameSpecifierLoc QualifierLoc,
12390 const IdentifierInfo &II, SourceLocation IILoc,
12391 bool DeducedTSTContext = true);
12392
12393 /// Rebuilds a type within the context of the current instantiation.
12394 ///
12395 /// The type \p T is part of the type of an out-of-line member definition of
12396 /// a class template (or class template partial specialization) that was
12397 /// parsed and constructed before we entered the scope of the class template
12398 /// (or partial specialization thereof). This routine will rebuild that type
12399 /// now that we have entered the declarator's scope, which may produce
12400 /// different canonical types, e.g.,
12401 ///
12402 /// \code
12403 /// template<typename T>
12404 /// struct X {
12405 /// typedef T* pointer;
12406 /// pointer data();
12407 /// };
12408 ///
12409 /// template<typename T>
12410 /// typename X<T>::pointer X<T>::data() { ... }
12411 /// \endcode
12412 ///
12413 /// Here, the type "typename X<T>::pointer" will be created as a
12414 /// DependentNameType, since we do not know that we can look into X<T> when we
12415 /// parsed the type. This function will rebuild the type, performing the
12416 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12417 /// canonical type is the same as the canonical type of T*, allowing the
12418 /// return types of the out-of-line definition and the declaration to match.
12419 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
12420 SourceLocation Loc,
12421 DeclarationName Name);
12422 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
12423
12424 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
12425
12426 /// Rebuild the template parameters now that we know we're in a current
12427 /// instantiation.
12428 bool
12429 RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params);
12430
12431 /// Produces a formatted string that describes the binding of
12432 /// template parameters to template arguments.
12433 std::string
12434 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12435 const TemplateArgumentList &Args);
12436
12437 std::string
12438 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12439 const TemplateArgument *Args,
12440 unsigned NumArgs);
12441
12442 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
12443 SourceLocation Less,
12444 SourceLocation Greater);
12445
12446 /// ActOnDependentIdExpression - Handle a dependent id-expression that
12447 /// was just parsed. This is only possible with an explicit scope
12448 /// specifier naming a dependent type.
12449 ExprResult ActOnDependentIdExpression(
12450 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12451 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12452 const TemplateArgumentListInfo *TemplateArgs);
12453
12454 ExprResult
12455 BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
12456 SourceLocation TemplateKWLoc,
12457 const DeclarationNameInfo &NameInfo,
12458 const TemplateArgumentListInfo *TemplateArgs);
12459
12460 // Calculates whether the expression Constraint depends on an enclosing
12461 // template, for the purposes of [temp.friend] p9.
12462 // TemplateDepth is the 'depth' of the friend function, which is used to
12463 // compare whether a declaration reference is referring to a containing
12464 // template, or just the current friend function. A 'lower' TemplateDepth in
12465 // the AST refers to a 'containing' template. As the constraint is
12466 // uninstantiated, this is relative to the 'top' of the TU.
12467 bool
12468 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
12469 unsigned TemplateDepth,
12470 const Expr *Constraint);
12471
12472 /// Find the failed Boolean condition within a given Boolean
12473 /// constant expression, and describe it with a string.
12474 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12475
12476 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
12477
12478 ConceptDecl *ActOnStartConceptDefinition(
12479 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12480 const IdentifierInfo *Name, SourceLocation NameLoc);
12481
12482 ConceptDecl *ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
12483 Expr *ConstraintExpr,
12484 const ParsedAttributesView &Attrs);
12485
12486 void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
12487 bool &AddToScope);
12488 bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc);
12489
12490 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12491 const CXXScopeSpec &SS,
12492 const IdentifierInfo *Name,
12493 SourceLocation TagLoc, SourceLocation NameLoc);
12494
12495 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
12496 CachedTokens &Toks);
12497 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
12498 bool IsInsideALocalClassWithinATemplateFunction();
12499
12500 /// We've found a use of a templated declaration that would trigger an
12501 /// implicit instantiation. Check that any relevant explicit specializations
12502 /// and partial specializations are visible/reachable, and diagnose if not.
12503 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
12504 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
12505
12506 ///@}
12507
12508 //
12509 //
12510 // -------------------------------------------------------------------------
12511 //
12512 //
12513
12514 /// \name C++ Template Argument Deduction
12515 /// Implementations are in SemaTemplateDeduction.cpp
12516 ///@{
12517
12518public:
12519 class SFINAETrap;
12520
12521 struct SFINAEContextBase {
12522 SFINAEContextBase(Sema &S, SFINAETrap *Cur)
12523 : S(S), Prev(std::exchange(obj&: S.CurrentSFINAEContext, new_val&: Cur)) {}
12524
12525 protected:
12526 Sema &S;
12527 ~SFINAEContextBase() { S.CurrentSFINAEContext = Prev; }
12528 SFINAEContextBase(const SFINAEContextBase &) = delete;
12529 SFINAEContextBase &operator=(const SFINAEContextBase &) = delete;
12530
12531 private:
12532 SFINAETrap *Prev;
12533 };
12534
12535 struct NonSFINAEContext : SFINAEContextBase {
12536 NonSFINAEContext(Sema &S) : SFINAEContextBase(S, nullptr) {}
12537 };
12538
12539 /// RAII class used to determine whether SFINAE has
12540 /// trapped any errors that occur during template argument
12541 /// deduction.
12542 class SFINAETrap : SFINAEContextBase {
12543 bool HasErrorOcurred = false;
12544 bool WithAccessChecking = false;
12545 bool PrevLastDiagnosticIgnored =
12546 S.getDiagnostics().isLastDiagnosticIgnored();
12547 sema::TemplateDeductionInfo *DeductionInfo = nullptr;
12548
12549 SFINAETrap(Sema &S, sema::TemplateDeductionInfo *Info,
12550 bool WithAccessChecking)
12551 : SFINAEContextBase(S, this), WithAccessChecking(WithAccessChecking),
12552 DeductionInfo(Info) {}
12553
12554 public:
12555 /// \param WithAccessChecking If true, discard all diagnostics (from the
12556 /// immediate context) instead of adding them to the currently active
12557 /// \ref TemplateDeductionInfo.
12558 explicit SFINAETrap(Sema &S, bool WithAccessChecking = false)
12559 : SFINAETrap(S, /*Info=*/nullptr, WithAccessChecking) {}
12560
12561 SFINAETrap(Sema &S, sema::TemplateDeductionInfo &Info)
12562 : SFINAETrap(S, &Info, /*WithAccessChecking=*/false) {}
12563
12564 ~SFINAETrap() {
12565 S.getDiagnostics().setLastDiagnosticIgnored(PrevLastDiagnosticIgnored);
12566 }
12567
12568 SFINAETrap(const SFINAETrap &) = delete;
12569 SFINAETrap &operator=(const SFINAETrap &) = delete;
12570
12571 sema::TemplateDeductionInfo *getDeductionInfo() const {
12572 return DeductionInfo;
12573 }
12574
12575 /// Determine whether any SFINAE errors have been trapped.
12576 bool hasErrorOccurred() const { return HasErrorOcurred; }
12577 void setErrorOccurred() { HasErrorOcurred = true; }
12578
12579 bool withAccessChecking() const { return WithAccessChecking; }
12580 };
12581
12582 /// RAII class used to indicate that we are performing provisional
12583 /// semantic analysis to determine the validity of a construct, so
12584 /// typo-correction and diagnostics in the immediate context (not within
12585 /// implicitly-instantiated templates) should be suppressed.
12586 class TentativeAnalysisScope {
12587 Sema &SemaRef;
12588 // FIXME: Using a SFINAETrap for this is a hack.
12589 SFINAETrap Trap;
12590 bool PrevDisableTypoCorrection;
12591
12592 public:
12593 explicit TentativeAnalysisScope(Sema &SemaRef)
12594 : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12595 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12596 SemaRef.DisableTypoCorrection = true;
12597 }
12598 ~TentativeAnalysisScope() {
12599 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12600 }
12601
12602 TentativeAnalysisScope(const TentativeAnalysisScope &) = delete;
12603 TentativeAnalysisScope &operator=(const TentativeAnalysisScope &) = delete;
12604 };
12605
12606 /// For each declaration that involved template argument deduction, the
12607 /// set of diagnostics that were suppressed during that template argument
12608 /// deduction.
12609 ///
12610 /// FIXME: Serialize this structure to the AST file.
12611 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12612 SuppressedDiagnosticsMap;
12613 SuppressedDiagnosticsMap SuppressedDiagnostics;
12614
12615 /// Compare types for equality with respect to possibly compatible
12616 /// function types (noreturn adjustment, implicit calling conventions). If any
12617 /// of parameter and argument is not a function, just perform type comparison.
12618 ///
12619 /// \param P the template parameter type.
12620 ///
12621 /// \param A the argument type.
12622 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
12623
12624 /// Allocate a TemplateArgumentLoc where all locations have
12625 /// been initialized to the given location.
12626 ///
12627 /// \param Arg The template argument we are producing template argument
12628 /// location information for.
12629 ///
12630 /// \param NTTPType For a declaration template argument, the type of
12631 /// the non-type template parameter that corresponds to this template
12632 /// argument. Can be null if no type sugar is available to add to the
12633 /// type from the template argument.
12634 ///
12635 /// \param Loc The source location to use for the resulting template
12636 /// argument.
12637 TemplateArgumentLoc
12638 getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType,
12639 SourceLocation Loc,
12640 NamedDecl *TemplateParam = nullptr);
12641
12642 /// Get a template argument mapping the given template parameter to itself,
12643 /// e.g. for X in \c template<int X>, this would return an expression template
12644 /// argument referencing X.
12645 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
12646 SourceLocation Location);
12647
12648 /// Adjust the type \p ArgFunctionType to match the calling convention,
12649 /// noreturn, and optionally the exception specification of \p FunctionType.
12650 /// Deduction often wants to ignore these properties when matching function
12651 /// types.
12652 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
12653 bool AdjustExceptionSpec = false);
12654
12655 TemplateDeductionResult
12656 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
12657 ArrayRef<TemplateArgument> TemplateArgs,
12658 sema::TemplateDeductionInfo &Info);
12659
12660 TemplateDeductionResult
12661 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
12662 ArrayRef<TemplateArgument> TemplateArgs,
12663 sema::TemplateDeductionInfo &Info);
12664
12665 /// Deduce the template arguments of the given template from \p FromType.
12666 /// Used to implement the IsDeducible constraint for alias CTAD per C++
12667 /// [over.match.class.deduct]p4.
12668 ///
12669 /// It only supports class or type alias templates.
12670 TemplateDeductionResult
12671 DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType,
12672 sema::TemplateDeductionInfo &Info);
12673
12674 TemplateDeductionResult DeduceTemplateArguments(
12675 TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps,
12676 ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info,
12677 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12678 bool NumberOfArgumentsMustMatch);
12679
12680 /// Substitute the explicitly-provided template arguments into the
12681 /// given function template according to C++ [temp.arg.explicit].
12682 ///
12683 /// \param FunctionTemplate the function template into which the explicit
12684 /// template arguments will be substituted.
12685 ///
12686 /// \param ExplicitTemplateArgs the explicitly-specified template
12687 /// arguments.
12688 ///
12689 /// \param Deduced the deduced template arguments, which will be populated
12690 /// with the converted and checked explicit template arguments.
12691 ///
12692 /// \param ParamTypes will be populated with the instantiated function
12693 /// parameters.
12694 ///
12695 /// \param FunctionType if non-NULL, the result type of the function template
12696 /// will also be instantiated and the pointed-to value will be updated with
12697 /// the instantiated function type.
12698 ///
12699 /// \param Info if substitution fails for any reason, this object will be
12700 /// populated with more information about the failure.
12701 ///
12702 /// \returns TemplateDeductionResult::Success if substitution was successful,
12703 /// or some failure condition.
12704 TemplateDeductionResult SubstituteExplicitTemplateArguments(
12705 FunctionTemplateDecl *FunctionTemplate,
12706 TemplateArgumentListInfo &ExplicitTemplateArgs,
12707 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12708 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
12709 sema::TemplateDeductionInfo &Info);
12710
12711 /// brief A function argument from which we performed template argument
12712 // deduction for a call.
12713 struct OriginalCallArg {
12714 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
12715 unsigned ArgIdx, QualType OriginalArgType)
12716 : OriginalParamType(OriginalParamType),
12717 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
12718 OriginalArgType(OriginalArgType) {}
12719
12720 QualType OriginalParamType;
12721 bool DecomposedParam;
12722 unsigned ArgIdx;
12723 QualType OriginalArgType;
12724 };
12725
12726 /// Finish template argument deduction for a function template,
12727 /// checking the deduced template arguments for completeness and forming
12728 /// the function template specialization.
12729 ///
12730 /// \param OriginalCallArgs If non-NULL, the original call arguments against
12731 /// which the deduced argument types should be compared.
12732 /// \param CheckNonDependent Callback before substituting into the declaration
12733 /// with the deduced template arguments.
12734 /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12735 /// some breakages introduced by CWG2369, where non-user-defined conversions
12736 /// are checked first before the constraints.
12737 TemplateDeductionResult FinishTemplateArgumentDeduction(
12738 FunctionTemplateDecl *FunctionTemplate,
12739 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12740 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12741 sema::TemplateDeductionInfo &Info,
12742 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12743 bool PartialOverloading, bool PartialOrdering,
12744 bool ForOverloadSetAddressResolution,
12745 llvm::function_ref<bool(bool)> CheckNonDependent =
12746 [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12747 return false;
12748 });
12749
12750 /// Perform template argument deduction from a function call
12751 /// (C++ [temp.deduct.call]).
12752 ///
12753 /// \param FunctionTemplate the function template for which we are performing
12754 /// template argument deduction.
12755 ///
12756 /// \param ExplicitTemplateArgs the explicit template arguments provided
12757 /// for this call.
12758 ///
12759 /// \param Args the function call arguments
12760 ///
12761 /// \param Specialization if template argument deduction was successful,
12762 /// this will be set to the function template specialization produced by
12763 /// template argument deduction.
12764 ///
12765 /// \param Info the argument will be updated to provide additional information
12766 /// about template argument deduction.
12767 ///
12768 /// \param CheckNonDependent A callback to invoke to check conversions for
12769 /// non-dependent parameters, between deduction and substitution, per DR1391.
12770 /// If this returns true, substitution will be skipped and we return
12771 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12772 /// passed the parameter types (after substituting explicit template
12773 /// arguments).
12774 ///
12775 /// \returns the result of template argument deduction.
12776 TemplateDeductionResult DeduceTemplateArguments(
12777 FunctionTemplateDecl *FunctionTemplate,
12778 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12779 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12780 bool PartialOverloading, bool AggregateDeductionCandidate,
12781 bool PartialOrdering, QualType ObjectType,
12782 Expr::Classification ObjectClassification,
12783 bool ForOverloadSetAddressResolution,
12784 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12785
12786 /// Deduce template arguments when taking the address of a function
12787 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12788 /// a template.
12789 ///
12790 /// \param FunctionTemplate the function template for which we are performing
12791 /// template argument deduction.
12792 ///
12793 /// \param ExplicitTemplateArgs the explicitly-specified template
12794 /// arguments.
12795 ///
12796 /// \param ArgFunctionType the function type that will be used as the
12797 /// "argument" type (A) when performing template argument deduction from the
12798 /// function template's function type. This type may be NULL, if there is no
12799 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
12800 ///
12801 /// \param Specialization if template argument deduction was successful,
12802 /// this will be set to the function template specialization produced by
12803 /// template argument deduction.
12804 ///
12805 /// \param Info the argument will be updated to provide additional information
12806 /// about template argument deduction.
12807 ///
12808 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12809 /// the address of a function template per [temp.deduct.funcaddr] and
12810 /// [over.over]. If \c false, we are looking up a function template
12811 /// specialization based on its signature, per [temp.deduct.decl].
12812 ///
12813 /// \returns the result of template argument deduction.
12814 TemplateDeductionResult DeduceTemplateArguments(
12815 FunctionTemplateDecl *FunctionTemplate,
12816 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
12817 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12818 bool IsAddressOfFunction = false);
12819
12820 /// Deduce template arguments for a templated conversion
12821 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
12822 /// conversion function template specialization.
12823 TemplateDeductionResult DeduceTemplateArguments(
12824 FunctionTemplateDecl *FunctionTemplate, QualType ObjectType,
12825 Expr::Classification ObjectClassification, QualType ToType,
12826 CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info);
12827
12828 /// Deduce template arguments for a function template when there is
12829 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
12830 ///
12831 /// \param FunctionTemplate the function template for which we are performing
12832 /// template argument deduction.
12833 ///
12834 /// \param ExplicitTemplateArgs the explicitly-specified template
12835 /// arguments.
12836 ///
12837 /// \param Specialization if template argument deduction was successful,
12838 /// this will be set to the function template specialization produced by
12839 /// template argument deduction.
12840 ///
12841 /// \param Info the argument will be updated to provide additional information
12842 /// about template argument deduction.
12843 ///
12844 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12845 /// the address of a function template in a context where we do not have a
12846 /// target type, per [over.over]. If \c false, we are looking up a function
12847 /// template specialization based on its signature, which only happens when
12848 /// deducing a function parameter type from an argument that is a template-id
12849 /// naming a function template specialization.
12850 ///
12851 /// \returns the result of template argument deduction.
12852 TemplateDeductionResult
12853 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
12854 TemplateArgumentListInfo *ExplicitTemplateArgs,
12855 FunctionDecl *&Specialization,
12856 sema::TemplateDeductionInfo &Info,
12857 bool IsAddressOfFunction = false);
12858
12859 /// Substitute Replacement for \p auto in \p TypeWithAuto
12860 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
12861 /// Substitute Replacement for auto in TypeWithAuto
12862 TypeSourceInfo *SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12863 QualType Replacement);
12864
12865 // Substitute auto in TypeWithAuto for a Dependent auto type
12866 QualType SubstAutoTypeDependent(QualType TypeWithAuto);
12867
12868 // Substitute auto in TypeWithAuto for a Dependent auto type
12869 TypeSourceInfo *
12870 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
12871
12872 /// Completely replace the \c auto in \p TypeWithAuto by
12873 /// \p Replacement. This does not retain any \c auto type sugar.
12874 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
12875 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12876 QualType Replacement);
12877
12878 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
12879 ///
12880 /// Note that this is done even if the initializer is dependent. (This is
12881 /// necessary to support partial ordering of templates using 'auto'.)
12882 /// A dependent type will be produced when deducing from a dependent type.
12883 ///
12884 /// \param Type the type pattern using the auto type-specifier.
12885 /// \param Init the initializer for the variable whose type is to be deduced.
12886 /// \param Result if type deduction was successful, this will be set to the
12887 /// deduced type.
12888 /// \param Info the argument will be updated to provide additional information
12889 /// about template argument deduction.
12890 /// \param DependentDeduction Set if we should permit deduction in
12891 /// dependent cases. This is necessary for template partial ordering
12892 /// with 'auto' template parameters. The template parameter depth to be
12893 /// used should be specified in the 'Info' parameter.
12894 /// \param IgnoreConstraints Set if we should not fail if the deduced type
12895 /// does not satisfy the type-constraint in the auto
12896 /// type.
12897 TemplateDeductionResult
12898 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result,
12899 sema::TemplateDeductionInfo &Info,
12900 bool DependentDeduction = false,
12901 bool IgnoreConstraints = false,
12902 TemplateSpecCandidateSet *FailedTSC = nullptr);
12903 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
12904 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
12905 bool Diagnose = true);
12906
12907 bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD,
12908 SourceLocation Loc);
12909
12910 /// Returns the more specialized class template partial specialization
12911 /// according to the rules of partial ordering of class template partial
12912 /// specializations (C++ [temp.class.order]).
12913 ///
12914 /// \param PS1 the first class template partial specialization
12915 ///
12916 /// \param PS2 the second class template partial specialization
12917 ///
12918 /// \returns the more specialized class template partial specialization. If
12919 /// neither partial specialization is more specialized, returns NULL.
12920 ClassTemplatePartialSpecializationDecl *
12921 getMoreSpecializedPartialSpecialization(
12922 ClassTemplatePartialSpecializationDecl *PS1,
12923 ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
12924
12925 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
12926 sema::TemplateDeductionInfo &Info);
12927
12928 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
12929 VarTemplatePartialSpecializationDecl *PS1,
12930 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
12931
12932 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
12933 sema::TemplateDeductionInfo &Info);
12934
12935 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
12936 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
12937 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
12938 bool PartialOrdering, bool *StrictPackMatch);
12939
12940 /// Mark which template parameters are used in a given expression.
12941 ///
12942 /// \param E the expression from which template parameters will be deduced.
12943 ///
12944 /// \param Used a bit vector whose elements will be set to \c true
12945 /// to indicate when the corresponding template parameter will be
12946 /// deduced.
12947 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
12948 unsigned Depth, llvm::SmallBitVector &Used);
12949
12950 /// Mark which template parameters are named in a given expression.
12951 ///
12952 /// Unlike MarkUsedTemplateParameters, this excludes parameter that
12953 /// are used but not directly named by an expression - i.e. it excludes
12954 /// any template parameter that denotes the type of a referenced NTTP.
12955 ///
12956 /// \param Used a bit vector whose elements will be set to \c true
12957 /// to indicate when the corresponding template parameter will be
12958 /// deduced.
12959 void MarkUsedTemplateParametersForSubsumptionParameterMapping(
12960 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used);
12961
12962 /// Mark which template parameters can be deduced from a given
12963 /// template argument list.
12964 ///
12965 /// \param TemplateArgs the template argument list from which template
12966 /// parameters will be deduced.
12967 ///
12968 /// \param Used a bit vector whose elements will be set to \c true
12969 /// to indicate when the corresponding template parameter will be
12970 /// deduced.
12971 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
12972 bool OnlyDeduced, unsigned Depth,
12973 llvm::SmallBitVector &Used);
12974
12975 void MarkUsedTemplateParameters(ArrayRef<TemplateArgument> TemplateArgs,
12976 unsigned Depth, llvm::SmallBitVector &Used);
12977
12978 void MarkUsedTemplateParameters(ArrayRef<TemplateArgumentLoc> TemplateArgs,
12979 unsigned Depth, llvm::SmallBitVector &Used);
12980
12981 void
12982 MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate,
12983 llvm::SmallBitVector &Deduced) {
12984 return MarkDeducedTemplateParameters(Ctx&: Context, FunctionTemplate, Deduced);
12985 }
12986
12987 /// Marks all of the template parameters that will be deduced by a
12988 /// call to the given function template.
12989 static void
12990 MarkDeducedTemplateParameters(ASTContext &Ctx,
12991 const FunctionTemplateDecl *FunctionTemplate,
12992 llvm::SmallBitVector &Deduced);
12993
12994 /// Returns the more specialized function template according
12995 /// to the rules of function template partial ordering (C++
12996 /// [temp.func.order]).
12997 ///
12998 /// \param FT1 the first function template
12999 ///
13000 /// \param FT2 the second function template
13001 ///
13002 /// \param TPOC the context in which we are performing partial ordering of
13003 /// function templates.
13004 ///
13005 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
13006 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
13007 /// when calling a member function.
13008 ///
13009 /// \param RawObj1Ty The type of the object parameter of FT1 if a member
13010 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
13011 /// template from a member function
13012 ///
13013 /// \param RawObj2Ty The type of the object parameter of FT2 if a member
13014 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
13015 /// template from a member function
13016 ///
13017 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
13018 /// candidate with a reversed parameter order. In this case, the corresponding
13019 /// P/A pairs between FT1 and FT2 are reversed.
13020 ///
13021 /// \returns the more specialized function template. If neither
13022 /// template is more specialized, returns NULL.
13023 FunctionTemplateDecl *getMoreSpecializedTemplate(
13024 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
13025 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
13026 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
13027 bool PartialOverloading = false);
13028
13029 /// Retrieve the most specialized of the given function template
13030 /// specializations.
13031 ///
13032 /// \param SpecBegin the start iterator of the function template
13033 /// specializations that we will be comparing.
13034 ///
13035 /// \param SpecEnd the end iterator of the function template
13036 /// specializations, paired with \p SpecBegin.
13037 ///
13038 /// \param Loc the location where the ambiguity or no-specializations
13039 /// diagnostic should occur.
13040 ///
13041 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
13042 /// no matching candidates.
13043 ///
13044 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
13045 /// occurs.
13046 ///
13047 /// \param CandidateDiag partial diagnostic used for each function template
13048 /// specialization that is a candidate in the ambiguous ordering. One
13049 /// parameter in this diagnostic should be unbound, which will correspond to
13050 /// the string describing the template arguments for the function template
13051 /// specialization.
13052 ///
13053 /// \returns the most specialized function template specialization, if
13054 /// found. Otherwise, returns SpecEnd.
13055 UnresolvedSetIterator
13056 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
13057 TemplateSpecCandidateSet &FailedCandidates,
13058 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
13059 const PartialDiagnostic &AmbigDiag,
13060 const PartialDiagnostic &CandidateDiag,
13061 bool Complain = true, QualType TargetType = QualType());
13062
13063 /// Returns the more constrained function according to the rules of
13064 /// partial ordering by constraints (C++ [temp.constr.order]).
13065 ///
13066 /// \param FD1 the first function
13067 ///
13068 /// \param FD2 the second function
13069 ///
13070 /// \returns the more constrained function. If neither function is
13071 /// more constrained, returns NULL.
13072 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
13073 FunctionDecl *FD2);
13074
13075 ///@}
13076
13077 //
13078 //
13079 // -------------------------------------------------------------------------
13080 //
13081 //
13082
13083 /// \name C++ Template Deduction Guide
13084 /// Implementations are in SemaTemplateDeductionGuide.cpp
13085 ///@{
13086
13087 /// Declare implicit deduction guides for a class template if we've
13088 /// not already done so.
13089 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
13090 SourceLocation Loc);
13091
13092 FunctionTemplateDecl *DeclareAggregateDeductionGuideFromInitList(
13093 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
13094 SourceLocation Loc);
13095
13096 ///@}
13097
13098 //
13099 //
13100 // -------------------------------------------------------------------------
13101 //
13102 //
13103
13104 /// \name C++ Template Instantiation
13105 /// Implementations are in SemaTemplateInstantiate.cpp
13106 ///@{
13107
13108public:
13109 /// A helper class for building up ExtParameterInfos.
13110 class ExtParameterInfoBuilder {
13111 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
13112 bool HasInteresting = false;
13113
13114 public:
13115 /// Set the ExtParameterInfo for the parameter at the given index,
13116 ///
13117 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
13118 assert(Infos.size() <= index);
13119 Infos.resize(N: index);
13120 Infos.push_back(Elt: info);
13121
13122 if (!HasInteresting)
13123 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
13124 }
13125
13126 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
13127 /// ExtParameterInfo array we've built up.
13128 const FunctionProtoType::ExtParameterInfo *
13129 getPointerOrNull(unsigned numParams) {
13130 if (!HasInteresting)
13131 return nullptr;
13132 Infos.resize(N: numParams);
13133 return Infos.data();
13134 }
13135 };
13136
13137 /// The current instantiation scope used to store local
13138 /// variables.
13139 LocalInstantiationScope *CurrentInstantiationScope;
13140
13141 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
13142 UnparsedDefaultArgInstantiationsMap;
13143
13144 /// A mapping from parameters with unparsed default arguments to the
13145 /// set of instantiations of each parameter.
13146 ///
13147 /// This mapping is a temporary data structure used when parsing
13148 /// nested class templates or nested classes of class templates,
13149 /// where we might end up instantiating an inner class before the
13150 /// default arguments of its methods have been parsed.
13151 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
13152
13153 using InstantiatingSpecializationsKey = llvm::PointerIntPair<Decl *, 2>;
13154
13155 struct RecursiveInstGuard {
13156 enum class Kind {
13157 Template,
13158 DefaultArgument,
13159 ExceptionSpec,
13160 };
13161
13162 RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
13163 : S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
13164 auto [_, Created] = S.InstantiatingSpecializations.insert(V: Key);
13165 if (!Created)
13166 Key = {};
13167 }
13168
13169 ~RecursiveInstGuard() {
13170 if (Key.getOpaqueValue()) {
13171 [[maybe_unused]] bool Erased =
13172 S.InstantiatingSpecializations.erase(V: Key);
13173 assert(Erased);
13174 }
13175 }
13176
13177 RecursiveInstGuard(const RecursiveInstGuard &) = delete;
13178 RecursiveInstGuard &operator=(const RecursiveInstGuard &) = delete;
13179
13180 operator bool() const { return Key.getOpaqueValue() == nullptr; }
13181
13182 private:
13183 Sema &S;
13184 Sema::InstantiatingSpecializationsKey Key;
13185 };
13186
13187 /// A context in which code is being synthesized (where a source location
13188 /// alone is not sufficient to identify the context). This covers template
13189 /// instantiation and various forms of implicitly-generated functions.
13190 struct CodeSynthesisContext {
13191 /// The kind of template instantiation we are performing
13192 enum SynthesisKind {
13193 /// We are instantiating a template declaration. The entity is
13194 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
13195 TemplateInstantiation,
13196
13197 /// We are instantiating a default argument for a template
13198 /// parameter. The Entity is the template parameter whose argument is
13199 /// being instantiated, the Template is the template, and the
13200 /// TemplateArgs/NumTemplateArguments provide the template arguments as
13201 /// specified.
13202 DefaultTemplateArgumentInstantiation,
13203
13204 /// We are instantiating a default argument for a function.
13205 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
13206 /// provides the template arguments as specified.
13207 DefaultFunctionArgumentInstantiation,
13208
13209 /// We are substituting explicit template arguments provided for
13210 /// a function template. The entity is a FunctionTemplateDecl.
13211 ExplicitTemplateArgumentSubstitution,
13212
13213 /// We are substituting template argument determined as part of
13214 /// template argument deduction for either a class template
13215 /// partial specialization or a function template. The
13216 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
13217 /// a TemplateDecl.
13218 DeducedTemplateArgumentSubstitution,
13219
13220 /// We are substituting into a lambda expression.
13221 LambdaExpressionSubstitution,
13222
13223 /// We are substituting prior template arguments into a new
13224 /// template parameter. The template parameter itself is either a
13225 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
13226 PriorTemplateArgumentSubstitution,
13227
13228 /// We are checking the validity of a default template argument that
13229 /// has been used when naming a template-id.
13230 DefaultTemplateArgumentChecking,
13231
13232 /// We are computing the exception specification for a defaulted special
13233 /// member function.
13234 ExceptionSpecEvaluation,
13235
13236 /// We are instantiating the exception specification for a function
13237 /// template which was deferred until it was needed.
13238 ExceptionSpecInstantiation,
13239
13240 /// We are instantiating a requirement of a requires expression.
13241 RequirementInstantiation,
13242
13243 /// We are checking the satisfaction of a nested requirement of a requires
13244 /// expression.
13245 NestedRequirementConstraintsCheck,
13246
13247 /// We are declaring an implicit special member function.
13248 DeclaringSpecialMember,
13249
13250 /// We are declaring an implicit 'operator==' for a defaulted
13251 /// 'operator<=>'.
13252 DeclaringImplicitEqualityComparison,
13253
13254 /// We are defining a synthesized function (such as a defaulted special
13255 /// member).
13256 DefiningSynthesizedFunction,
13257
13258 // We are checking the constraints associated with a constrained entity or
13259 // the constraint expression of a concept. This includes the checks that
13260 // atomic constraints have the type 'bool' and that they can be constant
13261 // evaluated.
13262 ConstraintsCheck,
13263
13264 // We are substituting template arguments into a constraint expression.
13265 ConstraintSubstitution,
13266
13267 // We are normalizing a constraint expression.
13268 ConstraintNormalization,
13269
13270 // Instantiating a Requires Expression parameter clause.
13271 RequirementParameterInstantiation,
13272
13273 // We are substituting into the parameter mapping of an atomic constraint
13274 // during normalization.
13275 ParameterMappingSubstitution,
13276
13277 /// We are rewriting a comparison operator in terms of an operator<=>.
13278 RewritingOperatorAsSpaceship,
13279
13280 /// We are initializing a structured binding.
13281 InitializingStructuredBinding,
13282
13283 /// We are marking a class as __dllexport.
13284 MarkingClassDllexported,
13285
13286 /// We are building an implied call from __builtin_dump_struct. The
13287 /// arguments are in CallArgs.
13288 BuildingBuiltinDumpStructCall,
13289
13290 /// Added for Template instantiation observation.
13291 /// Memoization means we are _not_ instantiating a template because
13292 /// it is already instantiated (but we entered a context where we
13293 /// would have had to if it was not already instantiated).
13294 Memoization,
13295
13296 /// We are building deduction guides for a class.
13297 BuildingDeductionGuides,
13298
13299 /// We are instantiating a type alias template declaration.
13300 TypeAliasTemplateInstantiation,
13301
13302 /// We are performing partial ordering for template template parameters.
13303 PartialOrderingTTP,
13304
13305 /// We are performing name lookup for a function template or variable
13306 /// template named 'sycl_kernel_launch'.
13307 SYCLKernelLaunchLookup,
13308
13309 /// We are performing overload resolution for a call to a function
13310 /// template or variable template named 'sycl_kernel_launch'.
13311 SYCLKernelLaunchOverloadResolution,
13312 } Kind;
13313
13314 /// Whether we're substituting into constraints.
13315 bool InConstraintSubstitution;
13316
13317 /// Whether we're substituting into the parameter mapping of a constraint.
13318 bool InParameterMappingSubstitution;
13319
13320 /// The point of instantiation or synthesis within the source code.
13321 SourceLocation PointOfInstantiation;
13322
13323 /// The entity that is being synthesized.
13324 Decl *Entity;
13325
13326 /// The template (or partial specialization) in which we are
13327 /// performing the instantiation, for substitutions of prior template
13328 /// arguments.
13329 NamedDecl *Template;
13330
13331 union {
13332 /// The list of template arguments we are substituting, if they
13333 /// are not part of the entity.
13334 const TemplateArgument *TemplateArgs;
13335
13336 /// The list of argument expressions in a synthesized call.
13337 const Expr *const *CallArgs;
13338 };
13339
13340 // FIXME: Wrap this union around more members, or perhaps store the
13341 // kind-specific members in the RAII object owning the context.
13342 union {
13343 /// The number of template arguments in TemplateArgs.
13344 unsigned NumTemplateArgs;
13345
13346 /// The number of expressions in CallArgs.
13347 unsigned NumCallArgs;
13348
13349 /// The special member being declared or defined.
13350 CXXSpecialMemberKind SpecialMember;
13351 };
13352
13353 ArrayRef<TemplateArgument> template_arguments() const {
13354 assert(Kind != DeclaringSpecialMember);
13355 return {TemplateArgs, NumTemplateArgs};
13356 }
13357
13358 /// The source range that covers the construct that cause
13359 /// the instantiation, e.g., the template-id that causes a class
13360 /// template instantiation.
13361 SourceRange InstantiationRange;
13362
13363 CodeSynthesisContext()
13364 : Kind(TemplateInstantiation), InConstraintSubstitution(false),
13365 InParameterMappingSubstitution(false), Entity(nullptr),
13366 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0) {}
13367
13368 /// Determines whether this template is an actual instantiation
13369 /// that should be counted toward the maximum instantiation depth.
13370 bool isInstantiationRecord() const;
13371 };
13372
13373 /// A stack object to be created when performing template
13374 /// instantiation.
13375 ///
13376 /// Construction of an object of type \c InstantiatingTemplate
13377 /// pushes the current instantiation onto the stack of active
13378 /// instantiations. If the size of this stack exceeds the maximum
13379 /// number of recursive template instantiations, construction
13380 /// produces an error and evaluates true.
13381 ///
13382 /// Destruction of this object will pop the named instantiation off
13383 /// the stack.
13384 struct InstantiatingTemplate {
13385 /// Note that we are instantiating a class template,
13386 /// function template, variable template, alias template,
13387 /// or a member thereof.
13388 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13389 Decl *Entity,
13390 SourceRange InstantiationRange = SourceRange());
13391
13392 struct ExceptionSpecification {};
13393 /// Note that we are instantiating an exception specification
13394 /// of a function template.
13395 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13396 FunctionDecl *Entity, ExceptionSpecification,
13397 SourceRange InstantiationRange = SourceRange());
13398
13399 /// Note that we are instantiating a type alias template declaration.
13400 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13401 TypeAliasTemplateDecl *Entity,
13402 ArrayRef<TemplateArgument> TemplateArgs,
13403 SourceRange InstantiationRange = SourceRange());
13404
13405 /// Note that we are instantiating a default argument in a
13406 /// template-id.
13407 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13408 TemplateParameter Param, TemplateDecl *Template,
13409 ArrayRef<TemplateArgument> TemplateArgs,
13410 SourceRange InstantiationRange = SourceRange());
13411
13412 /// Note that we are substituting either explicitly-specified or
13413 /// deduced template arguments during function template argument deduction.
13414 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13415 FunctionTemplateDecl *FunctionTemplate,
13416 ArrayRef<TemplateArgument> TemplateArgs,
13417 CodeSynthesisContext::SynthesisKind Kind,
13418 SourceRange InstantiationRange = SourceRange());
13419
13420 /// Note that we are instantiating as part of template
13421 /// argument deduction for a class template declaration.
13422 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13423 TemplateDecl *Template,
13424 ArrayRef<TemplateArgument> TemplateArgs,
13425 SourceRange InstantiationRange = SourceRange());
13426
13427 /// Note that we are instantiating as part of template
13428 /// argument deduction for a class template partial
13429 /// specialization.
13430 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13431 ClassTemplatePartialSpecializationDecl *PartialSpec,
13432 ArrayRef<TemplateArgument> TemplateArgs,
13433 SourceRange InstantiationRange = SourceRange());
13434
13435 /// Note that we are instantiating as part of template
13436 /// argument deduction for a variable template partial
13437 /// specialization.
13438 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13439 VarTemplatePartialSpecializationDecl *PartialSpec,
13440 ArrayRef<TemplateArgument> TemplateArgs,
13441 SourceRange InstantiationRange = SourceRange());
13442
13443 /// Note that we are instantiating a default argument for a function
13444 /// parameter.
13445 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13446 ParmVarDecl *Param,
13447 ArrayRef<TemplateArgument> TemplateArgs,
13448 SourceRange InstantiationRange = SourceRange());
13449
13450 /// Note that we are substituting prior template arguments into a
13451 /// non-type parameter.
13452 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13453 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
13454 ArrayRef<TemplateArgument> TemplateArgs,
13455 SourceRange InstantiationRange);
13456
13457 /// Note that we are substituting prior template arguments into a
13458 /// template template parameter.
13459 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13460 NamedDecl *Template, TemplateTemplateParmDecl *Param,
13461 ArrayRef<TemplateArgument> TemplateArgs,
13462 SourceRange InstantiationRange);
13463
13464 /// Note that we are checking the default template argument
13465 /// against the template parameter for a given template-id.
13466 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13467 TemplateDecl *Template, NamedDecl *Param,
13468 ArrayRef<TemplateArgument> TemplateArgs,
13469 SourceRange InstantiationRange);
13470
13471 struct ConstraintsCheck {};
13472 /// \brief Note that we are checking the constraints associated with some
13473 /// constrained entity (a concept declaration or a template with associated
13474 /// constraints).
13475 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13476 ConstraintsCheck, NamedDecl *Template,
13477 ArrayRef<TemplateArgument> TemplateArgs,
13478 SourceRange InstantiationRange);
13479
13480 struct ConstraintSubstitution {};
13481 /// \brief Note that we are checking a constraint expression associated
13482 /// with a template declaration or as part of the satisfaction check of a
13483 /// concept.
13484 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13485 ConstraintSubstitution, NamedDecl *Template,
13486 SourceRange InstantiationRange);
13487
13488 struct ConstraintNormalization {};
13489 /// \brief Note that we are normalizing a constraint expression.
13490 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13491 ConstraintNormalization, NamedDecl *Template,
13492 SourceRange InstantiationRange);
13493
13494 struct ParameterMappingSubstitution {};
13495 /// \brief Note that we are subtituting into the parameter mapping of an
13496 /// atomic constraint during constraint normalization.
13497 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13498 ParameterMappingSubstitution, NamedDecl *Template,
13499 SourceRange InstantiationRange);
13500
13501 /// \brief Note that we are substituting template arguments into a part of
13502 /// a requirement of a requires expression.
13503 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13504 concepts::Requirement *Req,
13505 SourceRange InstantiationRange = SourceRange());
13506
13507 /// \brief Note that we are checking the satisfaction of the constraint
13508 /// expression inside of a nested requirement.
13509 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13510 concepts::NestedRequirement *Req, ConstraintsCheck,
13511 SourceRange InstantiationRange = SourceRange());
13512
13513 /// \brief Note that we are checking a requires clause.
13514 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13515 const RequiresExpr *E,
13516 SourceRange InstantiationRange);
13517
13518 struct BuildingDeductionGuidesTag {};
13519 /// \brief Note that we are building deduction guides.
13520 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13521 TemplateDecl *Entity, BuildingDeductionGuidesTag,
13522 SourceRange InstantiationRange = SourceRange());
13523
13524 struct PartialOrderingTTP {};
13525 /// \brief Note that we are partial ordering template template parameters.
13526 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13527 PartialOrderingTTP, TemplateDecl *PArg,
13528 SourceRange InstantiationRange = SourceRange());
13529
13530 /// Note that we have finished instantiating this template.
13531 void Clear();
13532
13533 ~InstantiatingTemplate() { Clear(); }
13534
13535 /// Determines whether we have exceeded the maximum
13536 /// recursive template instantiations.
13537 bool isInvalid() const { return Invalid; }
13538
13539 private:
13540 Sema &SemaRef;
13541 bool Invalid;
13542
13543 InstantiatingTemplate(Sema &SemaRef,
13544 CodeSynthesisContext::SynthesisKind Kind,
13545 SourceLocation PointOfInstantiation,
13546 SourceRange InstantiationRange, Decl *Entity,
13547 NamedDecl *Template = nullptr,
13548 ArrayRef<TemplateArgument> TemplateArgs = {});
13549
13550 InstantiatingTemplate(const InstantiatingTemplate &) = delete;
13551
13552 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13553 };
13554
13555 bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13556 const MultiLevelTemplateArgumentList &TemplateArgs,
13557 TemplateArgumentLoc &Output,
13558 SourceLocation Loc = {},
13559 const DeclarationName &Entity = {});
13560 bool
13561 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13562 const MultiLevelTemplateArgumentList &TemplateArgs,
13563 TemplateArgumentListInfo &Outputs);
13564
13565 /// Substitute concept template arguments in the constraint expression
13566 /// of a concept-id. This is used to implement [temp.constr.normal].
13567 ExprResult
13568 SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE,
13569 const Expr *ConstraintExpr,
13570 const MultiLevelTemplateArgumentList &MLTAL);
13571
13572 bool SubstTemplateArgumentsInParameterMapping(
13573 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
13574 const MultiLevelTemplateArgumentList &TemplateArgs,
13575 TemplateArgumentListInfo &Out);
13576
13577 /// Retrieve the template argument list(s) that should be used to
13578 /// instantiate the definition of the given declaration.
13579 ///
13580 /// \param ND the declaration for which we are computing template
13581 /// instantiation arguments.
13582 ///
13583 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13584 /// the decl context where it will be created. In this case, the `Innermost`
13585 /// should likely be provided. If ND is non-null, this is ignored.
13586 ///
13587 /// \param Innermost if non-NULL, specifies a template argument list for the
13588 /// template declaration passed as ND.
13589 ///
13590 /// \param RelativeToPrimary true if we should get the template
13591 /// arguments relative to the primary template, even when we're
13592 /// dealing with a specialization. This is only relevant for function
13593 /// template specializations.
13594 ///
13595 /// \param Pattern If non-NULL, indicates the pattern from which we will be
13596 /// instantiating the definition of the given declaration, \p ND. This is
13597 /// used to determine the proper set of template instantiation arguments for
13598 /// friend function template specializations.
13599 ///
13600 /// \param ForConstraintInstantiation when collecting arguments,
13601 /// ForConstraintInstantiation indicates we should continue looking when
13602 /// encountering a lambda generic call operator, and continue looking for
13603 /// arguments on an enclosing class template.
13604 ///
13605 /// \param SkipForSpecialization when specified, any template specializations
13606 /// in a traversal would be ignored.
13607 ///
13608 /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13609 /// when encountering a specialized member function template, rather than
13610 /// returning immediately.
13611 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13612 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13613 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13614 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13615 bool ForConstraintInstantiation = false,
13616 bool SkipForSpecialization = false,
13617 bool ForDefaultArgumentSubstitution = false);
13618
13619 /// RAII object to handle the state changes required to synthesize
13620 /// a function body.
13621 class SynthesizedFunctionScope {
13622 Sema &S;
13623 Sema::ContextRAII SavedContext;
13624 bool PushedCodeSynthesisContext = false;
13625
13626 public:
13627 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
13628 : S(S), SavedContext(S, DC) {
13629 auto *FD = dyn_cast<FunctionDecl>(Val: DC);
13630 S.PushFunctionScope();
13631 S.PushExpressionEvaluationContextForFunction(
13632 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, FD);
13633 if (FD)
13634 FD->setWillHaveBody(true);
13635 else
13636 assert(isa<ObjCMethodDecl>(DC));
13637 }
13638
13639 void addContextNote(SourceLocation UseLoc) {
13640 assert(!PushedCodeSynthesisContext);
13641
13642 Sema::CodeSynthesisContext Ctx;
13643 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
13644 Ctx.PointOfInstantiation = UseLoc;
13645 Ctx.Entity = cast<Decl>(Val: S.CurContext);
13646 S.pushCodeSynthesisContext(Ctx);
13647
13648 PushedCodeSynthesisContext = true;
13649 }
13650
13651 ~SynthesizedFunctionScope() {
13652 if (PushedCodeSynthesisContext)
13653 S.popCodeSynthesisContext();
13654 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
13655 FD->setWillHaveBody(false);
13656 S.CheckImmediateEscalatingFunctionDefinition(FD, FSI: S.getCurFunction());
13657 }
13658 S.PopExpressionEvaluationContext();
13659 S.PopFunctionScopeInfo();
13660 }
13661
13662 SynthesizedFunctionScope(const SynthesizedFunctionScope &) = delete;
13663 SynthesizedFunctionScope &
13664 operator=(const SynthesizedFunctionScope &) = delete;
13665 };
13666
13667 /// RAII object to ensure that a code synthesis context is popped on scope
13668 /// exit.
13669 class ScopedCodeSynthesisContext {
13670 Sema &S;
13671
13672 public:
13673 ScopedCodeSynthesisContext(Sema &S, const CodeSynthesisContext &Ctx)
13674 : S(S) {
13675 S.pushCodeSynthesisContext(Ctx);
13676 }
13677
13678 ~ScopedCodeSynthesisContext() { S.popCodeSynthesisContext(); }
13679 };
13680
13681 /// List of active code synthesis contexts.
13682 ///
13683 /// This vector is treated as a stack. As synthesis of one entity requires
13684 /// synthesis of another, additional contexts are pushed onto the stack.
13685 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
13686
13687 /// Specializations whose definitions are currently being instantiated.
13688 llvm::DenseSet<InstantiatingSpecializationsKey> InstantiatingSpecializations;
13689
13690 /// Non-dependent types used in templates that have already been instantiated
13691 /// by some template instantiation.
13692 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13693
13694 /// Extra modules inspected when performing a lookup during a template
13695 /// instantiation. Computed lazily.
13696 SmallVector<Module *, 16> CodeSynthesisContextLookupModules;
13697
13698 /// Cache of additional modules that should be used for name lookup
13699 /// within the current template instantiation. Computed lazily; use
13700 /// getLookupModules() to get a complete set.
13701 llvm::DenseSet<Module *> LookupModulesCache;
13702
13703 /// Map from the most recent declaration of a namespace to the most
13704 /// recent visible declaration of that namespace.
13705 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13706
13707 SFINAETrap *CurrentSFINAEContext = nullptr;
13708
13709 /// The number of \p CodeSynthesisContexts that are not template
13710 /// instantiations and, therefore, should not be counted as part of the
13711 /// instantiation depth.
13712 ///
13713 /// When the instantiation depth reaches the user-configurable limit
13714 /// \p LangOptions::InstantiationDepth we will abort instantiation.
13715 // FIXME: Should we have a similar limit for other forms of synthesis?
13716 unsigned NonInstantiationEntries;
13717
13718 /// The depth of the context stack at the point when the most recent
13719 /// error or warning was produced.
13720 ///
13721 /// This value is used to suppress printing of redundant context stacks
13722 /// when there are multiple errors or warnings in the same instantiation.
13723 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13724 unsigned LastEmittedCodeSynthesisContextDepth = 0;
13725
13726 /// The template instantiation callbacks to trace or track
13727 /// instantiations (objects can be chained).
13728 ///
13729 /// This callbacks is used to print, trace or track template
13730 /// instantiations as they are being constructed.
13731 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
13732 TemplateInstCallbacks;
13733
13734 /// The current index into pack expansion arguments that will be
13735 /// used for substitution of parameter packs.
13736 ///
13737 /// The pack expansion index will be none to indicate that parameter packs
13738 /// should be instantiated as themselves. Otherwise, the index specifies
13739 /// which argument within the parameter pack will be used for substitution.
13740 UnsignedOrNone ArgPackSubstIndex;
13741
13742 /// RAII object used to change the argument pack substitution index
13743 /// within a \c Sema object.
13744 ///
13745 /// See \c ArgPackSubstIndex for more information.
13746 class ArgPackSubstIndexRAII {
13747 Sema &Self;
13748 UnsignedOrNone OldSubstIndex;
13749
13750 public:
13751 ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
13752 : Self(Self),
13753 OldSubstIndex(std::exchange(obj&: Self.ArgPackSubstIndex, new_val&: NewSubstIndex)) {}
13754
13755 ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13756 ArgPackSubstIndexRAII(const ArgPackSubstIndexRAII &) = delete;
13757 ArgPackSubstIndexRAII &operator=(const ArgPackSubstIndexRAII &) = delete;
13758 };
13759
13760 bool pushCodeSynthesisContext(CodeSynthesisContext Ctx);
13761 void popCodeSynthesisContext();
13762
13763 void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc) {
13764 if (!CodeSynthesisContexts.empty() &&
13765 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
13766 PrintInstantiationStack(DiagFunc);
13767 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
13768 }
13769 if (PragmaAttributeCurrentTargetDecl)
13770 PrintPragmaAttributeInstantiationPoint(DiagFunc);
13771 }
13772 void PrintContextStack() { PrintContextStack(DiagFunc: getDefaultDiagFunc()); }
13773 /// Prints the current instantiation stack through a series of
13774 /// notes.
13775 void PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc);
13776 void PrintInstantiationStack() {
13777 PrintInstantiationStack(DiagFunc: getDefaultDiagFunc());
13778 }
13779
13780 /// Returns a pointer to the current SFINAE context, if any.
13781 [[nodiscard]] SFINAETrap *getSFINAEContext() const {
13782 return CurrentSFINAEContext;
13783 }
13784 [[nodiscard]] bool isSFINAEContext() const {
13785 return CurrentSFINAEContext != nullptr;
13786 }
13787
13788 /// Perform substitution on the type T with a given set of template
13789 /// arguments.
13790 ///
13791 /// This routine substitutes the given template arguments into the
13792 /// type T and produces the instantiated type.
13793 ///
13794 /// \param T the type into which the template arguments will be
13795 /// substituted. If this type is not dependent, it will be returned
13796 /// immediately.
13797 ///
13798 /// \param Args the template arguments that will be
13799 /// substituted for the top-level template parameters within T.
13800 ///
13801 /// \param Loc the location in the source code where this substitution
13802 /// is being performed. It will typically be the location of the
13803 /// declarator (if we're instantiating the type of some declaration)
13804 /// or the location of the type in the source code (if, e.g., we're
13805 /// instantiating the type of a cast expression).
13806 ///
13807 /// \param Entity the name of the entity associated with a declaration
13808 /// being instantiated (if any). May be empty to indicate that there
13809 /// is no such entity (if, e.g., this is a type that occurs as part of
13810 /// a cast expression) or that the entity has no name (e.g., an
13811 /// unnamed function parameter).
13812 ///
13813 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
13814 /// acceptable as the top level type of the result.
13815 ///
13816 /// \param IsIncompleteSubstitution If provided, the pointee will be set
13817 /// whenever substitution would perform a replacement with a null or
13818 /// non-existent template argument.
13819 ///
13820 /// \returns If the instantiation succeeds, the instantiated
13821 /// type. Otherwise, produces diagnostics and returns a NULL type.
13822 TypeSourceInfo *SubstType(TypeSourceInfo *T,
13823 const MultiLevelTemplateArgumentList &TemplateArgs,
13824 SourceLocation Loc, DeclarationName Entity,
13825 bool AllowDeducedTST = false);
13826
13827 QualType SubstType(QualType T,
13828 const MultiLevelTemplateArgumentList &TemplateArgs,
13829 SourceLocation Loc, DeclarationName Entity,
13830 bool *IsIncompleteSubstitution = nullptr);
13831
13832 TypeSourceInfo *SubstType(TypeLoc TL,
13833 const MultiLevelTemplateArgumentList &TemplateArgs,
13834 SourceLocation Loc, DeclarationName Entity);
13835
13836 /// A form of SubstType intended specifically for instantiating the
13837 /// type of a FunctionDecl. Its purpose is solely to force the
13838 /// instantiation of default-argument expressions and to avoid
13839 /// instantiating an exception-specification.
13840 TypeSourceInfo *SubstFunctionDeclType(
13841 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
13842 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
13843 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
13844 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
13845 const MultiLevelTemplateArgumentList &Args);
13846 bool SubstExceptionSpec(SourceLocation Loc,
13847 FunctionProtoType::ExceptionSpecInfo &ESI,
13848 SmallVectorImpl<QualType> &ExceptionStorage,
13849 const MultiLevelTemplateArgumentList &Args);
13850 ParmVarDecl *
13851 SubstParmVarDecl(ParmVarDecl *D,
13852 const MultiLevelTemplateArgumentList &TemplateArgs,
13853 int indexAdjustment, UnsignedOrNone NumExpansions,
13854 bool ExpectParameterPack, bool EvaluateConstraints = true);
13855
13856 /// Substitute the given template arguments into the given set of
13857 /// parameters, producing the set of parameter types that would be generated
13858 /// from such a substitution.
13859 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
13860 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
13861 const MultiLevelTemplateArgumentList &TemplateArgs,
13862 SmallVectorImpl<QualType> &ParamTypes,
13863 SmallVectorImpl<ParmVarDecl *> *OutParams,
13864 ExtParameterInfoBuilder &ParamInfos);
13865
13866 /// Substitute the given template arguments into the default argument.
13867 bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param,
13868 const MultiLevelTemplateArgumentList &TemplateArgs,
13869 bool ForCallExpr = false);
13870 ExprResult SubstExpr(Expr *E,
13871 const MultiLevelTemplateArgumentList &TemplateArgs);
13872 /// Substitute an expression as if it is a address-of-operand, which makes it
13873 /// act like a CXXIdExpression rather than an attempt to call.
13874 ExprResult SubstCXXIdExpr(Expr *E,
13875 const MultiLevelTemplateArgumentList &TemplateArgs);
13876
13877 // A RAII type used by the TemplateDeclInstantiator and TemplateInstantiator
13878 // to disable constraint evaluation, then restore the state.
13879 template <typename InstTy> struct ConstraintEvalRAII {
13880 InstTy &TI;
13881 bool OldValue;
13882
13883 ConstraintEvalRAII(InstTy &TI)
13884 : TI(TI), OldValue(TI.getEvaluateConstraints()) {
13885 TI.setEvaluateConstraints(false);
13886 }
13887 ~ConstraintEvalRAII() { TI.setEvaluateConstraints(OldValue); }
13888 ConstraintEvalRAII(const ConstraintEvalRAII &) = delete;
13889 ConstraintEvalRAII &operator=(const ConstraintEvalRAII &) = delete;
13890 };
13891
13892 // Must be used instead of SubstExpr at 'constraint checking' time.
13893 ExprResult
13894 SubstConstraintExpr(Expr *E,
13895 const MultiLevelTemplateArgumentList &TemplateArgs);
13896 // Unlike the above, this does not evaluate constraints.
13897 ExprResult SubstConstraintExprWithoutSatisfaction(
13898 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
13899
13900 /// Substitute the given template arguments into a list of
13901 /// expressions, expanding pack expansions if required.
13902 ///
13903 /// \param Exprs The list of expressions to substitute into.
13904 ///
13905 /// \param IsCall Whether this is some form of call, in which case
13906 /// default arguments will be dropped.
13907 ///
13908 /// \param TemplateArgs The set of template arguments to substitute.
13909 ///
13910 /// \param Outputs Will receive all of the substituted arguments.
13911 ///
13912 /// \returns true if an error occurred, false otherwise.
13913 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
13914 const MultiLevelTemplateArgumentList &TemplateArgs,
13915 SmallVectorImpl<Expr *> &Outputs);
13916
13917 StmtResult SubstStmt(Stmt *S,
13918 const MultiLevelTemplateArgumentList &TemplateArgs);
13919
13920 ExprResult
13921 SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs,
13922 bool CXXDirectInit);
13923
13924 /// Perform substitution on the base class specifiers of the
13925 /// given class template specialization.
13926 ///
13927 /// Produces a diagnostic and returns true on error, returns false and
13928 /// attaches the instantiated base classes to the class template
13929 /// specialization if successful.
13930 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13931 const MultiLevelTemplateArgumentList &TemplateArgs);
13932
13933 /// Instantiate the definition of a class from a given pattern.
13934 ///
13935 /// \param PointOfInstantiation The point of instantiation within the
13936 /// source code.
13937 ///
13938 /// \param Instantiation is the declaration whose definition is being
13939 /// instantiated. This will be either a class template specialization
13940 /// or a member class of a class template specialization.
13941 ///
13942 /// \param Pattern is the pattern from which the instantiation
13943 /// occurs. This will be either the declaration of a class template or
13944 /// the declaration of a member class of a class template.
13945 ///
13946 /// \param TemplateArgs The template arguments to be substituted into
13947 /// the pattern.
13948 ///
13949 /// \param TSK the kind of implicit or explicit instantiation to perform.
13950 ///
13951 /// \param Complain whether to complain if the class cannot be instantiated
13952 /// due to the lack of a definition.
13953 ///
13954 /// \returns true if an error occurred, false otherwise.
13955 bool InstantiateClass(SourceLocation PointOfInstantiation,
13956 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13957 const MultiLevelTemplateArgumentList &TemplateArgs,
13958 TemplateSpecializationKind TSK, bool Complain = true);
13959
13960private:
13961 bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
13962 CXXRecordDecl *Instantiation,
13963 CXXRecordDecl *Pattern,
13964 const MultiLevelTemplateArgumentList &TemplateArgs,
13965 TemplateSpecializationKind TSK, bool Complain);
13966
13967public:
13968 /// Instantiate the definition of an enum from a given pattern.
13969 ///
13970 /// \param PointOfInstantiation The point of instantiation within the
13971 /// source code.
13972 /// \param Instantiation is the declaration whose definition is being
13973 /// instantiated. This will be a member enumeration of a class
13974 /// temploid specialization, or a local enumeration within a
13975 /// function temploid specialization.
13976 /// \param Pattern The templated declaration from which the instantiation
13977 /// occurs.
13978 /// \param TemplateArgs The template arguments to be substituted into
13979 /// the pattern.
13980 /// \param TSK The kind of implicit or explicit instantiation to perform.
13981 ///
13982 /// \return \c true if an error occurred, \c false otherwise.
13983 bool InstantiateEnum(SourceLocation PointOfInstantiation,
13984 EnumDecl *Instantiation, EnumDecl *Pattern,
13985 const MultiLevelTemplateArgumentList &TemplateArgs,
13986 TemplateSpecializationKind TSK);
13987
13988 /// Instantiate the definition of a field from the given pattern.
13989 ///
13990 /// \param PointOfInstantiation The point of instantiation within the
13991 /// source code.
13992 /// \param Instantiation is the declaration whose definition is being
13993 /// instantiated. This will be a class of a class temploid
13994 /// specialization, or a local enumeration within a function temploid
13995 /// specialization.
13996 /// \param Pattern The templated declaration from which the instantiation
13997 /// occurs.
13998 /// \param TemplateArgs The template arguments to be substituted into
13999 /// the pattern.
14000 ///
14001 /// \return \c true if an error occurred, \c false otherwise.
14002 bool InstantiateInClassInitializer(
14003 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
14004 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
14005
14006 bool usesPartialOrExplicitSpecialization(
14007 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
14008
14009 bool InstantiateClassTemplateSpecialization(
14010 SourceLocation PointOfInstantiation,
14011 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14012 TemplateSpecializationKind TSK, bool Complain,
14013 bool PrimaryStrictPackMatch);
14014
14015 /// Instantiates the definitions of all of the member
14016 /// of the given class, which is an instantiation of a class template
14017 /// or a member class of a template.
14018 void
14019 InstantiateClassMembers(SourceLocation PointOfInstantiation,
14020 CXXRecordDecl *Instantiation,
14021 const MultiLevelTemplateArgumentList &TemplateArgs,
14022 TemplateSpecializationKind TSK);
14023
14024 /// Instantiate the definitions of all of the members of the
14025 /// given class template specialization, which was named as part of an
14026 /// explicit instantiation.
14027 void InstantiateClassTemplateSpecializationMembers(
14028 SourceLocation PointOfInstantiation,
14029 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14030 TemplateSpecializationKind TSK);
14031
14032 NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(
14033 NestedNameSpecifierLoc NNS,
14034 const MultiLevelTemplateArgumentList &TemplateArgs);
14035
14036 /// Do template substitution on declaration name info.
14037 DeclarationNameInfo
14038 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
14039 const MultiLevelTemplateArgumentList &TemplateArgs);
14040 TemplateName
14041 SubstTemplateName(SourceLocation TemplateKWLoc,
14042 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
14043 SourceLocation NameLoc,
14044 const MultiLevelTemplateArgumentList &TemplateArgs);
14045
14046 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
14047 const MultiLevelTemplateArgumentList &TemplateArgs,
14048 bool EvaluateConstraint);
14049
14050 /// Determine whether we are currently performing template instantiation.
14051 bool inTemplateInstantiation() const {
14052 return CodeSynthesisContexts.size() > NonInstantiationEntries;
14053 }
14054
14055 /// Determine whether we are currently performing constraint substitution.
14056 bool inConstraintSubstitution() const {
14057 return !CodeSynthesisContexts.empty() &&
14058 CodeSynthesisContexts.back().InConstraintSubstitution;
14059 }
14060
14061 bool inParameterMappingSubstitution() const {
14062 return !CodeSynthesisContexts.empty() &&
14063 CodeSynthesisContexts.back().InParameterMappingSubstitution &&
14064 !inConstraintSubstitution();
14065 }
14066
14067 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
14068
14069 /// \brief create a Requirement::SubstitutionDiagnostic with only a
14070 /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
14071 concepts::Requirement::SubstitutionDiagnostic *
14072 createSubstDiagAt(SourceLocation Location, EntityPrinter Printer);
14073
14074 ///@}
14075
14076 //
14077 //
14078 // -------------------------------------------------------------------------
14079 //
14080 //
14081
14082 /// \name C++ Template Declaration Instantiation
14083 /// Implementations are in SemaTemplateInstantiateDecl.cpp
14084 ///@{
14085
14086public:
14087 /// An entity for which implicit template instantiation is required.
14088 ///
14089 /// The source location associated with the declaration is the first place in
14090 /// the source code where the declaration was "used". It is not necessarily
14091 /// the point of instantiation (which will be either before or after the
14092 /// namespace-scope declaration that triggered this implicit instantiation),
14093 /// However, it is the location that diagnostics should generally refer to,
14094 /// because users will need to know what code triggered the instantiation.
14095 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
14096
14097 /// The queue of implicit template instantiations that are required
14098 /// but have not yet been performed.
14099 std::deque<PendingImplicitInstantiation> PendingInstantiations;
14100
14101 /// Queue of implicit template instantiations that cannot be performed
14102 /// eagerly.
14103 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
14104
14105 SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses;
14106 SmallVector<std::deque<PendingImplicitInstantiation>, 8>
14107 SavedPendingInstantiations;
14108
14109 /// The queue of implicit template instantiations that are required
14110 /// and must be performed within the current local scope.
14111 ///
14112 /// This queue is only used for member functions of local classes in
14113 /// templates, which must be instantiated in the same scope as their
14114 /// enclosing function, so that they can reference function-local
14115 /// types, static variables, enumerators, etc.
14116 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
14117
14118 class LocalEagerInstantiationScope {
14119 public:
14120 LocalEagerInstantiationScope(Sema &S, bool AtEndOfTU)
14121 : S(S), AtEndOfTU(AtEndOfTU) {
14122 SavedPendingLocalImplicitInstantiations.swap(
14123 x&: S.PendingLocalImplicitInstantiations);
14124 }
14125
14126 void perform() {
14127 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: true,
14128 /*AtEndOfTU=*/AtEndOfTU);
14129 }
14130
14131 ~LocalEagerInstantiationScope() {
14132 assert(S.PendingLocalImplicitInstantiations.empty() &&
14133 "there shouldn't be any pending local implicit instantiations");
14134 SavedPendingLocalImplicitInstantiations.swap(
14135 x&: S.PendingLocalImplicitInstantiations);
14136 }
14137
14138 LocalEagerInstantiationScope(const LocalEagerInstantiationScope &) = delete;
14139 LocalEagerInstantiationScope &
14140 operator=(const LocalEagerInstantiationScope &) = delete;
14141
14142 private:
14143 Sema &S;
14144 bool AtEndOfTU;
14145 std::deque<PendingImplicitInstantiation>
14146 SavedPendingLocalImplicitInstantiations;
14147 };
14148
14149 /// Records and restores the CurFPFeatures state on entry/exit of compound
14150 /// statements.
14151 class FPFeaturesStateRAII {
14152 public:
14153 FPFeaturesStateRAII(Sema &S);
14154 ~FPFeaturesStateRAII();
14155 FPOptionsOverride getOverrides() { return OldOverrides; }
14156
14157 private:
14158 Sema &S;
14159 FPOptions OldFPFeaturesState;
14160 FPOptionsOverride OldOverrides;
14161 LangOptions::FPEvalMethodKind OldEvalMethod;
14162 SourceLocation OldFPPragmaLocation;
14163 };
14164
14165 class GlobalEagerInstantiationScope {
14166 public:
14167 GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
14168 : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
14169 if (!Enabled)
14170 return;
14171
14172 S.SavedPendingInstantiations.emplace_back();
14173 S.SavedPendingInstantiations.back().swap(x&: S.PendingInstantiations);
14174
14175 S.SavedVTableUses.emplace_back();
14176 S.SavedVTableUses.back().swap(RHS&: S.VTableUses);
14177 }
14178
14179 void perform() {
14180 if (Enabled) {
14181 S.DefineUsedVTables();
14182 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: false,
14183 /*AtEndOfTU=*/AtEndOfTU);
14184 }
14185 }
14186
14187 ~GlobalEagerInstantiationScope() {
14188 if (!Enabled)
14189 return;
14190
14191 // Restore the set of pending vtables.
14192 assert(S.VTableUses.empty() &&
14193 "VTableUses should be empty before it is discarded.");
14194 S.VTableUses.swap(RHS&: S.SavedVTableUses.back());
14195 S.SavedVTableUses.pop_back();
14196
14197 // Restore the set of pending implicit instantiations.
14198 if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
14199 AtEndOfTU) {
14200 assert(S.PendingInstantiations.empty() &&
14201 "PendingInstantiations should be empty before it is discarded.");
14202 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14203 S.SavedPendingInstantiations.pop_back();
14204 } else {
14205 // Template instantiations in the PCH may be delayed until the TU.
14206 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14207 S.PendingInstantiations.insert(
14208 position: S.PendingInstantiations.end(),
14209 first: S.SavedPendingInstantiations.back().begin(),
14210 last: S.SavedPendingInstantiations.back().end());
14211 S.SavedPendingInstantiations.pop_back();
14212 }
14213 }
14214
14215 GlobalEagerInstantiationScope(const GlobalEagerInstantiationScope &) =
14216 delete;
14217 GlobalEagerInstantiationScope &
14218 operator=(const GlobalEagerInstantiationScope &) = delete;
14219
14220 private:
14221 Sema &S;
14222 bool Enabled;
14223 bool AtEndOfTU;
14224 };
14225
14226 ExplicitSpecifier instantiateExplicitSpecifier(
14227 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
14228
14229 struct LateInstantiatedAttribute {
14230 const Attr *TmplAttr;
14231 LocalInstantiationScope *Scope;
14232 Decl *NewDecl;
14233
14234 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
14235 Decl *D)
14236 : TmplAttr(A), Scope(S), NewDecl(D) {}
14237 };
14238 typedef SmallVector<LateInstantiatedAttribute, 1> LateInstantiatedAttrVec;
14239
14240 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14241 const Decl *Pattern, Decl *Inst,
14242 LateInstantiatedAttrVec *LateAttrs = nullptr,
14243 LocalInstantiationScope *OuterMostScope = nullptr);
14244
14245 /// Update instantiation attributes after template was late parsed.
14246 ///
14247 /// Some attributes are evaluated based on the body of template. If it is
14248 /// late parsed, such attributes cannot be evaluated when declaration is
14249 /// instantiated. This function is used to update instantiation attributes
14250 /// when template definition is ready.
14251 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
14252
14253 void
14254 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
14255 const Decl *Pattern, Decl *Inst,
14256 LateInstantiatedAttrVec *LateAttrs = nullptr,
14257 LocalInstantiationScope *OuterMostScope = nullptr);
14258
14259 /// In the MS ABI, we need to instantiate default arguments of dllexported
14260 /// default constructors along with the constructor definition. This allows IR
14261 /// gen to emit a constructor closure which calls the default constructor with
14262 /// its default arguments.
14263 void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
14264
14265 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
14266 ParmVarDecl *Param);
14267 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
14268 FunctionDecl *Function);
14269
14270 /// Instantiate (or find existing instantiation of) a function template with a
14271 /// given set of template arguments.
14272 ///
14273 /// Usually this should not be used, and template argument deduction should be
14274 /// used in its place.
14275 FunctionDecl *InstantiateFunctionDeclaration(
14276 FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
14277 SourceLocation Loc,
14278 CodeSynthesisContext::SynthesisKind CSC =
14279 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution);
14280
14281 /// Instantiate the definition of the given function from its
14282 /// template.
14283 ///
14284 /// \param PointOfInstantiation the point at which the instantiation was
14285 /// required. Note that this is not precisely a "point of instantiation"
14286 /// for the function, but it's close.
14287 ///
14288 /// \param Function the already-instantiated declaration of a
14289 /// function template specialization or member function of a class template
14290 /// specialization.
14291 ///
14292 /// \param Recursive if true, recursively instantiates any functions that
14293 /// are required by this instantiation.
14294 ///
14295 /// \param DefinitionRequired if true, then we are performing an explicit
14296 /// instantiation where the body of the function is required. Complain if
14297 /// there is no such body.
14298 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
14299 FunctionDecl *Function,
14300 bool Recursive = false,
14301 bool DefinitionRequired = false,
14302 bool AtEndOfTU = false);
14303 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
14304 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
14305 const TemplateArgumentList *PartialSpecArgs,
14306 SmallVectorImpl<TemplateArgument> &Converted,
14307 SourceLocation PointOfInstantiation,
14308 LateInstantiatedAttrVec *LateAttrs = nullptr,
14309 LocalInstantiationScope *StartingScope = nullptr);
14310
14311 /// Instantiates a variable template specialization by completing it
14312 /// with appropriate type information and initializer.
14313 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
14314 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14315 const MultiLevelTemplateArgumentList &TemplateArgs);
14316
14317 /// BuildVariableInstantiation - Used after a new variable has been created.
14318 /// Sets basic variable data and decides whether to postpone the
14319 /// variable instantiation.
14320 void
14321 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
14322 const MultiLevelTemplateArgumentList &TemplateArgs,
14323 LateInstantiatedAttrVec *LateAttrs,
14324 DeclContext *Owner,
14325 LocalInstantiationScope *StartingScope,
14326 bool InstantiatingVarTemplate = false,
14327 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14328
14329 /// Instantiate the initializer of a variable.
14330 void InstantiateVariableInitializer(
14331 VarDecl *Var, VarDecl *OldVar,
14332 const MultiLevelTemplateArgumentList &TemplateArgs);
14333
14334 /// Instantiate the definition of the given variable from its
14335 /// template.
14336 ///
14337 /// \param PointOfInstantiation the point at which the instantiation was
14338 /// required. Note that this is not precisely a "point of instantiation"
14339 /// for the variable, but it's close.
14340 ///
14341 /// \param Var the already-instantiated declaration of a templated variable.
14342 ///
14343 /// \param Recursive if true, recursively instantiates any functions that
14344 /// are required by this instantiation.
14345 ///
14346 /// \param DefinitionRequired if true, then we are performing an explicit
14347 /// instantiation where a definition of the variable is required. Complain
14348 /// if there is no such definition.
14349 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14350 VarDecl *Var, bool Recursive = false,
14351 bool DefinitionRequired = false,
14352 bool AtEndOfTU = false);
14353
14354 void InstantiateMemInitializers(
14355 CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl,
14356 const MultiLevelTemplateArgumentList &TemplateArgs);
14357
14358 /// Find the instantiation of the given declaration within the
14359 /// current instantiation.
14360 ///
14361 /// This routine is intended to be used when \p D is a declaration
14362 /// referenced from within a template, that needs to mapped into the
14363 /// corresponding declaration within an instantiation. For example,
14364 /// given:
14365 ///
14366 /// \code
14367 /// template<typename T>
14368 /// struct X {
14369 /// enum Kind {
14370 /// KnownValue = sizeof(T)
14371 /// };
14372 ///
14373 /// bool getKind() const { return KnownValue; }
14374 /// };
14375 ///
14376 /// template struct X<int>;
14377 /// \endcode
14378 ///
14379 /// In the instantiation of X<int>::getKind(), we need to map the \p
14380 /// EnumConstantDecl for \p KnownValue (which refers to
14381 /// X<T>::<Kind>::KnownValue) to its instantiation
14382 /// (X<int>::<Kind>::KnownValue).
14383 /// \p FindInstantiatedDecl performs this mapping from within the
14384 /// instantiation of X<int>.
14385 NamedDecl *
14386 FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
14387 const MultiLevelTemplateArgumentList &TemplateArgs,
14388 bool FindingInstantiatedContext = false);
14389
14390 /// Finds the instantiation of the given declaration context
14391 /// within the current instantiation.
14392 ///
14393 /// \returns NULL if there was an error
14394 DeclContext *
14395 FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
14396 const MultiLevelTemplateArgumentList &TemplateArgs);
14397
14398 Decl *SubstDecl(Decl *D, DeclContext *Owner,
14399 const MultiLevelTemplateArgumentList &TemplateArgs);
14400
14401 /// Substitute the name and return type of a defaulted 'operator<=>' to form
14402 /// an implicit 'operator=='.
14403 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
14404 FunctionDecl *Spaceship);
14405
14406 /// Performs template instantiation for all implicit template
14407 /// instantiations we have seen until this point.
14408 void PerformPendingInstantiations(bool LocalOnly = false,
14409 bool AtEndOfTU = true);
14410
14411 TemplateParameterList *
14412 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
14413 const MultiLevelTemplateArgumentList &TemplateArgs,
14414 bool EvaluateConstraints = true);
14415
14416 void PerformDependentDiagnostics(
14417 const DeclContext *Pattern,
14418 const MultiLevelTemplateArgumentList &TemplateArgs);
14419
14420private:
14421 /// Introduce the instantiated local variables into the local
14422 /// instantiation scope.
14423 void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14424 const FunctionDecl *PatternDecl,
14425 LocalInstantiationScope &Scope);
14426 /// Introduce the instantiated function parameters into the local
14427 /// instantiation scope, and set the parameter names to those used
14428 /// in the template.
14429 bool addInstantiatedParametersToScope(
14430 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14431 LocalInstantiationScope &Scope,
14432 const MultiLevelTemplateArgumentList &TemplateArgs);
14433
14434 /// Introduce the instantiated captures of the lambda into the local
14435 /// instantiation scope.
14436 bool addInstantiatedCapturesToScope(
14437 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14438 LocalInstantiationScope &Scope,
14439 const MultiLevelTemplateArgumentList &TemplateArgs);
14440
14441 int ParsingClassDepth = 0;
14442
14443 class SavePendingParsedClassStateRAII {
14444 public:
14445 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14446
14447 ~SavePendingParsedClassStateRAII() {
14448 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14449 "there shouldn't be any pending delayed exception spec checks");
14450 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14451 "there shouldn't be any pending delayed exception spec checks");
14452 swapSavedState();
14453 }
14454
14455 SavePendingParsedClassStateRAII(const SavePendingParsedClassStateRAII &) =
14456 delete;
14457 SavePendingParsedClassStateRAII &
14458 operator=(const SavePendingParsedClassStateRAII &) = delete;
14459
14460 private:
14461 Sema &S;
14462 decltype(DelayedOverridingExceptionSpecChecks)
14463 SavedOverridingExceptionSpecChecks;
14464 decltype(DelayedEquivalentExceptionSpecChecks)
14465 SavedEquivalentExceptionSpecChecks;
14466
14467 void swapSavedState() {
14468 SavedOverridingExceptionSpecChecks.swap(
14469 RHS&: S.DelayedOverridingExceptionSpecChecks);
14470 SavedEquivalentExceptionSpecChecks.swap(
14471 RHS&: S.DelayedEquivalentExceptionSpecChecks);
14472 }
14473 };
14474
14475 ///@}
14476
14477 //
14478 //
14479 // -------------------------------------------------------------------------
14480 //
14481 //
14482
14483 /// \name C++ Variadic Templates
14484 /// Implementations are in SemaTemplateVariadic.cpp
14485 ///@{
14486
14487public:
14488 /// Determine whether an unexpanded parameter pack might be permitted in this
14489 /// location. Useful for error recovery.
14490 bool isUnexpandedParameterPackPermitted();
14491
14492 /// The context in which an unexpanded parameter pack is
14493 /// being diagnosed.
14494 ///
14495 /// Note that the values of this enumeration line up with the first
14496 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14497 enum UnexpandedParameterPackContext {
14498 /// An arbitrary expression.
14499 UPPC_Expression = 0,
14500
14501 /// The base type of a class type.
14502 UPPC_BaseType,
14503
14504 /// The type of an arbitrary declaration.
14505 UPPC_DeclarationType,
14506
14507 /// The type of a data member.
14508 UPPC_DataMemberType,
14509
14510 /// The size of a bit-field.
14511 UPPC_BitFieldWidth,
14512
14513 /// The expression in a static assertion.
14514 UPPC_StaticAssertExpression,
14515
14516 /// The fixed underlying type of an enumeration.
14517 UPPC_FixedUnderlyingType,
14518
14519 /// The enumerator value.
14520 UPPC_EnumeratorValue,
14521
14522 /// A using declaration.
14523 UPPC_UsingDeclaration,
14524
14525 /// A friend declaration.
14526 UPPC_FriendDeclaration,
14527
14528 /// A declaration qualifier.
14529 UPPC_DeclarationQualifier,
14530
14531 /// An initializer.
14532 UPPC_Initializer,
14533
14534 /// A default argument.
14535 UPPC_DefaultArgument,
14536
14537 /// The type of a non-type template parameter.
14538 UPPC_NonTypeTemplateParameterType,
14539
14540 /// The type of an exception.
14541 UPPC_ExceptionType,
14542
14543 /// Explicit specialization.
14544 UPPC_ExplicitSpecialization,
14545
14546 /// Partial specialization.
14547 UPPC_PartialSpecialization,
14548
14549 /// Microsoft __if_exists.
14550 UPPC_IfExists,
14551
14552 /// Microsoft __if_not_exists.
14553 UPPC_IfNotExists,
14554
14555 /// Lambda expression.
14556 UPPC_Lambda,
14557
14558 /// Block expression.
14559 UPPC_Block,
14560
14561 /// A type constraint.
14562 UPPC_TypeConstraint,
14563
14564 // A requirement in a requires-expression.
14565 UPPC_Requirement,
14566
14567 // A requires-clause.
14568 UPPC_RequiresClause,
14569 };
14570
14571 /// Diagnose unexpanded parameter packs.
14572 ///
14573 /// \param Loc The location at which we should emit the diagnostic.
14574 ///
14575 /// \param UPPC The context in which we are diagnosing unexpanded
14576 /// parameter packs.
14577 ///
14578 /// \param Unexpanded the set of unexpanded parameter packs.
14579 ///
14580 /// \returns true if an error occurred, false otherwise.
14581 bool DiagnoseUnexpandedParameterPacks(
14582 SourceLocation Loc, UnexpandedParameterPackContext UPPC,
14583 ArrayRef<UnexpandedParameterPack> Unexpanded);
14584
14585 /// If the given type contains an unexpanded parameter pack,
14586 /// diagnose the error.
14587 ///
14588 /// \param Loc The source location where a diagnostc should be emitted.
14589 ///
14590 /// \param T The type that is being checked for unexpanded parameter
14591 /// packs.
14592 ///
14593 /// \returns true if an error occurred, false otherwise.
14594 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
14595 UnexpandedParameterPackContext UPPC);
14596
14597 /// If the given expression contains an unexpanded parameter
14598 /// pack, diagnose the error.
14599 ///
14600 /// \param E The expression that is being checked for unexpanded
14601 /// parameter packs.
14602 ///
14603 /// \returns true if an error occurred, false otherwise.
14604 bool DiagnoseUnexpandedParameterPack(
14605 Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression);
14606
14607 /// If the given requirees-expression contains an unexpanded reference to one
14608 /// of its own parameter packs, diagnose the error.
14609 ///
14610 /// \param RE The requiress-expression that is being checked for unexpanded
14611 /// parameter packs.
14612 ///
14613 /// \returns true if an error occurred, false otherwise.
14614 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
14615
14616 /// If the given nested-name-specifier contains an unexpanded
14617 /// parameter pack, diagnose the error.
14618 ///
14619 /// \param SS The nested-name-specifier that is being checked for
14620 /// unexpanded parameter packs.
14621 ///
14622 /// \returns true if an error occurred, false otherwise.
14623 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
14624 UnexpandedParameterPackContext UPPC);
14625
14626 /// If the given name contains an unexpanded parameter pack,
14627 /// diagnose the error.
14628 ///
14629 /// \param NameInfo The name (with source location information) that
14630 /// is being checked for unexpanded parameter packs.
14631 ///
14632 /// \returns true if an error occurred, false otherwise.
14633 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
14634 UnexpandedParameterPackContext UPPC);
14635
14636 /// If the given template name contains an unexpanded parameter pack,
14637 /// diagnose the error.
14638 ///
14639 /// \param Loc The location of the template name.
14640 ///
14641 /// \param Template The template name that is being checked for unexpanded
14642 /// parameter packs.
14643 ///
14644 /// \returns true if an error occurred, false otherwise.
14645 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
14646 TemplateName Template,
14647 UnexpandedParameterPackContext UPPC);
14648
14649 /// If the given template argument contains an unexpanded parameter
14650 /// pack, diagnose the error.
14651 ///
14652 /// \param Arg The template argument that is being checked for unexpanded
14653 /// parameter packs.
14654 ///
14655 /// \returns true if an error occurred, false otherwise.
14656 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
14657 UnexpandedParameterPackContext UPPC);
14658
14659 /// Collect the set of unexpanded parameter packs within the given
14660 /// template argument.
14661 ///
14662 /// \param Arg The template argument that will be traversed to find
14663 /// unexpanded parameter packs.
14664 void collectUnexpandedParameterPacks(
14665 TemplateArgument Arg,
14666 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14667
14668 /// Collect the set of unexpanded parameter packs within the given
14669 /// template argument.
14670 ///
14671 /// \param Arg The template argument that will be traversed to find
14672 /// unexpanded parameter packs.
14673 void collectUnexpandedParameterPacks(
14674 TemplateArgumentLoc Arg,
14675 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14676
14677 /// Collect the set of unexpanded parameter packs within the given
14678 /// type.
14679 ///
14680 /// \param T The type that will be traversed to find
14681 /// unexpanded parameter packs.
14682 void collectUnexpandedParameterPacks(
14683 QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14684
14685 /// Collect the set of unexpanded parameter packs within the given
14686 /// type.
14687 ///
14688 /// \param TL The type that will be traversed to find
14689 /// unexpanded parameter packs.
14690 void collectUnexpandedParameterPacks(
14691 TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14692
14693 /// Collect the set of unexpanded parameter packs within the given
14694 /// nested-name-specifier.
14695 ///
14696 /// \param NNS The nested-name-specifier that will be traversed to find
14697 /// unexpanded parameter packs.
14698 void collectUnexpandedParameterPacks(
14699 NestedNameSpecifierLoc NNS,
14700 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14701
14702 /// Collect the set of unexpanded parameter packs within the given
14703 /// name.
14704 ///
14705 /// \param NameInfo The name that will be traversed to find
14706 /// unexpanded parameter packs.
14707 void collectUnexpandedParameterPacks(
14708 const DeclarationNameInfo &NameInfo,
14709 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14710
14711 /// Collect the set of unexpanded parameter packs within the given
14712 /// expression.
14713 static void collectUnexpandedParameterPacks(
14714 Expr *E, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14715
14716 /// Invoked when parsing a template argument.
14717 ///
14718 /// \param Arg the template argument, which may already be invalid.
14719 ///
14720 /// If it is followed by ellipsis, this function is called before
14721 /// `ActOnPackExpansion`.
14722 ParsedTemplateArgument
14723 ActOnTemplateTemplateArgument(const ParsedTemplateArgument &Arg);
14724
14725 /// Invoked when parsing a template argument followed by an
14726 /// ellipsis, which creates a pack expansion.
14727 ///
14728 /// \param Arg The template argument preceding the ellipsis, which
14729 /// may already be invalid.
14730 ///
14731 /// \param EllipsisLoc The location of the ellipsis.
14732 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
14733 SourceLocation EllipsisLoc);
14734
14735 /// Invoked when parsing a type followed by an ellipsis, which
14736 /// creates a pack expansion.
14737 ///
14738 /// \param Type The type preceding the ellipsis, which will become
14739 /// the pattern of the pack expansion.
14740 ///
14741 /// \param EllipsisLoc The location of the ellipsis.
14742 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
14743
14744 /// Construct a pack expansion type from the pattern of the pack
14745 /// expansion.
14746 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
14747 SourceLocation EllipsisLoc,
14748 UnsignedOrNone NumExpansions);
14749
14750 /// Construct a pack expansion type from the pattern of the pack
14751 /// expansion.
14752 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14753 SourceLocation EllipsisLoc,
14754 UnsignedOrNone NumExpansions);
14755
14756 /// Invoked when parsing an expression followed by an ellipsis, which
14757 /// creates a pack expansion.
14758 ///
14759 /// \param Pattern The expression preceding the ellipsis, which will become
14760 /// the pattern of the pack expansion.
14761 ///
14762 /// \param EllipsisLoc The location of the ellipsis.
14763 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14764
14765 /// Invoked when parsing an expression followed by an ellipsis, which
14766 /// creates a pack expansion.
14767 ///
14768 /// \param Pattern The expression preceding the ellipsis, which will become
14769 /// the pattern of the pack expansion.
14770 ///
14771 /// \param EllipsisLoc The location of the ellipsis.
14772 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14773 UnsignedOrNone NumExpansions);
14774
14775 /// Determine whether we could expand a pack expansion with the
14776 /// given set of parameter packs into separate arguments by repeatedly
14777 /// transforming the pattern.
14778 ///
14779 /// \param EllipsisLoc The location of the ellipsis that identifies the
14780 /// pack expansion.
14781 ///
14782 /// \param PatternRange The source range that covers the entire pattern of
14783 /// the pack expansion.
14784 ///
14785 /// \param Unexpanded The set of unexpanded parameter packs within the
14786 /// pattern.
14787 ///
14788 /// \param ShouldExpand Will be set to \c true if the transformer should
14789 /// expand the corresponding pack expansions into separate arguments. When
14790 /// set, \c NumExpansions must also be set.
14791 ///
14792 /// \param RetainExpansion Whether the caller should add an unexpanded
14793 /// pack expansion after all of the expanded arguments. This is used
14794 /// when extending explicitly-specified template argument packs per
14795 /// C++0x [temp.arg.explicit]p9.
14796 ///
14797 /// \param NumExpansions The number of separate arguments that will be in
14798 /// the expanded form of the corresponding pack expansion. This is both an
14799 /// input and an output parameter, which can be set by the caller if the
14800 /// number of expansions is known a priori (e.g., due to a prior substitution)
14801 /// and will be set by the callee when the number of expansions is known.
14802 /// The callee must set this value when \c ShouldExpand is \c true; it may
14803 /// set this value in other cases.
14804 ///
14805 /// \returns true if an error occurred (e.g., because the parameter packs
14806 /// are to be instantiated with arguments of different lengths), false
14807 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
14808 /// must be set.
14809 bool CheckParameterPacksForExpansion(
14810 SourceLocation EllipsisLoc, SourceRange PatternRange,
14811 ArrayRef<UnexpandedParameterPack> Unexpanded,
14812 const MultiLevelTemplateArgumentList &TemplateArgs,
14813 bool FailOnPackProducingTemplates, bool &ShouldExpand,
14814 bool &RetainExpansion, UnsignedOrNone &NumExpansions,
14815 bool Diagnose = true);
14816
14817 /// Determine the number of arguments in the given pack expansion
14818 /// type.
14819 ///
14820 /// This routine assumes that the number of arguments in the expansion is
14821 /// consistent across all of the unexpanded parameter packs in its pattern.
14822 ///
14823 /// Returns an empty Optional if the type can't be expanded.
14824 UnsignedOrNone getNumArgumentsInExpansion(
14825 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
14826
14827 UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(
14828 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
14829 const MultiLevelTemplateArgumentList &TemplateArgs);
14830
14831 /// Determine whether the given declarator contains any unexpanded
14832 /// parameter packs.
14833 ///
14834 /// This routine is used by the parser to disambiguate function declarators
14835 /// with an ellipsis prior to the ')', e.g.,
14836 ///
14837 /// \code
14838 /// void f(T...);
14839 /// \endcode
14840 ///
14841 /// To determine whether we have an (unnamed) function parameter pack or
14842 /// a variadic function.
14843 ///
14844 /// \returns true if the declarator contains any unexpanded parameter packs,
14845 /// false otherwise.
14846 bool containsUnexpandedParameterPacks(Declarator &D);
14847
14848 /// Returns the pattern of the pack expansion for a template argument.
14849 ///
14850 /// \param OrigLoc The template argument to expand.
14851 ///
14852 /// \param Ellipsis Will be set to the location of the ellipsis.
14853 ///
14854 /// \param NumExpansions Will be set to the number of expansions that will
14855 /// be generated from this pack expansion, if known a priori.
14856 TemplateArgumentLoc
14857 getTemplateArgumentPackExpansionPattern(TemplateArgumentLoc OrigLoc,
14858 SourceLocation &Ellipsis,
14859 UnsignedOrNone &NumExpansions) const;
14860
14861 /// Given a template argument that contains an unexpanded parameter pack, but
14862 /// which has already been substituted, attempt to determine the number of
14863 /// elements that will be produced once this argument is fully-expanded.
14864 ///
14865 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
14866 /// avoid actually expanding the pack where possible.
14867 UnsignedOrNone getFullyPackExpandedSize(TemplateArgument Arg);
14868
14869 /// Called when an expression computing the size of a parameter pack
14870 /// is parsed.
14871 ///
14872 /// \code
14873 /// template<typename ...Types> struct count {
14874 /// static const unsigned value = sizeof...(Types);
14875 /// };
14876 /// \endcode
14877 ///
14878 //
14879 /// \param OpLoc The location of the "sizeof" keyword.
14880 /// \param Name The name of the parameter pack whose size will be determined.
14881 /// \param NameLoc The source location of the name of the parameter pack.
14882 /// \param RParenLoc The location of the closing parentheses.
14883 ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc,
14884 IdentifierInfo &Name,
14885 SourceLocation NameLoc,
14886 SourceLocation RParenLoc);
14887
14888 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
14889 SourceLocation EllipsisLoc,
14890 SourceLocation LSquareLoc, Expr *IndexExpr,
14891 SourceLocation RSquareLoc);
14892
14893 ExprResult BuildPackIndexingExpr(Expr *PackExpression,
14894 SourceLocation EllipsisLoc, Expr *IndexExpr,
14895 SourceLocation RSquareLoc,
14896 ArrayRef<Expr *> ExpandedExprs = {},
14897 bool FullySubstituted = false);
14898
14899 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
14900 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
14901 tok::TokenKind Operator,
14902 SourceLocation EllipsisLoc, Expr *RHS,
14903 SourceLocation RParenLoc);
14904 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
14905 SourceLocation LParenLoc, Expr *LHS,
14906 BinaryOperatorKind Operator,
14907 SourceLocation EllipsisLoc, Expr *RHS,
14908 SourceLocation RParenLoc,
14909 UnsignedOrNone NumExpansions);
14910 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
14911 BinaryOperatorKind Operator);
14912
14913 ///@}
14914
14915 //
14916 //
14917 // -------------------------------------------------------------------------
14918 //
14919 //
14920
14921 /// \name Constraints and Concepts
14922 /// Implementations are in SemaConcept.cpp
14923 ///@{
14924
14925public:
14926 ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI);
14927
14928 ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc,
14929 TypeSourceInfo *TSI);
14930
14931public:
14932 void PushSatisfactionStackEntry(const NamedDecl *D,
14933 const llvm::FoldingSetNodeID &ID) {
14934 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
14935 SatisfactionStack.emplace_back(Args&: Can, Args: ID);
14936 }
14937
14938 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
14939
14940 bool SatisfactionStackContains(const NamedDecl *D,
14941 const llvm::FoldingSetNodeID &ID) const {
14942 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
14943 return llvm::is_contained(Range: SatisfactionStack,
14944 Element: SatisfactionStackEntryTy{Can, ID});
14945 }
14946
14947 using SatisfactionStackEntryTy =
14948 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
14949
14950 // Resets the current SatisfactionStack for cases where we are instantiating
14951 // constraints as a 'side effect' of normal instantiation in a way that is not
14952 // indicative of recursive definition.
14953 class SatisfactionStackResetRAII {
14954 llvm::SmallVector<SatisfactionStackEntryTy, 10> BackupSatisfactionStack;
14955 Sema &SemaRef;
14956
14957 public:
14958 SatisfactionStackResetRAII(Sema &S) : SemaRef(S) {
14959 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
14960 }
14961
14962 ~SatisfactionStackResetRAII() {
14963 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
14964 }
14965
14966 SatisfactionStackResetRAII(const SatisfactionStackResetRAII &) = delete;
14967 SatisfactionStackResetRAII &
14968 operator=(const SatisfactionStackResetRAII &) = delete;
14969 };
14970
14971 void SwapSatisfactionStack(
14972 llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) {
14973 SatisfactionStack.swap(RHS&: NewSS);
14974 }
14975
14976 using ConstrainedDeclOrNestedRequirement =
14977 llvm::PointerUnion<const NamedDecl *,
14978 const concepts::NestedRequirement *>;
14979
14980 /// Check whether the given expression is a valid constraint expression.
14981 /// A diagnostic is emitted if it is not, false is returned, and
14982 /// PossibleNonPrimary will be set to true if the failure might be due to a
14983 /// non-primary expression being used as an atomic constraint.
14984 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
14985 bool *PossibleNonPrimary = nullptr,
14986 bool IsTrailingRequiresClause = false);
14987
14988 /// \brief Check whether the given list of constraint expressions are
14989 /// satisfied (as if in a 'conjunction') given template arguments.
14990 /// \param Template the template-like entity that triggered the constraints
14991 /// check (either a concept or a constrained entity).
14992 /// \param ConstraintExprs a list of constraint expressions, treated as if
14993 /// they were 'AND'ed together.
14994 /// \param TemplateArgLists the list of template arguments to substitute into
14995 /// the constraint expression.
14996 /// \param TemplateIDRange The source range of the template id that
14997 /// caused the constraints check.
14998 /// \param Satisfaction if true is returned, will contain details of the
14999 /// satisfaction, with enough information to diagnose an unsatisfied
15000 /// expression.
15001 /// \returns true if an error occurred and satisfaction could not be checked,
15002 /// false otherwise.
15003 bool CheckConstraintSatisfaction(
15004 ConstrainedDeclOrNestedRequirement Entity,
15005 ArrayRef<AssociatedConstraint> AssociatedConstraints,
15006 const MultiLevelTemplateArgumentList &TemplateArgLists,
15007 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
15008 const ConceptReference *TopLevelConceptId = nullptr,
15009 Expr **ConvertedExpr = nullptr);
15010
15011 /// Check whether the given function decl's trailing requires clause is
15012 /// satisfied, if any. Returns false and updates Satisfaction with the
15013 /// satisfaction verdict if successful, emits a diagnostic and returns true if
15014 /// an error occurred and satisfaction could not be determined.
15015 ///
15016 /// \returns true if an error occurred, false otherwise.
15017 bool CheckFunctionConstraints(const FunctionDecl *FD,
15018 ConstraintSatisfaction &Satisfaction,
15019 SourceLocation UsageLoc = SourceLocation(),
15020 bool ForOverloadResolution = false);
15021
15022 // Calculates whether two constraint expressions are equal irrespective of a
15023 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
15024 // 'New', which are the "source" of the constraint, since this is necessary
15025 // for figuring out the relative 'depth' of the constraint. The depth of the
15026 // 'primary template' and the 'instantiated from' templates aren't necessarily
15027 // the same, such as a case when one is a 'friend' defined in a class.
15028 bool AreConstraintExpressionsEqual(const NamedDecl *Old,
15029 const Expr *OldConstr,
15030 const TemplateCompareNewDeclInfo &New,
15031 const Expr *NewConstr);
15032
15033 // Calculates whether the friend function depends on an enclosing template for
15034 // the purposes of [temp.friend] p9.
15035 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
15036
15037 /// \brief Ensure that the given template arguments satisfy the constraints
15038 /// associated with the given template, emitting a diagnostic if they do not.
15039 ///
15040 /// \param Template The template to which the template arguments are being
15041 /// provided.
15042 ///
15043 /// \param TemplateArgs The converted, canonicalized template arguments.
15044 ///
15045 /// \param TemplateIDRange The source range of the template id that
15046 /// caused the constraints check.
15047 ///
15048 /// \returns true if the constrains are not satisfied or could not be checked
15049 /// for satisfaction, false if the constraints are satisfied.
15050 bool EnsureTemplateArgumentListConstraints(
15051 TemplateDecl *Template,
15052 const MultiLevelTemplateArgumentList &TemplateArgs,
15053 SourceRange TemplateIDRange);
15054
15055 bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
15056 FunctionDecl *Decl,
15057 ArrayRef<TemplateArgument> TemplateArgs,
15058 ConstraintSatisfaction &Satisfaction);
15059
15060 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15061 /// unsatisfied.
15062 /// \param First whether this is the first time an unsatisfied constraint is
15063 /// diagnosed for this error.
15064 void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
15065 SourceLocation Loc = {},
15066 bool First = true);
15067
15068 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15069 /// unsatisfied.
15070 void
15071 DiagnoseUnsatisfiedConstraint(const ConceptSpecializationExpr *ConstraintExpr,
15072 bool First = true);
15073
15074 const NormalizedConstraint *getNormalizedAssociatedConstraints(
15075 ConstrainedDeclOrNestedRequirement Entity,
15076 ArrayRef<AssociatedConstraint> AssociatedConstraints);
15077
15078 /// \brief Check whether the given declaration's associated constraints are
15079 /// at least as constrained than another declaration's according to the
15080 /// partial ordering of constraints.
15081 ///
15082 /// \param Result If no error occurred, receives the result of true if D1 is
15083 /// at least constrained than D2, and false otherwise.
15084 ///
15085 /// \returns true if an error occurred, false otherwise.
15086 bool IsAtLeastAsConstrained(const NamedDecl *D1,
15087 MutableArrayRef<AssociatedConstraint> AC1,
15088 const NamedDecl *D2,
15089 MutableArrayRef<AssociatedConstraint> AC2,
15090 bool &Result);
15091
15092 /// If D1 was not at least as constrained as D2, but would've been if a pair
15093 /// of atomic constraints involved had been declared in a concept and not
15094 /// repeated in two separate places in code.
15095 /// \returns true if such a diagnostic was emitted, false otherwise.
15096 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(
15097 const NamedDecl *D1, ArrayRef<AssociatedConstraint> AC1,
15098 const NamedDecl *D2, ArrayRef<AssociatedConstraint> AC2);
15099
15100 /// Cache the satisfaction of an atomic constraint.
15101 /// The key is based on the unsubstituted expression and the parameter
15102 /// mapping. This lets us not substituting the mapping more than once,
15103 /// which is (very!) expensive.
15104 /// FIXME: this should be private.
15105 llvm::DenseMap<llvm::FoldingSetNodeID,
15106 UnsubstitutedConstraintSatisfactionCacheResult>
15107 UnsubstitutedConstraintSatisfactionCache;
15108
15109private:
15110 /// Caches pairs of template-like decls whose associated constraints were
15111 /// checked for subsumption and whether or not the first's constraints did in
15112 /// fact subsume the second's.
15113 llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
15114 SubsumptionCache;
15115 /// Caches the normalized associated constraints of declarations (concepts or
15116 /// constrained declarations). If an error occurred while normalizing the
15117 /// associated constraints of the template or concept, nullptr will be cached
15118 /// here.
15119 llvm::DenseMap<ConstrainedDeclOrNestedRequirement, NormalizedConstraint *>
15120 NormalizationCache;
15121
15122 /// Cache whether the associated constraint of a declaration
15123 /// is satisfied.
15124 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
15125 SatisfactionCache;
15126
15127 // The current stack of constraint satisfactions, so we can exit-early.
15128 llvm::SmallVector<SatisfactionStackEntryTy, 10> SatisfactionStack;
15129
15130 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
15131 /// LocalInstantiationScope of the current non-lambda function. For lambdas,
15132 /// use LambdaScopeForCallOperatorInstantiationRAII.
15133 bool
15134 SetupConstraintScope(FunctionDecl *FD,
15135 std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15136 const MultiLevelTemplateArgumentList &MLTAL,
15137 LocalInstantiationScope &Scope);
15138
15139 /// Used during constraint checking, sets up the constraint template argument
15140 /// lists, and calls SetupConstraintScope to set up the
15141 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
15142 std::optional<MultiLevelTemplateArgumentList>
15143 SetupConstraintCheckingTemplateArgumentsAndScope(
15144 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15145 LocalInstantiationScope &Scope);
15146
15147 ///@}
15148
15149 //
15150 //
15151 // -------------------------------------------------------------------------
15152 //
15153 //
15154
15155 /// \name Types
15156 /// Implementations are in SemaType.cpp
15157 ///@{
15158
15159public:
15160 /// A mapping that describes the nullability we've seen in each header file.
15161 FileNullabilityMap NullabilityMap;
15162
15163 static int getPrintable(int I) { return I; }
15164 static unsigned getPrintable(unsigned I) { return I; }
15165 static bool getPrintable(bool B) { return B; }
15166 static const char *getPrintable(const char *S) { return S; }
15167 static StringRef getPrintable(StringRef S) { return S; }
15168 static const std::string &getPrintable(const std::string &S) { return S; }
15169 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
15170 return II;
15171 }
15172 static DeclarationName getPrintable(DeclarationName N) { return N; }
15173 static QualType getPrintable(QualType T) { return T; }
15174 static SourceRange getPrintable(SourceRange R) { return R; }
15175 static SourceRange getPrintable(SourceLocation L) { return L; }
15176 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
15177 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange(); }
15178
15179 enum class CompleteTypeKind {
15180 /// Apply the normal rules for complete types. In particular,
15181 /// treat all sizeless types as incomplete.
15182 Normal,
15183
15184 /// Relax the normal rules for complete types so that they include
15185 /// sizeless built-in types.
15186 AcceptSizeless,
15187
15188 // FIXME: Eventually we should flip the default to Normal and opt in
15189 // to AcceptSizeless rather than opt out of it.
15190 Default = AcceptSizeless
15191 };
15192
15193 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
15194 const DeclSpec *DS = nullptr);
15195 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
15196 const DeclSpec *DS = nullptr);
15197
15198 /// Build a pointer type.
15199 ///
15200 /// \param T The type to which we'll be building a pointer.
15201 ///
15202 /// \param Loc The location of the entity whose type involves this
15203 /// pointer type or, if there is no such entity, the location of the
15204 /// type that will have pointer type.
15205 ///
15206 /// \param Entity The name of the entity that involves the pointer
15207 /// type, if known.
15208 ///
15209 /// \returns A suitable pointer type, if there are no
15210 /// errors. Otherwise, returns a NULL type.
15211 QualType BuildPointerType(QualType T, SourceLocation Loc,
15212 DeclarationName Entity);
15213
15214 /// Build a reference type.
15215 ///
15216 /// \param T The type to which we'll be building a reference.
15217 ///
15218 /// \param Loc The location of the entity whose type involves this
15219 /// reference type or, if there is no such entity, the location of the
15220 /// type that will have reference type.
15221 ///
15222 /// \param Entity The name of the entity that involves the reference
15223 /// type, if known.
15224 ///
15225 /// \returns A suitable reference type, if there are no
15226 /// errors. Otherwise, returns a NULL type.
15227 QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc,
15228 DeclarationName Entity);
15229
15230 /// Build an array type.
15231 ///
15232 /// \param T The type of each element in the array.
15233 ///
15234 /// \param ASM C99 array size modifier (e.g., '*', 'static').
15235 ///
15236 /// \param ArraySize Expression describing the size of the array.
15237 ///
15238 /// \param Brackets The range from the opening '[' to the closing ']'.
15239 ///
15240 /// \param Entity The name of the entity that involves the array
15241 /// type, if known.
15242 ///
15243 /// \returns A suitable array type, if there are no errors. Otherwise,
15244 /// returns a NULL type.
15245 QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize,
15246 unsigned Quals, SourceRange Brackets,
15247 DeclarationName Entity);
15248 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
15249
15250 /// Build an ext-vector type.
15251 ///
15252 /// Run the required checks for the extended vector type.
15253 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
15254 SourceLocation AttrLoc);
15255 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
15256 SourceLocation AttrLoc);
15257
15258 QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy,
15259 Expr *CountExpr,
15260 bool CountInBytes,
15261 bool OrNull);
15262
15263 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
15264 /// expression is uninstantiated. If instantiated it will apply the
15265 /// appropriate address space to the type. This function allows dependent
15266 /// template variables to be used in conjunction with the address_space
15267 /// attribute
15268 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
15269 SourceLocation AttrLoc);
15270
15271 /// Same as above, but constructs the AddressSpace index if not provided.
15272 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
15273 SourceLocation AttrLoc);
15274
15275 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
15276
15277 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
15278
15279 /// Build a function type.
15280 ///
15281 /// This routine checks the function type according to C++ rules and
15282 /// under the assumption that the result type and parameter types have
15283 /// just been instantiated from a template. It therefore duplicates
15284 /// some of the behavior of GetTypeForDeclarator, but in a much
15285 /// simpler form that is only suitable for this narrow use case.
15286 ///
15287 /// \param T The return type of the function.
15288 ///
15289 /// \param ParamTypes The parameter types of the function. This array
15290 /// will be modified to account for adjustments to the types of the
15291 /// function parameters.
15292 ///
15293 /// \param Loc The location of the entity whose type involves this
15294 /// function type or, if there is no such entity, the location of the
15295 /// type that will have function type.
15296 ///
15297 /// \param Entity The name of the entity that involves the function
15298 /// type, if known.
15299 ///
15300 /// \param EPI Extra information about the function type. Usually this will
15301 /// be taken from an existing function with the same prototype.
15302 ///
15303 /// \returns A suitable function type, if there are no errors. The
15304 /// unqualified type will always be a FunctionProtoType.
15305 /// Otherwise, returns a NULL type.
15306 QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes,
15307 SourceLocation Loc, DeclarationName Entity,
15308 const FunctionProtoType::ExtProtoInfo &EPI);
15309
15310 /// Build a member pointer type \c T Class::*.
15311 ///
15312 /// \param T the type to which the member pointer refers.
15313 /// \param Class the class type into which the member pointer points.
15314 /// \param Loc the location where this type begins
15315 /// \param Entity the name of the entity that will have this member pointer
15316 /// type
15317 ///
15318 /// \returns a member pointer type, if successful, or a NULL type if there was
15319 /// an error.
15320 QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS,
15321 CXXRecordDecl *Cls, SourceLocation Loc,
15322 DeclarationName Entity);
15323
15324 /// Build a block pointer type.
15325 ///
15326 /// \param T The type to which we'll be building a block pointer.
15327 ///
15328 /// \param Loc The source location, used for diagnostics.
15329 ///
15330 /// \param Entity The name of the entity that involves the block pointer
15331 /// type, if known.
15332 ///
15333 /// \returns A suitable block pointer type, if there are no
15334 /// errors. Otherwise, returns a NULL type.
15335 QualType BuildBlockPointerType(QualType T, SourceLocation Loc,
15336 DeclarationName Entity);
15337
15338 /// Build a paren type including \p T.
15339 QualType BuildParenType(QualType T);
15340 QualType BuildAtomicType(QualType T, SourceLocation Loc);
15341
15342 /// Build a Read-only Pipe type.
15343 ///
15344 /// \param T The type to which we'll be building a Pipe.
15345 ///
15346 /// \param Loc We do not use it for now.
15347 ///
15348 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15349 /// a NULL type.
15350 QualType BuildReadPipeType(QualType T, SourceLocation Loc);
15351
15352 /// Build a Write-only Pipe type.
15353 ///
15354 /// \param T The type to which we'll be building a Pipe.
15355 ///
15356 /// \param Loc We do not use it for now.
15357 ///
15358 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15359 /// a NULL type.
15360 QualType BuildWritePipeType(QualType T, SourceLocation Loc);
15361
15362 /// Build a bit-precise integer type.
15363 ///
15364 /// \param IsUnsigned Boolean representing the signedness of the type.
15365 ///
15366 /// \param BitWidth Size of this int type in bits, or an expression
15367 /// representing that.
15368 ///
15369 /// \param Loc Location of the keyword.
15370 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15371
15372 /// GetTypeForDeclarator - Convert the type for the specified
15373 /// declarator to Type instances.
15374 ///
15375 /// The result of this call will never be null, but the associated
15376 /// type may be a null type if there's an unrecoverable error.
15377 TypeSourceInfo *GetTypeForDeclarator(Declarator &D);
15378 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
15379
15380 /// Package the given type and TSI into a ParsedType.
15381 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
15382 static QualType GetTypeFromParser(ParsedType Ty,
15383 TypeSourceInfo **TInfo = nullptr);
15384
15385 TypeResult ActOnTypeName(Declarator &D);
15386
15387 // Check whether the size of array element of type \p EltTy is a multiple of
15388 // its alignment and return false if it isn't.
15389 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
15390
15391 void
15392 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15393 SourceLocation FallbackLoc,
15394 SourceLocation ConstQualLoc = SourceLocation(),
15395 SourceLocation VolatileQualLoc = SourceLocation(),
15396 SourceLocation RestrictQualLoc = SourceLocation(),
15397 SourceLocation AtomicQualLoc = SourceLocation(),
15398 SourceLocation UnalignedQualLoc = SourceLocation());
15399
15400 /// Retrieve the keyword associated
15401 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
15402
15403 /// Adjust the calling convention of a method to be the ABI default if it
15404 /// wasn't specified explicitly. This handles method types formed from
15405 /// function type typedefs and typename template arguments.
15406 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15407 bool IsCtorOrDtor, SourceLocation Loc);
15408
15409 // Check if there is an explicit attribute, but only look through parens.
15410 // The intent is to look for an attribute on the current declarator, but not
15411 // one that came from a typedef.
15412 bool hasExplicitCallingConv(QualType T);
15413
15414 /// Check whether a nullability type specifier can be added to the given
15415 /// type through some means not written in source (e.g. API notes).
15416 ///
15417 /// \param Type The type to which the nullability specifier will be
15418 /// added. On success, this type will be updated appropriately.
15419 ///
15420 /// \param Nullability The nullability specifier to add.
15421 ///
15422 /// \param DiagLoc The location to use for diagnostics.
15423 ///
15424 /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15425 /// array type (e.g., because it will decay to a pointer).
15426 ///
15427 /// \param OverrideExisting Whether to override an existing, locally-specified
15428 /// nullability specifier rather than complaining about the conflict.
15429 ///
15430 /// \returns true if nullability cannot be applied, false otherwise.
15431 bool CheckImplicitNullabilityTypeSpecifier(QualType &Type,
15432 NullabilityKind Nullability,
15433 SourceLocation DiagLoc,
15434 bool AllowArrayTypes,
15435 bool OverrideExisting);
15436
15437 /// Check whether the given variable declaration has a size that fits within
15438 /// the address space it is declared in. This issues a diagnostic if not.
15439 ///
15440 /// \param VD The variable declaration to check the size of.
15441 ///
15442 /// \param AS The address space to check the size of \p VD against.
15443 ///
15444 /// \returns true if the variable's size fits within the address space, false
15445 /// otherwise.
15446 bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS);
15447
15448 /// Get the type of expression E, triggering instantiation to complete the
15449 /// type if necessary -- that is, if the expression refers to a templated
15450 /// static data member of incomplete array type.
15451 ///
15452 /// May still return an incomplete type if instantiation was not possible or
15453 /// if the type is incomplete for a different reason. Use
15454 /// RequireCompleteExprType instead if a diagnostic is expected for an
15455 /// incomplete expression type.
15456 QualType getCompletedType(Expr *E);
15457
15458 void completeExprArrayBound(Expr *E);
15459
15460 /// Ensure that the type of the given expression is complete.
15461 ///
15462 /// This routine checks whether the expression \p E has a complete type. If
15463 /// the expression refers to an instantiable construct, that instantiation is
15464 /// performed as needed to complete its type. Furthermore
15465 /// Sema::RequireCompleteType is called for the expression's type (or in the
15466 /// case of a reference type, the referred-to type).
15467 ///
15468 /// \param E The expression whose type is required to be complete.
15469 /// \param Kind Selects which completeness rules should be applied.
15470 /// \param Diagnoser The object that will emit a diagnostic if the type is
15471 /// incomplete.
15472 ///
15473 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15474 /// otherwise.
15475 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
15476 TypeDiagnoser &Diagnoser);
15477 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15478
15479 template <typename... Ts>
15480 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15481 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15482 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
15483 }
15484
15485 // Returns the underlying type of a decltype with the given expression.
15486 QualType getDecltypeForExpr(Expr *E);
15487
15488 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
15489 /// If AsUnevaluated is false, E is treated as though it were an evaluated
15490 /// context, such as when building a type for decltype(auto).
15491 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15492
15493 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15494 SourceLocation Loc,
15495 SourceLocation EllipsisLoc);
15496 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15497 SourceLocation Loc, SourceLocation EllipsisLoc,
15498 bool FullySubstituted = false,
15499 ArrayRef<QualType> Expansions = {});
15500
15501 using UTTKind = UnaryTransformType::UTTKind;
15502 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
15503 SourceLocation Loc);
15504 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
15505 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
15506 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
15507 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
15508 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
15509 SourceLocation Loc);
15510 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
15511 SourceLocation Loc);
15512 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
15513 SourceLocation Loc);
15514
15515 QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc) {
15516 return BuiltinRemoveReference(BaseType, UKind: UTTKind::RemoveCVRef, Loc);
15517 }
15518
15519 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
15520 SourceLocation Loc);
15521 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
15522 SourceLocation Loc);
15523
15524 bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15525
15526 /// Ensure that the type T is a literal type.
15527 ///
15528 /// This routine checks whether the type @p T is a literal type. If @p T is an
15529 /// incomplete type, an attempt is made to complete it. If @p T is a literal
15530 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15531 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15532 /// it the type @p T), along with notes explaining why the type is not a
15533 /// literal type, and returns true.
15534 ///
15535 /// @param Loc The location in the source that the non-literal type
15536 /// diagnostic should refer to.
15537 ///
15538 /// @param T The type that this routine is examining for literalness.
15539 ///
15540 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15541 ///
15542 /// @returns @c true if @p T is not a literal type and a diagnostic was
15543 /// emitted, @c false otherwise.
15544 bool RequireLiteralType(SourceLocation Loc, QualType T,
15545 TypeDiagnoser &Diagnoser);
15546 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15547
15548 template <typename... Ts>
15549 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15550 const Ts &...Args) {
15551 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15552 return RequireLiteralType(Loc, T, Diagnoser);
15553 }
15554
15555 bool isCompleteType(SourceLocation Loc, QualType T,
15556 CompleteTypeKind Kind = CompleteTypeKind::Default) {
15557 return !RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser: nullptr);
15558 }
15559
15560 /// Ensure that the type T is a complete type.
15561 ///
15562 /// This routine checks whether the type @p T is complete in any
15563 /// context where a complete type is required. If @p T is a complete
15564 /// type, returns false. If @p T is a class template specialization,
15565 /// this routine then attempts to perform class template
15566 /// instantiation. If instantiation fails, or if @p T is incomplete
15567 /// and cannot be completed, issues the diagnostic @p diag (giving it
15568 /// the type @p T) and returns true.
15569 ///
15570 /// @param Loc The location in the source that the incomplete type
15571 /// diagnostic should refer to.
15572 ///
15573 /// @param T The type that this routine is examining for completeness.
15574 ///
15575 /// @param Kind Selects which completeness rules should be applied.
15576 ///
15577 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15578 /// @c false otherwise.
15579 bool RequireCompleteType(SourceLocation Loc, QualType T,
15580 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15581 bool RequireCompleteType(SourceLocation Loc, QualType T,
15582 CompleteTypeKind Kind, unsigned DiagID);
15583
15584 bool RequireCompleteType(SourceLocation Loc, QualType T,
15585 TypeDiagnoser &Diagnoser) {
15586 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, Diagnoser);
15587 }
15588 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15589 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, DiagID);
15590 }
15591
15592 template <typename... Ts>
15593 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15594 const Ts &...Args) {
15595 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15596 return RequireCompleteType(Loc, T, Diagnoser);
15597 }
15598
15599 /// Determine whether a declaration is visible to name lookup.
15600 bool isVisible(const NamedDecl *D) {
15601 return D->isUnconditionallyVisible() ||
15602 isAcceptableSlow(D, Kind: AcceptableKind::Visible);
15603 }
15604
15605 /// Determine whether a declaration is reachable.
15606 bool isReachable(const NamedDecl *D) {
15607 // All visible declarations are reachable.
15608 return D->isUnconditionallyVisible() ||
15609 isAcceptableSlow(D, Kind: AcceptableKind::Reachable);
15610 }
15611
15612 /// Determine whether a declaration is acceptable (visible/reachable).
15613 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
15614 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15615 }
15616
15617 /// Determine if \p D and \p Suggested have a structurally compatible
15618 /// layout as described in C11 6.2.7/1.
15619 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15620
15621 /// Determine if \p D has a visible definition. If not, suggest a declaration
15622 /// that should be made visible to expose the definition.
15623 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15624 bool OnlyNeedComplete = false);
15625 bool hasVisibleDefinition(const NamedDecl *D) {
15626 NamedDecl *Hidden;
15627 return hasVisibleDefinition(D: const_cast<NamedDecl *>(D), Suggested: &Hidden);
15628 }
15629 /// Determine if \p D has a definition which allows we redefine it in current
15630 /// TU. \p Suggested is the definition that should be made visible to expose
15631 /// the definition.
15632 bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
15633 bool &Visible);
15634 bool isRedefinitionAllowedFor(const NamedDecl *D, bool &Visible) {
15635 NamedDecl *Hidden;
15636 return isRedefinitionAllowedFor(D: const_cast<NamedDecl *>(D), Suggested: &Hidden,
15637 Visible);
15638 }
15639
15640 /// Determine if \p D has a reachable definition. If not, suggest a
15641 /// declaration that should be made reachable to expose the definition.
15642 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15643 bool OnlyNeedComplete = false);
15644 bool hasReachableDefinition(NamedDecl *D) {
15645 NamedDecl *Hidden;
15646 return hasReachableDefinition(D, Suggested: &Hidden);
15647 }
15648
15649 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15650 AcceptableKind Kind,
15651 bool OnlyNeedComplete = false);
15652 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
15653 NamedDecl *Hidden;
15654 return hasAcceptableDefinition(D, Suggested: &Hidden, Kind);
15655 }
15656
15657 /// Try to parse the conditional expression attached to an effect attribute
15658 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15659 /// optional on error.
15660 std::optional<FunctionEffectMode>
15661 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15662
15663 void ActOnCleanupAttr(Decl *D, const Attr *A);
15664 void ActOnInitPriorityAttr(Decl *D, const Attr *A);
15665
15666private:
15667 /// The implementation of RequireCompleteType
15668 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15669 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15670
15671 /// Nullability type specifiers.
15672 IdentifierInfo *Ident__Nonnull = nullptr;
15673 IdentifierInfo *Ident__Nullable = nullptr;
15674 IdentifierInfo *Ident__Nullable_result = nullptr;
15675 IdentifierInfo *Ident__Null_unspecified = nullptr;
15676
15677 ///@}
15678
15679 //
15680 //
15681 // -------------------------------------------------------------------------
15682 //
15683 //
15684
15685 /// \name FixIt Helpers
15686 /// Implementations are in SemaFixItUtils.cpp
15687 ///@{
15688
15689public:
15690 /// Get a string to suggest for zero-initialization of a type.
15691 std::string getFixItZeroInitializerForType(QualType T,
15692 SourceLocation Loc) const;
15693 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15694
15695 ///@}
15696
15697 //
15698 //
15699 // -------------------------------------------------------------------------
15700 //
15701 //
15702
15703 /// \name Function Effects
15704 /// Implementations are in SemaFunctionEffects.cpp
15705 ///@{
15706public:
15707 struct FunctionEffectDiff {
15708 enum class Kind { Added, Removed, ConditionMismatch };
15709
15710 FunctionEffect::Kind EffectKind;
15711 Kind DiffKind;
15712 std::optional<FunctionEffectWithCondition>
15713 Old; // Invalid when 'Kind' is 'Added'.
15714 std::optional<FunctionEffectWithCondition>
15715 New; // Invalid when 'Kind' is 'Removed'.
15716
15717 StringRef effectName() const {
15718 if (Old)
15719 return Old.value().Effect.name();
15720 return New.value().Effect.name();
15721 }
15722
15723 /// Describes the result of effects differing between a base class's virtual
15724 /// method and an overriding method in a subclass.
15725 enum class OverrideResult {
15726 NoAction,
15727 Warn,
15728 Merge // Merge missing effect from base to derived.
15729 };
15730
15731 /// Return true if adding or removing the effect as part of a type
15732 /// conversion should generate a diagnostic.
15733 bool shouldDiagnoseConversion(QualType SrcType,
15734 const FunctionEffectsRef &SrcFX,
15735 QualType DstType,
15736 const FunctionEffectsRef &DstFX) const;
15737
15738 /// Return true if adding or removing the effect in a redeclaration should
15739 /// generate a diagnostic.
15740 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
15741 const FunctionEffectsRef &OldFX,
15742 const FunctionDecl &NewFunction,
15743 const FunctionEffectsRef &NewFX) const;
15744
15745 /// Return true if adding or removing the effect in a C++ virtual method
15746 /// override should generate a diagnostic.
15747 OverrideResult shouldDiagnoseMethodOverride(
15748 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
15749 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
15750 };
15751
15752 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
15753 /// Caller should short-circuit by checking for equality first.
15754 FunctionEffectDiffVector(const FunctionEffectsRef &Old,
15755 const FunctionEffectsRef &New);
15756 };
15757
15758 /// All functions/lambdas/blocks which have bodies and which have a non-empty
15759 /// FunctionEffectsRef to be verified.
15760 SmallVector<const Decl *> DeclsWithEffectsToVerify;
15761
15762 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
15763 /// are all null.
15764 FunctionEffectKindSet AllEffectsToVerify;
15765
15766public:
15767 /// Warn and return true if adding a function effect to a set would create a
15768 /// conflict.
15769 bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX,
15770 const FunctionEffectWithCondition &EC,
15771 SourceLocation NewAttrLoc);
15772
15773 // Report a failure to merge function effects between declarations due to a
15774 // conflict.
15775 void
15776 diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs,
15777 SourceLocation NewLoc,
15778 SourceLocation OldLoc);
15779
15780 /// Inline checks from the start of maybeAddDeclWithEffects, to
15781 /// minimize performance impact on code not using effects.
15782 template <class FuncOrBlockDecl>
15783 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
15784 if (Context.hasAnyFunctionEffects())
15785 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
15786 maybeAddDeclWithEffects(D, FX);
15787 }
15788
15789 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
15790 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15791
15792 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
15793 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15794
15795 void performFunctionEffectAnalysis(TranslationUnitDecl *TU);
15796
15797 ///@}
15798};
15799
15800DeductionFailureInfo
15801MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK,
15802 sema::TemplateDeductionInfo &Info);
15803
15804/// Contains a late templated function.
15805/// Will be parsed at the end of the translation unit, used by Sema & Parser.
15806struct LateParsedTemplate {
15807 CachedTokens Toks;
15808 /// The template function declaration to be late parsed.
15809 Decl *D;
15810 /// Floating-point options in the point of definition.
15811 FPOptions FPO;
15812};
15813
15814template <>
15815void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
15816 PragmaMsStackAction Action,
15817 llvm::StringRef StackSlotLabel,
15818 AlignPackInfo Value);
15819
15820} // end namespace clang
15821
15822#endif
15823